lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
1907ba24e99be42b6c9fc2dbfe93727fdff229f4
0
gbif/checklistbank,gbif/checklistbank
package org.gbif.checklistbank.service.mybatis; import org.gbif.api.model.checklistbank.NameUsage; import org.gbif.api.model.checklistbank.NameUsageMetrics; import org.gbif.api.model.checklistbank.ParsedName; import org.gbif.api.model.common.paging.Pageable; import org.gbif.api.model.common.paging.PagingConstants; import org.gbif.api.model.common.paging.PagingRequest; import org.gbif.api.service.checklistbank.NameUsageService; import org.gbif.api.vocabulary.Origin; import org.gbif.api.vocabulary.Rank; import org.gbif.checklistbank.service.mybatis.postgres.DatabaseDrivenChecklistBankTestRule; import java.net.URI; import java.util.List; import java.util.Locale; import java.util.UUID; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class NameUsageServiceMyBatisIT { private static final UUID CHECKLIST_KEY = UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"); private final int NOT_FOUND_KEY = -10; @Rule public DatabaseDrivenChecklistBankTestRule<NameUsageService> ddt = DatabaseDrivenChecklistBankTestRule.squirrels(NameUsageService.class); @Test public void testGet() { final NameUsage rodentia = ddt.getService().get(100000004, Locale.UK); final NameUsageMetrics rodentiaM = ddt.getService().getMetrics(100000004); assertNotNull(rodentia); assertEquals((Integer) 10, rodentia.getNubKey()); assertFalse(rodentia.isSynonym()); assertEquals("1000", rodentia.getTaxonID()); assertEquals("Rodentia", rodentia.getCanonicalName()); assertEquals("Rodentia Bowdich, 1821", rodentia.getScientificName()); assertEquals("Bowdich, 1821", rodentia.getAuthorship()); assertEquals(Rank.ORDER, rodentia.getRank()); assertEquals((Integer) 100000003, rodentia.getParentKey()); assertEquals("Animalia", rodentia.getKingdom()); assertEquals((Integer) 100000001, rodentia.getKingdomKey()); assertEquals("Chordata", rodentia.getPhylum()); assertEquals((Integer) 100000002, rodentia.getPhylumKey()); assertEquals(0, rodentiaM.getNumPhylum()); assertEquals("Mammalia", rodentia.getClazz()); assertEquals((Integer) 100000003, rodentia.getClassKey()); assertEquals(0, rodentiaM.getNumClass()); assertEquals(1, rodentiaM.getNumOrder()); assertEquals(1, rodentiaM.getNumFamily()); assertEquals(2, rodentiaM.getNumGenus()); assertEquals(3, rodentiaM.getNumSpecies()); assertEquals(8, rodentiaM.getNumSynonyms()); assertEquals(1, rodentiaM.getNumChildren()); assertEquals(24, rodentia.getNumDescendants()); assertEquals(Origin.SOURCE, rodentia.getOrigin()); assertEquals(UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"), rodentia.getDatasetKey()); assertNull(rodentia.getPublishedIn()); assertEquals("1000", rodentia.getTaxonID()); NameUsage squirrel = ddt.getService().get(100000025, Locale.UK); final NameUsageMetrics squirrelM = ddt.getService().getMetrics(100000025); assertNotNull(squirrel); assertNull(squirrel.getNubKey()); assertFalse(squirrel.isSynonym()); assertEquals("Sciurus vulgaris", squirrel.getCanonicalName()); assertEquals("Sciurus vulgaris Linnaeus, 1758", squirrel.getScientificName()); assertEquals("Linnaeus, 1758", squirrel.getAuthorship()); assertEquals("Eurasian Red Squirrel", squirrel.getVernacularName()); assertEquals(Rank.SPECIES, squirrel.getRank()); assertEquals((Integer) 100000024, squirrel.getParentKey()); assertEquals("Animalia", squirrel.getKingdom()); assertEquals((Integer) 100000001, squirrel.getKingdomKey()); assertEquals("Chordata", squirrel.getPhylum()); assertEquals((Integer) 100000002, squirrel.getPhylumKey()); assertEquals(0, squirrelM.getNumPhylum()); assertEquals("Mammalia", squirrel.getClazz()); assertEquals((Integer) 100000003, squirrel.getClassKey()); assertEquals(0, squirrelM.getNumClass()); assertEquals("Rodentia", squirrel.getOrder()); assertEquals((Integer) 100000004, squirrel.getOrderKey()); assertEquals(0, squirrelM.getNumOrder()); assertEquals("Sciuridae", squirrel.getFamily()); assertEquals((Integer) 100000005, squirrel.getFamilyKey()); assertEquals(0, squirrelM.getNumFamily()); assertEquals("Sciurus", squirrel.getGenus()); assertEquals((Integer) 100000011, squirrel.getGenusKey()); assertEquals(0, squirrelM.getNumGenus()); assertEquals(1, squirrelM.getNumSpecies()); assertEquals(9, squirrelM.getNumChildren()); assertEquals(4, squirrelM.getNumSynonyms()); assertEquals(UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"), squirrel.getDatasetKey()); assertEquals("Syst. Nat. , 10th ed. vol. 1 p. 63", squirrel.getPublishedIn()); assertEquals("2010030", squirrel.getTaxonID()); // TEST VERNACULAR squirrel = ddt.getService().get(100000040, null); assertNull(squirrel.getVernacularName()); squirrel = ddt.getService().get(100000040, Locale.GERMANY); assertEquals("Kaukasischen Eichhörnchen", squirrel.getVernacularName()); // TEST non existing language VERNACULAR squirrel = ddt.getService().get(100000040, Locale.CHINESE); assertEquals("Caucasian Squirrel", squirrel.getVernacularName()); // TEST MULTIPLE IDENTIFIERS squirrel = ddt.getService().get(100000007, Locale.GERMANY); assertEquals("6905528", squirrel.getTaxonID()); assertEquals(URI.create("http://www.catalogueoflife.org/details/species/id/6905528"), squirrel.getReferences()); // TEST SYNONYM NameUsage syn = ddt.getService().get(100000027, Locale.FRENCH); assertNotNull(syn); assertTrue(syn.isSynonym()); assertEquals("Sciurus nadymensis", syn.getCanonicalName()); assertEquals("Sciurus nadymensis Serebrennikov, 1928", syn.getScientificName()); assertNull(syn.getVernacularName()); assertEquals(Rank.SPECIES, syn.getRank()); assertEquals((Integer) 100000024, syn.getParentKey()); assertEquals((Integer) 100000025, syn.getAcceptedKey()); assertEquals("Sciurus vulgaris Linnaeus, 1758", syn.getAccepted()); assertFalse(syn.isProParte()); } @Test public void testArraySet() { // test nomenclatoral status set NameUsage syn = ddt.getService().get(100000026, Locale.FRENCH); //TODO: get the array mapper working assertEquals(2, syn.getNomenclaturalStatus().size()); } @Test public void testGetNotFound() { assertNull(ddt.getService().get(NOT_FOUND_KEY, Locale.UK)); } @Test public void testGetParsedName() { final ParsedName rodentia = ddt.getService().getParsedName(100000004); assertNotNull(rodentia); assertEquals("Rodentia", rodentia.getGenusOrAbove()); assertEquals("Bowdich", rodentia.getAuthorship()); assertEquals("1821", rodentia.getYear()); assertNull(rodentia.getRank()); } @Test public void testGetParsedNameNotFound() { assertNull(ddt.getService().getParsedName(NOT_FOUND_KEY)); } @Test public void testList() { List<NameUsage> usages = ddt.getService().list(Locale.UK, null, null, null).getResults(); assertEquals(PagingConstants.DEFAULT_PARAM_LIMIT, usages.size()); // test paging Pageable page = new PagingRequest(1l, 1); usages = ddt.getService().list(Locale.UK, null, null, page).getResults(); assertEquals(1, usages.size()); NameUsage u1 = usages.get(0); page = new PagingRequest(0l, 2); usages = ddt.getService().list(Locale.UK, null, null, page).getResults(); assertEquals(2, usages.size()); assertEquals(u1, usages.get(1)); // test by source id usages = ddt.getService().list(Locale.UK, null, "1", null).getResults(); assertEquals(1, usages.size()); assertEquals((Integer) 100000001, usages.get(0).getKey()); // test by checklist key usages = ddt.getService().list(Locale.UK, UUID.fromString("d7dddbf4-2cf0-4f39-9b2a-bb099caae36c"), null, null) .getResults(); assertEquals(2, usages.size()); // test combined usages = ddt.getService().list(Locale.UK, UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"), "1", null).getResults(); assertEquals(1, usages.size()); assertEquals((Integer) 100000001, usages.get(0).getKey()); } @Test public void testByTaxonId() { List<NameUsage> usages = ddt.getService().list(Locale.UK, CHECKLIST_KEY, "100000", null).getResults(); assertEquals(1, usages.size()); assertEquals(ddt.getService().get(100000006, Locale.UK), usages.get(0)); } @Test public void testListRelated() { List<NameUsage> usages = ddt.getService().listRelated(1, Locale.UK); assertEquals(1, usages.size()); usages = ddt.getService().listRelated(1, Locale.UK, UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4")); assertEquals(1, usages.size()); usages = ddt.getService().listRelated(1, Locale.UK, UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"), UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f5")); assertEquals(1, usages.size()); usages = ddt.getService().listRelated(1, Locale.UK, UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088ff")); assertEquals(0, usages.size()); } @Test public void testListRelatedNotFound() { assertTrue(ddt.getService().listRelated(NOT_FOUND_KEY, Locale.UK).isEmpty()); } @Test public void testListChildren() { List<NameUsage> usages = ddt.getService().listChildren(100000025, Locale.UK, null).getResults(); assertEquals(9, usages.size()); // assert we start with highest ranks, then lower ones assertEquals(Rank.SUBSPECIES, usages.get(0).getRank()); assertEquals(Rank.SUBSPECIES, usages.get(1).getRank()); assertEquals(Rank.VARIETY, usages.get(7).getRank()); assertEquals(Rank.VARIETY, usages.get(8).getRank()); // test paging Pageable page = new PagingRequest(3, 2); usages = ddt.getService().listChildren(100000025, Locale.UK, page).getResults(); assertEquals(2, usages.size()); page = new PagingRequest(2, 5); List<NameUsage> usages2 = ddt.getService().listChildren(100000025, Locale.UK, page).getResults(); assertEquals(5, usages2.size()); assertEquals(usages.get(0), usages2.get(1)); assertEquals(usages.get(1), usages2.get(2)); } @Test public void testListChildrenNotFound() { assertTrue(ddt.getService().listChildren(NOT_FOUND_KEY, Locale.UK, null).getResults().isEmpty()); } @Test public void testListRoot() { List<NameUsage> usages = ddt.getService().listRoot(CHECKLIST_KEY, Locale.UK, null).getResults(); assertEquals(1, usages.size()); // test paging Pageable page = new PagingRequest(1l, 1); usages = ddt.getService().listRoot(CHECKLIST_KEY, Locale.UK, page).getResults(); assertEquals(0, usages.size()); page = new PagingRequest(0l, 2); usages = ddt.getService().listRoot(CHECKLIST_KEY, Locale.UK, page).getResults(); assertEquals(1, usages.size()); } @Test public void testListSynonyms() { List<NameUsage> usages = ddt.getService().listSynonyms(100000025, Locale.UK, null).getResults(); assertEquals(4, usages.size()); // test paging Pageable page = new PagingRequest(0, 2); usages = ddt.getService().listSynonyms(100000025, Locale.UK, page).getResults(); assertEquals(2, usages.size()); page = new PagingRequest(1, 2); List<NameUsage> usages2 = ddt.getService().listSynonyms(100000025, Locale.UK, page).getResults(); assertEquals(2, usages2.size()); assertEquals(usages.get(1), usages2.get(0)); } @Test public void testListSynonymsNotFound() { assertTrue(ddt.getService().listSynonyms(NOT_FOUND_KEY, Locale.UK, null).getResults().isEmpty()); } @Test public void testVerbatim() { // even though the record exists the verbatim smile data is empty, so null here assertNull(ddt.getService().getVerbatim(100000011)); assertNull(ddt.getService().getVerbatim(NOT_FOUND_KEY)); } @Test public void testUsageMetrics() { NameUsageMetrics m = ddt.getService().getMetrics(100000011); assertNotNull(m); assertEquals((Integer) 100000011, m.getKey()); assertEquals(2, m.getNumChildren()); assertEquals(12, m.getNumSynonyms()); assertEquals(1, m.getNumGenus()); assertEquals(2, m.getNumSubgenus()); assertEquals(2, m.getNumSpecies()); // not set in dbunit file assertEquals(3, m.getNumDescendants()); assertEquals(0, m.getNumFamily()); assertNull(ddt.getService().getMetrics(NOT_FOUND_KEY)); } }
checklistbank-mybatis-service/src/test/java/org/gbif/checklistbank/service/mybatis/NameUsageServiceMyBatisIT.java
package org.gbif.checklistbank.service.mybatis; import org.gbif.api.model.checklistbank.NameUsage; import org.gbif.api.model.checklistbank.NameUsageMetrics; import org.gbif.api.model.checklistbank.ParsedName; import org.gbif.api.model.common.paging.Pageable; import org.gbif.api.model.common.paging.PagingConstants; import org.gbif.api.model.common.paging.PagingRequest; import org.gbif.api.service.checklistbank.NameUsageService; import org.gbif.api.vocabulary.Origin; import org.gbif.api.vocabulary.Rank; import org.gbif.checklistbank.service.mybatis.postgres.DatabaseDrivenChecklistBankTestRule; import java.net.URI; import java.util.List; import java.util.Locale; import java.util.UUID; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class NameUsageServiceMyBatisIT { private static final UUID CHECKLIST_KEY = UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"); private final int NOT_FOUND_KEY = -10; @Rule public DatabaseDrivenChecklistBankTestRule<NameUsageService> ddt = DatabaseDrivenChecklistBankTestRule.squirrels(NameUsageService.class); @Test public void testGet() { final NameUsage rodentia = ddt.getService().get(100000004, Locale.UK); final NameUsageMetrics rodentiaM = ddt.getService().getMetrics(100000004); assertNotNull(rodentia); assertEquals((Integer) 10, rodentia.getNubKey()); assertFalse(rodentia.isSynonym()); assertEquals("1000", rodentia.getTaxonID()); assertEquals("Rodentia", rodentia.getCanonicalName()); assertEquals("Rodentia Bowdich, 1821", rodentia.getScientificName()); assertEquals("Bowdich, 1821", rodentia.getAuthorship()); assertEquals(Rank.ORDER, rodentia.getRank()); assertEquals((Integer) 100000003, rodentia.getParentKey()); assertEquals("Animalia", rodentia.getKingdom()); assertEquals((Integer) 100000001, rodentia.getKingdomKey()); assertEquals("Chordata", rodentia.getPhylum()); assertEquals((Integer) 100000002, rodentia.getPhylumKey()); assertEquals(0, rodentiaM.getNumPhylum()); assertEquals("Mammalia", rodentia.getClazz()); assertEquals((Integer) 100000003, rodentia.getClassKey()); assertEquals(0, rodentiaM.getNumClass()); assertEquals(1, rodentiaM.getNumOrder()); assertEquals(1, rodentiaM.getNumFamily()); assertEquals(2, rodentiaM.getNumGenus()); assertEquals(3, rodentiaM.getNumSpecies()); assertEquals(8, rodentiaM.getNumSynonyms()); assertEquals(1, rodentiaM.getNumChildren()); assertEquals(24, rodentia.getNumDescendants()); assertEquals(Origin.SOURCE, rodentia.getOrigin()); assertEquals(UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"), rodentia.getDatasetKey()); assertNull(rodentia.getPublishedIn()); assertEquals("1000", rodentia.getTaxonID()); NameUsage squirrel = ddt.getService().get(100000025, Locale.UK); final NameUsageMetrics squirrelM = ddt.getService().getMetrics(100000025); assertNotNull(squirrel); assertNull(squirrel.getNubKey()); assertFalse(squirrel.isSynonym()); assertEquals("Sciurus vulgaris", squirrel.getCanonicalName()); assertEquals("Sciurus vulgaris Linnaeus, 1758", squirrel.getScientificName()); assertEquals("Linnaeus, 1758", squirrel.getAuthorship()); assertEquals("Eurasian Red Squirrel", squirrel.getVernacularName()); assertEquals(Rank.SPECIES, squirrel.getRank()); assertEquals((Integer) 100000024, squirrel.getParentKey()); assertEquals("Animalia", squirrel.getKingdom()); assertEquals((Integer) 100000001, squirrel.getKingdomKey()); assertEquals("Chordata", squirrel.getPhylum()); assertEquals((Integer) 100000002, squirrel.getPhylumKey()); assertEquals(0, squirrelM.getNumPhylum()); assertEquals("Mammalia", squirrel.getClazz()); assertEquals((Integer) 100000003, squirrel.getClassKey()); assertEquals(0, squirrelM.getNumClass()); assertEquals("Rodentia", squirrel.getOrder()); assertEquals((Integer) 100000004, squirrel.getOrderKey()); assertEquals(0, squirrelM.getNumOrder()); assertEquals("Sciuridae", squirrel.getFamily()); assertEquals((Integer) 100000005, squirrel.getFamilyKey()); assertEquals(0, squirrelM.getNumFamily()); assertEquals("Sciurus", squirrel.getGenus()); assertEquals((Integer) 100000011, squirrel.getGenusKey()); assertEquals(0, squirrelM.getNumGenus()); assertEquals(1, squirrelM.getNumSpecies()); assertEquals(9, squirrelM.getNumChildren()); assertEquals(4, squirrelM.getNumSynonyms()); assertEquals(UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"), squirrel.getDatasetKey()); assertEquals("Syst. Nat. , 10th ed. vol. 1 p. 63", squirrel.getPublishedIn()); assertEquals("2010030", squirrel.getTaxonID()); // TEST VERNACULAR squirrel = ddt.getService().get(100000040, null); assertNull(squirrel.getVernacularName()); squirrel = ddt.getService().get(100000040, Locale.GERMANY); assertEquals("Kaukasischen Eichhörnchen", squirrel.getVernacularName()); // TEST non existing language VERNACULAR squirrel = ddt.getService().get(100000040, Locale.CHINESE); assertEquals("Caucasian Squirrel", squirrel.getVernacularName()); // TEST MULTIPLE IDENTIFIERS squirrel = ddt.getService().get(100000007, Locale.GERMANY); assertEquals("6905528", squirrel.getTaxonID()); assertEquals(URI.create("http://www.catalogueoflife.org/details/species/id/6905528"), squirrel.getReferences()); // TEST SYNONYM NameUsage syn = ddt.getService().get(100000027, Locale.FRENCH); assertNotNull(syn); assertTrue(syn.isSynonym()); assertEquals("Sciurus nadymensis", syn.getCanonicalName()); assertEquals("Sciurus nadymensis Serebrennikov, 1928", syn.getScientificName()); assertNull(syn.getVernacularName()); assertEquals(Rank.SPECIES, syn.getRank()); assertEquals((Integer) 100000024, syn.getParentKey()); assertEquals((Integer) 100000025, syn.getAcceptedKey()); assertEquals("Sciurus vulgaris Linnaeus, 1758", syn.getAccepted()); assertFalse(syn.isProParte()); } @Test public void testArraySet() { // test nomenclatoral status set NameUsage syn = ddt.getService().get(100000026, Locale.FRENCH); //TODO: get the array mapper working assertEquals(2, syn.getNomenclaturalStatus().size()); } @Test public void testGetNotFound() { assertNull(ddt.getService().get(NOT_FOUND_KEY, Locale.UK)); } @Test public void testGetParsedName() { final ParsedName rodentia = ddt.getService().getParsedName(100000004); assertNotNull(rodentia); assertEquals("Rodentia", rodentia.getGenusOrAbove()); assertEquals("Bowdich", rodentia.getAuthorship()); assertEquals("1821", rodentia.getYear()); assertNull(rodentia.getRank()); } @Test public void testGetParsedNameNotFound() { assertNull(ddt.getService().getParsedName(NOT_FOUND_KEY)); } @Test public void testList() { List<NameUsage> usages = ddt.getService().list(Locale.UK, null, null, null).getResults(); assertEquals(PagingConstants.DEFAULT_PARAM_LIMIT, usages.size()); // test paging Pageable page = new PagingRequest(1l, 1); usages = ddt.getService().list(Locale.UK, null, null, page).getResults(); assertEquals(1, usages.size()); NameUsage u1 = usages.get(0); page = new PagingRequest(0l, 2); usages = ddt.getService().list(Locale.UK, null, null, page).getResults(); assertEquals(2, usages.size()); assertEquals(u1, usages.get(1)); // test by source id usages = ddt.getService().list(Locale.UK, null, "1", null).getResults(); assertEquals(1, usages.size()); assertEquals((Integer) 100000001, usages.get(0).getKey()); // test by checklist key usages = ddt.getService().list(Locale.UK, UUID.fromString("d7dddbf4-2cf0-4f39-9b2a-bb099caae36c"), null, null) .getResults(); assertEquals(2, usages.size()); // test combined usages = ddt.getService().list(Locale.UK, UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"), "1", null).getResults(); assertEquals(1, usages.size()); assertEquals((Integer) 100000001, usages.get(0).getKey()); } @Test public void testByTaxonId() { List<NameUsage> usages = ddt.getService().list(Locale.UK, CHECKLIST_KEY, "100000", null).getResults(); assertEquals(1, usages.size()); assertEquals(ddt.getService().get(100000006, Locale.UK), usages.get(0)); } @Test public void testListRelated() { List<NameUsage> usages = ddt.getService().listRelated(1, Locale.UK); assertEquals(1, usages.size()); usages = ddt.getService().listRelated(1, Locale.UK, UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4")); assertEquals(1, usages.size()); usages = ddt.getService().listRelated(1, Locale.UK, UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f4"), UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088f5")); assertEquals(1, usages.size()); usages = ddt.getService().listRelated(1, Locale.UK, UUID.fromString("109aea14-c252-4a85-96e2-f5f4d5d088ff")); assertEquals(0, usages.size()); } @Test public void testListRelatedNotFound() { assertTrue(ddt.getService().listRelated(NOT_FOUND_KEY, Locale.UK).isEmpty()); } @Test public void testListChildren() { List<NameUsage> usages = ddt.getService().listChildren(100000025, Locale.UK, null).getResults(); assertEquals(9, usages.size()); // assert we start with highest ranks, then lower ones assertEquals(Rank.SUBSPECIES, usages.get(0).getRank()); assertEquals(Rank.SUBSPECIES, usages.get(1).getRank()); assertEquals(Rank.VARIETY, usages.get(7).getRank()); assertEquals(Rank.VARIETY, usages.get(8).getRank()); // test paging Pageable page = new PagingRequest(3, 2); usages = ddt.getService().listChildren(100000025, Locale.UK, page).getResults(); assertEquals(2, usages.size()); page = new PagingRequest(2, 5); List<NameUsage> usages2 = ddt.getService().listChildren(100000025, Locale.UK, page).getResults(); assertEquals(5, usages2.size()); assertEquals(usages.get(0), usages2.get(1)); assertEquals(usages.get(1), usages2.get(2)); } @Test public void testListChildrenNotFound() { assertTrue(ddt.getService().listChildren(NOT_FOUND_KEY, Locale.UK, null).getResults().isEmpty()); } @Test public void testListRoot() { List<NameUsage> usages = ddt.getService().listRoot(CHECKLIST_KEY, Locale.UK, null).getResults(); assertEquals(1, usages.size()); // test paging Pageable page = new PagingRequest(1l, 1); usages = ddt.getService().listRoot(CHECKLIST_KEY, Locale.UK, page).getResults(); assertEquals(0, usages.size()); page = new PagingRequest(0l, 2); usages = ddt.getService().listRoot(CHECKLIST_KEY, Locale.UK, page).getResults(); assertEquals(1, usages.size()); } @Test public void testListSynonyms() { List<NameUsage> usages = ddt.getService().listSynonyms(100000025, Locale.UK, null).getResults(); assertEquals(4, usages.size()); // test paging Pageable page = new PagingRequest(0, 2); usages = ddt.getService().listSynonyms(100000025, Locale.UK, page).getResults(); assertEquals(2, usages.size()); page = new PagingRequest(1, 2); List<NameUsage> usages2 = ddt.getService().listSynonyms(100000025, Locale.UK, page).getResults(); assertEquals(2, usages2.size()); assertEquals(usages.get(1), usages2.get(0)); } @Test public void testListSynonymsNotFound() { assertTrue(ddt.getService().listSynonyms(NOT_FOUND_KEY, Locale.UK, null).getResults().isEmpty()); } @Test public void testVerbatim() { // even though the record exists the verbatim smile data is empty, so null here assertNull(ddt.getService().getVerbatim(100000011)); assertNull(ddt.getService().getVerbatim(NOT_FOUND_KEY)); } @Test public void testUsageMetrics() { NameUsageMetrics m = ddt.getService().getMetrics(100000011); assertNotNull(m); assertEquals((Integer) 100000011, m.getKey()); assertEquals(2, m.getNumChildren()); assertEquals(12, m.getNumSynonyms()); assertEquals(1, m.getNumGenus()); assertEquals(2, m.getNumSubgenus()); assertEquals(2, m.getNumSpecies()); // not set in dbunit file assertEquals(0, m.getNumDescendants()); assertEquals(0, m.getNumFamily()); assertNull(ddt.getService().getMetrics(NOT_FOUND_KEY)); } }
test fix
checklistbank-mybatis-service/src/test/java/org/gbif/checklistbank/service/mybatis/NameUsageServiceMyBatisIT.java
test fix
<ide><path>hecklistbank-mybatis-service/src/test/java/org/gbif/checklistbank/service/mybatis/NameUsageServiceMyBatisIT.java <ide> assertEquals(2, m.getNumSubgenus()); <ide> assertEquals(2, m.getNumSpecies()); <ide> // not set in dbunit file <del> assertEquals(0, m.getNumDescendants()); <add> assertEquals(3, m.getNumDescendants()); <ide> assertEquals(0, m.getNumFamily()); <ide> <ide> assertNull(ddt.getService().getMetrics(NOT_FOUND_KEY));
Java
bsd-3-clause
928ec54fdd31e67027c5a3fd6a7f46dcf8a03be1
0
team-worthwhile/worthwhile,team-worthwhile/worthwhile
package edu.kit.iti.formal.pse.worthwhile.prover; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import edu.kit.iti.formal.pse.worthwhile.model.BooleanValue; import edu.kit.iti.formal.pse.worthwhile.model.IntegerValue; import edu.kit.iti.formal.pse.worthwhile.model.Value; import edu.kit.iti.formal.pse.worthwhile.model.ast.Equal; import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression; import edu.kit.iti.formal.pse.worthwhile.model.ast.Implication; import edu.kit.iti.formal.pse.worthwhile.model.ast.Literal; import edu.kit.iti.formal.pse.worthwhile.model.ast.Negation; import edu.kit.iti.formal.pse.worthwhile.model.ast.Program; import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableDeclaration; import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableReference; import edu.kit.iti.formal.pse.worthwhile.model.ast.util.AstNodeCloneHelper; import edu.kit.iti.formal.pse.worthwhile.model.ast.util.AstNodeCreatorHelper; /** * Facade class for the {@link edu.kit.iti.formal.pse.worthwhile.prover} package. */ public class SpecificationChecker { /** * Time delta in seconds after which a prover call times out. * * Defaults to zero. */ private Integer timeout = 1; /** * @return the timeout */ public final Integer getTimeout() { return this.timeout; } /** * @param timeout * the timeout to set, minimum 1 */ public final void setTimeout(final Integer timeout) { if (timeout > 0) { this.timeout = timeout; } else { this.timeout = 1; } } /** * The {@link ProverCaller} that is called for checking the satisfiability of formulae. * * Defaults to {@link Z3Prover} instance. */ private ProverCaller prover = new Z3Prover(); /** * The {@link FormulaGenerator} that is called for generating a formula from a {@link Program}. */ private FormulaGenerator transformer; /** * @return the transformer */ public final FormulaGenerator getTransformer() { return this.transformer; } /** * @param transformer * the transformer to set */ public final void setTransformer(final FormulaGenerator transformer) { this.transformer = transformer; } /** * The result of the last call to {@link prover}. */ private ProverResult checkResult; /** * @return the checkResult */ public final ProverResult getCheckResult() { return this.checkResult; } /** * The listener that distributes fired events to other event listeners attached to this instance. */ private final DistributorProverEventListener listener = new DistributorProverEventListener(); /** * Add an event listener to this instance. * * @param listener * the listener to add * @return true if adding the listener succeeded, else false */ public final boolean addProverEventListener(final AbstractProverEventListener listener) { return this.listener.addProverEventListener(listener); } /** * Remove an event listener to this instance. * * @param listener * the listener to remove * @return true if removing the listener succeeded, else false */ public final boolean removeProverEventListener(final AbstractProverEventListener listener) { return this.listener.removeProverEventListener(listener); } /** * Uses {@link WPStrategy} as {@link SpecificationChecker#transformer}. */ public SpecificationChecker() { this.transformer = new WPStrategy(); } /** * @param transformer * Is called to transform {@link Program}s into formulae. */ public SpecificationChecker(final FormulaGenerator transformer) { this.transformer = transformer; } /** * @param formula * the {@link Expression} to check * @param environment * a list of variable values and axioms * @return the {@link Validity} of <code>formula</code> when <code>environment</code> is applied */ // TODO we need error reporting, return UNKNOWN for now in case of ProverCallerException public final Validity checkFormula(final Expression formula, final Map<VariableDeclaration, Value> environment) { // TODO apply Worthwhile specific runtime assertions // TODO apply axiom list Expression environmentExpression = AstNodeCreatorHelper.createTrueLiteral(); for (VariableDeclaration environmentVariable : environment.keySet()) { // create a reference to the variable VariableReference variableReference = AstNodeCreatorHelper .createVariableReference(environmentVariable); Value variableValue = environment.get(environmentVariable); // create the literal that epxresses the value of the symbol Literal variableValueLiteral = null; // TODO: array symbols if (variableValue instanceof BooleanValue) { variableValueLiteral = AstNodeCreatorHelper .createBooleanLiteral(((BooleanValue) variableValue).getValue()); } else if (variableValue instanceof IntegerValue) { variableValueLiteral = AstNodeCreatorHelper .createIntegerLiteral(((IntegerValue) variableValue).getValue()); } // create the ref = literal expression Equal equal = AstNodeCreatorHelper.createEqual(variableReference, variableValueLiteral); // conjunctively add the equals to the expression expressing the environment environmentExpression = AstNodeCreatorHelper.createConjunction(environmentExpression, equal); } // create the environment => expression implication Implication environmentImpliesFormula = AstNodeCreatorHelper.createImplication(environmentExpression, AstNodeCloneHelper.clone(formula)); return this.checkProgram(AstNodeCreatorHelper.createProgram(AstNodeCreatorHelper .createAssertion(environmentImpliesFormula))); } /** * Checks a formula's validity and returns the result. * * @param formula * the {@link Expression} whose {@link Validity} to determine * @return <code>formula</code>'s {@link Validity} */ private Validity getValidity(final Expression formula) { final Negation negation = AstNodeCreatorHelper.createNegation(formula); // let prover check formula and initialize checkResult with the returned result /** * Thread that detaches to execute the prover caller. * * @author Leon Handreke */ class ProverCallerTask implements Callable<ProverResult> { @Override public ProverResult call() throws ProverCallerException { return SpecificationChecker.this.prover.checkFormula(negation); } } // run the prover caller ExecutorService executor = Executors.newSingleThreadExecutor(); Future<ProverResult> resultFuture = executor.submit(new ProverCallerTask()); try { this.checkResult = resultFuture.get(this.timeout, TimeUnit.SECONDS); } catch (InterruptedException e) { // don't care e.printStackTrace(); } catch (ExecutionException e) { // what could possibly go wrong? e.printStackTrace(); } catch (TimeoutException e) { // timeout - result unknown this.checkResult = new ProverResult("timeout") { @Override public FormulaSatisfiability getSatisfiability() { return FormulaSatisfiability.UNKOWN; } }; } executor.shutdown(); // determine formula's validity based on negation's satisfiability, which is VALID only if the latter is // UNSATISFIABLE and INVALID only if the latter is SATISFIABLE, UNKNOWN otherwise Validity validity = Validity.UNKNOWN; switch (this.checkResult.getSatisfiability()) { case SATISFIABLE: validity = Validity.INVALID; break; case UNSATISFIABLE: validity = Validity.VALID; break; default: validity = Validity.UNKNOWN; } return validity; } /** * @param program * the {@link Program} to check * @return the {@link Validity} of <code>program</code> */ public final Validity checkProgram(final Program program) { // TODO apply Worthwhile specific runtime assertions // we don't want to pollute the o Program modifiedProgram = AstNodeCloneHelper.clone(program); // add assertions to check that the divisors are not zero DivisionByZeroAssertionInserter divisionByZeroAssertionInserter = new DivisionByZeroAssertionInserter(); modifiedProgram.accept(divisionByZeroAssertionInserter); // generate formula from program Expression formula = this.transformer.transformProgram(modifiedProgram); // get the validity from the prover Validity validity = this.getValidity(formula); // fire the event listener this.listener.programVerified(program, validity, this.getCheckResult()); return validity; } }
implementierung/src/worthwhile.prover/src/edu/kit/iti/formal/pse/worthwhile/prover/SpecificationChecker.java
package edu.kit.iti.formal.pse.worthwhile.prover; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import edu.kit.iti.formal.pse.worthwhile.model.BooleanValue; import edu.kit.iti.formal.pse.worthwhile.model.IntegerValue; import edu.kit.iti.formal.pse.worthwhile.model.Value; import edu.kit.iti.formal.pse.worthwhile.model.ast.Equal; import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression; import edu.kit.iti.formal.pse.worthwhile.model.ast.Implication; import edu.kit.iti.formal.pse.worthwhile.model.ast.Literal; import edu.kit.iti.formal.pse.worthwhile.model.ast.Negation; import edu.kit.iti.formal.pse.worthwhile.model.ast.Program; import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableDeclaration; import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableReference; import edu.kit.iti.formal.pse.worthwhile.model.ast.util.AstNodeCloneHelper; import edu.kit.iti.formal.pse.worthwhile.model.ast.util.AstNodeCreatorHelper; /** * Facade class for the {@link edu.kit.iti.formal.pse.worthwhile.prover} package. */ public class SpecificationChecker { /** * Time delta in seconds after which a prover call times out. * * Defaults to zero. */ private Integer timeout = 1; /** * @return the timeout */ public final Integer getTimeout() { return this.timeout; } /** * @param timeout * the timeout to set, minimum 1 */ public final void setTimeout(final Integer timeout) { if (timeout > 0) { this.timeout = timeout; } else { this.timeout = 1; } } /** * The {@link ProverCaller} that is called for checking the satisfiability of formulae. * * Defaults to {@link Z3Prover} instance. */ private ProverCaller prover = new Z3Prover(); /** * The {@link FormulaGenerator} that is called for generating a formula from a {@link Program}. */ private FormulaGenerator transformer; /** * @return the transformer */ public final FormulaGenerator getTransformer() { return this.transformer; } /** * @param transformer * the transformer to set */ public final void setTransformer(final FormulaGenerator transformer) { this.transformer = transformer; } /** * The result of the last call to {@link prover}. */ private ProverResult checkResult; /** * @return the checkResult */ public final ProverResult getCheckResult() { return this.checkResult; } /** * The listener that distributes fired events to other event listeners attached to this instance. */ private final DistributorProverEventListener listener = new DistributorProverEventListener(); /** * Add an event listener to this instance. * * @param listener * the listener to add * @return true if adding the listener succeeded, else false */ public final boolean addProverEventListener(final AbstractProverEventListener listener) { return this.listener.addProverEventListener(listener); } /** * Remove an event listener to this instance. * * @param listener * the listener to remove * @return true if removing the listener succeeded, else false */ public final boolean removeProverEventListener(final AbstractProverEventListener listener) { return this.listener.removeProverEventListener(listener); } /** * Uses {@link WPStrategy} as {@link SpecificationChecker#transformer}. */ public SpecificationChecker() { this.transformer = new WPStrategy(); } /** * @param transformer * Is called to transform {@link Program}s into formulae. */ public SpecificationChecker(final FormulaGenerator transformer) { this.transformer = transformer; } /** * @param formula * the {@link Expression} to check * @param environment * a list of variable values and axioms * @return the {@link Validity} of <code>formula</code> when <code>environment</code> is applied */ // TODO we need error reporting, return UNKNOWN for now in case of ProverCallerException public final Validity checkFormula(final Expression formula, final Map<VariableDeclaration, Value> environment) { // TODO apply Worthwhile specific runtime assertions // TODO apply axiom list Expression environmentExpression = AstNodeCreatorHelper.createTrueLiteral(); for (VariableDeclaration environmentVariable : environment.keySet()) { // create a reference to the variable VariableReference variableReference = AstNodeCreatorHelper .createVariableReference(environmentVariable); Value variableValue = environment.get(environmentVariable); // create the literal that epxresses the value of the symbol Literal variableValueLiteral = null; // TODO: array symbols if (variableValue instanceof BooleanValue) { variableValueLiteral = AstNodeCreatorHelper .createBooleanLiteral(((BooleanValue) variableValue).getValue()); } else if (variableValue instanceof IntegerValue) { variableValueLiteral = AstNodeCreatorHelper .createIntegerLiteral(((IntegerValue) variableValue).getValue()); } // create the ref = literal expression Equal equal = AstNodeCreatorHelper.createEqual(variableReference, variableValueLiteral); // conjunctively add the equals to the expression expressing the environment environmentExpression = AstNodeCreatorHelper.createConjunction(environmentExpression, equal); } // create the environment => expression implication Implication environmentImpliesFormula = AstNodeCreatorHelper.createImplication(environmentExpression, AstNodeCloneHelper.clone(formula)); return getValidity(environmentImpliesFormula); } /** * Checks a formula's validity and returns the result. * * @param formula * the {@link Expression} whose {@link Validity} to determine * @return <code>formula</code>'s {@link Validity} */ private Validity getValidity(final Expression formula) { final Negation negation = AstNodeCreatorHelper.createNegation(formula); // let prover check formula and initialize checkResult with the returned result /** * Thread that detaches to execute the prover caller. * * @author Leon Handreke */ class ProverCallerTask implements Callable<ProverResult> { @Override public ProverResult call() throws ProverCallerException { return SpecificationChecker.this.prover.checkFormula(negation); } } // run the prover caller ExecutorService executor = Executors.newSingleThreadExecutor(); Future<ProverResult> resultFuture = executor.submit(new ProverCallerTask()); try { this.checkResult = resultFuture.get(this.timeout, TimeUnit.SECONDS); } catch (InterruptedException e) { // don't care e.printStackTrace(); } catch (ExecutionException e) { // what could possibly go wrong? e.printStackTrace(); } catch (TimeoutException e) { // timeout - result unknown this.checkResult = new ProverResult("timeout") { @Override public FormulaSatisfiability getSatisfiability() { return FormulaSatisfiability.UNKOWN; } }; } executor.shutdown(); // determine formula's validity based on negation's satisfiability, which is VALID only if the latter is // UNSATISFIABLE and INVALID only if the latter is SATISFIABLE, UNKNOWN otherwise Validity validity = Validity.UNKNOWN; switch (this.checkResult.getSatisfiability()) { case SATISFIABLE: validity = Validity.INVALID; break; case UNSATISFIABLE: validity = Validity.VALID; break; default: validity = Validity.UNKNOWN; } return validity; } /** * @param program * the {@link Program} to check * @return the {@link Validity} of <code>program</code> */ public final Validity checkProgram(final Program program) { // TODO apply Worthwhile specific runtime assertions // we don't want to pollute the o Program modifiedProgram = AstNodeCloneHelper.clone(program); // add assertions to check that the divisors are not zero DivisionByZeroAssertionInserter divisionByZeroAssertionInserter = new DivisionByZeroAssertionInserter(); modifiedProgram.accept(divisionByZeroAssertionInserter); // generate formula from program Expression formula = this.transformer.transformProgram(modifiedProgram); // get the validity from the prover Validity validity = this.getValidity(formula); // fire the event listener this.listener.programVerified(program, validity, this.getCheckResult()); return validity; } }
[prover] Wrap to be checked formula in a Program and checkProgram it - when checking formulae we also want to apply the Worthwhile specific modifications (like resolving function calls) so wrap the passed formula in a single Assertion Statement and call checkProgram with it
implementierung/src/worthwhile.prover/src/edu/kit/iti/formal/pse/worthwhile/prover/SpecificationChecker.java
[prover] Wrap to be checked formula in a Program and checkProgram it
<ide><path>mplementierung/src/worthwhile.prover/src/edu/kit/iti/formal/pse/worthwhile/prover/SpecificationChecker.java <ide> // create the environment => expression implication <ide> Implication environmentImpliesFormula = AstNodeCreatorHelper.createImplication(environmentExpression, <ide> AstNodeCloneHelper.clone(formula)); <del> return getValidity(environmentImpliesFormula); <add> return this.checkProgram(AstNodeCreatorHelper.createProgram(AstNodeCreatorHelper <add> .createAssertion(environmentImpliesFormula))); <ide> } <ide> <ide> /**
Java
apache-2.0
b4172eb34f4aa109974f5255cef26064d84c4db9
0
RoaringBitmap/RoaringBitmap,RoaringBitmap/RoaringBitmap,RoaringBitmap/RoaringBitmap,RoaringBitmap/RoaringBitmap
/* * (c) the authors Licensed under the Apache License, Version 2.0. */ package org.roaringbitmap.longlong; import org.roaringbitmap.*; import org.roaringbitmap.buffer.MutableRoaringBitmap; import java.io.*; import java.util.*; import java.util.Map.Entry; /** * Roaring64NavigableMap extends RoaringBitmap to the whole range of longs (or unsigned longs). It * enables a cardinality greater up to Long.MAX_VALUE * * Longs are added by default in unsigned sorted order (i.e. -1L is the greater long to be added * while 0 has no previous value). It can be configured to signed sorted order (in which case, 0 is * preceded by 1). That is, they are treated as unsigned integers (see Java 8's * Integer.toUnsignedLong function). Up to 4294967296 integers can be stored. * * * */ // this class is not thread-safe // @Beta: this class is still in early stage. Its API may change and has not proofed itself as // bug-proof public class Roaring64NavigableMap implements Externalizable, LongBitmapDataProvider { // Not final to enable initialization in Externalizable.readObject private NavigableMap<Integer, BitmapDataProvider> highToBitmap; // If true, we handle longs a plain java longs: -1 if right before 0 // If false, we handle longs as unsigned longs: 0 has no predecessor and Long.MAX_VALUE + 1L is // expressed as a // negative long private boolean signedLongs = false; private BitmapDataProviderSupplier supplier; // By default, we cache cardinalities private transient boolean doCacheCardinalities = true; // Prevent recomputing all cardinalities when requesting consecutive ranks private transient int firstHighNotValid = highestHigh() + 1; // This boolean needs firstHighNotValid == Integer.MAX_VALUE to be allowed to be true // If false, it means nearly all cumulated cardinalities are valid, except high=Integer.MAX_VALUE // If true, it means all cumulated cardinalities are valid, even high=Integer.MAX_VALUE private transient boolean allValid = false; // TODO: I would prefer not managing arrays myself private transient long[] sortedCumulatedCardinality = new long[0]; private transient int[] sortedHighs = new int[0]; // We guess consecutive .addLong will be on proximate longs: we remember the bitmap attached to // this bucket in order // to skip the indirection private transient Map.Entry<Integer, BitmapDataProvider> latestAddedHigh = null; private static final boolean DEFAULT_ORDER_IS_SIGNED = false; private static final boolean DEFAULT_CARDINALITIES_ARE_CACHED = true; /** * By default, we consider longs are unsigned longs: normal longs: 0 is the lowest possible long. * Long.MAX_VALUE is followed by Long.MIN_VALUE. -1L is the highest possible value */ public Roaring64NavigableMap() { this(DEFAULT_ORDER_IS_SIGNED); } /** * * By default, use RoaringBitmap as underlyings {@link BitmapDataProvider} * * @param signedLongs true if longs has to be ordered as plain java longs. False to handle them as * unsigned 64bits long (as RoaringBitmap with unsigned integers) */ public Roaring64NavigableMap(boolean signedLongs) { this(signedLongs, DEFAULT_CARDINALITIES_ARE_CACHED); } /** * By default, use RoaringBitmap as underlyings {@link BitmapDataProvider} * * @param signedLongs true if longs has to be ordered as plain java longs. False to handle them as * unsigned 64bits long (as RoaringBitmap with unsigned integers) * @param cacheCardinalities true if cardinalities have to be cached. It will prevent many * iteration along the NavigableMap */ public Roaring64NavigableMap(boolean signedLongs, boolean cacheCardinalities) { this(signedLongs, cacheCardinalities, new RoaringBitmapSupplier()); } /** * By default, longs are managed as unsigned longs and cardinalities are cached. * * @param supplier provide the logic to instantiate new {@link BitmapDataProvider}, typically * instantiated once per high. */ public Roaring64NavigableMap(BitmapDataProviderSupplier supplier) { this(DEFAULT_ORDER_IS_SIGNED, DEFAULT_CARDINALITIES_ARE_CACHED, supplier); } /** * By default, we activating cardinalities caching. * * @param signedLongs true if longs has to be ordered as plain java longs. False to handle them as * unsigned 64bits long (as RoaringBitmap with unsigned integers) * @param supplier provide the logic to instantiate new {@link BitmapDataProvider}, typically * instantiated once per high. */ public Roaring64NavigableMap(boolean signedLongs, BitmapDataProviderSupplier supplier) { this(signedLongs, DEFAULT_CARDINALITIES_ARE_CACHED, supplier); } /** * * @param signedLongs true if longs has to be ordered as plain java longs. False to handle them as * unsigned 64bits long (as RoaringBitmap with unsigned integers) * @param cacheCardinalities true if cardinalities have to be cached. It will prevent many * iteration along the NavigableMap * @param supplier provide the logic to instantiate new {@link BitmapDataProvider}, typically * instantiated once per high. */ public Roaring64NavigableMap(boolean signedLongs, boolean cacheCardinalities, BitmapDataProviderSupplier supplier) { this.signedLongs = signedLongs; this.supplier = supplier; if (signedLongs) { highToBitmap = new TreeMap<>(); } else { highToBitmap = new TreeMap<>(RoaringIntPacking.unsignedComparator()); } this.doCacheCardinalities = cacheCardinalities; resetPerfHelpers(); } private void resetPerfHelpers() { firstHighNotValid = RoaringIntPacking.highestHigh(signedLongs) + 1; allValid = false; sortedCumulatedCardinality = new long[0]; sortedHighs = new int[0]; latestAddedHigh = null; } // Package-friendly: for the sake of unit-testing // @VisibleForTesting NavigableMap<Integer, BitmapDataProvider> getHighToBitmap() { return highToBitmap; } // Package-friendly: for the sake of unit-testing // @VisibleForTesting int getLowestInvalidHigh() { return firstHighNotValid; } // Package-friendly: for the sake of unit-testing // @VisibleForTesting long[] getSortedCumulatedCardinality() { return sortedCumulatedCardinality; } /** * Add the value to the container (set the value to "true"), whether it already appears or not. * * Java lacks native unsigned longs but the x argument is considered to be unsigned. Within * bitmaps, numbers are ordered according to {@link Long#compareUnsigned}. We order the numbers * like 0, 1, ..., 9223372036854775807, -9223372036854775808, -9223372036854775807,..., -1. * * @param x long value */ @Override public void addLong(long x) { int high = high(x); int low = low(x); // Copy the reference to prevent race-condition Map.Entry<Integer, BitmapDataProvider> local = latestAddedHigh; BitmapDataProvider bitmap; if (local != null && local.getKey().intValue() == high) { bitmap = local.getValue(); } else { bitmap = highToBitmap.get(high); if (bitmap == null) { bitmap = newRoaringBitmap(); pushBitmapForHigh(high, bitmap); } latestAddedHigh = new AbstractMap.SimpleImmutableEntry<>(high, bitmap); } bitmap.add(low); invalidateAboveHigh(high); } /** * Add the integer value to the container (set the value to "true"), whether it already appears or * not. * * Javac lacks native unsigned integers but the x argument is considered to be unsigned. Within * bitmaps, numbers are ordered according to {@link Integer#compareUnsigned}. We order the numbers * like 0, 1, ..., 2147483647, -2147483648, -2147483647,..., -1. * * @param x integer value */ public void addInt(int x) { addLong(Util.toUnsignedLong(x)); } private BitmapDataProvider newRoaringBitmap() { return supplier.newEmpty(); } private void invalidateAboveHigh(int high) { // The cardinalities after this bucket may not be valid anymore if (compare(firstHighNotValid, high) > 0) { // High was valid up to now firstHighNotValid = high; int indexNotValid = binarySearch(sortedHighs, firstHighNotValid); final int indexAfterWhichToReset; if (indexNotValid >= 0) { indexAfterWhichToReset = indexNotValid; } else { // We have invalidate a high not already present: added a value for a brand new high indexAfterWhichToReset = -indexNotValid - 1; } // This way, sortedHighs remains sorted, without making a new/shorter array Arrays.fill(sortedHighs, indexAfterWhichToReset, sortedHighs.length, highestHigh()); } allValid = false; } private int compare(int x, int y) { if (signedLongs) { return Integer.compare(x, y); } else { return RoaringIntPacking.compareUnsigned(x, y); } } private void pushBitmapForHigh(int high, BitmapDataProvider bitmap) { // TODO .size is too slow // int nbHighBefore = highToBitmap.headMap(high).size(); BitmapDataProvider previous = highToBitmap.put(high, bitmap); assert previous == null : "Should push only not-existing high"; } private int low(long id) { return RoaringIntPacking.low(id); } private int high(long id) { return RoaringIntPacking.high(id); } /** * Returns the number of distinct integers added to the bitmap (e.g., number of bits set). * * @return the cardinality */ @Override public long getLongCardinality() { if (doCacheCardinalities) { if (highToBitmap.isEmpty()) { return 0L; } int indexOk = ensureCumulatives(highestHigh()); // ensureCumulatives may have removed empty bitmaps if (highToBitmap.isEmpty()) { return 0L; } return sortedCumulatedCardinality[indexOk - 1]; } else { long cardinality = 0L; for (BitmapDataProvider bitmap : highToBitmap.values()) { cardinality += bitmap.getLongCardinality(); } return cardinality; } } /** * * @return the cardinality as an int * * @throws UnsupportedOperationException if the cardinality does not fit in an int */ public int getIntCardinality() throws UnsupportedOperationException { long cardinality = getLongCardinality(); if (cardinality > Integer.MAX_VALUE) { // TODO: we should handle cardinality fitting in an unsigned int throw new UnsupportedOperationException( "Can not call .getIntCardinality as the cardinality is bigger than Integer.MAX_VALUE"); } return (int) cardinality; } /** * Return the jth value stored in this bitmap. * * @param j index of the value * * @return the value * @throws IllegalArgumentException if j is out of the bounds of the bitmap cardinality */ @Override public long select(final long j) throws IllegalArgumentException { if (!doCacheCardinalities) { return selectNoCache(j); } // Ensure all cumulatives as we we have straightforward way to know in advance the high of the // j-th value int indexOk = ensureCumulatives(highestHigh()); if (highToBitmap.isEmpty()) { return throwSelectInvalidIndex(j); } // Use normal binarySearch as cardinality does not depends on considering longs signed or // unsigned // We need sortedCumulatedCardinality not to contain duplicated, else binarySearch may return // any of the duplicates: we need to ensure it holds no high associated to an empty bitmap int position = Arrays.binarySearch(sortedCumulatedCardinality, 0, indexOk, j); if (position >= 0) { if (position == indexOk - 1) { // .select has been called on this.getCardinality return throwSelectInvalidIndex(j); } // There is a bucket leading to this cardinality: the j-th element is the first element of // next bucket int high = sortedHighs[position + 1]; BitmapDataProvider nextBitmap = highToBitmap.get(high); return RoaringIntPacking.pack(high, nextBitmap.select(0)); } else { // There is no bucket with this cardinality int insertionPoint = -position - 1; final long previousBucketCardinality; if (insertionPoint == 0) { previousBucketCardinality = 0L; } else if (insertionPoint >= indexOk) { return throwSelectInvalidIndex(j); } else { previousBucketCardinality = sortedCumulatedCardinality[insertionPoint - 1]; } // We get a 'select' query for a single bitmap: should fit in an int final int givenBitmapSelect = (int) (j - previousBucketCardinality); int high = sortedHighs[insertionPoint]; BitmapDataProvider lowBitmap = highToBitmap.get(high); int low = lowBitmap.select(givenBitmapSelect); return RoaringIntPacking.pack(high, low); } } // For benchmarks: compute without using cardinalities cache // https://github.com/RoaringBitmap/CRoaring/blob/master/cpp/roaring64map.hh private long selectNoCache(long j) { long left = j; for (Entry<Integer, BitmapDataProvider> entry : highToBitmap.entrySet()) { long lowCardinality = entry.getValue().getCardinality(); if (left >= lowCardinality) { left -= lowCardinality; } else { // It is legit for left to be negative int leftAsUnsignedInt = (int) left; return RoaringIntPacking.pack(entry.getKey(), entry.getValue().select(leftAsUnsignedInt)); } } return throwSelectInvalidIndex(j); } private long throwSelectInvalidIndex(long j) { // see org.roaringbitmap.buffer.ImmutableRoaringBitmap.select(int) throw new IllegalArgumentException( "select " + j + " when the cardinality is " + this.getLongCardinality()); } /** * For better performance, consider the Use the {@link #forEach forEach} method. * * @return a custom iterator over set bits, the bits are traversed in ascending sorted order */ public Iterator<Long> iterator() { final LongIterator it = getLongIterator(); return new Iterator<Long>() { @Override public boolean hasNext() { return it.hasNext(); } @Override public Long next() { return it.next(); } @Override public void remove() { // TODO? throw new UnsupportedOperationException(); } }; } @Override public void forEach(final LongConsumer lc) { for (final Entry<Integer, BitmapDataProvider> highEntry : highToBitmap.entrySet()) { highEntry.getValue().forEach(new IntConsumer() { @Override public void accept(int low) { lc.accept(RoaringIntPacking.pack(highEntry.getKey(), low)); } }); } } @Override public long rankLong(long id) { int high = RoaringIntPacking.high(id); int low = RoaringIntPacking.low(id); if (!doCacheCardinalities) { return rankLongNoCache(high, low); } int indexOk = ensureCumulatives(high); int highPosition = binarySearch(sortedHighs, 0, indexOk, high); if (highPosition >= 0) { // There is a bucket holding this item final long previousBucketCardinality; if (highPosition == 0) { previousBucketCardinality = 0; } else { previousBucketCardinality = sortedCumulatedCardinality[highPosition - 1]; } BitmapDataProvider lowBitmap = highToBitmap.get(sortedHighs[highPosition]); // Rank is previous cardinality plus rank in current bitmap return previousBucketCardinality + lowBitmap.rankLong(low); } else { // There is no bucket holding this item: insertionPoint is previous bitmap int insertionPoint = -highPosition - 1; if (insertionPoint == 0) { // this key is before all inserted keys return 0; } else { // The rank is the cardinality of this previous bitmap return sortedCumulatedCardinality[insertionPoint - 1]; } } } // https://github.com/RoaringBitmap/CRoaring/blob/master/cpp/roaring64map.hh private long rankLongNoCache(int high, int low) { long result = 0L; BitmapDataProvider lastBitmap = highToBitmap.get(high); if (lastBitmap == null) { // There is no value with same high: the rank is a sum of cardinalities for (Entry<Integer, BitmapDataProvider> bitmap : highToBitmap.entrySet()) { if (bitmap.getKey().intValue() > high) { break; } else { result += bitmap.getValue().getLongCardinality(); } } } else { for (BitmapDataProvider bitmap : highToBitmap.values()) { if (bitmap == lastBitmap) { result += bitmap.rankLong(low); break; } else { result += bitmap.getLongCardinality(); } } } return result; } /** * * @param high for which high bucket should we compute the cardinality * @return the highest validatedIndex */ protected int ensureCumulatives(int high) { if (allValid) { // the whole array is valid (up-to its actual length, not its capacity) return highToBitmap.size(); } else if (compare(high, firstHighNotValid) < 0) { // The high is strictly below the first not valid: it is valid // sortedHighs may have only a subset of valid values on the right. However, these invalid // values have been set to maxValue, and we are here as high < firstHighNotValid ==> high < // maxHigh() int position = binarySearch(sortedHighs, high); if (position >= 0) { // This high has a bitmap: +1 as this index will be used as right (excluded) bound in a // binary-search return position + 1; } else { // This high has no bitmap: it could be between 2 highs with bitmaps int insertionPosition = -position - 1; return insertionPosition; } } else { // For each deprecated buckets SortedMap<Integer, BitmapDataProvider> tailMap = highToBitmap.tailMap(firstHighNotValid, true); // TODO .size on tailMap make an iterator: arg int indexOk = highToBitmap.size() - tailMap.size(); // TODO: It should be possible to compute indexOk based on sortedHighs array // assert indexOk == binarySearch(sortedHighs, firstHighNotValid); Iterator<Entry<Integer, BitmapDataProvider>> it = tailMap.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, BitmapDataProvider> e = it.next(); int currentHigh = e.getKey(); if (compare(currentHigh, high) > 0) { // No need to compute more than needed break; } else if (e.getValue().isEmpty()) { // highToBitmap can not be modified as we iterate over it if (latestAddedHigh != null && latestAddedHigh.getKey().intValue() == currentHigh) { // Dismiss the cached bitmap as it is removed from the NavigableMap latestAddedHigh = null; } it.remove(); } else { ensureOne(e, currentHigh, indexOk); // We have added one valid cardinality indexOk++; } } if (highToBitmap.isEmpty() || indexOk == highToBitmap.size()) { // We have compute all cardinalities allValid = true; } return indexOk; } } private int binarySearch(int[] array, int key) { if (signedLongs) { return Arrays.binarySearch(array, key); } else { return unsignedBinarySearch(array, 0, array.length, key, RoaringIntPacking.unsignedComparator()); } } private int binarySearch(int[] array, int from, int to, int key) { if (signedLongs) { return Arrays.binarySearch(array, from, to, key); } else { return unsignedBinarySearch(array, from, to, key, RoaringIntPacking.unsignedComparator()); } } // From Arrays.binarySearch (Comparator). Check with org.roaringbitmap.Util.unsignedBinarySearch private static int unsignedBinarySearch(int[] a, int fromIndex, int toIndex, int key, Comparator<? super Integer> c) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; int cmp = c.compare(midVal, key); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { return mid; // key found } } return -(low + 1); // key not found. } private void ensureOne(Map.Entry<Integer, BitmapDataProvider> e, int currentHigh, int indexOk) { // sortedHighs are valid only up to some index assert indexOk <= sortedHighs.length : indexOk + " is bigger than " + sortedHighs.length; final int index; if (indexOk == 0) { if (sortedHighs.length == 0) { index = -1; // } else if (sortedHighs[0] == currentHigh) { // index = 0; } else { index = -1; } } else if (indexOk < sortedHighs.length) { index = -indexOk - 1; } else { index = -sortedHighs.length - 1; } assert index == binarySearch(sortedHighs, 0, indexOk, currentHigh) : "Computed " + index + " differs from dummy binary-search index: " + binarySearch(sortedHighs, 0, indexOk, currentHigh); if (index >= 0) { // This would mean calling .ensureOne is useless: should never got here at the first time throw new IllegalStateException("Unexpectedly found " + currentHigh + " in " + Arrays.toString(sortedHighs) + " strictly before index" + indexOk); } else { int insertionPosition = -index - 1; // This is a new key if (insertionPosition >= sortedHighs.length) { int previousSize = sortedHighs.length; // TODO softer growing factor int newSize = Math.min(Integer.MAX_VALUE, sortedHighs.length * 2 + 1); // Insertion at the end sortedHighs = Arrays.copyOf(sortedHighs, newSize); sortedCumulatedCardinality = Arrays.copyOf(sortedCumulatedCardinality, newSize); // Not actually needed. But simplify the reading of array content Arrays.fill(sortedHighs, previousSize, sortedHighs.length, highestHigh()); Arrays.fill(sortedCumulatedCardinality, previousSize, sortedHighs.length, Long.MAX_VALUE); } sortedHighs[insertionPosition] = currentHigh; final long previousCardinality; if (insertionPosition >= 1) { previousCardinality = sortedCumulatedCardinality[insertionPosition - 1]; } else { previousCardinality = 0; } sortedCumulatedCardinality[insertionPosition] = previousCardinality + e.getValue().getLongCardinality(); if (currentHigh == highestHigh()) { // We are already on the highest high. Do not set allValid as it is set anyway out of the // loop firstHighNotValid = currentHigh; } else { // The first not valid is the next high // TODO: The entry comes from a NavigableMap: it may be quite cheap to know the next high firstHighNotValid = currentHigh + 1; } } } private int highestHigh() { return RoaringIntPacking.highestHigh(signedLongs); } /** * In-place bitwise OR (union) operation. The current bitmap is modified. * * @param x2 other bitmap */ public void or(final Roaring64NavigableMap x2) { boolean firstBucket = true; for (Entry<Integer, BitmapDataProvider> e2 : x2.highToBitmap.entrySet()) { // Keep object to prevent auto-boxing Integer high = e2.getKey(); BitmapDataProvider lowBitmap1 = this.highToBitmap.get(high); BitmapDataProvider lowBitmap2 = e2.getValue(); // TODO Reviewers: is it a good idea to rely on BitmapDataProvider except in methods // expecting an actual MutableRoaringBitmap? // TODO This code may lead to closing a buffer Bitmap in current Navigable even if current is // not on buffer if ((lowBitmap1 == null || lowBitmap1 instanceof RoaringBitmap) && lowBitmap2 instanceof RoaringBitmap) { if (lowBitmap1 == null) { // Clone to prevent future modification of this modifying the input Bitmap RoaringBitmap lowBitmap2Clone = ((RoaringBitmap) lowBitmap2).clone(); pushBitmapForHigh(high, lowBitmap2Clone); } else { ((RoaringBitmap) lowBitmap1).or((RoaringBitmap) lowBitmap2); } } else if ((lowBitmap1 == null || lowBitmap1 instanceof MutableRoaringBitmap) && lowBitmap2 instanceof MutableRoaringBitmap) { if (lowBitmap1 == null) { // Clone to prevent future modification of this modifying the input Bitmap BitmapDataProvider lowBitmap2Clone = ((MutableRoaringBitmap) lowBitmap2).clone(); pushBitmapForHigh(high, lowBitmap2Clone); } else { ((MutableRoaringBitmap) lowBitmap1).or((MutableRoaringBitmap) lowBitmap2); } } else { throw new UnsupportedOperationException( ".or is not between " + this.getClass() + " and " + lowBitmap2.getClass()); } if (firstBucket) { firstBucket = false; // Invalidate the lowest high as lowest not valid firstHighNotValid = Math.min(firstHighNotValid, high); allValid = false; } } } /** * In-place bitwise XOR (symmetric difference) operation. The current bitmap is modified. * * @param x2 other bitmap */ public void xor(final Roaring64NavigableMap x2) { boolean firstBucket = true; for (Entry<Integer, BitmapDataProvider> e2 : x2.highToBitmap.entrySet()) { // Keep object to prevent auto-boxing Integer high = e2.getKey(); BitmapDataProvider lowBitmap1 = this.highToBitmap.get(high); BitmapDataProvider lowBitmap2 = e2.getValue(); // TODO Reviewers: is it a good idea to rely on BitmapDataProvider except in methods // expecting an actual MutableRoaringBitmap? // TODO This code may lead to closing a buffer Bitmap in current Navigable even if current is // not on buffer if ((lowBitmap1 == null || lowBitmap1 instanceof RoaringBitmap) && lowBitmap2 instanceof RoaringBitmap) { if (lowBitmap1 == null) { // Clone to prevent future modification of this modifying the input Bitmap RoaringBitmap lowBitmap2Clone = ((RoaringBitmap) lowBitmap2).clone(); pushBitmapForHigh(high, lowBitmap2Clone); } else { ((RoaringBitmap) lowBitmap1).xor((RoaringBitmap) lowBitmap2); } } else if ((lowBitmap1 == null || lowBitmap1 instanceof MutableRoaringBitmap) && lowBitmap2 instanceof MutableRoaringBitmap) { if (lowBitmap1 == null) { // Clone to prevent future modification of this modifying the input Bitmap BitmapDataProvider lowBitmap2Clone = ((MutableRoaringBitmap) lowBitmap2).clone(); pushBitmapForHigh(high, lowBitmap2Clone); } else { ((MutableRoaringBitmap) lowBitmap1).xor((MutableRoaringBitmap) lowBitmap2); } } else { throw new UnsupportedOperationException( ".or is not between " + this.getClass() + " and " + lowBitmap2.getClass()); } if (firstBucket) { firstBucket = false; // Invalidate the lowest high as lowest not valid firstHighNotValid = Math.min(firstHighNotValid, high); allValid = false; } } } /** * In-place bitwise AND (intersection) operation. The current bitmap is modified. * * @param x2 other bitmap */ public void and(final Roaring64NavigableMap x2) { boolean firstBucket = true; Iterator<Entry<Integer, BitmapDataProvider>> thisIterator = highToBitmap.entrySet().iterator(); while (thisIterator.hasNext()) { Entry<Integer, BitmapDataProvider> e1 = thisIterator.next(); // Keep object to prevent auto-boxing Integer high = e1.getKey(); BitmapDataProvider lowBitmap2 = x2.highToBitmap.get(high); if (lowBitmap2 == null) { // None of given high values are present in x2 thisIterator.remove(); } else { BitmapDataProvider lowBitmap1 = e1.getValue(); if (lowBitmap2 instanceof RoaringBitmap && lowBitmap1 instanceof RoaringBitmap) { ((RoaringBitmap) lowBitmap1).and((RoaringBitmap) lowBitmap2); } else if (lowBitmap2 instanceof MutableRoaringBitmap && lowBitmap1 instanceof MutableRoaringBitmap) { ((MutableRoaringBitmap) lowBitmap1).and((MutableRoaringBitmap) lowBitmap2); } else { throw new UnsupportedOperationException( ".and is not between " + this.getClass() + " and " + lowBitmap1.getClass()); } } if (firstBucket) { firstBucket = false; // Invalidate the lowest high as lowest not valid firstHighNotValid = Math.min(firstHighNotValid, high); allValid = false; } } } /** * In-place bitwise ANDNOT (difference) operation. The current bitmap is modified. * * @param x2 other bitmap */ public void andNot(final Roaring64NavigableMap x2) { boolean firstBucket = true; Iterator<Entry<Integer, BitmapDataProvider>> thisIterator = highToBitmap.entrySet().iterator(); while (thisIterator.hasNext()) { Entry<Integer, BitmapDataProvider> e1 = thisIterator.next(); // Keep object to prevent auto-boxing Integer high = e1.getKey(); BitmapDataProvider lowBitmap2 = x2.highToBitmap.get(high); if (lowBitmap2 != null) { BitmapDataProvider lowBitmap1 = e1.getValue(); if (lowBitmap2 instanceof RoaringBitmap && lowBitmap1 instanceof RoaringBitmap) { ((RoaringBitmap) lowBitmap1).andNot((RoaringBitmap) lowBitmap2); } else if (lowBitmap2 instanceof MutableRoaringBitmap && lowBitmap1 instanceof MutableRoaringBitmap) { ((MutableRoaringBitmap) lowBitmap1).andNot((MutableRoaringBitmap) lowBitmap2); } else { throw new UnsupportedOperationException( ".and is not between " + this.getClass() + " and " + lowBitmap1.getClass()); } } if (firstBucket) { firstBucket = false; // Invalidate the lowest high as lowest not valid firstHighNotValid = Math.min(firstHighNotValid, high); allValid = false; } } } /** * {@link Roaring64NavigableMap} are serializable. However, contrary to RoaringBitmap, the * serialization format is not well-defined: for now, it is strongly coupled with Java standard * serialization. Just like the serialization may be incompatible between various Java versions, * {@link Roaring64NavigableMap} are subject to incompatibilities. Moreover, even on a given Java * versions, the serialization format may change from one RoaringBitmap version to another */ @Override public void writeExternal(ObjectOutput out) throws IOException { serialize(out); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { deserialize(in); } /** * A string describing the bitmap. * * @return the string */ @Override public String toString() { final StringBuilder answer = new StringBuilder(); final LongIterator i = this.getLongIterator(); answer.append("{"); if (i.hasNext()) { if (signedLongs) { answer.append(i.next()); } else { answer.append(RoaringIntPacking.toUnsignedString(i.next())); } } while (i.hasNext()) { answer.append(","); // to avoid using too much memory, we limit the size if (answer.length() > 0x80000) { answer.append("..."); break; } if (signedLongs) { answer.append(i.next()); } else { answer.append(RoaringIntPacking.toUnsignedString(i.next())); } } answer.append("}"); return answer.toString(); } /** * * For better performance, consider the Use the {@link #forEach forEach} method. * * @return a custom iterator over set bits, the bits are traversed in ascending sorted order */ @Override public LongIterator getLongIterator() { final Iterator<Map.Entry<Integer, BitmapDataProvider>> it = highToBitmap.entrySet().iterator(); return toIterator(it, false); } protected LongIterator toIterator(final Iterator<Map.Entry<Integer, BitmapDataProvider>> it, final boolean reversed) { return new LongIterator() { protected int currentKey; protected IntIterator currentIt; @Override public boolean hasNext() { if (currentIt == null) { // Were initially empty if (!moveToNextEntry(it)) { return false; } } while (true) { if (currentIt.hasNext()) { return true; } else { if (!moveToNextEntry(it)) { return false; } } } } /** * * @param it the underlying iterator which has to be moved to next long * @return true if we MAY have more entries. false if there is definitely nothing more */ private boolean moveToNextEntry(Iterator<Map.Entry<Integer, BitmapDataProvider>> it) { if (it.hasNext()) { Map.Entry<Integer, BitmapDataProvider> next = it.next(); currentKey = next.getKey(); if (reversed) { currentIt = next.getValue().getReverseIntIterator(); } else { currentIt = next.getValue().getIntIterator(); } // We may have more long return true; } else { // We know there is nothing more return false; } } @Override public long next() { if (hasNext()) { return RoaringIntPacking.pack(currentKey, currentIt.next()); } else { throw new IllegalStateException("empty"); } } @Override public LongIterator clone() { throw new UnsupportedOperationException("TODO"); } }; } @Override public boolean contains(long x) { int high = RoaringIntPacking.high(x); BitmapDataProvider lowBitmap = highToBitmap.get(high); if (lowBitmap == null) { return false; } int low = RoaringIntPacking.low(x); return lowBitmap.contains(low); } @Override public int getSizeInBytes() { return (int) getLongSizeInBytes(); } @Override public long getLongSizeInBytes() { long size = 8; // Size of containers size += highToBitmap.values().stream().mapToLong(p -> p.getLongSizeInBytes()).sum(); // Size of Map data-structure: we consider each TreeMap entry costs 40 bytes // http://java-performance.info/memory-consumption-of-java-data-types-2/ size += 8L + 40L * highToBitmap.size(); // Size of (boxed) Integers used as keys size += 16L * highToBitmap.size(); // The cache impacts the size in heap size += 8L * sortedCumulatedCardinality.length; size += 4L * sortedHighs.length; return size; } @Override public boolean isEmpty() { return getLongCardinality() == 0L; } @Override public ImmutableLongBitmapDataProvider limit(long x) { throw new UnsupportedOperationException("TODO"); } /** * Use a run-length encoding where it is estimated as more space efficient * * @return whether a change was applied */ public boolean runOptimize() { boolean hasChanged = false; for (BitmapDataProvider lowBitmap : highToBitmap.values()) { if (lowBitmap instanceof RoaringBitmap) { hasChanged |= ((RoaringBitmap) lowBitmap).runOptimize(); } else if (lowBitmap instanceof MutableRoaringBitmap) { hasChanged |= ((MutableRoaringBitmap) lowBitmap).runOptimize(); } } return hasChanged; } /** * Serialize this bitmap. * * Unlike RoaringBitmap, there is no specification for now: it may change from onve java version * to another, and from one RoaringBitmap version to another. * * Consider calling {@link #runOptimize} before serialization to improve compression. * * The current bitmap is not modified. * * @param out the DataOutput stream * @throws IOException Signals that an I/O exception has occurred. */ @Override public void serialize(DataOutput out) throws IOException { // TODO: Should we transport the performance tweak 'doCacheCardinalities'? out.writeBoolean(signedLongs); out.writeInt(highToBitmap.size()); for (Entry<Integer, BitmapDataProvider> entry : highToBitmap.entrySet()) { out.writeInt(entry.getKey().intValue()); entry.getValue().serialize(out); } } /** * Deserialize (retrieve) this bitmap. * * Unlike RoaringBitmap, there is no specification for now: it may change from one java version to * another, and from one RoaringBitmap version to another. * * The current bitmap is overwritten. * * @param in the DataInput stream * @throws IOException Signals that an I/O exception has occurred. */ public void deserialize(DataInput in) throws IOException { this.clear(); signedLongs = in.readBoolean(); int nbHighs = in.readInt(); // Other NavigableMap may accept a target capacity if (signedLongs) { highToBitmap = new TreeMap<>(); } else { highToBitmap = new TreeMap<>(RoaringIntPacking.unsignedComparator()); } for (int i = 0; i < nbHighs; i++) { int high = in.readInt(); RoaringBitmap provider = new RoaringBitmap(); provider.deserialize(in); highToBitmap.put(high, provider); } resetPerfHelpers(); } @Override public long serializedSizeInBytes() { long nbBytes = 0L; // .writeBoolean for signedLongs boolean nbBytes += 1; // .writeInt for number of different high values nbBytes += 4; for (Entry<Integer, BitmapDataProvider> entry : highToBitmap.entrySet()) { // .writeInt for high nbBytes += 4; // The low bitmap size in bytes nbBytes += entry.getValue().serializedSizeInBytes(); } return nbBytes; } /** * reset to an empty bitmap; result occupies as much space a newly created bitmap. */ public void clear() { this.highToBitmap.clear(); resetPerfHelpers(); } /** * Return the set values as an array, if the cardinality is smaller than 2147483648. The long * values are in sorted order. * * @return array representing the set values. */ @Override public long[] toArray() { long cardinality = this.getLongCardinality(); if (cardinality > Integer.MAX_VALUE) { throw new IllegalStateException("The cardinality does not fit in an array"); } final long[] array = new long[(int) cardinality]; int pos = 0; LongIterator it = getLongIterator(); while (it.hasNext()) { array[pos++] = it.next(); } return array; } /** * Generate a bitmap with the specified values set to true. The provided longs values don't have * to be in sorted order, but it may be preferable to sort them from a performance point of view. * * @param dat set values * @return a new bitmap */ public static Roaring64NavigableMap bitmapOf(final long... dat) { final Roaring64NavigableMap ans = new Roaring64NavigableMap(); ans.add(dat); return ans; } /** * Set all the specified values to true. This can be expected to be slightly faster than calling * "add" repeatedly. The provided integers values don't have to be in sorted order, but it may be * preferable to sort them from a performance point of view. * * @param dat set values */ public void add(long... dat) { for (long oneLong : dat) { addLong(oneLong); } } /** * Add to the current bitmap all longs in [rangeStart,rangeEnd). * * @param rangeStart inclusive beginning of range * @param rangeEnd exclusive ending of range */ public void add(final long rangeStart, final long rangeEnd) { int startHigh = high(rangeStart); int startLow = low(rangeStart); int endHigh = high(rangeEnd); int endLow = low(rangeEnd); for (int high = startHigh; high <= endHigh; high++) { final int currentStartLow; if (startHigh == high) { // The whole range starts in this bucket currentStartLow = startLow; } else { // Add the bucket from the beginning currentStartLow = 0; } long startLowAsLong = Util.toUnsignedLong(currentStartLow); final long endLowAsLong; if (endHigh == high) { // The whole range ends in this bucket endLowAsLong = Util.toUnsignedLong(endLow); } else { // Add the bucket until the end: we have a +1 as, in RoaringBitmap.add(long,long), the end // is excluded endLowAsLong = Util.toUnsignedLong(-1) + 1; } if (endLowAsLong > startLowAsLong) { // Initialize the bitmap only if there is access data to write BitmapDataProvider bitmap = highToBitmap.get(high); if (bitmap == null) { bitmap = new MutableRoaringBitmap(); pushBitmapForHigh(high, bitmap); } bitmap.add(startLowAsLong, endLowAsLong); } } invalidateAboveHigh(startHigh); } @Override public LongIterator getReverseLongIterator() { return toIterator(highToBitmap.descendingMap().entrySet().iterator(), true); } @Override public void removeLong(long x) { int high = high(x); BitmapDataProvider bitmap = highToBitmap.get(high); if (bitmap != null) { int low = low(x); bitmap.remove(low); // Invalidate only if actually modified invalidateAboveHigh(high); } } @Override public void trim() { for (BitmapDataProvider bitmap : highToBitmap.values()) { bitmap.trim(); } } @Override public int hashCode() { return highToBitmap.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Roaring64NavigableMap other = (Roaring64NavigableMap) obj; return Objects.equals(highToBitmap, other.highToBitmap); } /** * Add the value if it is not already present, otherwise remove it. * * @param x long value */ public void flip(final long x) { int high = RoaringIntPacking.high(x); BitmapDataProvider lowBitmap = highToBitmap.get(high); if (lowBitmap == null) { // The value is not added: add it without any flip specific code addLong(x); } else { int low = RoaringIntPacking.low(x); // .flip is not in BitmapDataProvider contract // TODO Is it relevant to calling .flip with a cast? if (lowBitmap instanceof RoaringBitmap) { ((RoaringBitmap) lowBitmap).flip(low); } else if (lowBitmap instanceof MutableRoaringBitmap) { ((MutableRoaringBitmap) lowBitmap).flip(low); } else { // Fallback to a manual flip if (lowBitmap.contains(low)) { lowBitmap.remove(low); } else { lowBitmap.add(low); } } } invalidateAboveHigh(high); } }
RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
/* * (c) the authors Licensed under the Apache License, Version 2.0. */ package org.roaringbitmap.longlong; import org.roaringbitmap.*; import org.roaringbitmap.buffer.MutableRoaringBitmap; import java.io.*; import java.util.*; import java.util.Map.Entry; /** * Roaring64NavigableMap extends RoaringBitmap to the whole range of longs (or unsigned longs). It * enables a cardinality greater up to Long.MAX_VALUE * * Longs are added by default in unsigned sorted order (i.e. -1L is the greater long to be added * while 0 has no previous value). It can be configured to signed sorted order (in which case, 0 is * preceded by 1). That is, they are treated as unsigned integers (see Java 8's * Integer.toUnsignedLong function). Up to 4294967296 integers can be stored. * * * */ // this class is not thread-safe // @Beta: this class is still in early stage. Its API may change and has not proofed itself as // bug-proof public class Roaring64NavigableMap implements Externalizable, LongBitmapDataProvider { // Not final to enable initialization in Externalizable.readObject private NavigableMap<Integer, BitmapDataProvider> highToBitmap; // If true, we handle longs a plain java longs: -1 if right before 0 // If false, we handle longs as unsigned longs: 0 has no predecessor and Long.MAX_VALUE + 1L is // expressed as a // negative long private boolean signedLongs = false; private BitmapDataProviderSupplier supplier; // By default, we cache cardinalities private transient boolean doCacheCardinalities = true; // Prevent recomputing all cardinalities when requesting consecutive ranks private transient int firstHighNotValid = highestHigh() + 1; // This boolean needs firstHighNotValid == Integer.MAX_VALUE to be allowed to be true // If false, it means nearly all cumulated cardinalities are valid, except high=Integer.MAX_VALUE // If true, it means all cumulated cardinalities are valid, even high=Integer.MAX_VALUE private transient boolean allValid = false; // TODO: I would prefer not managing arrays myself private transient long[] sortedCumulatedCardinality = new long[0]; private transient int[] sortedHighs = new int[0]; // We guess consecutive .addLong will be on proximate longs: we remember the bitmap attached to // this bucket in order // to skip the indirection private transient Map.Entry<Integer, BitmapDataProvider> latestAddedHigh = null; private static final boolean DEFAULT_ORDER_IS_SIGNED = false; private static final boolean DEFAULT_CARDINALITIES_ARE_CACHED = true; /** * By default, we consider longs are unsigned longs: normal longs: 0 is the lowest possible long. * Long.MAX_VALUE is followed by Long.MIN_VALUE. -1L is the highest possible value */ public Roaring64NavigableMap() { this(DEFAULT_ORDER_IS_SIGNED); } /** * * By default, use RoaringBitmap as underlyings {@link BitmapDataProvider} * * @param signedLongs true if longs has to be ordered as plain java longs. False to handle them as * unsigned 64bits long (as RoaringBitmap with unsigned integers) */ public Roaring64NavigableMap(boolean signedLongs) { this(signedLongs, DEFAULT_CARDINALITIES_ARE_CACHED); } /** * By default, use RoaringBitmap as underlyings {@link BitmapDataProvider} * * @param signedLongs true if longs has to be ordered as plain java longs. False to handle them as * unsigned 64bits long (as RoaringBitmap with unsigned integers) * @param cacheCardinalities true if cardinalities have to be cached. It will prevent many * iteration along the NavigableMap */ public Roaring64NavigableMap(boolean signedLongs, boolean cacheCardinalities) { this(signedLongs, cacheCardinalities, new RoaringBitmapSupplier()); } /** * By default, longs are managed as unsigned longs and cardinalities are cached. * * @param supplier provide the logic to instantiate new {@link BitmapDataProvider}, typically * instantiated once per high. */ public Roaring64NavigableMap(BitmapDataProviderSupplier supplier) { this(DEFAULT_ORDER_IS_SIGNED, DEFAULT_CARDINALITIES_ARE_CACHED, supplier); } /** * By default, we activating cardinalities caching. * * @param signedLongs true if longs has to be ordered as plain java longs. False to handle them as * unsigned 64bits long (as RoaringBitmap with unsigned integers) * @param supplier provide the logic to instantiate new {@link BitmapDataProvider}, typically * instantiated once per high. */ public Roaring64NavigableMap(boolean signedLongs, BitmapDataProviderSupplier supplier) { this(signedLongs, DEFAULT_CARDINALITIES_ARE_CACHED, supplier); } /** * * @param signedLongs true if longs has to be ordered as plain java longs. False to handle them as * unsigned 64bits long (as RoaringBitmap with unsigned integers) * @param cacheCardinalities true if cardinalities have to be cached. It will prevent many * iteration along the NavigableMap * @param supplier provide the logic to instantiate new {@link BitmapDataProvider}, typically * instantiated once per high. */ public Roaring64NavigableMap(boolean signedLongs, boolean cacheCardinalities, BitmapDataProviderSupplier supplier) { this.signedLongs = signedLongs; this.supplier = supplier; if (signedLongs) { highToBitmap = new TreeMap<>(); } else { highToBitmap = new TreeMap<>(RoaringIntPacking.unsignedComparator()); } this.doCacheCardinalities = cacheCardinalities; resetPerfHelpers(); } private void resetPerfHelpers() { firstHighNotValid = RoaringIntPacking.highestHigh(signedLongs) + 1; allValid = false; sortedCumulatedCardinality = new long[0]; sortedHighs = new int[0]; latestAddedHigh = null; } // Package-friendly: for the sake of unit-testing // @VisibleForTesting NavigableMap<Integer, BitmapDataProvider> getHighToBitmap() { return highToBitmap; } // Package-friendly: for the sake of unit-testing // @VisibleForTesting int getLowestInvalidHigh() { return firstHighNotValid; } // Package-friendly: for the sake of unit-testing // @VisibleForTesting long[] getSortedCumulatedCardinality() { return sortedCumulatedCardinality; } /** * Add the value to the container (set the value to "true"), whether it already appears or not. * * Java lacks native unsigned longs but the x argument is considered to be unsigned. Within * bitmaps, numbers are ordered according to {@link Long#compareUnsigned}. We order the numbers * like 0, 1, ..., 9223372036854775807, -9223372036854775808, -9223372036854775807,..., -1. * * @param x long value */ @Override public void addLong(long x) { int high = high(x); int low = low(x); // Copy the reference to prevent race-condition Map.Entry<Integer, BitmapDataProvider> local = latestAddedHigh; BitmapDataProvider bitmap; if (local != null && local.getKey().intValue() == high) { bitmap = local.getValue(); } else { bitmap = highToBitmap.get(high); if (bitmap == null) { bitmap = newRoaringBitmap(); pushBitmapForHigh(high, bitmap); } latestAddedHigh = new AbstractMap.SimpleImmutableEntry<>(high, bitmap); } bitmap.add(low); invalidateAboveHigh(high); } /** * Add the integer value to the container (set the value to "true"), whether it already appears or * not. * * Javac lacks native unsigned integers but the x argument is considered to be unsigned. Within * bitmaps, numbers are ordered according to {@link Integer#compareUnsigned}. We order the numbers * like 0, 1, ..., 2147483647, -2147483648, -2147483647,..., -1. * * @param x integer value */ public void addInt(int x) { addLong(Util.toUnsignedLong(x)); } private BitmapDataProvider newRoaringBitmap() { return supplier.newEmpty(); } private void invalidateAboveHigh(int high) { // The cardinalities after this bucket may not be valid anymore if (compare(firstHighNotValid, high) > 0) { // High was valid up to now firstHighNotValid = high; int indexNotValid = binarySearch(sortedHighs, firstHighNotValid); final int indexAfterWhichToReset; if (indexNotValid >= 0) { indexAfterWhichToReset = indexNotValid; } else { // We have invalidate a high not already present: added a value for a brand new high indexAfterWhichToReset = -indexNotValid - 1; } // This way, sortedHighs remains sorted, without making a new/shorter array Arrays.fill(sortedHighs, indexAfterWhichToReset, sortedHighs.length, highestHigh()); } allValid = false; } private int compare(int x, int y) { if (signedLongs) { return Integer.compare(x, y); } else { return RoaringIntPacking.compareUnsigned(x, y); } } private void pushBitmapForHigh(int high, BitmapDataProvider bitmap) { // TODO .size is too slow // int nbHighBefore = highToBitmap.headMap(high).size(); BitmapDataProvider previous = highToBitmap.put(high, bitmap); assert previous == null : "Should push only not-existing high"; } private int low(long id) { return RoaringIntPacking.low(id); } private int high(long id) { return RoaringIntPacking.high(id); } /** * Returns the number of distinct integers added to the bitmap (e.g., number of bits set). * * @return the cardinality */ @Override public long getLongCardinality() { if (doCacheCardinalities) { if (highToBitmap.isEmpty()) { return 0L; } int indexOk = ensureCumulatives(highestHigh()); // ensureCumulatives may have removed empty bitmaps if (highToBitmap.isEmpty()) { return 0L; } return sortedCumulatedCardinality[indexOk - 1]; } else { long cardinality = 0L; for (BitmapDataProvider bitmap : highToBitmap.values()) { cardinality += bitmap.getLongCardinality(); } return cardinality; } } /** * * @return the cardinality as an int * * @throws UnsupportedOperationException if the cardinality does not fit in an int */ public int getIntCardinality() throws UnsupportedOperationException { long cardinality = getLongCardinality(); if (cardinality > Integer.MAX_VALUE) { // TODO: we should handle cardinality fitting in an unsigned int throw new UnsupportedOperationException( "Can not call .getIntCardinality as the cardinality is bigger than Integer.MAX_VALUE"); } return (int) cardinality; } /** * Return the jth value stored in this bitmap. * * @param j index of the value * * @return the value * @throws IllegalArgumentException if j is out of the bounds of the bitmap cardinality */ @Override public long select(final long j) throws IllegalArgumentException { if (!doCacheCardinalities) { return selectNoCache(j); } // Ensure all cumulatives as we we have straightforward way to know in advance the high of the // j-th value int indexOk = ensureCumulatives(highestHigh()); if (highToBitmap.isEmpty()) { return throwSelectInvalidIndex(j); } // Use normal binarySearch as cardinality does not depends on considering longs signed or // unsigned // We need sortedCumulatedCardinality not to contain duplicated, else binarySearch may return // any of the duplicates: we need to ensure it holds no high associated to an empty bitmap int position = Arrays.binarySearch(sortedCumulatedCardinality, 0, indexOk, j); if (position >= 0) { if (position == indexOk - 1) { // .select has been called on this.getCardinality return throwSelectInvalidIndex(j); } // There is a bucket leading to this cardinality: the j-th element is the first element of // next bucket int high = sortedHighs[position + 1]; BitmapDataProvider nextBitmap = highToBitmap.get(high); return RoaringIntPacking.pack(high, nextBitmap.select(0)); } else { // There is no bucket with this cardinality int insertionPoint = -position - 1; final long previousBucketCardinality; if (insertionPoint == 0) { previousBucketCardinality = 0L; } else if (insertionPoint >= indexOk) { return throwSelectInvalidIndex(j); } else { previousBucketCardinality = sortedCumulatedCardinality[insertionPoint - 1]; } // We get a 'select' query for a single bitmap: should fit in an int final int givenBitmapSelect = (int) (j - previousBucketCardinality); int high = sortedHighs[insertionPoint]; BitmapDataProvider lowBitmap = highToBitmap.get(high); int low = lowBitmap.select(givenBitmapSelect); return RoaringIntPacking.pack(high, low); } } // For benchmarks: compute without using cardinalities cache // https://github.com/RoaringBitmap/CRoaring/blob/master/cpp/roaring64map.hh private long selectNoCache(long j) { long left = j; for (Entry<Integer, BitmapDataProvider> entry : highToBitmap.entrySet()) { long lowCardinality = entry.getValue().getCardinality(); if (left >= lowCardinality) { left -= lowCardinality; } else { // It is legit for left to be negative int leftAsUnsignedInt = (int) left; return RoaringIntPacking.pack(entry.getKey(), entry.getValue().select(leftAsUnsignedInt)); } } return throwSelectInvalidIndex(j); } private long throwSelectInvalidIndex(long j) { // see org.roaringbitmap.buffer.ImmutableRoaringBitmap.select(int) throw new IllegalArgumentException( "select " + j + " when the cardinality is " + this.getLongCardinality()); } /** * For better performance, consider the Use the {@link #forEach forEach} method. * * @return a custom iterator over set bits, the bits are traversed in ascending sorted order */ public Iterator<Long> iterator() { final LongIterator it = getLongIterator(); return new Iterator<Long>() { @Override public boolean hasNext() { return it.hasNext(); } @Override public Long next() { return it.next(); } @Override public void remove() { // TODO? throw new UnsupportedOperationException(); } }; } @Override public void forEach(final LongConsumer lc) { for (final Entry<Integer, BitmapDataProvider> highEntry : highToBitmap.entrySet()) { highEntry.getValue().forEach(new IntConsumer() { @Override public void accept(int low) { lc.accept(RoaringIntPacking.pack(highEntry.getKey(), low)); } }); } } @Override public long rankLong(long id) { int high = RoaringIntPacking.high(id); int low = RoaringIntPacking.low(id); if (!doCacheCardinalities) { return rankLongNoCache(high, low); } int indexOk = ensureCumulatives(high); int highPosition = binarySearch(sortedHighs, 0, indexOk, high); if (highPosition >= 0) { // There is a bucket holding this item final long previousBucketCardinality; if (highPosition == 0) { previousBucketCardinality = 0; } else { previousBucketCardinality = sortedCumulatedCardinality[highPosition - 1]; } BitmapDataProvider lowBitmap = highToBitmap.get(sortedHighs[highPosition]); // Rank is previous cardinality plus rank in current bitmap return previousBucketCardinality + lowBitmap.rankLong(low); } else { // There is no bucket holding this item: insertionPoint is previous bitmap int insertionPoint = -highPosition - 1; if (insertionPoint == 0) { // this key is before all inserted keys return 0; } else { // The rank is the cardinality of this previous bitmap return sortedCumulatedCardinality[insertionPoint - 1]; } } } // https://github.com/RoaringBitmap/CRoaring/blob/master/cpp/roaring64map.hh private long rankLongNoCache(int high, int low) { long result = 0L; BitmapDataProvider lastBitmap = highToBitmap.get(high); if (lastBitmap == null) { // There is no value with same high: the rank is a sum of cardinalities for (Entry<Integer, BitmapDataProvider> bitmap : highToBitmap.entrySet()) { if (bitmap.getKey().intValue() > high) { break; } else { result += bitmap.getValue().getLongCardinality(); } } } else { for (BitmapDataProvider bitmap : highToBitmap.values()) { if (bitmap == lastBitmap) { result += bitmap.rankLong(low); break; } else { result += bitmap.getLongCardinality(); } } } return result; } /** * * @param high for which high bucket should we compute the cardinality * @return the highest validatedIndex */ protected int ensureCumulatives(int high) { if (allValid) { // the whole array is valid (up-to its actual length, not its capacity) return highToBitmap.size(); } else if (compare(high, firstHighNotValid) < 0) { // The high is strictly below the first not valid: it is valid // sortedHighs may have only a subset of valid values on the right. However, these invalid // values have been set to maxValue, and we are here as high < firstHighNotValid ==> high < // maxHigh() int position = binarySearch(sortedHighs, high); if (position >= 0) { // This high has a bitmap: +1 as this index will be used as right (excluded) bound in a // binary-search return position + 1; } else { // This high has no bitmap: it could be between 2 highs with bitmaps int insertionPosition = -position - 1; return insertionPosition; } } else { // For each deprecated buckets SortedMap<Integer, BitmapDataProvider> tailMap = highToBitmap.tailMap(firstHighNotValid, true); // TODO .size on tailMap make an iterator: arg int indexOk = highToBitmap.size() - tailMap.size(); // TODO: It should be possible to compute indexOk based on sortedHighs array // assert indexOk == binarySearch(sortedHighs, firstHighNotValid); Iterator<Entry<Integer, BitmapDataProvider>> it = tailMap.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, BitmapDataProvider> e = it.next(); int currentHigh = e.getKey(); if (compare(currentHigh, high) > 0) { // No need to compute more than needed break; } else if (e.getValue().isEmpty()) { // highToBitmap can not be modified as we iterate over it if (latestAddedHigh != null && latestAddedHigh.getKey().intValue() == currentHigh) { // Dismiss the cached bitmap as it is removed from the NavigableMap latestAddedHigh = null; } it.remove(); } else { ensureOne(e, currentHigh, indexOk); // We have added one valid cardinality indexOk++; } } if (highToBitmap.isEmpty() || indexOk == highToBitmap.size()) { // We have compute all cardinalities allValid = true; } return indexOk; } } private int binarySearch(int[] array, int key) { if (signedLongs) { return Arrays.binarySearch(array, key); } else { return unsignedBinarySearch(array, 0, array.length, key, RoaringIntPacking.unsignedComparator()); } } private int binarySearch(int[] array, int from, int to, int key) { if (signedLongs) { return Arrays.binarySearch(array, from, to, key); } else { return unsignedBinarySearch(array, from, to, key, RoaringIntPacking.unsignedComparator()); } } // From Arrays.binarySearch (Comparator). Check with org.roaringbitmap.Util.unsignedBinarySearch private static int unsignedBinarySearch(int[] a, int fromIndex, int toIndex, int key, Comparator<? super Integer> c) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; int cmp = c.compare(midVal, key); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { return mid; // key found } } return -(low + 1); // key not found. } private void ensureOne(Map.Entry<Integer, BitmapDataProvider> e, int currentHigh, int indexOk) { // sortedHighs are valid only up to some index assert indexOk <= sortedHighs.length : indexOk + " is bigger than " + sortedHighs.length; final int index; if (indexOk == 0) { if (sortedHighs.length == 0) { index = -1; // } else if (sortedHighs[0] == currentHigh) { // index = 0; } else { index = -1; } } else if (indexOk < sortedHighs.length) { index = -indexOk - 1; } else { index = -sortedHighs.length - 1; } assert index == binarySearch(sortedHighs, 0, indexOk, currentHigh) : "Computed " + index + " differs from dummy binary-search index: " + binarySearch(sortedHighs, 0, indexOk, currentHigh); if (index >= 0) { // This would mean calling .ensureOne is useless: should never got here at the first time throw new IllegalStateException("Unexpectedly found " + currentHigh + " in " + Arrays.toString(sortedHighs) + " strictly before index" + indexOk); } else { int insertionPosition = -index - 1; // This is a new key if (insertionPosition >= sortedHighs.length) { int previousSize = sortedHighs.length; // TODO softer growing factor int newSize = Math.min(Integer.MAX_VALUE, sortedHighs.length * 2 + 1); // Insertion at the end sortedHighs = Arrays.copyOf(sortedHighs, newSize); sortedCumulatedCardinality = Arrays.copyOf(sortedCumulatedCardinality, newSize); // Not actually needed. But simplify the reading of array content Arrays.fill(sortedHighs, previousSize, sortedHighs.length, highestHigh()); Arrays.fill(sortedCumulatedCardinality, previousSize, sortedHighs.length, Long.MAX_VALUE); } sortedHighs[insertionPosition] = currentHigh; final long previousCardinality; if (insertionPosition >= 1) { previousCardinality = sortedCumulatedCardinality[insertionPosition - 1]; } else { previousCardinality = 0; } sortedCumulatedCardinality[insertionPosition] = previousCardinality + e.getValue().getLongCardinality(); if (currentHigh == highestHigh()) { // We are already on the highest high. Do not set allValid as it is set anyway out of the // loop firstHighNotValid = currentHigh; } else { // The first not valid is the next high // TODO: The entry comes from a NavigableMap: it may be quite cheap to know the next high firstHighNotValid = currentHigh + 1; } } } private int highestHigh() { return RoaringIntPacking.highestHigh(signedLongs); } /** * In-place bitwise OR (union) operation. The current bitmap is modified. * * @param x2 other bitmap */ public void or(final Roaring64NavigableMap x2) { boolean firstBucket = true; for (Entry<Integer, BitmapDataProvider> e2 : x2.highToBitmap.entrySet()) { // Keep object to prevent auto-boxing Integer high = e2.getKey(); BitmapDataProvider lowBitmap1 = this.highToBitmap.get(high); BitmapDataProvider lowBitmap2 = e2.getValue(); // TODO Reviewers: is it a good idea to rely on BitmapDataProvider except in methods // expecting an actual MutableRoaringBitmap? // TODO This code may lead to closing a buffer Bitmap in current Navigable even if current is // not on buffer if ((lowBitmap1 == null || lowBitmap1 instanceof RoaringBitmap) && lowBitmap2 instanceof RoaringBitmap) { if (lowBitmap1 == null) { // Clone to prevent future modification of this modifying the input Bitmap RoaringBitmap lowBitmap2Clone = ((RoaringBitmap) lowBitmap2).clone(); pushBitmapForHigh(high, lowBitmap2Clone); } else { ((RoaringBitmap) lowBitmap1).or((RoaringBitmap) lowBitmap2); } } else if ((lowBitmap1 == null || lowBitmap1 instanceof MutableRoaringBitmap) && lowBitmap2 instanceof MutableRoaringBitmap) { if (lowBitmap1 == null) { // Clone to prevent future modification of this modifying the input Bitmap BitmapDataProvider lowBitmap2Clone = ((MutableRoaringBitmap) lowBitmap2).clone(); pushBitmapForHigh(high, lowBitmap2Clone); } else { ((MutableRoaringBitmap) lowBitmap1).or((MutableRoaringBitmap) lowBitmap2); } } else { throw new UnsupportedOperationException( ".or is not between " + this.getClass() + " and " + lowBitmap2.getClass()); } if (firstBucket) { firstBucket = false; // Invalidate the lowest high as lowest not valid firstHighNotValid = Math.min(firstHighNotValid, high); allValid = false; } } } /** * In-place bitwise XOR (symmetric difference) operation. The current bitmap is modified. * * @param x2 other bitmap */ public void xor(final Roaring64NavigableMap x2) { boolean firstBucket = true; for (Entry<Integer, BitmapDataProvider> e2 : x2.highToBitmap.entrySet()) { // Keep object to prevent auto-boxing Integer high = e2.getKey(); BitmapDataProvider lowBitmap1 = this.highToBitmap.get(high); BitmapDataProvider lowBitmap2 = e2.getValue(); // TODO Reviewers: is it a good idea to rely on BitmapDataProvider except in methods // expecting an actual MutableRoaringBitmap? // TODO This code may lead to closing a buffer Bitmap in current Navigable even if current is // not on buffer if ((lowBitmap1 == null || lowBitmap1 instanceof RoaringBitmap) && lowBitmap2 instanceof RoaringBitmap) { if (lowBitmap1 == null) { // Clone to prevent future modification of this modifying the input Bitmap RoaringBitmap lowBitmap2Clone = ((RoaringBitmap) lowBitmap2).clone(); pushBitmapForHigh(high, lowBitmap2Clone); } else { ((RoaringBitmap) lowBitmap1).xor((RoaringBitmap) lowBitmap2); } } else if ((lowBitmap1 == null || lowBitmap1 instanceof MutableRoaringBitmap) && lowBitmap2 instanceof MutableRoaringBitmap) { if (lowBitmap1 == null) { // Clone to prevent future modification of this modifying the input Bitmap BitmapDataProvider lowBitmap2Clone = ((MutableRoaringBitmap) lowBitmap2).clone(); pushBitmapForHigh(high, lowBitmap2Clone); } else { ((MutableRoaringBitmap) lowBitmap1).xor((MutableRoaringBitmap) lowBitmap2); } } else { throw new UnsupportedOperationException( ".or is not between " + this.getClass() + " and " + lowBitmap2.getClass()); } if (firstBucket) { firstBucket = false; // Invalidate the lowest high as lowest not valid firstHighNotValid = Math.min(firstHighNotValid, high); allValid = false; } } } /** * In-place bitwise AND (intersection) operation. The current bitmap is modified. * * @param x2 other bitmap */ public void and(final Roaring64NavigableMap x2) { boolean firstBucket = true; Iterator<Entry<Integer, BitmapDataProvider>> thisIterator = highToBitmap.entrySet().iterator(); while (thisIterator.hasNext()) { Entry<Integer, BitmapDataProvider> e1 = thisIterator.next(); // Keep object to prevent auto-boxing Integer high = e1.getKey(); BitmapDataProvider lowBitmap2 = x2.highToBitmap.get(high); if (lowBitmap2 == null) { // None of given high values are present in x2 thisIterator.remove(); } else { BitmapDataProvider lowBitmap1 = e1.getValue(); if (lowBitmap2 instanceof RoaringBitmap && lowBitmap1 instanceof RoaringBitmap) { ((RoaringBitmap) lowBitmap1).and((RoaringBitmap) lowBitmap2); } else if (lowBitmap2 instanceof MutableRoaringBitmap && lowBitmap1 instanceof MutableRoaringBitmap) { ((MutableRoaringBitmap) lowBitmap1).and((MutableRoaringBitmap) lowBitmap2); } else { throw new UnsupportedOperationException( ".and is not between " + this.getClass() + " and " + lowBitmap1.getClass()); } } if (firstBucket) { firstBucket = false; // Invalidate the lowest high as lowest not valid firstHighNotValid = Math.min(firstHighNotValid, high); allValid = false; } } } /** * In-place bitwise ANDNOT (difference) operation. The current bitmap is modified. * * @param x2 other bitmap */ public void andNot(final Roaring64NavigableMap x2) { boolean firstBucket = true; Iterator<Entry<Integer, BitmapDataProvider>> thisIterator = highToBitmap.entrySet().iterator(); while (thisIterator.hasNext()) { Entry<Integer, BitmapDataProvider> e1 = thisIterator.next(); // Keep object to prevent auto-boxing Integer high = e1.getKey(); BitmapDataProvider lowBitmap2 = x2.highToBitmap.get(high); if (lowBitmap2 != null) { BitmapDataProvider lowBitmap1 = e1.getValue(); if (lowBitmap2 instanceof RoaringBitmap && lowBitmap1 instanceof RoaringBitmap) { ((RoaringBitmap) lowBitmap1).andNot((RoaringBitmap) lowBitmap2); } else if (lowBitmap2 instanceof MutableRoaringBitmap && lowBitmap1 instanceof MutableRoaringBitmap) { ((MutableRoaringBitmap) lowBitmap1).andNot((MutableRoaringBitmap) lowBitmap2); } else { throw new UnsupportedOperationException( ".and is not between " + this.getClass() + " and " + lowBitmap1.getClass()); } } if (firstBucket) { firstBucket = false; // Invalidate the lowest high as lowest not valid firstHighNotValid = Math.min(firstHighNotValid, high); allValid = false; } } } /** * {@link Roaring64NavigableMap} are serializable. However, contrary to RoaringBitmap, the * serialization format is not well-defined: for now, it is strongly coupled with Java standard * serialization. Just like the serialization may be incompatible between various Java versions, * {@link Roaring64NavigableMap} are subject to incompatibilities. Moreover, even on a given Java * versions, the serialization format may change from one RoaringBitmap version to another */ @Override public void writeExternal(ObjectOutput out) throws IOException { serialize(out); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { deserialize(in); } /** * A string describing the bitmap. * * @return the string */ @Override public String toString() { final StringBuilder answer = new StringBuilder(); final LongIterator i = this.getLongIterator(); answer.append("{"); if (i.hasNext()) { if (signedLongs) { answer.append(i.next()); } else { answer.append(RoaringIntPacking.toUnsignedString(i.next())); } } while (i.hasNext()) { answer.append(","); // to avoid using too much memory, we limit the size if (answer.length() > 0x80000) { answer.append("..."); break; } if (signedLongs) { answer.append(i.next()); } else { answer.append(RoaringIntPacking.toUnsignedString(i.next())); } } answer.append("}"); return answer.toString(); } /** * * For better performance, consider the Use the {@link #forEach forEach} method. * * @return a custom iterator over set bits, the bits are traversed in ascending sorted order */ @Override public LongIterator getLongIterator() { final Iterator<Map.Entry<Integer, BitmapDataProvider>> it = highToBitmap.entrySet().iterator(); return toIterator(it, false); } protected LongIterator toIterator(final Iterator<Map.Entry<Integer, BitmapDataProvider>> it, final boolean reversed) { return new LongIterator() { protected int currentKey; protected IntIterator currentIt; @Override public boolean hasNext() { if (currentIt == null) { // Were initially empty if (!moveToNextEntry(it)) { return false; } } while (true) { if (currentIt.hasNext()) { return true; } else { if (!moveToNextEntry(it)) { return false; } } } } /** * * @param it the underlying iterator which has to be moved to next long * @return true if we MAY have more entries. false if there is definitely nothing more */ private boolean moveToNextEntry(Iterator<Map.Entry<Integer, BitmapDataProvider>> it) { if (it.hasNext()) { Map.Entry<Integer, BitmapDataProvider> next = it.next(); currentKey = next.getKey(); if (reversed) { currentIt = next.getValue().getReverseIntIterator(); } else { currentIt = next.getValue().getIntIterator(); } // We may have more long return true; } else { // We know there is nothing more return false; } } @Override public long next() { if (hasNext()) { return RoaringIntPacking.pack(currentKey, currentIt.next()); } else { throw new IllegalStateException("empty"); } } @Override public LongIterator clone() { throw new UnsupportedOperationException("TODO"); } }; } @Override public boolean contains(long x) { int high = RoaringIntPacking.high(x); BitmapDataProvider lowBitmap = highToBitmap.get(high); if (lowBitmap == null) { return false; } int low = RoaringIntPacking.low(x); return lowBitmap.contains(low); } @Override public int getSizeInBytes() { return (int) getLongSizeInBytes(); } @Override public long getLongSizeInBytes() { long size = 8; // Size of containers size += highToBitmap.values().stream().mapToLong(p -> p.getLongSizeInBytes()).sum(); // Size of Map data-structure: we consider each TreeMap entry costs 40 bytes // http://java-performance.info/memory-consumption-of-java-data-types-2/ size += 8L + 40L * highToBitmap.size(); // Size of (boxed) Integers used as keys size += 16L * highToBitmap.size(); // The cache impacts the size in heap size += 8L * sortedCumulatedCardinality.length; size += 4L * sortedHighs.length; return size; } @Override public boolean isEmpty() { return getLongCardinality() == 0L; } @Override public ImmutableLongBitmapDataProvider limit(long x) { throw new UnsupportedOperationException("TODO"); } /** * Use a run-length encoding where it is estimated as more space efficient * * @return whether a change was applied */ public boolean runOptimize() { boolean hasChanged = false; for (BitmapDataProvider lowBitmap : highToBitmap.values()) { if (lowBitmap instanceof RoaringBitmap) { hasChanged |= ((RoaringBitmap) lowBitmap).runOptimize(); } else if (lowBitmap instanceof MutableRoaringBitmap) { hasChanged |= ((MutableRoaringBitmap) lowBitmap).runOptimize(); } } return hasChanged; } /** * Serialize this bitmap. * * Unlike RoaringBitmap, there is no specification for now: it may change from onve java version * to another, and from one RoaringBitmap version to another. * * Consider calling {@link #runOptimize} before serialization to improve compression. * * The current bitmap is not modified. * * @param out the DataOutput stream * @throws IOException Signals that an I/O exception has occurred. */ @Override public void serialize(DataOutput out) throws IOException { // TODO: Should we transport the performance tweak 'doCacheCardinalities'? out.writeBoolean(signedLongs); out.writeInt(highToBitmap.size()); for (Entry<Integer, BitmapDataProvider> entry : highToBitmap.entrySet()) { out.writeInt(entry.getKey().intValue()); entry.getValue().serialize(out); } } /** * Deserialize (retrieve) this bitmap. * * Unlike RoaringBitmap, there is no specification for now: it may change from one java version to * another, and from one RoaringBitmap version to another. * * The current bitmap is overwritten. * * @param in the DataInput stream * @throws IOException Signals that an I/O exception has occurred. */ public void deserialize(DataInput in) throws IOException { this.clear(); signedLongs = in.readBoolean(); int nbHighs = in.readInt(); // Other NavigableMap may accept a target capacity if (signedLongs) { highToBitmap = new TreeMap<>(); } else { highToBitmap = new TreeMap<>(RoaringIntPacking.unsignedComparator()); } for (int i = 0; i < nbHighs; i++) { int high = in.readInt(); RoaringBitmap provider = new RoaringBitmap(); provider.deserialize(in); highToBitmap.put(high, provider); } resetPerfHelpers(); } @Override public long serializedSizeInBytes() { long nbBytes = 0L; // .writeBoolean for signedLongs boolean nbBytes += 1; // .writeInt for number of different high values nbBytes += 4; for (Entry<Integer, BitmapDataProvider> entry : highToBitmap.entrySet()) { // .writeInt for high nbBytes += 4; // The low bitmap size in bytes nbBytes += entry.getValue().serializedSizeInBytes(); } return nbBytes; } /** * reset to an empty bitmap; result occupies as much space a newly created bitmap. */ public void clear() { this.highToBitmap.clear(); resetPerfHelpers(); } /** * Return the set values as an array, if the cardinality is smaller than 2147483648. The long * values are in sorted order. * * @return array representing the set values. */ @Override public long[] toArray() { long cardinality = this.getLongCardinality(); if (cardinality > Integer.MAX_VALUE) { throw new IllegalStateException("The cardinality does not fit in an array"); } final long[] array = new long[(int) cardinality]; int pos = 0; LongIterator it = getLongIterator(); while (it.hasNext()) { array[pos++] = it.next(); } return array; } /** * Generate a bitmap with the specified values set to true. The provided longs values don't have * to be in sorted order, but it may be preferable to sort them from a performance point of view. * * @param dat set values * @return a new bitmap */ public static Roaring64NavigableMap bitmapOf(final long... dat) { final Roaring64NavigableMap ans = new Roaring64NavigableMap(); ans.add(dat); return ans; } /** * Set all the specified values to true. This can be expected to be slightly faster than calling * "add" repeatedly. The provided integers values don't have to be in sorted order, but it may be * preferable to sort them from a performance point of view. * * @param dat set values */ public void add(long... dat) { for (long oneLong : dat) { addLong(oneLong); } } /** * Add to the current bitmap all longs in [rangeStart,rangeEnd). * * @param rangeStart inclusive beginning of range * @param rangeEnd exclusive ending of range */ public void add(final long rangeStart, final long rangeEnd) { int startHigh = high(rangeStart); int startLow = low(rangeStart); int endHigh = high(rangeEnd); int endLow = low(rangeEnd); for (int high = startHigh; high <= endHigh; high++) { final int currentStartLow; if (startHigh == high) { // The whole range starts in this bucket currentStartLow = startLow; } else { // Add the bucket from the beginning currentStartLow = 0; } long startLowAsLong = Util.toUnsignedLong(currentStartLow); final long endLowAsLong; if (endHigh == high) { // The whole range ends in this bucket endLowAsLong = Util.toUnsignedLong(endLow); } else { // Add the bucket until the end: we have a +1 as, in RoaringBitmap.add(long,long), the end // is excluded endLowAsLong = Util.toUnsignedLong(-1) + 1; } if (endLowAsLong > startLowAsLong) { // Initialize the bitmap only if there is access data to write BitmapDataProvider bitmap = highToBitmap.get(high); if (bitmap == null) { bitmap = new MutableRoaringBitmap(); pushBitmapForHigh(high, bitmap); } if (bitmap instanceof RoaringBitmap) { ((RoaringBitmap) bitmap).add(startLowAsLong, endLowAsLong); } else if (bitmap instanceof MutableRoaringBitmap) { ((MutableRoaringBitmap) bitmap).add(startLowAsLong, endLowAsLong); } else { throw new UnsupportedOperationException("TODO. Not for " + bitmap.getClass()); } } } invalidateAboveHigh(startHigh); } @Override public LongIterator getReverseLongIterator() { return toIterator(highToBitmap.descendingMap().entrySet().iterator(), true); } @Override public void removeLong(long x) { int high = high(x); BitmapDataProvider bitmap = highToBitmap.get(high); if (bitmap != null) { int low = low(x); bitmap.remove(low); // Invalidate only if actually modified invalidateAboveHigh(high); } } @Override public void trim() { for (BitmapDataProvider bitmap : highToBitmap.values()) { bitmap.trim(); } } @Override public int hashCode() { return highToBitmap.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Roaring64NavigableMap other = (Roaring64NavigableMap) obj; return Objects.equals(highToBitmap, other.highToBitmap); } /** * Add the value if it is not already present, otherwise remove it. * * @param x long value */ public void flip(final long x) { int high = RoaringIntPacking.high(x); BitmapDataProvider lowBitmap = highToBitmap.get(high); if (lowBitmap == null) { // The value is not added: add it without any flip specific code addLong(x); } else { int low = RoaringIntPacking.low(x); // .flip is not in BitmapDataProvider contract // TODO Is it relevant to calling .flip with a cast? if (lowBitmap instanceof RoaringBitmap) { ((RoaringBitmap) lowBitmap).flip(low); } else if (lowBitmap instanceof MutableRoaringBitmap) { ((MutableRoaringBitmap) lowBitmap).flip(low); } else { // Fallback to a manual flip if (lowBitmap.contains(low)) { lowBitmap.remove(low); } else { lowBitmap.add(low); } } } invalidateAboveHigh(high); } }
Use BitmapDataProvider.add in Roaring64NavigableMap.add (#457)
RoaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
Use BitmapDataProvider.add in Roaring64NavigableMap.add (#457)
<ide><path>oaringBitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java <ide> pushBitmapForHigh(high, bitmap); <ide> } <ide> <del> if (bitmap instanceof RoaringBitmap) { <del> ((RoaringBitmap) bitmap).add(startLowAsLong, endLowAsLong); <del> } else if (bitmap instanceof MutableRoaringBitmap) { <del> ((MutableRoaringBitmap) bitmap).add(startLowAsLong, endLowAsLong); <del> } else { <del> throw new UnsupportedOperationException("TODO. Not for " + bitmap.getClass()); <del> } <add> bitmap.add(startLowAsLong, endLowAsLong); <ide> } <ide> } <ide>
JavaScript
mit
c3b335499a973d5bad29219da44cea87bc9752ca
0
medley-inc/simple-calendar,medley-inc/simple-calendar
/*global require, module, window*/ var Calendar = function (properties) { 'use strict'; properties = properties || {}; var calendar = {}, m = window.m || require("mithril"), actual = new Date(), functionType = Object.prototype.toString.call(function () {}); properties.time = properties.time === undefined ? true : properties.time; calendar.actual = m.prop(new Date(actual.getFullYear(), actual.getMonth(), actual.getDate())); calendar.now = properties.now ? m.prop(properties.now) : m.prop(new Date()); calendar.mindate = properties.mindate; if (calendar.mindate) { calendar.mindate_nt = new Date(calendar.mindate.getFullYear(), calendar.mindate.getMonth(), calendar.mindate.getDate()); } calendar.maxdate = properties.maxdate; if (calendar.maxdate) { calendar.maxdate_nt = new Date(calendar.maxdate.getFullYear(), calendar.maxdate.getMonth(), calendar.maxdate.getDate()); } if (properties.isDisabledCell) { calendar.isDisabledCell = properties.isDisabledCell; } if (properties.ondatechange) { calendar.ondatechange = properties.ondatechange; } if (calendar.mindate && +calendar.now() < +calendar.mindate) { calendar.now(calendar.mindate); } if (calendar.maxdate && +calendar.now() > +calendar.maxdate) { calendar.now(calendar.maxdate); } function daysInMonth(month, year) { return new Date(year, month, 0).getDate(); } function merge(obj1, obj2) { for (var p in obj2) { try { // Property in destination object set; update its value. if (obj2[p].constructor == Object) { obj1[p] = merge(obj1[p], obj2[p]); } else { obj1[p] = obj2[p]; } } catch (e) { // Property in destination object not set; create it and set its value. obj1[p] = obj2[p]; } } return obj1; } calendar.editYear = function(date) { var cal = this, year = date().getFullYear(); return m('span', [ m('span', { onclick: function () { calendar.editingYear(true); }, style: calendar.editingYear() ? 'display:none;' : 'cursor: pointer;text-decoration: underline;' }, year), m('input', { value: year, maxlength: 4, type: 'text', required: 'required', style: !calendar.editingYear() ? 'display:none;' : 'width: 40px;padding: 1px;', config: function (element) { if (calendar.editingYear()) { element.focus(); element.selectionStart = element.value.length; } }, onblur: function () { if (+this.value < 1800 || +this.value > 2999) { return; } if (cal.mindate && this.value < cal.mindate.getFullYear()) { return; } if (cal.maxdate && this.value > cal.maxdate.getFullYear()) { return; } cal.date().setFullYear(this.value); if (cal.ondatechange) { cal.ondatechange(cal.date()); } cal.editingYear(false); } }), ]); }; calendar.editingYear = m.prop(false); calendar.i18n = { monthsLong: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], daysLong: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], days: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], today: 'Today' }; calendar.small = properties.small; calendar.i18n = merge(calendar.i18n, properties.i18n); calendar.className = { wrapperClass: '.ui.row.four.column', controlWrapperClass: '', prevBtnClass: '', prevBtnITagClass: '.angle.double.left.icon', dateClass: '.center.aligned.eight.wide', nextBtnClass: '.right.aligned', nextBtnITagClass: '.angle.double.right.icon', tableWrapperClass: '.sixteen.wide', tableClass: '.ui.table.striped.celled.unstackable.seven.column.compact.small', timeClass: '.center.aligned.sixteen.wide' }; calendar.className = merge(calendar.className, properties.className); calendar.color = { today: '#FFFFFF', selected: '#FFFFFF', todayBg: '#00B5AD', selectedBg: '#5BBD72' }; calendar.color = merge(calendar.color, properties.color); calendar.formatCell = properties.formatCell || function (date) { var style = { cursor: 'pointer' }; var claz = '', cal = this; if (+date === +this.actual()) { style['background-color'] = calendar.color.todayBg; style.color = calendar.color.today; } if (+date === +this.value()) { style['background-color'] = calendar.color.selectedBg; style.color = calendar.color.selected; } if ((cal.mindate_nt && date < cal.mindate_nt) || (cal.maxdate_nt && date > cal.maxdate_nt) || (cal.isDisabledCell && cal.isDisabledCell(date))) { claz = '.disabled'; } return m('td.center.aligned' + claz, { style: style, onclick: function (e) { e.preventDefault(); cal.value(date); if (properties.onclick) { properties.onclick(cal.getDate()); } } }, [ claz.indexOf('.disabled') < 0 ? m('a[href="#"]', { style: style, onclick: function (e) { e.preventDefault(); } }, date.getDate()) : date.getDate() ]); }; calendar.goToDate = function (date) { if (Object.prototype.toString.call(date) === functionType) { date = date.date(); } calendar.now(date); if (calendar.mindate && +date < +calendar.mindate) { calendar.now(calendar.mindate); } if (calendar.maxdate && +date > +calendar.maxdate) { calendar.now(calendar.maxdate); } calendar.now = m.prop(new Date(calendar.now().getFullYear(), calendar.now().getMonth(), calendar.now().getDate())); calendar.date = m.prop(new Date(calendar.now().getFullYear(), calendar.now().getMonth(), 1)); calendar.hours = m.prop(date.getHours()); calendar.minutes = m.prop(date.getMinutes()); calendar.value = m.prop(calendar.now()); if (calendar.ondatechange) { calendar.ondatechange(calendar.date()); } }; calendar.getDate = function () { return new Date(this.value().getFullYear(), this.value().getMonth(), this.value().getDate(), this.hours(), this.minutes()); }; calendar.hours = properties.time ? m.prop(calendar.now().getHours()) : m.prop(0); calendar.minutes = properties.time ? m.prop(calendar.now().getMinutes()) : m.prop(0); calendar.now = m.prop(new Date(calendar.now().getFullYear(), calendar.now().getMonth(), calendar.now().getDate())); calendar.date = m.prop(new Date(calendar.now().getFullYear(), calendar.now().getMonth(), 1)); calendar.goToDate(properties.value || calendar.now());//m.prop(calendar.now()); calendar.setMaxDate = function (date) { m.startComputation(); calendar.maxdate = date || null; if (calendar.maxdate) { calendar.maxdate_nt = new Date(calendar.maxdate.getFullYear(), calendar.maxdate.getMonth(), calendar.maxdate.getDate()); } if (calendar.maxdate && +calendar.now() > +calendar.maxdate) { calendar.now(calendar.maxdate); } m.endComputation(); }; calendar.setMinDate = function (date) { m.startComputation(); calendar.mindate = date || null; if (date) { calendar.mindate_nt = new Date(calendar.mindate.getFullYear(), calendar.mindate.getMonth(), calendar.mindate.getDate()); } if (calendar.mindate && +calendar.now() < +calendar.mindate) { calendar.now(calendar.mindate); } m.endComputation(); }; calendar.view = function () { var date, dates, out = [], all = [], cal = this, next = true, year, previous = true, className = cal.className; //add dates //create data view date = new Date(cal.date().getFullYear(), cal.date().getMonth(), 1); year = date.getFullYear(); if (calendar.mindate && (cal.date().getFullYear() <= cal.mindate_nt.getFullYear())) { year = cal.mindate.getFullYear(); cal.date().setFullYear(year); if (cal.date().getMonth() - 1 < cal.mindate.getMonth()) { date.setMonth(cal.mindate.getMonth()); previous = false; } if (cal.date().getMonth() < cal.mindate.getMonth()) { cal.date().setMonth(cal.mindate.getMonth()); } } if (calendar.maxdate && (cal.date().getFullYear() >= cal.maxdate_nt.getFullYear())) { year = cal.maxdate.getFullYear(); cal.date().setFullYear(year); if (cal.date().getMonth() + 1 > cal.maxdate.getMonth()) { date.setMonth(cal.maxdate.getMonth()); cal.date().setMonth(cal.maxdate.getMonth()); next = false; } } date.setFullYear(year); date.setDate(date.getDate() - date.getDay()); for (var i = 1; i < 43; i += 1) { var d = date.getDate(); out.push(new Date(date)); date.setDate(d + 1); if (i % 7 === 0) { all.push(out); out = []; } } dates = m.prop(all); return m('.sm-calendar' + className.wrapperClass + (cal.small ? '.sm-calendar-small' : ''), { config: function (el, init) { if (!init) { if (el.parentNode.className.indexOf('grid') < 0) { el.className += " grid"; if (properties.pageclass) { el.className += ' page'; } el.className = el.className.replace('row',''); } } } }, [ m('.column' + className.controlWrapperClass, [ m('.column' + className.prevBtnClass, { style: 'padding-bottom: 0;' }, [ previous ? m('a[href=#].sm-calendar-arrow', { onclick: function (e) { e.preventDefault(); cal.date().setDate(cal.date().getDate() - daysInMonth(cal.date().getMonth(), cal.date().getFullYear())); if (cal.ondatechange) { cal.ondatechange(cal.date()); } } }, [ m('i.sm-calendar-arrow' + className.prevBtnITagClass), !cal.small ? m('span', cal.i18n.monthsLong[cal.date().getMonth() - 1 < 0 ? cal.i18n.months.length - 1 : cal.date().getMonth() - 1]) : '' ]) : '' ]), m('.column' + className.dateClass, { style: 'padding-bottom: 0;' }, [ calendar.editYear (cal.date), m('select', { style: 'border: 0;background: transparent;padding: 0 3px;cursor: pointer;-webkit-appearance: none;-moz-appearance: none;appearance: none;text-decoration: underline;display: inline;width: auto;', value: cal.date().getMonth(), config: function (el) { el.value = cal.date().getMonth(); }, onchange: function () { cal.date().setMonth(this.value); if (cal.ondatechange) { cal.ondatechange(cal.date()); } } }, cal.i18n.months.map(function (item, idx) { if (cal.mindate && (+cal.date().getFullYear() <= +cal.mindate_nt.getFullYear()) && idx < cal.mindate.getMonth()) { return ''; } if (cal.maxdate && (+cal.date().getFullYear() >= +cal.maxdate_nt.getFullYear()) && idx > cal.maxdate.getMonth()) { return ''; } return m('option[value=' + idx + ']', !cal.small ? cal.i18n.monthsLong[idx] : cal.i18n.months[idx]); })) ]), m('.column' + className.nextBtnClass, { style: 'padding-bottom: 0;' }, [ next ? m('a[href=#].sm-calendar-arrow', { onclick: function (e) { e.preventDefault(); cal.date().setMonth(cal.date().getMonth() + 1); if (cal.ondatechange) { cal.ondatechange(cal.date()); } } }, [ !cal.small ? m('span', cal.i18n.monthsLong[cal.date().getMonth() + 1 >= cal.i18n.months.length ? 0 : cal.date().getMonth() + 1]) : '', m('i.sm-calendar-arrow' + className.nextBtnITagClass) ]) : '' ]) ]), m('.column' + className.tableWrapperClass, [ m('table' + className.tableClass, [ m('thead', [ m('tr', cal.i18n.days.map(function (item) { return m('th', { style: cal.small ? 'padding: 0;' : '' }, item); })) ]), m('tbody', dates().map(function (row) { return m('tr', row.map(cal.formatCell.bind(cal))); })) ]) ]), m('.column' + className.timeClass, { style: 'padding-top: 0;' }, properties.time ? [ m('select', { style: 'border: 0;background: transparent;padding: 0 3px;cursor: pointer;-webkit-appearance: none;-moz-appearance: none;appearance: none;text-decoration: underline;display: inline;width: auto;', value: cal.hours(), onchange: m.withAttr('value', cal.hours), config: function (element) { cal.hours(element.value); } }, Array.apply(null, new Array(24)).map(function (item, idx) { idx += 1; if (cal.mindate && (+cal.value() <= +cal.mindate_nt) && idx < cal.mindate.getHours()) { return; } if (cal.maxdate && (+cal.value() >= +cal.maxdate_nt) && idx > cal.maxdate.getHours()) { return; } return m('option[value=' + idx + ']', idx < 10 ? ('0' + idx) : idx); })), ':', m('select', { style: 'border: 0;background: transparent;padding: 0 3px;cursor: pointer;-webkit-appearance: none;-moz-appearance: none;appearance: none;text-decoration: underline;display: inline;width: auto;', value: cal.minutes(), onchange: m.withAttr('value', cal.minutes), config: function (element) { cal.minutes(element.value); } }, Array.apply(null, new Array(60)).map(function (item, idx) { if (cal.mindate && (+cal.value() <= +cal.mindate_nt) && idx < cal.mindate.getMinutes()) { return; } if (cal.maxdate && (+cal.value() >= +cal.maxdate_nt) && idx > cal.maxdate.getMinutes()) { return; } return m('option[value=' + idx + ']', idx < 10 ? ('0' + idx) : idx); })), m('a[href="#"]', { style: 'padding: 0 3px;float:right;', onclick: function (e) { e.preventDefault(); cal.goToDate(new Date()); } }, cal.i18n.today) ] : [ m('a[href="#"]', { style: 'padding: 0 3px;float:right;', onclick: function (e) { e.preventDefault(); cal.goToDate(new Date()); } }, cal.i18n.today) ]) ]); }; return calendar; }; if (typeof module !== 'undefined' && module.exports) { module.exports = Calendar; }
Calendar.js
/*global require, module, window*/ var Calendar = function (properties) { 'use strict'; properties = properties || {}; var calendar = {}, m = window.m || require("mithril"), actual = new Date(), functionType = Object.prototype.toString.call(function () {}); properties.time = properties.time === undefined ? true : properties.time; calendar.actual = m.prop(new Date(actual.getFullYear(), actual.getMonth(), actual.getDate())); calendar.now = properties.now ? m.prop(properties.now) : m.prop(new Date()); calendar.mindate = properties.mindate; if (calendar.mindate) { calendar.mindate_nt = new Date(calendar.mindate.getFullYear(), calendar.mindate.getMonth(), calendar.mindate.getDate()); } calendar.maxdate = properties.maxdate; if (calendar.maxdate) { calendar.maxdate_nt = new Date(calendar.maxdate.getFullYear(), calendar.maxdate.getMonth(), calendar.maxdate.getDate()); } if (properties.isDisabledCell) { calendar.isDisabledCell = properties.isDisabledCell; } if (properties.ondatechange) { calendar.ondatechange = properties.ondatechange; } if (calendar.mindate && +calendar.now() < +calendar.mindate) { calendar.now(calendar.mindate); } if (calendar.maxdate && +calendar.now() > +calendar.maxdate) { calendar.now(calendar.maxdate); } function daysInMonth(month, year) { return new Date(year, month, 0).getDate(); } function merge(obj1, obj2) { for (var p in obj2) { try { // Property in destination object set; update its value. if (obj2[p].constructor == Object) { obj1[p] = merge(obj1[p], obj2[p]); } else { obj1[p] = obj2[p]; } } catch (e) { // Property in destination object not set; create it and set its value. obj1[p] = obj2[p]; } } return obj1; } calendar.editYear = function(date) { var cal = this, year = date().getFullYear(); return m('span', [ m('span', { onclick: function () { calendar.editingYear(true); }, style: calendar.editingYear() ? 'display:none;' : 'cursor: pointer;text-decoration: underline;' }, year), m('input', { value: year, maxlength: 4, type: 'text', required: 'required', style: !calendar.editingYear() ? 'display:none;' : 'width: 40px;padding: 1px;', config: function (element) { if (calendar.editingYear()) { element.focus(); element.selectionStart = element.value.length; } }, onblur: function () { if (+this.value < 1800 || +this.value > 2999) { return; } if (cal.mindate && this.value < cal.mindate.getFullYear()) { return; } if (cal.maxdate && this.value > cal.maxdate.getFullYear()) { return; } cal.date().setFullYear(this.value); if (cal.ondatechange) { cal.ondatechange(cal.date()); } cal.editingYear(false); } }), ]); }; calendar.editingYear = m.prop(false); calendar.i18n = { monthsLong: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], daysLong: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], days: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], today: 'Today' }; calendar.small = properties.small; calendar.i18n = merge(calendar.i18n, properties.i18n); calendar.className = { wrapperClass: '.ui.row.four.column', prevBtnClass: '', prevBtnITagClass: '.angle.double.left.icon', dateClass: '.center.aligned.eight.wide', nextBtnClass: '.right.aligned', nextBtnITagClass: '.angle.double.right.icon', tableWrapperClass: '.sixteen.wide', tableClass: '.ui.table.striped.celled.unstackable.seven.column.compact.small', timeClass: '.center.aligned.sixteen.wide' }; calendar.className = merge(calendar.className, properties.className); calendar.color = { today: '#FFFFFF', selected: '#FFFFFF', todayBg: '#00B5AD', selectedBg: '#5BBD72' }; calendar.color = merge(calendar.color, properties.color); calendar.formatCell = properties.formatCell || function (date) { var style = { cursor: 'pointer' }; var claz = '', cal = this; if (+date === +this.actual()) { style['background-color'] = calendar.color.todayBg; style.color = calendar.color.today; } if (+date === +this.value()) { style['background-color'] = calendar.color.selectedBg; style.color = calendar.color.selected; } if ((cal.mindate_nt && date < cal.mindate_nt) || (cal.maxdate_nt && date > cal.maxdate_nt) || (cal.isDisabledCell && cal.isDisabledCell(date))) { claz = '.disabled'; } return m('td.center.aligned' + claz, { style: style, onclick: function (e) { e.preventDefault(); cal.value(date); if (properties.onclick) { properties.onclick(cal.getDate()); } } }, [ claz.indexOf('.disabled') < 0 ? m('a[href="#"]', { style: style, onclick: function (e) { e.preventDefault(); } }, date.getDate()) : date.getDate() ]); }; calendar.goToDate = function (date) { if (Object.prototype.toString.call(date) === functionType) { date = date.date(); } calendar.now(date); if (calendar.mindate && +date < +calendar.mindate) { calendar.now(calendar.mindate); } if (calendar.maxdate && +date > +calendar.maxdate) { calendar.now(calendar.maxdate); } calendar.now = m.prop(new Date(calendar.now().getFullYear(), calendar.now().getMonth(), calendar.now().getDate())); calendar.date = m.prop(new Date(calendar.now().getFullYear(), calendar.now().getMonth(), 1)); calendar.hours = m.prop(date.getHours()); calendar.minutes = m.prop(date.getMinutes()); calendar.value = m.prop(calendar.now()); if (calendar.ondatechange) { calendar.ondatechange(calendar.date()); } }; calendar.getDate = function () { return new Date(this.value().getFullYear(), this.value().getMonth(), this.value().getDate(), this.hours(), this.minutes()); }; calendar.hours = properties.time ? m.prop(calendar.now().getHours()) : m.prop(0); calendar.minutes = properties.time ? m.prop(calendar.now().getMinutes()) : m.prop(0); calendar.now = m.prop(new Date(calendar.now().getFullYear(), calendar.now().getMonth(), calendar.now().getDate())); calendar.date = m.prop(new Date(calendar.now().getFullYear(), calendar.now().getMonth(), 1)); calendar.goToDate(properties.value || calendar.now());//m.prop(calendar.now()); calendar.setMaxDate = function (date) { m.startComputation(); calendar.maxdate = date || null; if (calendar.maxdate) { calendar.maxdate_nt = new Date(calendar.maxdate.getFullYear(), calendar.maxdate.getMonth(), calendar.maxdate.getDate()); } if (calendar.maxdate && +calendar.now() > +calendar.maxdate) { calendar.now(calendar.maxdate); } m.endComputation(); }; calendar.setMinDate = function (date) { m.startComputation(); calendar.mindate = date || null; if (date) { calendar.mindate_nt = new Date(calendar.mindate.getFullYear(), calendar.mindate.getMonth(), calendar.mindate.getDate()); } if (calendar.mindate && +calendar.now() < +calendar.mindate) { calendar.now(calendar.mindate); } m.endComputation(); }; calendar.view = function () { var date, dates, out = [], all = [], cal = this, next = true, year, previous = true, className = cal.className; //add dates //create data view date = new Date(cal.date().getFullYear(), cal.date().getMonth(), 1); year = date.getFullYear(); if (calendar.mindate && (cal.date().getFullYear() <= cal.mindate_nt.getFullYear())) { year = cal.mindate.getFullYear(); cal.date().setFullYear(year); if (cal.date().getMonth() - 1 < cal.mindate.getMonth()) { date.setMonth(cal.mindate.getMonth()); previous = false; } if (cal.date().getMonth() < cal.mindate.getMonth()) { cal.date().setMonth(cal.mindate.getMonth()); } } if (calendar.maxdate && (cal.date().getFullYear() >= cal.maxdate_nt.getFullYear())) { year = cal.maxdate.getFullYear(); cal.date().setFullYear(year); if (cal.date().getMonth() + 1 > cal.maxdate.getMonth()) { date.setMonth(cal.maxdate.getMonth()); cal.date().setMonth(cal.maxdate.getMonth()); next = false; } } date.setFullYear(year); date.setDate(date.getDate() - date.getDay()); for (var i = 1; i < 43; i += 1) { var d = date.getDate(); out.push(new Date(date)); date.setDate(d + 1); if (i % 7 === 0) { all.push(out); out = []; } } dates = m.prop(all); return m('.sm-calendar' + className.wrapperClass + (cal.small ? '.sm-calendar-small' : ''), { config: function (el, init) { if (!init) { if (el.parentNode.className.indexOf('grid') < 0) { el.className += " grid"; if (properties.pageclass) { el.className += ' page'; } el.className = el.className.replace('row',''); } } } }, [ m('.column' + className.prevBtnClass, { style: 'padding-bottom: 0;' }, [ previous ? m('a[href=#].sm-calendar-arrow', { onclick: function (e) { e.preventDefault(); cal.date().setDate(cal.date().getDate() - daysInMonth(cal.date().getMonth(), cal.date().getFullYear())); if (cal.ondatechange) { cal.ondatechange(cal.date()); } } }, [ m('i.sm-calendar-arrow' + className.prevBtnITagClass), !cal.small ? m('span', cal.i18n.monthsLong[cal.date().getMonth() - 1 < 0 ? cal.i18n.months.length - 1 : cal.date().getMonth() - 1]) : '' ]) : '' ]), m('.column' + className.dateClass, { style: 'padding-bottom: 0;' }, [ m('select', { style: 'border: 0;background: transparent;padding: 0 3px;cursor: pointer;-webkit-appearance: none;-moz-appearance: none;appearance: none;text-decoration: underline;display: inline;width: auto;', value: cal.date().getMonth(), config: function (el) { el.value = cal.date().getMonth(); }, onchange: function () { cal.date().setMonth(this.value); if (cal.ondatechange) { cal.ondatechange(cal.date()); } } }, cal.i18n.months.map(function (item, idx) { if (cal.mindate && (+cal.date().getFullYear() <= +cal.mindate_nt.getFullYear()) && idx < cal.mindate.getMonth()) { return ''; } if (cal.maxdate && (+cal.date().getFullYear() >= +cal.maxdate_nt.getFullYear()) && idx > cal.maxdate.getMonth()) { return ''; } return m('option[value=' + idx + ']', !cal.small ? cal.i18n.monthsLong[idx] : cal.i18n.months[idx]); })), calendar.editYear (cal.date) ]), m('.column' + className.nextBtnClass, { style: 'padding-bottom: 0;' }, [ next ? m('a[href=#].sm-calendar-arrow', { onclick: function (e) { e.preventDefault(); cal.date().setMonth(cal.date().getMonth() + 1); if (cal.ondatechange) { cal.ondatechange(cal.date()); } } }, [ !cal.small ? m('span', cal.i18n.monthsLong[cal.date().getMonth() + 1 >= cal.i18n.months.length ? 0 : cal.date().getMonth() + 1]) : '', m('i.sm-calendar-arrow' + className.nextBtnITagClass) ]) : '' ]), m('.column' + className.tableWrapperClass, [ m('table' + className.tableClass, [ m('thead', [ m('tr', cal.i18n.days.map(function (item) { return m('th', { style: cal.small ? 'padding: 0;' : '' }, item); })) ]), m('tbody', dates().map(function (row) { return m('tr', row.map(cal.formatCell.bind(cal))); })) ]) ]), m('.column' + className.timeClass, { style: 'padding-top: 0;' }, properties.time ? [ m('select', { style: 'border: 0;background: transparent;padding: 0 3px;cursor: pointer;-webkit-appearance: none;-moz-appearance: none;appearance: none;text-decoration: underline;display: inline;width: auto;', value: cal.hours(), onchange: m.withAttr('value', cal.hours), config: function (element) { cal.hours(element.value); } }, Array.apply(null, new Array(24)).map(function (item, idx) { idx += 1; if (cal.mindate && (+cal.value() <= +cal.mindate_nt) && idx < cal.mindate.getHours()) { return; } if (cal.maxdate && (+cal.value() >= +cal.maxdate_nt) && idx > cal.maxdate.getHours()) { return; } return m('option[value=' + idx + ']', idx < 10 ? ('0' + idx) : idx); })), ':', m('select', { style: 'border: 0;background: transparent;padding: 0 3px;cursor: pointer;-webkit-appearance: none;-moz-appearance: none;appearance: none;text-decoration: underline;display: inline;width: auto;', value: cal.minutes(), onchange: m.withAttr('value', cal.minutes), config: function (element) { cal.minutes(element.value); } }, Array.apply(null, new Array(60)).map(function (item, idx) { if (cal.mindate && (+cal.value() <= +cal.mindate_nt) && idx < cal.mindate.getMinutes()) { return; } if (cal.maxdate && (+cal.value() >= +cal.maxdate_nt) && idx > cal.maxdate.getMinutes()) { return; } return m('option[value=' + idx + ']', idx < 10 ? ('0' + idx) : idx); })), m('a[href="#"]', { style: 'padding: 0 3px;float:right;', onclick: function (e) { e.preventDefault(); cal.goToDate(new Date()); } }, cal.i18n.today) ] : [ m('a[href="#"]', { style: 'padding: 0 3px;float:right;', onclick: function (e) { e.preventDefault(); cal.goToDate(new Date()); } }, cal.i18n.today) ]) ]); }; return calendar; }; if (typeof module !== 'undefined' && module.exports) { module.exports = Calendar; }
add control wrapper
Calendar.js
add control wrapper
<ide><path>alendar.js <ide> <ide> calendar.className = { <ide> wrapperClass: '.ui.row.four.column', <add> controlWrapperClass: '', <ide> prevBtnClass: '', <ide> prevBtnITagClass: '.angle.double.left.icon', <ide> dateClass: '.center.aligned.eight.wide', <ide> } <ide> } <ide> }, [ <del> m('.column' + className.prevBtnClass, { <del> style: 'padding-bottom: 0;' <del> }, [ <del> previous ? m('a[href=#].sm-calendar-arrow', { <del> onclick: function (e) { <del> e.preventDefault(); <del> cal.date().setDate(cal.date().getDate() - daysInMonth(cal.date().getMonth(), cal.date().getFullYear())); <del> if (cal.ondatechange) { <del> cal.ondatechange(cal.date()); <del> } <del> } <add> m('.column' + className.controlWrapperClass, [ <add> m('.column' + className.prevBtnClass, { <add> style: 'padding-bottom: 0;' <ide> }, [ <del> m('i.sm-calendar-arrow' + className.prevBtnITagClass), <del> !cal.small ? m('span', cal.i18n.monthsLong[cal.date().getMonth() - 1 < 0 ? cal.i18n.months.length - 1 : cal.date().getMonth() - 1]) : '' <del> ]) : '' <del> ]), <del> m('.column' + className.dateClass, { <del> style: 'padding-bottom: 0;' <del> }, [ <del> m('select', { <del> style: 'border: 0;background: transparent;padding: 0 3px;cursor: pointer;-webkit-appearance: none;-moz-appearance: none;appearance: none;text-decoration: underline;display: inline;width: auto;', <del> value: cal.date().getMonth(), <del> config: function (el) { <del> el.value = cal.date().getMonth(); <del> }, <del> onchange: function () { <del> cal.date().setMonth(this.value); <del> if (cal.ondatechange) { <del> cal.ondatechange(cal.date()); <del> } <del> } <del> }, cal.i18n.months.map(function (item, idx) { <del> if (cal.mindate && (+cal.date().getFullYear() <= +cal.mindate_nt.getFullYear()) && idx < cal.mindate.getMonth()) { <del> return ''; <del> } <del> if (cal.maxdate && (+cal.date().getFullYear() >= +cal.maxdate_nt.getFullYear()) && idx > cal.maxdate.getMonth()) { <del> return ''; <del> } <del> return m('option[value=' + idx + ']', !cal.small ? cal.i18n.monthsLong[idx] : cal.i18n.months[idx]); <del> })), <del> calendar.editYear (cal.date) <del> ]), <del> m('.column' + className.nextBtnClass, { <del> style: 'padding-bottom: 0;' <del> }, [ <del> next ? m('a[href=#].sm-calendar-arrow', { <del> onclick: function (e) { <del> e.preventDefault(); <del> cal.date().setMonth(cal.date().getMonth() + 1); <del> if (cal.ondatechange) { <del> cal.ondatechange(cal.date()); <del> } <del> } <add> previous ? m('a[href=#].sm-calendar-arrow', { <add> onclick: function (e) { <add> e.preventDefault(); <add> cal.date().setDate(cal.date().getDate() - daysInMonth(cal.date().getMonth(), cal.date().getFullYear())); <add> if (cal.ondatechange) { <add> cal.ondatechange(cal.date()); <add> } <add> } <add> }, [ <add> m('i.sm-calendar-arrow' + className.prevBtnITagClass), <add> !cal.small ? m('span', cal.i18n.monthsLong[cal.date().getMonth() - 1 < 0 ? cal.i18n.months.length - 1 : cal.date().getMonth() - 1]) : '' <add> ]) : '' <add> ]), <add> m('.column' + className.dateClass, { <add> style: 'padding-bottom: 0;' <ide> }, [ <del> !cal.small ? m('span', cal.i18n.monthsLong[cal.date().getMonth() + 1 >= cal.i18n.months.length ? 0 : cal.date().getMonth() + 1]) : '', <del> m('i.sm-calendar-arrow' + className.nextBtnITagClass) <del> ]) : '' <add> calendar.editYear (cal.date), <add> m('select', { <add> style: 'border: 0;background: transparent;padding: 0 3px;cursor: pointer;-webkit-appearance: none;-moz-appearance: none;appearance: none;text-decoration: underline;display: inline;width: auto;', <add> value: cal.date().getMonth(), <add> config: function (el) { <add> el.value = cal.date().getMonth(); <add> }, <add> onchange: function () { <add> cal.date().setMonth(this.value); <add> if (cal.ondatechange) { <add> cal.ondatechange(cal.date()); <add> } <add> } <add> }, cal.i18n.months.map(function (item, idx) { <add> if (cal.mindate && (+cal.date().getFullYear() <= +cal.mindate_nt.getFullYear()) && idx < cal.mindate.getMonth()) { <add> return ''; <add> } <add> if (cal.maxdate && (+cal.date().getFullYear() >= +cal.maxdate_nt.getFullYear()) && idx > cal.maxdate.getMonth()) { <add> return ''; <add> } <add> return m('option[value=' + idx + ']', !cal.small ? cal.i18n.monthsLong[idx] : cal.i18n.months[idx]); <add> })) <add> ]), <add> m('.column' + className.nextBtnClass, { <add> style: 'padding-bottom: 0;' <add> }, [ <add> next ? m('a[href=#].sm-calendar-arrow', { <add> onclick: function (e) { <add> e.preventDefault(); <add> cal.date().setMonth(cal.date().getMonth() + 1); <add> if (cal.ondatechange) { <add> cal.ondatechange(cal.date()); <add> } <add> } <add> }, [ <add> !cal.small ? m('span', cal.i18n.monthsLong[cal.date().getMonth() + 1 >= cal.i18n.months.length ? 0 : cal.date().getMonth() + 1]) : '', <add> m('i.sm-calendar-arrow' + className.nextBtnITagClass) <add> ]) : '' <add> ]) <ide> ]), <ide> m('.column' + className.tableWrapperClass, [ <ide> m('table' + className.tableClass, [
Java
mit
978d374ceb38e6fa1ea677db27b4ac0e976463ce
0
testcontainers/testcontainers-java,rnorth/test-containers,rnorth/test-containers,testcontainers/testcontainers-java,outofcoffee/testcontainers-java,testcontainers/testcontainers-java,rnorth/test-containers,outofcoffee/testcontainers-java,outofcoffee/testcontainers-java
package org.testcontainers.containers; import com.github.dockerjava.api.command.CreateNetworkCmd; import lombok.Builder; import lombok.Getter; import lombok.Singular; import org.junit.rules.ExternalResource; import org.junit.rules.TestRule; import org.testcontainers.DockerClientFactory; import org.testcontainers.utility.ResourceReaper; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; public interface Network extends AutoCloseable, TestRule { Network SHARED = new NetworkImpl(false, null, Collections.emptySet(), null) { @Override public void close() { // Do not allow users to close SHARED network, only ResourceReaper is allowed to close (destroy) it } }; String getId(); @Override void close(); static Network newNetwork() { return builder().build(); } static NetworkImpl.NetworkImplBuilder builder() { return NetworkImpl.builder(); } @Builder @Getter class NetworkImpl extends ExternalResource implements Network { private final String name = UUID.randomUUID().toString(); private Boolean enableIpv6; private String driver; @Singular private Set<Consumer<CreateNetworkCmd>> createNetworkCmdModifiers; private String id; private final AtomicBoolean initialized = new AtomicBoolean(); @Override public synchronized String getId() { if (initialized.compareAndSet(false, true)) { id = create(); } return id; } private String create() { CreateNetworkCmd createNetworkCmd = DockerClientFactory.instance().client().createNetworkCmd(); createNetworkCmd.withName(name); createNetworkCmd.withCheckDuplicate(true); if (enableIpv6 != null) { createNetworkCmd.withEnableIpv6(enableIpv6); } if (driver != null) { createNetworkCmd.withDriver(driver); } for (Consumer<CreateNetworkCmd> consumer : createNetworkCmdModifiers) { consumer.accept(createNetworkCmd); } Map<String, String> labels = createNetworkCmd.getLabels(); labels = new HashMap<>(labels != null ? labels : Collections.emptyMap()); labels.putAll(DockerClientFactory.DEFAULT_LABELS); createNetworkCmd.withLabels(labels); return createNetworkCmd.exec().getId(); } @Override protected void after() { close(); } @Override public void close() { if (initialized.getAndSet(false)) { ResourceReaper.instance().removeNetworkById(id); } } } }
core/src/main/java/org/testcontainers/containers/Network.java
package org.testcontainers.containers; import com.github.dockerjava.api.command.CreateNetworkCmd; import lombok.Builder; import lombok.Getter; import lombok.Singular; import org.junit.rules.ExternalResource; import org.junit.rules.TestRule; import org.testcontainers.DockerClientFactory; import org.testcontainers.utility.ResourceReaper; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; public interface Network extends AutoCloseable, TestRule { Network SHARED = new NetworkImpl(false, null, Collections.emptySet(), null) { @Override public void close() { // Do not allow users to close SHARED network, only ResourceReaper is allowed to close (destroy) it } }; String getId(); static Network newNetwork() { return builder().build(); } static NetworkImpl.NetworkImplBuilder builder() { return NetworkImpl.builder(); } @Builder @Getter class NetworkImpl extends ExternalResource implements Network { private final String name = UUID.randomUUID().toString(); private Boolean enableIpv6; private String driver; @Singular private Set<Consumer<CreateNetworkCmd>> createNetworkCmdModifiers; private String id; private final AtomicBoolean initialized = new AtomicBoolean(); @Override public synchronized String getId() { if (initialized.compareAndSet(false, true)) { id = create(); } return id; } private String create() { CreateNetworkCmd createNetworkCmd = DockerClientFactory.instance().client().createNetworkCmd(); createNetworkCmd.withName(name); createNetworkCmd.withCheckDuplicate(true); if (enableIpv6 != null) { createNetworkCmd.withEnableIpv6(enableIpv6); } if (driver != null) { createNetworkCmd.withDriver(driver); } for (Consumer<CreateNetworkCmd> consumer : createNetworkCmdModifiers) { consumer.accept(createNetworkCmd); } Map<String, String> labels = createNetworkCmd.getLabels(); labels = new HashMap<>(labels != null ? labels : Collections.emptyMap()); labels.putAll(DockerClientFactory.DEFAULT_LABELS); createNetworkCmd.withLabels(labels); return createNetworkCmd.exec().getId(); } @Override protected void after() { close(); } @Override public void close() { if (initialized.getAndSet(false)) { ResourceReaper.instance().removeNetworkById(id); } } } }
#1389 Override close method without throws statement (#1392)
core/src/main/java/org/testcontainers/containers/Network.java
#1389 Override close method without throws statement (#1392)
<ide><path>ore/src/main/java/org/testcontainers/containers/Network.java <ide> }; <ide> <ide> String getId(); <add> <add> @Override <add> void close(); <ide> <ide> static Network newNetwork() { <ide> return builder().build();
Java
mit
168a65bf3635f8a047f271aec062acc1cbe9206c
0
yusufshakeel/Java-Image-Processing-Project
/** * File: Negative.java * * Description: * Convert color image to negative. * * @author Yusuf Shakeel * Date: 27-01-2014 mon * * www.github.com/yusufshakeel/Java-Image-Processing-Project */ import java.io.File; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class Negative{ public static void main(String args[])throws IOException{ BufferedImage img = null; File f = null; //read image try{ f = new File("D:\\Image\\Taj.jpg"); img = ImageIO.read(f); }catch(IOException e){ System.out.println(e); } //get image width and height int width = img.getWidth(); int height = img.getHeight(); //convert to negative for(int y = 0; y < height; y++){ for(int x = 0; x < width; x++){ int p = img.getRGB(x,y); int a = (p>>24)&0xff; int r = (p>>16)&0xff; int g = (p>>8)&0xff; int b = p&0xff; //subtract RGB from 255 r = 255 - r; g = 255 - g; b = 255 - b; //set new RGB value p = (a<<24) | (r<<16) | (g<<8) | b; img.setRGB(x, y, p); } } //write image try{ f = new File("D:\\Image\\Output.jpg"); ImageIO.write(img, "jpg", f); }catch(IOException e){ System.out.println(e); } }//main() ends here }//class ends here
example/Negative.java
/** * File: Negative.java * * Description: * Convert color image to negative. * * @author Yusuf Shakeel * Date: 27-01-2014 mon * * www.github.com/yusufshakeel/Java-Image-Processing-Project * */ import java.io.File; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class Negative{ public static void main(String args[])throws IOException{ BufferedImage img = null; File f = null; //read image try{ f = new File("D:\\Image\\Taj.jpg"); img = ImageIO.read(f); }catch(IOException e){ System.out.println(e); } //get image width and height int width = img.getWidth(); int height = img.getHeight(); //convert to negative for(int y = 0; y < height; y++){ for(int x = 0; x < width; x++){ int p = img.getRGB(x,y); int a = (p>>24)&0xff; int r = (p>>16)&0xff; int g = (p>>8)&0xff; int b = p&0xff; //subtract RGB from 255 r = 255 - r; g = 255 - g; b = 255 - b; //set new RGB value p = (a<<24) | (r<<16) | (g<<8) | b; img.setRGB(x, y, p); } } //write image try{ f = new File("D:\\Image\\Output.jpg"); ImageIO.write(img, "jpg", f); }catch(IOException e){ System.out.println(e); } }//main() ends here }//class ends here
update
example/Negative.java
update
<ide><path>xample/Negative.java <ide> * Date: 27-01-2014 mon <ide> * <ide> * www.github.com/yusufshakeel/Java-Image-Processing-Project <del> * <ide> */ <ide> <ide> import java.io.File;
Java
apache-2.0
8ccc365bcf12283c639f99781453992b03326c1d
0
squarY/voldemort,jalkjaer/voldemort,null-exception/voldemort,bitti/voldemort,jalkjaer/voldemort,dallasmarlow/voldemort,rickbw/voldemort,squarY/voldemort,voldemort/voldemort,arunthirupathi/voldemort,arunthirupathi/voldemort,HB-SI/voldemort,HB-SI/voldemort,null-exception/voldemort,jwlent55/voldemort,jwlent55/voldemort,medallia/voldemort,jeffpc/voldemort,voldemort/voldemort,HB-SI/voldemort,LeoYao/voldemort,jwlent55/voldemort,jalkjaer/voldemort,cshaxu/voldemort,LeoYao/voldemort,arunthirupathi/voldemort,arunthirupathi/voldemort,medallia/voldemort,jeffpc/voldemort,FelixGV/voldemort,squarY/voldemort,cshaxu/voldemort,rickbw/voldemort,jwlent55/voldemort,jeffpc/voldemort,bhasudha/voldemort,FelixGV/voldemort,mabh/voldemort,arunthirupathi/voldemort,FelixGV/voldemort,birendraa/voldemort,squarY/voldemort,gnb/voldemort,stotch/voldemort,LeoYao/voldemort,arunthirupathi/voldemort,PratikDeshpande/voldemort,FelixGV/voldemort,medallia/voldemort,FelixGV/voldemort,mabh/voldemort,LeoYao/voldemort,rickbw/voldemort,stotch/voldemort,bhasudha/voldemort,stotch/voldemort,jwlent55/voldemort,rickbw/voldemort,rickbw/voldemort,voldemort/voldemort,jalkjaer/voldemort,gnb/voldemort,FelixGV/voldemort,arunthirupathi/voldemort,bhasudha/voldemort,dallasmarlow/voldemort,null-exception/voldemort,null-exception/voldemort,PratikDeshpande/voldemort,bitti/voldemort,HB-SI/voldemort,gnb/voldemort,squarY/voldemort,FelixGV/voldemort,medallia/voldemort,medallia/voldemort,mabh/voldemort,gnb/voldemort,gnb/voldemort,squarY/voldemort,jeffpc/voldemort,voldemort/voldemort,PratikDeshpande/voldemort,squarY/voldemort,rickbw/voldemort,HB-SI/voldemort,stotch/voldemort,birendraa/voldemort,stotch/voldemort,dallasmarlow/voldemort,bitti/voldemort,bhasudha/voldemort,PratikDeshpande/voldemort,medallia/voldemort,dallasmarlow/voldemort,voldemort/voldemort,bitti/voldemort,jeffpc/voldemort,jalkjaer/voldemort,cshaxu/voldemort,birendraa/voldemort,cshaxu/voldemort,dallasmarlow/voldemort,bitti/voldemort,gnb/voldemort,jeffpc/voldemort,mabh/voldemort,jwlent55/voldemort,mabh/voldemort,cshaxu/voldemort,bitti/voldemort,null-exception/voldemort,stotch/voldemort,PratikDeshpande/voldemort,null-exception/voldemort,LeoYao/voldemort,mabh/voldemort,bhasudha/voldemort,voldemort/voldemort,jalkjaer/voldemort,cshaxu/voldemort,HB-SI/voldemort,birendraa/voldemort,bitti/voldemort,voldemort/voldemort,jalkjaer/voldemort,bhasudha/voldemort,PratikDeshpande/voldemort,LeoYao/voldemort,birendraa/voldemort,birendraa/voldemort,dallasmarlow/voldemort
/* * Copyright 2010 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.store.routed; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import voldemort.store.InsufficientOperationalNodesException; import voldemort.store.routed.action.AcknowledgeResponse; import voldemort.store.routed.action.Action; /** * A Pipeline is the main conduit through which an {@link Action} is run. An * {@link Action} is executed in response to the Pipeline receiving an event. * The majority of the events are self-initiated from within the Pipeline * itself. The only case thus-far where external entities create events are in * response to asynchronous responses from servers ({@link AcknowledgeResponse}, * for example). A {@link Response} instance is created on completion of an * asynchronous request and is fed back into the Pipeline where an appropriate * 'response handler' action is executed. * * <p/> * * A Pipeline instance is created per-request inside {@link RoutedStore}. This * is due to the fact that it includes internal state, specific to each * operation request (get, getAll, getVersions, put, and delete) invocation. * * <p/> * * Here is some example code for using a Pipeline: * * <pre> * pipeline.setEventActions(eventActions); * pipeline.addEvent(Event.STARTED); * pipeline.processEvents(timeoutMs, TimeUnit.MILLISECONDS); * * if(pipelineData.getFatalError() != null) * throw pipelineData.getFatalError(); * * for(Response&lt;?, ?&gt; response: pipelineData.getResponses()) { * // Do something with results... * } * </pre> */ public class Pipeline { public enum Event { STARTED, CONFIGURED, COMPLETED, INSUFFICIENT_SUCCESSES, RESPONSE_RECEIVED, RESPONSES_RECEIVED, NOP, ERROR, MASTER_DETERMINED; } public enum Operation { GET, GET_ALL, GET_VERSIONS, PUT, DELETE; public String getSimpleName() { return toString().toLowerCase().replace("_", " "); } } private final Operation operation; private final BlockingQueue<EventData> eventDataQueue; private Map<Event, Action> eventActions; private final Logger logger = Logger.getLogger(getClass()); public Pipeline(Operation operation) { this.operation = operation; this.eventDataQueue = new LinkedBlockingQueue<EventData>(); } public Operation getOperation() { return operation; } public Map<Event, Action> getEventActions() { return eventActions; } /** * Assigns the mapping of events to actions. When a given event is received, * it is expected that there is an action to handle it. * * @param eventActions Mapping of events to action handlers */ public void setEventActions(Map<Event, Action> eventActions) { this.eventActions = eventActions; } /** * Add an event to the queue. It will be processed in the order received. * * @param event Event */ public void addEvent(Event event) { addEvent(event, null); } /** * Add an event to the queue with event-specific data. It will be processed * in the order received. * * @param event Event * @param data Event-specific data */ public void addEvent(Event event, Object data) { if(logger.isTraceEnabled()) logger.trace("Adding event " + event); eventDataQueue.add(new EventData(event, data)); } /** * Process events in the order as they were received. * * <p/> * * The overall time to process the events must be within the bounds of the * timeout or an {@link InsufficientOperationalNodesException} will be * thrown. * * @param timeout Timeout * @param unit Unit of timeout */ public void processEvents(long timeout, TimeUnit unit) { long start = System.nanoTime(); while(true) { EventData eventData = null; try { eventData = eventDataQueue.poll(timeout, unit); } catch(InterruptedException e) { throw new InsufficientOperationalNodesException(operation.getSimpleName() + " operation interrupted!", e); } if((System.nanoTime() - start) > unit.toNanos(timeout)) throw new InsufficientOperationalNodesException(operation.getSimpleName() + " operation interrupted!"); if(eventData.event.equals(Event.ERROR)) { if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, events complete due to error"); break; } else if(eventData.event.equals(Event.COMPLETED)) { if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, events complete"); break; } if(eventData.event.equals(Event.NOP)) continue; Action action = eventActions.get(eventData.event); if(action == null) throw new IllegalStateException("action was null for event " + eventData.event); if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, action " + action.getClass().getSimpleName() + " to handle " + eventData.event + " event"); action.execute(this, eventData.data); } } private static class EventData { private final Event event; private final Object data; private EventData(Event event, Object data) { this.event = event; this.data = data; } } }
src/java/voldemort/store/routed/Pipeline.java
/* * Copyright 2010 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.store.routed; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import voldemort.store.InsufficientOperationalNodesException; import voldemort.store.routed.action.AcknowledgeResponse; import voldemort.store.routed.action.Action; /** * A Pipeline is the main conduit through which an {@link Action} is run. An * {@link Action} is executed in response to the Pipeline receiving an event. * The majority of the events are self-initiated from within the Pipeline * itself. The only case thus-far where external entities create events are in * response to asynchronous responses from servers ({@link AcknowledgeResponse}, * for example). A {@link Response} instance is created on completion of an * asynchronous request and is fed back into the Pipeline where an appropriate * 'response handler' action is executed. * * A Pipeline instance is created per-request inside {@link RoutedStore}. This * is due to the fact that it includes internal state, specific to each * operation request (get, getAll, getVersions, put, and delete) invocation. */ public class Pipeline { public enum Event { STARTED, CONFIGURED, COMPLETED, INSUFFICIENT_SUCCESSES, RESPONSE_RECEIVED, RESPONSES_RECEIVED, NOP, ERROR, MASTER_DETERMINED; } public enum Operation { GET, GET_ALL, GET_VERSIONS, PUT, DELETE; public String getSimpleName() { return toString().toLowerCase().replace("_", " "); } } private final Operation operation; private final BlockingQueue<EventData> eventDataQueue; private Map<Event, Action> eventActions; private final Logger logger = Logger.getLogger(getClass()); public Pipeline(Operation operation) { this.operation = operation; this.eventDataQueue = new LinkedBlockingQueue<EventData>(); } public Operation getOperation() { return operation; } public Map<Event, Action> getEventActions() { return eventActions; } /** * Assigns the mapping of events to actions. When a given event is received, * it is expected that there is an action to handle it. * * @param eventActions Mapping of events to action handlers */ public void setEventActions(Map<Event, Action> eventActions) { this.eventActions = eventActions; } /** * Add an event to the queue. It will be processed in the order received. * * @param event Event */ public void addEvent(Event event) { addEvent(event, null); } /** * Add an event to the queue with event-specific data. It will be processed * in the order received. * * @param event Event * @param data Event-specific data */ public void addEvent(Event event, Object data) { if(logger.isTraceEnabled()) logger.trace("Adding event " + event); eventDataQueue.add(new EventData(event, data)); } /** * Process events in the order as they were received. * * <p/> * * The overall time to process the events must be within the bounds of the * timeout or an {@link InsufficientOperationalNodesException} will be * thrown. * * @param timeout Timeout * @param unit Unit of timeout */ public void processEvents(long timeout, TimeUnit unit) { long start = System.nanoTime(); while(true) { EventData eventData = null; try { eventData = eventDataQueue.poll(timeout, unit); } catch(InterruptedException e) { throw new InsufficientOperationalNodesException(operation.getSimpleName() + " operation interrupted!", e); } if((System.nanoTime() - start) > unit.toNanos(timeout)) throw new InsufficientOperationalNodesException(operation.getSimpleName() + " operation interrupted!"); if(eventData.event.equals(Event.ERROR)) { if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, events complete due to error"); break; } else if(eventData.event.equals(Event.COMPLETED)) { if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, events complete"); break; } if(eventData.event.equals(Event.NOP)) continue; Action action = eventActions.get(eventData.event); if(action == null) throw new IllegalStateException("action was null for event " + eventData.event); if(logger.isTraceEnabled()) logger.trace(operation.getSimpleName() + " request, action " + action.getClass().getSimpleName() + " to handle " + eventData.event + " event"); action.execute(this, eventData.data); } } private static class EventData { private final Event event; private final Object data; private EventData(Event event, Object data) { this.event = event; this.data = data; } } }
Comments.
src/java/voldemort/store/routed/Pipeline.java
Comments.
<ide><path>rc/java/voldemort/store/routed/Pipeline.java <ide> * asynchronous request and is fed back into the Pipeline where an appropriate <ide> * 'response handler' action is executed. <ide> * <add> * <p/> <add> * <ide> * A Pipeline instance is created per-request inside {@link RoutedStore}. This <ide> * is due to the fact that it includes internal state, specific to each <ide> * operation request (get, getAll, getVersions, put, and delete) invocation. <add> * <add> * <p/> <add> * <add> * Here is some example code for using a Pipeline: <add> * <add> * <pre> <add> * pipeline.setEventActions(eventActions); <add> * pipeline.addEvent(Event.STARTED); <add> * pipeline.processEvents(timeoutMs, TimeUnit.MILLISECONDS); <add> * <add> * if(pipelineData.getFatalError() != null) <add> * throw pipelineData.getFatalError(); <add> * <add> * for(Response&lt;?, ?&gt; response: pipelineData.getResponses()) { <add> * // Do something with results... <add> * } <add> * </pre> <ide> */ <ide> <ide> public class Pipeline {
Java
mit
54051da5f7a29c91bf9b59fe89cc3a70a3379460
0
facebookarchive/AntennaPod,jimulabs/AntennaPod-mirror,gaohongyuan/AntennaPod,udif/AntennaPod,gaohongyuan/AntennaPod,wooi/AntennaPod,wangjun/AntennaPod,drabux/AntennaPod,orelogo/AntennaPod,TomHennen/AntennaPod,gk23/AntennaPod,wskplho/AntennaPod,mxttie/AntennaPod,SpicyCurry/AntennaPod,waylife/AntennaPod,volhol/AntennaPod,LTUvac/AntennaPod,the100rabh/AntennaPod,orelogo/AntennaPod,gk23/AntennaPod,johnjohndoe/AntennaPod,hgl888/AntennaPod,mxttie/AntennaPod,gaohongyuan/AntennaPod,hgl888/AntennaPod,mfietz/AntennaPod,wooi/AntennaPod,wangjun/AntennaPod,johnjohndoe/AntennaPod,queenp/AntennaPod,wskplho/AntennaPod,volhol/AntennaPod,waylife/AntennaPod,the100rabh/AntennaPod,volhol/AntennaPod,keunes/AntennaPod,keunes/AntennaPod,hgl888/AntennaPod,mfietz/AntennaPod,drabux/AntennaPod,wangjun/AntennaPod,jimulabs/AntennaPod-mirror,mfietz/AntennaPod,TimB0/AntennaPod,corecode/AntennaPod,domingos86/AntennaPod,udif/AntennaPod,twiceyuan/AntennaPod,keunes/AntennaPod,keunes/AntennaPod,the100rabh/AntennaPod,wskplho/AntennaPod,gaohongyuan/AntennaPod,johnjohndoe/AntennaPod,LTUvac/AntennaPod,twiceyuan/AntennaPod,ChaoticMind/AntennaPod,richq/AntennaPod,richq/AntennaPod,twiceyuan/AntennaPod,mxttie/AntennaPod,jimulabs/AntennaPod-mirror,orelogo/AntennaPod,gk23/AntennaPod,queenp/AntennaPod,drabux/AntennaPod,TimB0/AntennaPod,johnjohndoe/AntennaPod,facebookarchive/AntennaPod,LTUvac/AntennaPod,domingos86/AntennaPod,corecode/AntennaPod,samarone/AntennaPod,twiceyuan/AntennaPod,wooi/AntennaPod,cdysthe/AntennaPod,corecode/AntennaPod,domingos86/AntennaPod,drabux/AntennaPod,facebookarchive/AntennaPod,waylife/AntennaPod,queenp/AntennaPod,richq/AntennaPod,TimB0/AntennaPod,cdysthe/AntennaPod,ChaoticMind/AntennaPod,domingos86/AntennaPod,corecode/AntennaPod,samarone/AntennaPod,wooi/AntennaPod,orelogo/AntennaPod,SpicyCurry/AntennaPod,samarone/AntennaPod,wangjun/AntennaPod,udif/AntennaPod,udif/AntennaPod,cdysthe/AntennaPod,gk23/AntennaPod,SpicyCurry/AntennaPod,TomHennen/AntennaPod,LTUvac/AntennaPod,TimB0/AntennaPod,the100rabh/AntennaPod,TomHennen/AntennaPod,mxttie/AntennaPod,TomHennen/AntennaPod,SpicyCurry/AntennaPod,ChaoticMind/AntennaPod,mfietz/AntennaPod,richq/AntennaPod
package de.danoeh.antennapod.service.playback; import android.annotation.SuppressLint; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.*; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.AudioManager; import android.media.MediaMetadataRetriever; import android.media.MediaPlayer; import android.media.RemoteControlClient; import android.media.RemoteControlClient.MetadataEditor; import android.os.AsyncTask; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.util.Pair; import android.view.KeyEvent; import android.view.SurfaceHolder; import de.danoeh.antennapod.AppConfig; import de.danoeh.antennapod.PodcastApp; import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.AudioplayerActivity; import de.danoeh.antennapod.activity.VideoplayerActivity; import de.danoeh.antennapod.feed.Chapter; import de.danoeh.antennapod.feed.FeedItem; import de.danoeh.antennapod.feed.FeedMedia; import de.danoeh.antennapod.feed.MediaType; import de.danoeh.antennapod.preferences.PlaybackPreferences; import de.danoeh.antennapod.preferences.UserPreferences; import de.danoeh.antennapod.receiver.MediaButtonReceiver; import de.danoeh.antennapod.receiver.PlayerWidget; import de.danoeh.antennapod.storage.DBTasks; import de.danoeh.antennapod.storage.DBWriter; import de.danoeh.antennapod.util.BitmapDecoder; import de.danoeh.antennapod.util.QueueAccess; import de.danoeh.antennapod.util.flattr.FlattrUtils; import de.danoeh.antennapod.util.playback.Playable; import de.danoeh.antennapod.util.playback.PlaybackController; import java.util.List; /** * Controls the MediaPlayer that plays a FeedMedia-file */ public class PlaybackService extends Service { /** * Logging tag */ private static final String TAG = "PlaybackService"; /** * Parcelable of type Playable. */ public static final String EXTRA_PLAYABLE = "PlaybackService.PlayableExtra"; /** * True if media should be streamed. */ public static final String EXTRA_SHOULD_STREAM = "extra.de.danoeh.antennapod.service.shouldStream"; /** * True if playback should be started immediately after media has been * prepared. */ public static final String EXTRA_START_WHEN_PREPARED = "extra.de.danoeh.antennapod.service.startWhenPrepared"; public static final String EXTRA_PREPARE_IMMEDIATELY = "extra.de.danoeh.antennapod.service.prepareImmediately"; public static final String ACTION_PLAYER_STATUS_CHANGED = "action.de.danoeh.antennapod.service.playerStatusChanged"; private static final String AVRCP_ACTION_PLAYER_STATUS_CHANGED = "com.android.music.playstatechanged"; private static final String AVRCP_ACTION_META_CHANGED = "com.android.music.metachanged"; public static final String ACTION_PLAYER_NOTIFICATION = "action.de.danoeh.antennapod.service.playerNotification"; public static final String EXTRA_NOTIFICATION_CODE = "extra.de.danoeh.antennapod.service.notificationCode"; public static final String EXTRA_NOTIFICATION_TYPE = "extra.de.danoeh.antennapod.service.notificationType"; /** * If the PlaybackService receives this action, it will stop playback and * try to shutdown. */ public static final String ACTION_SHUTDOWN_PLAYBACK_SERVICE = "action.de.danoeh.antennapod.service.actionShutdownPlaybackService"; /** * If the PlaybackService receives this action, it will end playback of the * current episode and load the next episode if there is one available. */ public static final String ACTION_SKIP_CURRENT_EPISODE = "action.de.danoeh.antennapod.service.skipCurrentEpisode"; /** * Used in NOTIFICATION_TYPE_RELOAD. */ public static final int EXTRA_CODE_AUDIO = 1; public static final int EXTRA_CODE_VIDEO = 2; public static final int NOTIFICATION_TYPE_ERROR = 0; public static final int NOTIFICATION_TYPE_INFO = 1; public static final int NOTIFICATION_TYPE_BUFFER_UPDATE = 2; /** * Receivers of this intent should update their information about the curently playing media */ public static final int NOTIFICATION_TYPE_RELOAD = 3; /** * The state of the sleeptimer changed. */ public static final int NOTIFICATION_TYPE_SLEEPTIMER_UPDATE = 4; public static final int NOTIFICATION_TYPE_BUFFER_START = 5; public static final int NOTIFICATION_TYPE_BUFFER_END = 6; /** * No more episodes are going to be played. */ public static final int NOTIFICATION_TYPE_PLAYBACK_END = 7; /** * Playback speed has changed */ public static final int NOTIFICATION_TYPE_PLAYBACK_SPEED_CHANGE = 8; /** * Returned by getPositionSafe() or getDurationSafe() if the playbackService * is in an invalid state. */ public static final int INVALID_TIME = -1; /** * Is true if service is running. */ public static boolean isRunning = false; /** * Is true if service has received a valid start command. */ public static boolean started = false; private static final int NOTIFICATION_ID = 1; private RemoteControlClient remoteControlClient; private PlaybackServiceMediaPlayer mediaPlayer; private PlaybackServiceTaskManager taskManager; private static volatile MediaType currentMediaType = MediaType.UNKNOWN; private final IBinder mBinder = new LocalBinder(); public class LocalBinder extends Binder { public PlaybackService getService() { return PlaybackService.this; } } @Override public boolean onUnbind(Intent intent) { if (AppConfig.DEBUG) Log.d(TAG, "Received onUnbind event"); return super.onUnbind(intent); } /** * Returns an intent which starts an audio- or videoplayer, depending on the * type of media that is being played. If the playbackservice is not * running, the type of the last played media will be looked up. */ public static Intent getPlayerActivityIntent(Context context) { if (isRunning) { if (currentMediaType == MediaType.VIDEO) { return new Intent(context, VideoplayerActivity.class); } else { return new Intent(context, AudioplayerActivity.class); } } else { if (PlaybackPreferences.getCurrentEpisodeIsVideo()) { return new Intent(context, VideoplayerActivity.class); } else { return new Intent(context, AudioplayerActivity.class); } } } /** * Same as getPlayerActivityIntent(context), but here the type of activity * depends on the FeedMedia that is provided as an argument. */ public static Intent getPlayerActivityIntent(Context context, Playable media) { MediaType mt = media.getMediaType(); if (mt == MediaType.VIDEO) { return new Intent(context, VideoplayerActivity.class); } else { return new Intent(context, AudioplayerActivity.class); } } @SuppressLint("NewApi") @Override public void onCreate() { super.onCreate(); if (AppConfig.DEBUG) Log.d(TAG, "Service created."); isRunning = true; registerReceiver(headsetDisconnected, new IntentFilter( Intent.ACTION_HEADSET_PLUG)); registerReceiver(shutdownReceiver, new IntentFilter( ACTION_SHUTDOWN_PLAYBACK_SERVICE)); registerReceiver(audioBecomingNoisy, new IntentFilter( AudioManager.ACTION_AUDIO_BECOMING_NOISY)); registerReceiver(skipCurrentEpisodeReceiver, new IntentFilter( ACTION_SKIP_CURRENT_EPISODE)); remoteControlClient = setupRemoteControlClient(); taskManager = new PlaybackServiceTaskManager(this, taskManagerCallback); mediaPlayer = new PlaybackServiceMediaPlayer(this, mediaPlayerCallback); } @SuppressLint("NewApi") @Override public void onDestroy() { super.onDestroy(); if (AppConfig.DEBUG) Log.d(TAG, "Service is about to be destroyed"); isRunning = false; started = false; currentMediaType = MediaType.UNKNOWN; unregisterReceiver(headsetDisconnected); unregisterReceiver(shutdownReceiver); unregisterReceiver(audioBecomingNoisy); unregisterReceiver(skipCurrentEpisodeReceiver); mediaPlayer.shutdown(); taskManager.shutdown(); } @Override public IBinder onBind(Intent intent) { if (AppConfig.DEBUG) Log.d(TAG, "Received onBind event"); return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); if (AppConfig.DEBUG) Log.d(TAG, "OnStartCommand called"); final int keycode = intent.getIntExtra(MediaButtonReceiver.EXTRA_KEYCODE, -1); final Playable playable = intent.getParcelableExtra(EXTRA_PLAYABLE); if (keycode == -1 && playable == null) { Log.e(TAG, "PlaybackService was started with no arguments"); stopSelf(); } if ((flags & Service.START_FLAG_REDELIVERY) != 0) { if (AppConfig.DEBUG) Log.d(TAG, "onStartCommand is a redelivered intent, calling stopForeground now."); stopForeground(true); } else { if (keycode != -1) { if (AppConfig.DEBUG) Log.d(TAG, "Received media button event"); handleKeycode(keycode); } else { started = true; boolean stream = intent.getBooleanExtra(EXTRA_SHOULD_STREAM, true); boolean startWhenPrepared = intent.getBooleanExtra(EXTRA_START_WHEN_PREPARED, false); boolean prepareImmediately = intent.getBooleanExtra(EXTRA_PREPARE_IMMEDIATELY, false); sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, 0); mediaPlayer.playMediaObject(playable, stream, startWhenPrepared, prepareImmediately); } } return Service.START_REDELIVER_INTENT; } /** * Handles media button events */ private void handleKeycode(int keycode) { if (AppConfig.DEBUG) Log.d(TAG, "Handling keycode: " + keycode); final PlayerStatus status = mediaPlayer.getPSMPInfo().playerStatus; switch (keycode) { case KeyEvent.KEYCODE_HEADSETHOOK: case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: if (status == PlayerStatus.PLAYING) { mediaPlayer.pause(true, true); } else if (status == PlayerStatus.PAUSED || status == PlayerStatus.PREPARED) { mediaPlayer.resume(); } else if (status == PlayerStatus.PREPARING) { mediaPlayer.setStartWhenPrepared(!mediaPlayer.isStartWhenPrepared()); } else if (status == PlayerStatus.INITIALIZED) { mediaPlayer.setStartWhenPrepared(true); mediaPlayer.prepare(); } break; case KeyEvent.KEYCODE_MEDIA_PLAY: if (status == PlayerStatus.PAUSED || status == PlayerStatus.PREPARED) { mediaPlayer.resume(); } else if (status == PlayerStatus.INITIALIZED) { mediaPlayer.setStartWhenPrepared(true); mediaPlayer.prepare(); } break; case KeyEvent.KEYCODE_MEDIA_PAUSE: if (status == PlayerStatus.PLAYING) { mediaPlayer.pause(true, true); } break; case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: { mediaPlayer.seekDelta(PlaybackController.DEFAULT_SEEK_DELTA); break; } case KeyEvent.KEYCODE_MEDIA_REWIND: { mediaPlayer.seekDelta(-PlaybackController.DEFAULT_SEEK_DELTA); break; } } } /** * Called by a mediaplayer Activity as soon as it has prepared its * mediaplayer. */ public void setVideoSurface(SurfaceHolder sh) { if (AppConfig.DEBUG) Log.d(TAG, "Setting display"); mediaPlayer.setVideoSurface(sh); } /** * Called when the surface holder of the mediaplayer has to be changed. */ private void resetVideoSurface() { taskManager.cancelPositionSaver(); mediaPlayer.resetVideoSurface(); } public void notifyVideoSurfaceAbandoned() { stopForeground(true); mediaPlayer.resetVideoSurface(); } private final PlaybackServiceTaskManager.PSTMCallback taskManagerCallback = new PlaybackServiceTaskManager.PSTMCallback() { @Override public void positionSaverTick() { saveCurrentPosition(true, PlaybackServiceTaskManager.POSITION_SAVER_WAITING_INTERVAL); } @Override public void onSleepTimerExpired() { mediaPlayer.pause(true, true); sendNotificationBroadcast(NOTIFICATION_TYPE_SLEEPTIMER_UPDATE, 0); } @Override public void onWidgetUpdaterTick() { updateWidget(); } @Override public void onChapterLoaded(Playable media) { sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, 0); } }; private final PlaybackServiceMediaPlayer.PSMPCallback mediaPlayerCallback = new PlaybackServiceMediaPlayer.PSMPCallback() { @Override public void statusChanged(PlaybackServiceMediaPlayer.PSMPInfo newInfo) { currentMediaType = mediaPlayer.getCurrentMediaType(); switch (newInfo.playerStatus) { case INITIALIZED: writePlaybackPreferences(); break; case PREPARED: taskManager.startChapterLoader(newInfo.playable); break; case PAUSED: taskManager.cancelPositionSaver(); saveCurrentPosition(false, 0); taskManager.cancelWidgetUpdater(); stopForeground(true); break; case STOPPED: //setCurrentlyPlayingMedia(PlaybackPreferences.NO_MEDIA_PLAYING); //stopSelf(); break; case PLAYING: if (AppConfig.DEBUG) Log.d(TAG, "Audiofocus successfully requested"); if (AppConfig.DEBUG) Log.d(TAG, "Resuming/Starting playback"); taskManager.startPositionSaver(); taskManager.startWidgetUpdater(); setupNotification(newInfo); break; case ERROR: writePlaybackPreferencesNoMediaPlaying(); break; } sendBroadcast(new Intent(ACTION_PLAYER_STATUS_CHANGED)); updateWidget(); refreshRemoteControlClientState(newInfo); bluetoothNotifyChange(newInfo, AVRCP_ACTION_PLAYER_STATUS_CHANGED); bluetoothNotifyChange(newInfo, AVRCP_ACTION_META_CHANGED); } @Override public void shouldStop() { stopSelf(); } @Override public void playbackSpeedChanged(float s) { sendNotificationBroadcast( NOTIFICATION_TYPE_PLAYBACK_SPEED_CHANGE, 0); } @Override public void onBufferingUpdate(int percent) { sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_UPDATE, percent); } @Override public boolean onMediaPlayerInfo(int code) { switch (code) { case MediaPlayer.MEDIA_INFO_BUFFERING_START: sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_START, 0); return true; case MediaPlayer.MEDIA_INFO_BUFFERING_END: sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_END, 0); return true; default: return false; } } @Override public boolean onMediaPlayerError(Object inObj, int what, int extra) { final String TAG = "PlaybackService.onErrorListener"; Log.w(TAG, "An error has occured: " + what + " " + extra); if (mediaPlayer.getPSMPInfo().playerStatus == PlayerStatus.PLAYING) { mediaPlayer.pause(true, false); } sendNotificationBroadcast(NOTIFICATION_TYPE_ERROR, what); writePlaybackPreferencesNoMediaPlaying(); stopSelf(); return true; } @Override public boolean endPlayback(boolean playNextEpisode) { PlaybackService.this.endPlayback(true); return true; } @Override public RemoteControlClient getRemoteControlClient() { return remoteControlClient; } }; private void endPlayback(boolean playNextEpisode) { if (AppConfig.DEBUG) Log.d(TAG, "Playback ended"); final Playable media = mediaPlayer.getPSMPInfo().playable; if (media == null) { Log.e(TAG, "Cannot end playback: media was null"); return; } taskManager.cancelPositionSaver(); boolean isInQueue = false; FeedItem nextItem = null; if (media instanceof FeedMedia) { FeedItem item = ((FeedMedia) media).getItem(); DBWriter.markItemRead(PlaybackService.this, item, true, true); try { final List<FeedItem> queue = taskManager.getQueue(); isInQueue = QueueAccess.ItemListAccess(queue).contains(((FeedMedia) media).getItem().getId()); nextItem = DBTasks.getQueueSuccessorOfItem(this, item.getId(), queue); } catch (InterruptedException e) { e.printStackTrace(); // isInQueue remains false } if (isInQueue) { DBWriter.removeQueueItem(PlaybackService.this, item.getId(), true); } DBWriter.addItemToPlaybackHistory(PlaybackService.this, (FeedMedia) media); } // Load next episode if previous episode was in the queue and if there // is an episode in the queue left. // Start playback immediately if continuous playback is enabled Playable nextMedia = null; boolean loadNextItem = isInQueue && nextItem != null; playNextEpisode = playNextEpisode && loadNextItem && UserPreferences.isFollowQueue(); if (loadNextItem) { if (AppConfig.DEBUG) Log.d(TAG, "Loading next item in queue"); nextMedia = nextItem.getMedia(); } final boolean prepareImmediately; final boolean startWhenPrepared; final boolean stream; if (playNextEpisode) { if (AppConfig.DEBUG) Log.d(TAG, "Playback of next episode will start immediately."); prepareImmediately = startWhenPrepared = true; } else { if (AppConfig.DEBUG) Log.d(TAG, "No more episodes available to play"); prepareImmediately = startWhenPrepared = false; stopForeground(true); stopWidgetUpdater(); } writePlaybackPreferencesNoMediaPlaying(); if (nextMedia != null) { stream = !media.localFileAvailable(); mediaPlayer.playMediaObject(nextMedia, stream, startWhenPrepared, prepareImmediately); sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, (nextMedia.getMediaType() == MediaType.VIDEO) ? EXTRA_CODE_VIDEO : EXTRA_CODE_AUDIO); } else { sendNotificationBroadcast(NOTIFICATION_TYPE_PLAYBACK_END, 0); //stopSelf(); } } public void setSleepTimer(long waitingTime) { if (AppConfig.DEBUG) Log.d(TAG, "Setting sleep timer to " + Long.toString(waitingTime) + " milliseconds"); taskManager.setSleepTimer(waitingTime); sendNotificationBroadcast(NOTIFICATION_TYPE_SLEEPTIMER_UPDATE, 0); } public void disableSleepTimer() { taskManager.disableSleepTimer(); sendNotificationBroadcast(NOTIFICATION_TYPE_SLEEPTIMER_UPDATE, 0); } private void writePlaybackPreferencesNoMediaPlaying() { SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()).edit(); editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID, PlaybackPreferences.NO_MEDIA_PLAYING); editor.commit(); } private void writePlaybackPreferences() { if (AppConfig.DEBUG) Log.d(TAG, "Writing playback preferences"); SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()).edit(); PlaybackServiceMediaPlayer.PSMPInfo info = mediaPlayer.getPSMPInfo(); MediaType mediaType = mediaPlayer.getCurrentMediaType(); boolean stream = mediaPlayer.isStreaming(); if (info.playable != null) { editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA, info.playable.getPlayableType()); editor.putBoolean( PlaybackPreferences.PREF_CURRENT_EPISODE_IS_STREAM, stream); editor.putBoolean( PlaybackPreferences.PREF_CURRENT_EPISODE_IS_VIDEO, mediaType == MediaType.VIDEO); if (info.playable instanceof FeedMedia) { FeedMedia fMedia = (FeedMedia) info.playable; editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID, fMedia.getItem().getFeed().getId()); editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID, fMedia.getId()); } else { editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID, PlaybackPreferences.NO_MEDIA_PLAYING); } info.playable.writeToPreferences(editor); } else { editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID, PlaybackPreferences.NO_MEDIA_PLAYING); } editor.commit(); } /** * Send ACTION_PLAYER_STATUS_CHANGED without changing the status attribute. */ private void postStatusUpdateIntent() { sendBroadcast(new Intent(ACTION_PLAYER_STATUS_CHANGED)); } private void sendNotificationBroadcast(int type, int code) { Intent intent = new Intent(ACTION_PLAYER_NOTIFICATION); intent.putExtra(EXTRA_NOTIFICATION_TYPE, type); intent.putExtra(EXTRA_NOTIFICATION_CODE, code); sendBroadcast(intent); } /** * Used by setupNotification to load notification data in another thread. */ private AsyncTask<Void, Void, Void> notificationSetupTask; /** * Prepares notification and starts the service in the foreground. */ @SuppressLint("NewApi") private void setupNotification(final PlaybackServiceMediaPlayer.PSMPInfo info) { final PendingIntent pIntent = PendingIntent.getActivity(this, 0, PlaybackService.getPlayerActivityIntent(this), PendingIntent.FLAG_UPDATE_CURRENT); if (notificationSetupTask != null) { notificationSetupTask.cancel(true); } notificationSetupTask = new AsyncTask<Void, Void, Void>() { Bitmap icon = null; @Override protected Void doInBackground(Void... params) { if (AppConfig.DEBUG) Log.d(TAG, "Starting background work"); if (android.os.Build.VERSION.SDK_INT >= 11) { if (info.playable != null) { int iconSize = getResources().getDimensionPixelSize( android.R.dimen.notification_large_icon_width); icon = BitmapDecoder .decodeBitmapFromWorkerTaskResource(iconSize, info.playable); } } if (icon == null) { icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_antenna); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (!isCancelled() && info.playerStatus == PlayerStatus.PLAYING && info.playable != null) { String contentText = info.playable.getFeedTitle(); String contentTitle = info.playable.getEpisodeTitle(); Notification notification = null; if (android.os.Build.VERSION.SDK_INT >= 16) { Intent pauseButtonIntent = new Intent( PlaybackService.this, PlaybackService.class); pauseButtonIntent.putExtra( MediaButtonReceiver.EXTRA_KEYCODE, KeyEvent.KEYCODE_MEDIA_PAUSE); PendingIntent pauseButtonPendingIntent = PendingIntent .getService(PlaybackService.this, 0, pauseButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT); Notification.Builder notificationBuilder = new Notification.Builder( PlaybackService.this) .setContentTitle(contentTitle) .setContentText(contentText) .setOngoing(true) .setContentIntent(pIntent) .setLargeIcon(icon) .setSmallIcon(R.drawable.ic_stat_antenna) .addAction(android.R.drawable.ic_media_pause, getString(R.string.pause_label), pauseButtonPendingIntent); notification = notificationBuilder.build(); } else { NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( PlaybackService.this) .setContentTitle(contentTitle) .setContentText(contentText).setOngoing(true) .setContentIntent(pIntent).setLargeIcon(icon) .setSmallIcon(R.drawable.ic_stat_antenna); notification = notificationBuilder.getNotification(); } startForeground(NOTIFICATION_ID, notification); if (AppConfig.DEBUG) Log.d(TAG, "Notification set up"); } } }; if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { notificationSetupTask .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { notificationSetupTask.execute(); } } /** * Saves the current position of the media file to the DB * * @param updatePlayedDuration true if played_duration should be updated. This applies only to FeedMedia objects * @param deltaPlayedDuration value by which played_duration should be increased. */ private synchronized void saveCurrentPosition(boolean updatePlayedDuration, int deltaPlayedDuration) { int position = getCurrentPosition(); int duration = getDuration(); float playbackSpeed = getCurrentPlaybackSpeed(); final Playable playable = mediaPlayer.getPSMPInfo().playable; if (position != INVALID_TIME && duration != INVALID_TIME && playable != null) { if (AppConfig.DEBUG) Log.d(TAG, "Saving current position to " + position); if (updatePlayedDuration && playable instanceof FeedMedia) { FeedMedia m = (FeedMedia) playable; FeedItem item = m.getItem(); m.setPlayedDuration(m.getPlayedDuration() + ((int)(deltaPlayedDuration * playbackSpeed))); // Auto flattr if (FlattrUtils.hasToken() && UserPreferences.isAutoFlattr() && item.getPaymentLink() != null && item.getFlattrStatus().getUnflattred() && (m.getPlayedDuration() > UserPreferences.getPlayedDurationAutoflattrThreshold() * duration)) { if (AppConfig.DEBUG) Log.d(TAG, "saveCurrentPosition: performing auto flattr since played duration " + Integer.toString(m.getPlayedDuration()) + " is " + UserPreferences.getPlayedDurationAutoflattrThreshold() * 100 + "% of file duration " + Integer.toString(duration)); item.getFlattrStatus().setFlattrQueue(); DBWriter.setFeedItemFlattrStatus(PodcastApp.getInstance(), item, false); } } playable.saveCurrentPosition(PreferenceManager .getDefaultSharedPreferences(getApplicationContext()), position); } } private void stopWidgetUpdater() { taskManager.cancelWidgetUpdater(); sendBroadcast(new Intent(PlayerWidget.STOP_WIDGET_UPDATE)); } private void updateWidget() { PlaybackService.this.sendBroadcast(new Intent( PlayerWidget.FORCE_WIDGET_UPDATE)); } public boolean sleepTimerActive() { return taskManager.isSleepTimerActive(); } public long getSleepTimerTimeLeft() { return taskManager.getSleepTimerTimeLeft(); } @SuppressLint("NewApi") private RemoteControlClient setupRemoteControlClient() { if (Build.VERSION.SDK_INT < 14) { return null; } Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(new ComponentName(getPackageName(), MediaButtonReceiver.class.getName())); PendingIntent mediaPendingIntent = PendingIntent.getBroadcast( getApplicationContext(), 0, mediaButtonIntent, 0); remoteControlClient = new RemoteControlClient(mediaPendingIntent); int controlFlags; if (android.os.Build.VERSION.SDK_INT < 16) { controlFlags = RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_NEXT; } else { controlFlags = RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE; } remoteControlClient.setTransportControlFlags(controlFlags); return remoteControlClient; } /** * Refresh player status and metadata. */ @SuppressLint("NewApi") private void refreshRemoteControlClientState(PlaybackServiceMediaPlayer.PSMPInfo info) { if (android.os.Build.VERSION.SDK_INT >= 14) { if (remoteControlClient != null) { switch (info.playerStatus) { case PLAYING: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING); break; case PAUSED: case INITIALIZED: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED); break; case STOPPED: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED); break; case ERROR: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_ERROR); break; default: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_BUFFERING); } if (info.playable != null) { MetadataEditor editor = remoteControlClient .editMetadata(false); editor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, info.playable.getEpisodeTitle()); editor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, info.playable.getFeedTitle()); editor.apply(); } if (AppConfig.DEBUG) Log.d(TAG, "RemoteControlClient state was refreshed"); } } } private void bluetoothNotifyChange(PlaybackServiceMediaPlayer.PSMPInfo info, String whatChanged) { boolean isPlaying = false; if (info.playerStatus == PlayerStatus.PLAYING) { isPlaying = true; } if (info.playable != null) { Intent i = new Intent(whatChanged); i.putExtra("id", 1); i.putExtra("artist", ""); i.putExtra("album", info.playable.getFeedTitle()); i.putExtra("track", info.playable.getEpisodeTitle()); i.putExtra("playing", isPlaying); final List<FeedItem> queue = taskManager.getQueueIfLoaded(); if (queue != null) { i.putExtra("ListSize", queue.size()); } i.putExtra("duration", info.playable.getDuration()); i.putExtra("position", info.playable.getPosition()); sendBroadcast(i); } } /** * Pauses playback when the headset is disconnected and the preference is * set */ private BroadcastReceiver headsetDisconnected = new BroadcastReceiver() { private static final String TAG = "headsetDisconnected"; private static final int UNPLUGGED = 0; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) { int state = intent.getIntExtra("state", -1); if (state != -1) { if (AppConfig.DEBUG) Log.d(TAG, "Headset plug event. State is " + state); if (state == UNPLUGGED) { if (AppConfig.DEBUG) Log.d(TAG, "Headset was unplugged during playback."); pauseIfPauseOnDisconnect(); } } else { Log.e(TAG, "Received invalid ACTION_HEADSET_PLUG intent"); } } } }; private BroadcastReceiver audioBecomingNoisy = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // sound is about to change, eg. bluetooth -> speaker if (AppConfig.DEBUG) Log.d(TAG, "Pausing playback because audio is becoming noisy"); pauseIfPauseOnDisconnect(); } // android.media.AUDIO_BECOMING_NOISY }; /** * Pauses playback if PREF_PAUSE_ON_HEADSET_DISCONNECT was set to true. */ private void pauseIfPauseOnDisconnect() { if (UserPreferences.isPauseOnHeadsetDisconnect()) { mediaPlayer.pause(true, true); } } private BroadcastReceiver shutdownReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() != null && intent.getAction().equals(ACTION_SHUTDOWN_PLAYBACK_SERVICE)) { stopSelf(); } } }; private BroadcastReceiver skipCurrentEpisodeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() != null && intent.getAction().equals(ACTION_SKIP_CURRENT_EPISODE)) { if (AppConfig.DEBUG) Log.d(TAG, "Received SKIP_CURRENT_EPISODE intent"); mediaPlayer.endPlayback(); } } }; public static MediaType getCurrentMediaType() { return currentMediaType; } public void resume() { mediaPlayer.resume(); } public void prepare() { mediaPlayer.prepare(); } public void pause(boolean abandonAudioFocus, boolean reinit) { mediaPlayer.pause(abandonAudioFocus, reinit); } public void reinit() { mediaPlayer.reinit(); } public PlaybackServiceMediaPlayer.PSMPInfo getPSMPInfo() { return mediaPlayer.getPSMPInfo(); } public PlayerStatus getStatus() { return mediaPlayer.getPSMPInfo().playerStatus; } public Playable getPlayable() { return mediaPlayer.getPSMPInfo().playable; } public void setSpeed(float speed) { mediaPlayer.setSpeed(speed); } public boolean canSetSpeed() { return mediaPlayer.canSetSpeed(); } public float getCurrentPlaybackSpeed() { return mediaPlayer.getPlaybackSpeed(); } public boolean isStartWhenPrepared() { return mediaPlayer.isStartWhenPrepared(); } public void setStartWhenPrepared(boolean s) { mediaPlayer.setStartWhenPrepared(s); } public void seekTo(final int t) { mediaPlayer.seekTo(t); } public void seekDelta(final int d) { mediaPlayer.seekDelta(d); } /** * @see de.danoeh.antennapod.service.playback.PlaybackServiceMediaPlayer#seekToChapter(de.danoeh.antennapod.feed.Chapter) */ public void seekToChapter(Chapter c) { mediaPlayer.seekToChapter(c); } /** * call getDuration() on mediaplayer or return INVALID_TIME if player is in * an invalid state. */ public int getDuration() { return mediaPlayer.getDuration(); } /** * call getCurrentPosition() on mediaplayer or return INVALID_TIME if player * is in an invalid state. */ public int getCurrentPosition() { return mediaPlayer.getPosition(); } public boolean isStreaming() { return mediaPlayer.isStreaming(); } public Pair<Integer, Integer> getVideoSize() { return mediaPlayer.getVideoSize(); } }
src/de/danoeh/antennapod/service/playback/PlaybackService.java
package de.danoeh.antennapod.service.playback; import android.annotation.SuppressLint; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.*; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.AudioManager; import android.media.MediaMetadataRetriever; import android.media.MediaPlayer; import android.media.RemoteControlClient; import android.media.RemoteControlClient.MetadataEditor; import android.os.AsyncTask; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.util.Pair; import android.view.KeyEvent; import android.view.SurfaceHolder; import de.danoeh.antennapod.AppConfig; import de.danoeh.antennapod.PodcastApp; import de.danoeh.antennapod.R; import de.danoeh.antennapod.activity.AudioplayerActivity; import de.danoeh.antennapod.activity.VideoplayerActivity; import de.danoeh.antennapod.feed.Chapter; import de.danoeh.antennapod.feed.FeedItem; import de.danoeh.antennapod.feed.FeedMedia; import de.danoeh.antennapod.feed.MediaType; import de.danoeh.antennapod.preferences.PlaybackPreferences; import de.danoeh.antennapod.preferences.UserPreferences; import de.danoeh.antennapod.receiver.MediaButtonReceiver; import de.danoeh.antennapod.receiver.PlayerWidget; import de.danoeh.antennapod.storage.DBTasks; import de.danoeh.antennapod.storage.DBWriter; import de.danoeh.antennapod.util.BitmapDecoder; import de.danoeh.antennapod.util.QueueAccess; import de.danoeh.antennapod.util.flattr.FlattrUtils; import de.danoeh.antennapod.util.playback.Playable; import de.danoeh.antennapod.util.playback.PlaybackController; import java.util.List; /** * Controls the MediaPlayer that plays a FeedMedia-file */ public class PlaybackService extends Service { /** * Logging tag */ private static final String TAG = "PlaybackService"; /** * Parcelable of type Playable. */ public static final String EXTRA_PLAYABLE = "PlaybackService.PlayableExtra"; /** * True if media should be streamed. */ public static final String EXTRA_SHOULD_STREAM = "extra.de.danoeh.antennapod.service.shouldStream"; /** * True if playback should be started immediately after media has been * prepared. */ public static final String EXTRA_START_WHEN_PREPARED = "extra.de.danoeh.antennapod.service.startWhenPrepared"; public static final String EXTRA_PREPARE_IMMEDIATELY = "extra.de.danoeh.antennapod.service.prepareImmediately"; public static final String ACTION_PLAYER_STATUS_CHANGED = "action.de.danoeh.antennapod.service.playerStatusChanged"; private static final String AVRCP_ACTION_PLAYER_STATUS_CHANGED = "com.android.music.playstatechanged"; private static final String AVRCP_ACTION_META_CHANGED = "com.android.music.metachanged"; public static final String ACTION_PLAYER_NOTIFICATION = "action.de.danoeh.antennapod.service.playerNotification"; public static final String EXTRA_NOTIFICATION_CODE = "extra.de.danoeh.antennapod.service.notificationCode"; public static final String EXTRA_NOTIFICATION_TYPE = "extra.de.danoeh.antennapod.service.notificationType"; /** * If the PlaybackService receives this action, it will stop playback and * try to shutdown. */ public static final String ACTION_SHUTDOWN_PLAYBACK_SERVICE = "action.de.danoeh.antennapod.service.actionShutdownPlaybackService"; /** * If the PlaybackService receives this action, it will end playback of the * current episode and load the next episode if there is one available. */ public static final String ACTION_SKIP_CURRENT_EPISODE = "action.de.danoeh.antennapod.service.skipCurrentEpisode"; /** * Used in NOTIFICATION_TYPE_RELOAD. */ public static final int EXTRA_CODE_AUDIO = 1; public static final int EXTRA_CODE_VIDEO = 2; public static final int NOTIFICATION_TYPE_ERROR = 0; public static final int NOTIFICATION_TYPE_INFO = 1; public static final int NOTIFICATION_TYPE_BUFFER_UPDATE = 2; /** * Receivers of this intent should update their information about the curently playing media */ public static final int NOTIFICATION_TYPE_RELOAD = 3; /** * The state of the sleeptimer changed. */ public static final int NOTIFICATION_TYPE_SLEEPTIMER_UPDATE = 4; public static final int NOTIFICATION_TYPE_BUFFER_START = 5; public static final int NOTIFICATION_TYPE_BUFFER_END = 6; /** * No more episodes are going to be played. */ public static final int NOTIFICATION_TYPE_PLAYBACK_END = 7; /** * Playback speed has changed */ public static final int NOTIFICATION_TYPE_PLAYBACK_SPEED_CHANGE = 8; /** * Returned by getPositionSafe() or getDurationSafe() if the playbackService * is in an invalid state. */ public static final int INVALID_TIME = -1; /** * Is true if service is running. */ public static boolean isRunning = false; /** * Is true if service has received a valid start command. */ public static boolean started = false; private static final int NOTIFICATION_ID = 1; private RemoteControlClient remoteControlClient; private PlaybackServiceMediaPlayer mediaPlayer; private PlaybackServiceTaskManager taskManager; private static volatile MediaType currentMediaType = MediaType.UNKNOWN; private final IBinder mBinder = new LocalBinder(); public class LocalBinder extends Binder { public PlaybackService getService() { return PlaybackService.this; } } @Override public boolean onUnbind(Intent intent) { if (AppConfig.DEBUG) Log.d(TAG, "Received onUnbind event"); return super.onUnbind(intent); } /** * Returns an intent which starts an audio- or videoplayer, depending on the * type of media that is being played. If the playbackservice is not * running, the type of the last played media will be looked up. */ public static Intent getPlayerActivityIntent(Context context) { if (isRunning) { if (currentMediaType == MediaType.VIDEO) { return new Intent(context, VideoplayerActivity.class); } else { return new Intent(context, AudioplayerActivity.class); } } else { if (PlaybackPreferences.getCurrentEpisodeIsVideo()) { return new Intent(context, VideoplayerActivity.class); } else { return new Intent(context, AudioplayerActivity.class); } } } /** * Same as getPlayerActivityIntent(context), but here the type of activity * depends on the FeedMedia that is provided as an argument. */ public static Intent getPlayerActivityIntent(Context context, Playable media) { MediaType mt = media.getMediaType(); if (mt == MediaType.VIDEO) { return new Intent(context, VideoplayerActivity.class); } else { return new Intent(context, AudioplayerActivity.class); } } @SuppressLint("NewApi") @Override public void onCreate() { super.onCreate(); if (AppConfig.DEBUG) Log.d(TAG, "Service created."); isRunning = true; registerReceiver(headsetDisconnected, new IntentFilter( Intent.ACTION_HEADSET_PLUG)); registerReceiver(shutdownReceiver, new IntentFilter( ACTION_SHUTDOWN_PLAYBACK_SERVICE)); registerReceiver(audioBecomingNoisy, new IntentFilter( AudioManager.ACTION_AUDIO_BECOMING_NOISY)); registerReceiver(skipCurrentEpisodeReceiver, new IntentFilter( ACTION_SKIP_CURRENT_EPISODE)); remoteControlClient = setupRemoteControlClient(); taskManager = new PlaybackServiceTaskManager(this, taskManagerCallback); mediaPlayer = new PlaybackServiceMediaPlayer(this, mediaPlayerCallback); } @SuppressLint("NewApi") @Override public void onDestroy() { super.onDestroy(); if (AppConfig.DEBUG) Log.d(TAG, "Service is about to be destroyed"); isRunning = false; started = false; currentMediaType = MediaType.UNKNOWN; unregisterReceiver(headsetDisconnected); unregisterReceiver(shutdownReceiver); unregisterReceiver(audioBecomingNoisy); unregisterReceiver(skipCurrentEpisodeReceiver); mediaPlayer.shutdown(); taskManager.shutdown(); } @Override public IBinder onBind(Intent intent) { if (AppConfig.DEBUG) Log.d(TAG, "Received onBind event"); return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); if (AppConfig.DEBUG) Log.d(TAG, "OnStartCommand called"); final int keycode = intent.getIntExtra(MediaButtonReceiver.EXTRA_KEYCODE, -1); final Playable playable = intent.getParcelableExtra(EXTRA_PLAYABLE); if (keycode == -1 && playable == null) { Log.e(TAG, "PlaybackService was started with no arguments"); stopSelf(); } if ((flags & Service.START_FLAG_REDELIVERY) != 0) { if (AppConfig.DEBUG) Log.d(TAG, "onStartCommand is a redelivered intent, calling stopForeground now."); stopForeground(true); } else { if (keycode != -1) { if (AppConfig.DEBUG) Log.d(TAG, "Received media button event"); handleKeycode(keycode); } else { started = true; boolean stream = intent.getBooleanExtra(EXTRA_SHOULD_STREAM, true); boolean startWhenPrepared = intent.getBooleanExtra(EXTRA_START_WHEN_PREPARED, false); boolean prepareImmediately = intent.getBooleanExtra(EXTRA_PREPARE_IMMEDIATELY, false); sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, 0); mediaPlayer.playMediaObject(playable, stream, startWhenPrepared, prepareImmediately); } } return Service.START_REDELIVER_INTENT; } /** * Handles media button events */ private void handleKeycode(int keycode) { if (AppConfig.DEBUG) Log.d(TAG, "Handling keycode: " + keycode); final PlayerStatus status = mediaPlayer.getPSMPInfo().playerStatus; switch (keycode) { case KeyEvent.KEYCODE_HEADSETHOOK: case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: if (status == PlayerStatus.PLAYING) { mediaPlayer.pause(true, true); } else if (status == PlayerStatus.PAUSED || status == PlayerStatus.PREPARED) { mediaPlayer.resume(); } else if (status == PlayerStatus.PREPARING) { mediaPlayer.setStartWhenPrepared(!mediaPlayer.isStartWhenPrepared()); } else if (status == PlayerStatus.INITIALIZED) { mediaPlayer.setStartWhenPrepared(true); mediaPlayer.prepare(); } break; case KeyEvent.KEYCODE_MEDIA_PLAY: if (status == PlayerStatus.PAUSED || status == PlayerStatus.PREPARED) { mediaPlayer.resume(); } else if (status == PlayerStatus.INITIALIZED) { mediaPlayer.setStartWhenPrepared(true); mediaPlayer.prepare(); } break; case KeyEvent.KEYCODE_MEDIA_PAUSE: if (status == PlayerStatus.PLAYING) { mediaPlayer.pause(true, true); } break; case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: { mediaPlayer.seekDelta(PlaybackController.DEFAULT_SEEK_DELTA); break; } case KeyEvent.KEYCODE_MEDIA_REWIND: { mediaPlayer.seekDelta(-PlaybackController.DEFAULT_SEEK_DELTA); break; } } } /** * Called by a mediaplayer Activity as soon as it has prepared its * mediaplayer. */ public void setVideoSurface(SurfaceHolder sh) { if (AppConfig.DEBUG) Log.d(TAG, "Setting display"); mediaPlayer.setVideoSurface(sh); } /** * Called when the surface holder of the mediaplayer has to be changed. */ private void resetVideoSurface() { taskManager.cancelPositionSaver(); mediaPlayer.resetVideoSurface(); } public void notifyVideoSurfaceAbandoned() { stopForeground(true); mediaPlayer.resetVideoSurface(); } private final PlaybackServiceTaskManager.PSTMCallback taskManagerCallback = new PlaybackServiceTaskManager.PSTMCallback() { @Override public void positionSaverTick() { saveCurrentPosition(true, PlaybackServiceTaskManager.POSITION_SAVER_WAITING_INTERVAL); } @Override public void onSleepTimerExpired() { mediaPlayer.pause(true, true); sendNotificationBroadcast(NOTIFICATION_TYPE_SLEEPTIMER_UPDATE, 0); } @Override public void onWidgetUpdaterTick() { updateWidget(); } @Override public void onChapterLoaded(Playable media) { sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, 0); } }; private final PlaybackServiceMediaPlayer.PSMPCallback mediaPlayerCallback = new PlaybackServiceMediaPlayer.PSMPCallback() { @Override public void statusChanged(PlaybackServiceMediaPlayer.PSMPInfo newInfo) { currentMediaType = mediaPlayer.getCurrentMediaType(); switch (newInfo.playerStatus) { case INITIALIZED: writePlaybackPreferences(); break; case PREPARED: taskManager.startChapterLoader(newInfo.playable); break; case PAUSED: taskManager.cancelPositionSaver(); saveCurrentPosition(false, 0); taskManager.cancelWidgetUpdater(); stopForeground(true); break; case STOPPED: //setCurrentlyPlayingMedia(PlaybackPreferences.NO_MEDIA_PLAYING); //stopSelf(); break; case PLAYING: if (AppConfig.DEBUG) Log.d(TAG, "Audiofocus successfully requested"); if (AppConfig.DEBUG) Log.d(TAG, "Resuming/Starting playback"); taskManager.startPositionSaver(); taskManager.startWidgetUpdater(); setupNotification(newInfo); break; } sendBroadcast(new Intent(ACTION_PLAYER_STATUS_CHANGED)); updateWidget(); refreshRemoteControlClientState(newInfo); bluetoothNotifyChange(newInfo, AVRCP_ACTION_PLAYER_STATUS_CHANGED); bluetoothNotifyChange(newInfo, AVRCP_ACTION_META_CHANGED); } @Override public void shouldStop() { stopSelf(); } @Override public void playbackSpeedChanged(float s) { sendNotificationBroadcast( NOTIFICATION_TYPE_PLAYBACK_SPEED_CHANGE, 0); } @Override public void onBufferingUpdate(int percent) { sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_UPDATE, percent); } @Override public boolean onMediaPlayerInfo(int code) { switch (code) { case MediaPlayer.MEDIA_INFO_BUFFERING_START: sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_START, 0); return true; case MediaPlayer.MEDIA_INFO_BUFFERING_END: sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_END, 0); return true; default: return false; } } @Override public boolean onMediaPlayerError(Object inObj, int what, int extra) { final String TAG = "PlaybackService.onErrorListener"; Log.w(TAG, "An error has occured: " + what + " " + extra); if (mediaPlayer.getPSMPInfo().playerStatus == PlayerStatus.PLAYING) { mediaPlayer.pause(true, false); } sendNotificationBroadcast(NOTIFICATION_TYPE_ERROR, what); setCurrentlyPlayingMedia(PlaybackPreferences.NO_MEDIA_PLAYING); stopSelf(); return true; } @Override public boolean endPlayback(boolean playNextEpisode) { PlaybackService.this.endPlayback(true); return true; } @Override public RemoteControlClient getRemoteControlClient() { return remoteControlClient; } }; private void endPlayback(boolean playNextEpisode) { if (AppConfig.DEBUG) Log.d(TAG, "Playback ended"); final Playable media = mediaPlayer.getPSMPInfo().playable; if (media == null) { Log.e(TAG, "Cannot end playback: media was null"); return; } taskManager.cancelPositionSaver(); boolean isInQueue = false; FeedItem nextItem = null; if (media instanceof FeedMedia) { FeedItem item = ((FeedMedia) media).getItem(); DBWriter.markItemRead(PlaybackService.this, item, true, true); try { final List<FeedItem> queue = taskManager.getQueue(); isInQueue = QueueAccess.ItemListAccess(queue).contains(((FeedMedia) media).getItem().getId()); nextItem = DBTasks.getQueueSuccessorOfItem(this, item.getId(), queue); } catch (InterruptedException e) { e.printStackTrace(); // isInQueue remains false } if (isInQueue) { DBWriter.removeQueueItem(PlaybackService.this, item.getId(), true); } DBWriter.addItemToPlaybackHistory(PlaybackService.this, (FeedMedia) media); } // Load next episode if previous episode was in the queue and if there // is an episode in the queue left. // Start playback immediately if continuous playback is enabled Playable nextMedia = null; boolean loadNextItem = isInQueue && nextItem != null; playNextEpisode = playNextEpisode && loadNextItem && UserPreferences.isFollowQueue(); if (loadNextItem) { if (AppConfig.DEBUG) Log.d(TAG, "Loading next item in queue"); nextMedia = nextItem.getMedia(); } final boolean prepareImmediately; final boolean startWhenPrepared; final boolean stream; if (playNextEpisode) { if (AppConfig.DEBUG) Log.d(TAG, "Playback of next episode will start immediately."); prepareImmediately = startWhenPrepared = true; } else { if (AppConfig.DEBUG) Log.d(TAG, "No more episodes available to play"); prepareImmediately = startWhenPrepared = false; stopForeground(true); stopWidgetUpdater(); } writePlaybackPreferencesNoMediaPlaying(); if (nextMedia != null) { stream = !media.localFileAvailable(); mediaPlayer.playMediaObject(nextMedia, stream, startWhenPrepared, prepareImmediately); sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, (nextMedia.getMediaType() == MediaType.VIDEO) ? EXTRA_CODE_VIDEO : EXTRA_CODE_AUDIO); } else { sendNotificationBroadcast(NOTIFICATION_TYPE_PLAYBACK_END, 0); //stopSelf(); } } public void setSleepTimer(long waitingTime) { if (AppConfig.DEBUG) Log.d(TAG, "Setting sleep timer to " + Long.toString(waitingTime) + " milliseconds"); taskManager.setSleepTimer(waitingTime); sendNotificationBroadcast(NOTIFICATION_TYPE_SLEEPTIMER_UPDATE, 0); } public void disableSleepTimer() { taskManager.disableSleepTimer(); sendNotificationBroadcast(NOTIFICATION_TYPE_SLEEPTIMER_UPDATE, 0); } private void writePlaybackPreferencesNoMediaPlaying() { SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()).edit(); editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID, PlaybackPreferences.NO_MEDIA_PLAYING); editor.commit(); } private void writePlaybackPreferences() { if (AppConfig.DEBUG) Log.d(TAG, "Writing playback preferences"); SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()).edit(); PlaybackServiceMediaPlayer.PSMPInfo info = mediaPlayer.getPSMPInfo(); MediaType mediaType = mediaPlayer.getCurrentMediaType(); boolean stream = mediaPlayer.isStreaming(); if (info.playable != null) { editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA, info.playable.getPlayableType()); editor.putBoolean( PlaybackPreferences.PREF_CURRENT_EPISODE_IS_STREAM, stream); editor.putBoolean( PlaybackPreferences.PREF_CURRENT_EPISODE_IS_VIDEO, mediaType == MediaType.VIDEO); if (info.playable instanceof FeedMedia) { FeedMedia fMedia = (FeedMedia) info.playable; editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID, fMedia.getItem().getFeed().getId()); editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID, fMedia.getId()); } else { editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID, PlaybackPreferences.NO_MEDIA_PLAYING); } info.playable.writeToPreferences(editor); } else { editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID, PlaybackPreferences.NO_MEDIA_PLAYING); editor.putLong( PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID, PlaybackPreferences.NO_MEDIA_PLAYING); } editor.commit(); } /** * Send ACTION_PLAYER_STATUS_CHANGED without changing the status attribute. */ private void postStatusUpdateIntent() { sendBroadcast(new Intent(ACTION_PLAYER_STATUS_CHANGED)); } private void sendNotificationBroadcast(int type, int code) { Intent intent = new Intent(ACTION_PLAYER_NOTIFICATION); intent.putExtra(EXTRA_NOTIFICATION_TYPE, type); intent.putExtra(EXTRA_NOTIFICATION_CODE, code); sendBroadcast(intent); } /** * Used by setupNotification to load notification data in another thread. */ private AsyncTask<Void, Void, Void> notificationSetupTask; /** * Prepares notification and starts the service in the foreground. */ @SuppressLint("NewApi") private void setupNotification(final PlaybackServiceMediaPlayer.PSMPInfo info) { final PendingIntent pIntent = PendingIntent.getActivity(this, 0, PlaybackService.getPlayerActivityIntent(this), PendingIntent.FLAG_UPDATE_CURRENT); if (notificationSetupTask != null) { notificationSetupTask.cancel(true); } notificationSetupTask = new AsyncTask<Void, Void, Void>() { Bitmap icon = null; @Override protected Void doInBackground(Void... params) { if (AppConfig.DEBUG) Log.d(TAG, "Starting background work"); if (android.os.Build.VERSION.SDK_INT >= 11) { if (info.playable != null) { int iconSize = getResources().getDimensionPixelSize( android.R.dimen.notification_large_icon_width); icon = BitmapDecoder .decodeBitmapFromWorkerTaskResource(iconSize, info.playable); } } if (icon == null) { icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_antenna); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (!isCancelled() && info.playerStatus == PlayerStatus.PLAYING && info.playable != null) { String contentText = info.playable.getFeedTitle(); String contentTitle = info.playable.getEpisodeTitle(); Notification notification = null; if (android.os.Build.VERSION.SDK_INT >= 16) { Intent pauseButtonIntent = new Intent( PlaybackService.this, PlaybackService.class); pauseButtonIntent.putExtra( MediaButtonReceiver.EXTRA_KEYCODE, KeyEvent.KEYCODE_MEDIA_PAUSE); PendingIntent pauseButtonPendingIntent = PendingIntent .getService(PlaybackService.this, 0, pauseButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT); Notification.Builder notificationBuilder = new Notification.Builder( PlaybackService.this) .setContentTitle(contentTitle) .setContentText(contentText) .setOngoing(true) .setContentIntent(pIntent) .setLargeIcon(icon) .setSmallIcon(R.drawable.ic_stat_antenna) .addAction(android.R.drawable.ic_media_pause, getString(R.string.pause_label), pauseButtonPendingIntent); notification = notificationBuilder.build(); } else { NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( PlaybackService.this) .setContentTitle(contentTitle) .setContentText(contentText).setOngoing(true) .setContentIntent(pIntent).setLargeIcon(icon) .setSmallIcon(R.drawable.ic_stat_antenna); notification = notificationBuilder.getNotification(); } startForeground(NOTIFICATION_ID, notification); if (AppConfig.DEBUG) Log.d(TAG, "Notification set up"); } } }; if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) { notificationSetupTask .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { notificationSetupTask.execute(); } } /** * Saves the current position of the media file to the DB * * @param updatePlayedDuration true if played_duration should be updated. This applies only to FeedMedia objects * @param deltaPlayedDuration value by which played_duration should be increased. */ private synchronized void saveCurrentPosition(boolean updatePlayedDuration, int deltaPlayedDuration) { int position = getCurrentPosition(); int duration = getDuration(); float playbackSpeed = getCurrentPlaybackSpeed(); final Playable playable = mediaPlayer.getPSMPInfo().playable; if (position != INVALID_TIME && duration != INVALID_TIME && playable != null) { if (AppConfig.DEBUG) Log.d(TAG, "Saving current position to " + position); if (updatePlayedDuration && playable instanceof FeedMedia) { FeedMedia m = (FeedMedia) playable; FeedItem item = m.getItem(); m.setPlayedDuration(m.getPlayedDuration() + ((int)(deltaPlayedDuration * playbackSpeed))); // Auto flattr if (FlattrUtils.hasToken() && UserPreferences.isAutoFlattr() && item.getPaymentLink() != null && item.getFlattrStatus().getUnflattred() && (m.getPlayedDuration() > UserPreferences.getPlayedDurationAutoflattrThreshold() * duration)) { if (AppConfig.DEBUG) Log.d(TAG, "saveCurrentPosition: performing auto flattr since played duration " + Integer.toString(m.getPlayedDuration()) + " is " + UserPreferences.getPlayedDurationAutoflattrThreshold() * 100 + "% of file duration " + Integer.toString(duration)); item.getFlattrStatus().setFlattrQueue(); DBWriter.setFeedItemFlattrStatus(PodcastApp.getInstance(), item, false); } } playable.saveCurrentPosition(PreferenceManager .getDefaultSharedPreferences(getApplicationContext()), position); } } private void stopWidgetUpdater() { taskManager.cancelWidgetUpdater(); sendBroadcast(new Intent(PlayerWidget.STOP_WIDGET_UPDATE)); } private void updateWidget() { PlaybackService.this.sendBroadcast(new Intent( PlayerWidget.FORCE_WIDGET_UPDATE)); } public boolean sleepTimerActive() { return taskManager.isSleepTimerActive(); } public long getSleepTimerTimeLeft() { return taskManager.getSleepTimerTimeLeft(); } @SuppressLint("NewApi") private RemoteControlClient setupRemoteControlClient() { if (Build.VERSION.SDK_INT < 14) { return null; } Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(new ComponentName(getPackageName(), MediaButtonReceiver.class.getName())); PendingIntent mediaPendingIntent = PendingIntent.getBroadcast( getApplicationContext(), 0, mediaButtonIntent, 0); remoteControlClient = new RemoteControlClient(mediaPendingIntent); int controlFlags; if (android.os.Build.VERSION.SDK_INT < 16) { controlFlags = RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_NEXT; } else { controlFlags = RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE; } remoteControlClient.setTransportControlFlags(controlFlags); return remoteControlClient; } /** * Refresh player status and metadata. */ @SuppressLint("NewApi") private void refreshRemoteControlClientState(PlaybackServiceMediaPlayer.PSMPInfo info) { if (android.os.Build.VERSION.SDK_INT >= 14) { if (remoteControlClient != null) { switch (info.playerStatus) { case PLAYING: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING); break; case PAUSED: case INITIALIZED: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED); break; case STOPPED: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED); break; case ERROR: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_ERROR); break; default: remoteControlClient .setPlaybackState(RemoteControlClient.PLAYSTATE_BUFFERING); } if (info.playable != null) { MetadataEditor editor = remoteControlClient .editMetadata(false); editor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, info.playable.getEpisodeTitle()); editor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, info.playable.getFeedTitle()); editor.apply(); } if (AppConfig.DEBUG) Log.d(TAG, "RemoteControlClient state was refreshed"); } } } private void bluetoothNotifyChange(PlaybackServiceMediaPlayer.PSMPInfo info, String whatChanged) { boolean isPlaying = false; if (info.playerStatus == PlayerStatus.PLAYING) { isPlaying = true; } if (info.playable != null) { Intent i = new Intent(whatChanged); i.putExtra("id", 1); i.putExtra("artist", ""); i.putExtra("album", info.playable.getFeedTitle()); i.putExtra("track", info.playable.getEpisodeTitle()); i.putExtra("playing", isPlaying); final List<FeedItem> queue = taskManager.getQueueIfLoaded(); if (queue != null) { i.putExtra("ListSize", queue.size()); } i.putExtra("duration", info.playable.getDuration()); i.putExtra("position", info.playable.getPosition()); sendBroadcast(i); } } /** * Pauses playback when the headset is disconnected and the preference is * set */ private BroadcastReceiver headsetDisconnected = new BroadcastReceiver() { private static final String TAG = "headsetDisconnected"; private static final int UNPLUGGED = 0; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) { int state = intent.getIntExtra("state", -1); if (state != -1) { if (AppConfig.DEBUG) Log.d(TAG, "Headset plug event. State is " + state); if (state == UNPLUGGED) { if (AppConfig.DEBUG) Log.d(TAG, "Headset was unplugged during playback."); pauseIfPauseOnDisconnect(); } } else { Log.e(TAG, "Received invalid ACTION_HEADSET_PLUG intent"); } } } }; private BroadcastReceiver audioBecomingNoisy = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // sound is about to change, eg. bluetooth -> speaker if (AppConfig.DEBUG) Log.d(TAG, "Pausing playback because audio is becoming noisy"); pauseIfPauseOnDisconnect(); } // android.media.AUDIO_BECOMING_NOISY }; /** * Pauses playback if PREF_PAUSE_ON_HEADSET_DISCONNECT was set to true. */ private void pauseIfPauseOnDisconnect() { if (UserPreferences.isPauseOnHeadsetDisconnect()) { mediaPlayer.pause(true, true); } } private BroadcastReceiver shutdownReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() != null && intent.getAction().equals(ACTION_SHUTDOWN_PLAYBACK_SERVICE)) { stopSelf(); } } }; private BroadcastReceiver skipCurrentEpisodeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() != null && intent.getAction().equals(ACTION_SKIP_CURRENT_EPISODE)) { if (AppConfig.DEBUG) Log.d(TAG, "Received SKIP_CURRENT_EPISODE intent"); mediaPlayer.endPlayback(); } } }; public static MediaType getCurrentMediaType() { return currentMediaType; } public void resume() { mediaPlayer.resume(); } public void prepare() { mediaPlayer.prepare(); } public void pause(boolean abandonAudioFocus, boolean reinit) { mediaPlayer.pause(abandonAudioFocus, reinit); } public void reinit() { mediaPlayer.reinit(); } public PlaybackServiceMediaPlayer.PSMPInfo getPSMPInfo() { return mediaPlayer.getPSMPInfo(); } public PlayerStatus getStatus() { return mediaPlayer.getPSMPInfo().playerStatus; } public Playable getPlayable() { return mediaPlayer.getPSMPInfo().playable; } public void setSpeed(float speed) { mediaPlayer.setSpeed(speed); } public boolean canSetSpeed() { return mediaPlayer.canSetSpeed(); } public float getCurrentPlaybackSpeed() { return mediaPlayer.getPlaybackSpeed(); } public boolean isStartWhenPrepared() { return mediaPlayer.isStartWhenPrepared(); } public void setStartWhenPrepared(boolean s) { mediaPlayer.setStartWhenPrepared(s); } public void seekTo(final int t) { mediaPlayer.seekTo(t); } public void seekDelta(final int d) { mediaPlayer.seekDelta(d); } /** * @see de.danoeh.antennapod.service.playback.PlaybackServiceMediaPlayer#seekToChapter(de.danoeh.antennapod.feed.Chapter) */ public void seekToChapter(Chapter c) { mediaPlayer.seekToChapter(c); } /** * call getDuration() on mediaplayer or return INVALID_TIME if player is in * an invalid state. */ public int getDuration() { return mediaPlayer.getDuration(); } /** * call getCurrentPosition() on mediaplayer or return INVALID_TIME if player * is in an invalid state. */ public int getCurrentPosition() { return mediaPlayer.getPosition(); } public boolean isStreaming() { return mediaPlayer.isStreaming(); } public Pair<Integer, Integer> getVideoSize() { return mediaPlayer.getVideoSize(); } private void setCurrentlyPlayingMedia(long id) { SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()).edit(); editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA, id); editor.commit(); } }
PlaybackPreferences were not written correctly when a playback error occurred (issue #374)
src/de/danoeh/antennapod/service/playback/PlaybackService.java
PlaybackPreferences were not written correctly when a playback error occurred (issue #374)
<ide><path>rc/de/danoeh/antennapod/service/playback/PlaybackService.java <ide> taskManager.startWidgetUpdater(); <ide> setupNotification(newInfo); <ide> break; <add> case ERROR: <add> writePlaybackPreferencesNoMediaPlaying(); <add> break; <ide> <ide> } <ide> <ide> mediaPlayer.pause(true, false); <ide> } <ide> sendNotificationBroadcast(NOTIFICATION_TYPE_ERROR, what); <del> setCurrentlyPlayingMedia(PlaybackPreferences.NO_MEDIA_PLAYING); <add> writePlaybackPreferencesNoMediaPlaying(); <ide> stopSelf(); <ide> return true; <ide> } <ide> return mediaPlayer.getVideoSize(); <ide> } <ide> <del> private void setCurrentlyPlayingMedia(long id) { <del> SharedPreferences.Editor editor = PreferenceManager <del> .getDefaultSharedPreferences(getApplicationContext()).edit(); <del> editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA, id); <del> editor.commit(); <del> } <ide> }
Java
lgpl-2.1
da04f72e5092799918ca5224551d12fb303df27c
0
modius/railo,getrailo/railo,modius/railo,getrailo/railo,getrailo/railo,JordanReiter/railo,JordanReiter/railo
package railo.runtime.tag; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import railo.commons.io.IOUtil; import railo.commons.io.res.Resource; import railo.commons.io.res.util.ResourceUtil; import railo.commons.lang.StringUtil; import railo.commons.lang.SystemOut; import railo.runtime.PageContextImpl; import railo.runtime.exp.ApplicationException; import railo.runtime.exp.PageException; import railo.runtime.exp.TemplateException; import railo.runtime.ext.tag.BodyTagImpl; import railo.runtime.net.http.ReqRspUtil; import railo.runtime.op.Caster; import railo.runtime.type.List; /** * Defines the MIME type returned by the current page. Optionally, lets you specify the name of a file * to be returned with the page. * * * **/ public final class Content extends BodyTagImpl { private static final int RANGE_NONE = 0; private static final int RANGE_YES = 1; private static final int RANGE_NO = 2; /** Defines the File/ MIME content type returned by the current page. */ private String type; /** The name of the file being retrieved */ private String strFile; /** Yes or No. Yes discards output that precedes the call to cfcontent. No preserves the output that precedes the call. Defaults to Yes. The reset ** and file attributes are mutually exclusive. If you specify a file, the reset attribute has no effect. */ private boolean reset=true; private int _range=RANGE_NONE; /** Yes or No. Yes deletes the file after the download operation. Defaults to No. ** This attribute applies only if you specify a file with the file attribute. */ private boolean deletefile=false; private byte[] content; /** * @see javax.servlet.jsp.tagext.Tag#release() */ public void release() { super.release(); type=null; strFile=null; reset=true; deletefile=false; content=null; _range=RANGE_NONE; } /** set the value type * Defines the File/ MIME content type returned by the current page. * @param type value to set **/ public void setType(String type) { this.type=type.trim(); } public void setRange(boolean range) { this._range=range?RANGE_YES:RANGE_NO; } /** set the value file * The name of the file being retrieved * @param file value to set **/ public void setFile(String file) { this.strFile=file; } /** * the content to output as binary * @param content value to set * @deprecated replaced with <code>{@link #setVariable(String)}</code> **/ public void setContent(byte[] content) { this.content=content; } public void setVariable(Object variable) throws PageException { if(variable instanceof String) this.content=Caster.toBinary(pageContext.getVariable((String)variable)); else this.content=Caster.toBinary(variable); } /** set the value reset * Yes or No. Yes discards output that precedes the call to cfcontent. No preserves the output that precedes the call. Defaults to Yes. The reset * and file attributes are mutually exclusive. If you specify a file, the reset attribute has no effect. * @param reset value to set **/ public void setReset(boolean reset) { this.reset=reset; } /** set the value deletefile * Yes or No. Yes deletes the file after the download operation. Defaults to No. * This attribute applies only if you specify a file with the file attribute. * @param deletefile value to set **/ public void setDeletefile(boolean deletefile) { this.deletefile=deletefile; } /** * @see javax.servlet.jsp.tagext.Tag#doStartTag() */ public int doStartTag() throws PageException { //try { return _doStartTag(); /*} catch (IOException e) { throw Caster.toPageException(e); }*/ } private int _doStartTag() throws PageException { // check the file before doing anyrhing else Resource file=null; if(content==null && !StringUtil.isEmpty(strFile)) file = ResourceUtil.toResourceExisting(pageContext,strFile); // get response object HttpServletResponse rsp = pageContext. getHttpServletResponse(); // check commited if(rsp.isCommitted()) throw new ApplicationException("content is already flushed","you can't rewrite head of response after part of the page is flushed"); // set type setContentType(rsp); Range[] ranges=getRanges(); boolean hasRanges=ranges!=null && ranges.length>0; if(_range==RANGE_YES || hasRanges){ rsp.setHeader("Accept-Ranges", "bytes"); } else if(_range==RANGE_NO) { rsp.setHeader("Accept-Ranges", "none"); hasRanges=false; } // set content if(this.content!=null || file!=null) { pageContext.clear(); InputStream is=null; OutputStream os=null; long length; try { os=getOutputStream(); if(content!=null) { ReqRspUtil.setContentLength(rsp,content.length); length=content.length; is=new BufferedInputStream(new ByteArrayInputStream(content)); } else { ReqRspUtil.setContentLength(rsp,file.length()); pageContext.getConfig().getSecurityManager().checkFileLocation(file); length=file.length(); is=IOUtil.toBufferedInputStream(file.getInputStream()); } // write if(!hasRanges) IOUtil.copy(is,os,false,false); else { //print.out("do part"); //print.out(ranges); long off,len; long to; for(int i=0;i<ranges.length;i++) { off=ranges[i].from; if(ranges[i].to==-1) { len=-1; to=length; } else { len=ranges[i].to-ranges[i].from+1; to=ranges[i].to; } rsp.addHeader("Content-Range", "bytes "+off+"-"+to+"/"+Caster.toString(length)); //print.out("Content-Range: bytes "+off+"-"+to+"/"+Caster.toString(length)); IOUtil.copy(is, os,off,len); } } } catch(IOException ioe) {} finally { IOUtil.flushEL(os); IOUtil.closeEL(is,os); if(deletefile && file!=null) file.delete(); ((PageContextImpl)pageContext).getRootOut().setClosed(true); } throw new railo.runtime.exp.Abort(railo.runtime.exp.Abort.SCOPE_REQUEST); } // clear current content else if(reset)pageContext.clear(); return EVAL_BODY_INCLUDE;//EVAL_PAGE; } private OutputStream getOutputStream() throws PageException, IOException { try { return pageContext.getResponseStream(); } catch(IllegalStateException ise) { throw new TemplateException("content is already send to user, flush"); } } /** * @see javax.servlet.jsp.tagext.Tag#doEndTag() */ public int doEndTag() { return strFile == null ? EVAL_PAGE : SKIP_PAGE; } /** * set the content type of the side * @param rsp HTTP Servlet Response object */ private void setContentType(HttpServletResponse rsp) { if(!StringUtil.isEmpty(type)) { rsp.setContentType(type); } } /** * sets if tag has a body or not * @param hasBody */ public void hasBody(boolean hasBody) { } private Range[] getRanges() { HttpServletRequest req = pageContext.getHttpServletRequest(); Enumeration names = req.getHeaderNames(); if(names==null) return null; String name; Range[] range; while(names.hasMoreElements()) { name=(String) names.nextElement(); //print.out("header:"+name); if("range".equalsIgnoreCase(name)){ range = getRanges(name,req.getHeader(name)); if(range!=null) return range; } } return null; } private Range[] getRanges(String name,String range) { if(StringUtil.isEmpty(range, true)) return null; range=StringUtil.removeWhiteSpace(range); if(range.indexOf("bytes=")==0) range=range.substring(6); String[] arr=null; try { arr = List.toStringArray(List.listToArrayRemoveEmpty(range, ',')); } catch (PageException e) { failRange(name,range); return null; } String item; int index; long from,to; Range[] ranges=new Range[arr.length]; for(int i=0;i<ranges.length;i++) { item=arr[i].trim(); index=item.indexOf('-'); if(index!=-1) { from = Caster.toLongValue(item.substring(0,index),0); to = Caster.toLongValue(item.substring(index+1),-1); if(to!=-1 && from>to){ failRange(name,range); return null; //throw new ExpressionException("invalid range definition, from have to bigger than to ("+from+"-"+to+")"); } } else { from = Caster.toLongValue(item,0); to=-1; } ranges[i]=new Range(from,to); if(i>0 && ranges[i-1].to>=from){ PrintWriter err = pageContext.getConfig().getErrWriter(); SystemOut.printDate(err,"there is a overlapping of 2 ranges ("+ranges[i-1]+","+ranges[i]+")"); //throw new ExpressionException("there is a overlapping of 2 ranges ("+ranges[i-1]+","+ranges[i]+")"); return null; } } return ranges; } private void failRange(String name, String range) { PrintWriter err = pageContext.getConfig().getErrWriter(); SystemOut.printDate(err,"fails to parse the header field ["+name+":"+range+"]"); } } class Range { long from; long to; public Range(long from, long len) { this.from = from; this.to = len; } public String toString() { return from+"-"+to; } }
railo-java/railo-core/src/railo/runtime/tag/Content.java
package railo.runtime.tag; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import railo.commons.io.IOUtil; import railo.commons.io.res.Resource; import railo.commons.io.res.util.ResourceUtil; import railo.commons.lang.StringUtil; import railo.commons.lang.SystemOut; import railo.runtime.PageContextImpl; import railo.runtime.exp.ApplicationException; import railo.runtime.exp.PageException; import railo.runtime.exp.TemplateException; import railo.runtime.ext.tag.BodyTagImpl; import railo.runtime.net.http.ReqRspUtil; import railo.runtime.op.Caster; import railo.runtime.type.List; /** * Defines the MIME type returned by the current page. Optionally, lets you specify the name of a file * to be returned with the page. * * * **/ public final class Content extends BodyTagImpl { private static final int RANGE_NONE = 0; private static final int RANGE_YES = 1; private static final int RANGE_NO = 2; /** Defines the File/ MIME content type returned by the current page. */ private String type; /** The name of the file being retrieved */ private String strFile; /** Yes or No. Yes discards output that precedes the call to cfcontent. No preserves the output that precedes the call. Defaults to Yes. The reset ** and file attributes are mutually exclusive. If you specify a file, the reset attribute has no effect. */ private boolean reset=true; private int _range=RANGE_NONE; /** Yes or No. Yes deletes the file after the download operation. Defaults to No. ** This attribute applies only if you specify a file with the file attribute. */ private boolean deletefile=false; private byte[] content; /** * @see javax.servlet.jsp.tagext.Tag#release() */ public void release() { super.release(); type=null; strFile=null; reset=true; deletefile=false; content=null; _range=RANGE_NONE; } /** set the value type * Defines the File/ MIME content type returned by the current page. * @param type value to set **/ public void setType(String type) { this.type=type.trim(); } public void setRange(boolean range) { this._range=range?RANGE_YES:RANGE_NO; } /** set the value file * The name of the file being retrieved * @param file value to set **/ public void setFile(String file) { this.strFile=file; } /** * the content to output as binary * @param content value to set * @deprecated replaced with <code>{@link #setVariable(String)}</code> **/ public void setContent(byte[] content) { this.content=content; } public void setVariable(Object variable) throws PageException { if(variable instanceof String) this.content=Caster.toBinary(pageContext.getVariable((String)variable)); else this.content=Caster.toBinary(variable); } /** set the value reset * Yes or No. Yes discards output that precedes the call to cfcontent. No preserves the output that precedes the call. Defaults to Yes. The reset * and file attributes are mutually exclusive. If you specify a file, the reset attribute has no effect. * @param reset value to set **/ public void setReset(boolean reset) { this.reset=reset; } /** set the value deletefile * Yes or No. Yes deletes the file after the download operation. Defaults to No. * This attribute applies only if you specify a file with the file attribute. * @param deletefile value to set **/ public void setDeletefile(boolean deletefile) { this.deletefile=deletefile; } /** * @see javax.servlet.jsp.tagext.Tag#doStartTag() */ public int doStartTag() throws PageException { //try { return _doStartTag(); /*} catch (IOException e) { throw Caster.toPageException(e); }*/ } private int _doStartTag() throws PageException { // check the file before doing anyrhing else Resource file=null; if(content==null && !StringUtil.isEmpty(strFile)) file = ResourceUtil.toResourceExisting(pageContext,strFile); // get response object HttpServletResponse rsp = pageContext. getHttpServletResponse(); // check commited if(rsp.isCommitted()) throw new ApplicationException("content is already flushed","you can't rewrite head of response after part of the page is flushed"); // set type setContentType(rsp); Range[] ranges=getRanges(); boolean hasRanges=ranges!=null && ranges.length>0; if(_range==RANGE_YES || hasRanges){ rsp.setHeader("Accept-Ranges", "bytes"); } else if(_range==RANGE_NO) { rsp.setHeader("Accept-Ranges", "none"); hasRanges=false; } // set content if(this.content!=null || file!=null) { pageContext.clear(); InputStream is=null; OutputStream os=null; long length; try { os=getOutputStream(); if(content!=null) { ReqRspUtil.setContentLength(rsp,content.length); length=content.length; is=new BufferedInputStream(new ByteArrayInputStream(content)); } else { ReqRspUtil.setContentLength(rsp,file.length()); pageContext.getConfig().getSecurityManager().checkFileLocation(file); length=file.length(); is=IOUtil.toBufferedInputStream(file.getInputStream()); } // write if(!hasRanges) IOUtil.copy(is,os,false,false); else { //print.out("do part"); //print.out(ranges); long off,len; long to; for(int i=0;i<ranges.length;i++) { off=ranges[i].from; if(ranges[i].to==-1) { len=-1; to=length; } else { len=ranges[i].to-ranges[i].from+1; to=ranges[i].to; } rsp.addHeader("Content-Range", "bytes "+off+"-"+to+"/"+Caster.toString(length)); //print.out("Content-Range: bytes "+off+"-"+to+"/"+Caster.toString(length)); IOUtil.copy(is, os,off,len); } } } catch(IOException ioe) {} finally { IOUtil.flushEL(os); IOUtil.closeEL(is,os); if(deletefile && file!=null) file.delete(); ((PageContextImpl)pageContext).getRootOut().setClosed(true); } throw new railo.runtime.exp.Abort(railo.runtime.exp.Abort.SCOPE_REQUEST); } // clear current content else if(reset)pageContext.clear(); return EVAL_BODY_INCLUDE;//EVAL_PAGE; } private OutputStream getOutputStream() throws PageException, IOException { try { return ((PageContextImpl)pageContext).getResponseStream(); } catch(IllegalStateException ise) { throw new TemplateException("content is already send to user, flush"); } } /** * @see javax.servlet.jsp.tagext.Tag#doEndTag() */ public int doEndTag() { return strFile == null ? EVAL_PAGE : SKIP_PAGE; } /** * set the content type of the side * @param rsp HTTP Servlet Response object */ private void setContentType(HttpServletResponse rsp) { if(!StringUtil.isEmpty(type)) { rsp.setContentType(type); } } /** * sets if tag has a body or not * @param hasBody */ public void hasBody(boolean hasBody) { } private Range[] getRanges() { HttpServletRequest req = pageContext.getHttpServletRequest(); Enumeration names = req.getHeaderNames(); if(names==null) return null; String name; Range[] range; while(names.hasMoreElements()) { name=(String) names.nextElement(); //print.out("header:"+name); if("range".equalsIgnoreCase(name)){ range = getRanges(name,req.getHeader(name)); if(range!=null) return range; } } return null; } private Range[] getRanges(String name,String range) { if(StringUtil.isEmpty(range, true)) return null; range=StringUtil.removeWhiteSpace(range); if(range.indexOf("bytes=")==0) range=range.substring(6); String[] arr=null; try { arr = List.toStringArray(List.listToArrayRemoveEmpty(range, ',')); } catch (PageException e) { failRange(name,range); return null; } String item; int index; long from,to; Range[] ranges=new Range[arr.length]; for(int i=0;i<ranges.length;i++) { item=arr[i].trim(); index=item.indexOf('-'); if(index!=-1) { from = Caster.toLongValue(item.substring(0,index),0); to = Caster.toLongValue(item.substring(index+1),-1); if(to!=-1 && from>to){ failRange(name,range); return null; //throw new ExpressionException("invalid range definition, from have to bigger than to ("+from+"-"+to+")"); } } else { from = Caster.toLongValue(item,0); to=-1; } ranges[i]=new Range(from,to); if(i>0 && ranges[i-1].to>=from){ PrintWriter err = pageContext.getConfig().getErrWriter(); SystemOut.printDate(err,"there is a overlapping of 2 ranges ("+ranges[i-1]+","+ranges[i]+")"); //throw new ExpressionException("there is a overlapping of 2 ranges ("+ranges[i-1]+","+ranges[i]+")"); return null; } } return ranges; } private void failRange(String name, String range) { PrintWriter err = pageContext.getConfig().getErrWriter(); SystemOut.printDate(err,"fails to parse the header field ["+name+":"+range+"]"); } } class Range { long from; long to; public Range(long from, long len) { this.from = from; this.to = len; } public String toString() { return from+"-"+to; } }
removed unnecessary cast
railo-java/railo-core/src/railo/runtime/tag/Content.java
removed unnecessary cast
<ide><path>ailo-java/railo-core/src/railo/runtime/tag/Content.java <ide> <ide> private OutputStream getOutputStream() throws PageException, IOException { <ide> try { <del> return ((PageContextImpl)pageContext).getResponseStream(); <add> return pageContext.getResponseStream(); <ide> } <ide> catch(IllegalStateException ise) { <ide> throw new TemplateException("content is already send to user, flush");
Java
mpl-2.0
a9a8cf05cbf4854ca10a7ff93412690a4bb1f070
0
milankarunarathne/openmrs-core,jcantu1988/openmrs-core,prisamuel/openmrs-core,iLoop2/openmrs-core,prisamuel/openmrs-core,lilo2k/openmrs-core,spereverziev/openmrs-core,foolchan2556/openmrs-core,ssmusoke/openmrs-core,donaldgavis/openmrs-core,rbtracker/openmrs-core,joansmith/openmrs-core,andyvand/OpenMRS,hoquangtruong/TestMylyn,naraink/openmrs-core,maekstr/openmrs-core,chethandeshpande/openmrs-core,geoff-wasilwa/openmrs-core,MitchellBot/openmrs-core,rbtracker/openmrs-core,aj-jaswanth/openmrs-core,kabariyamilind/openMRSDEV,asifur77/openmrs,jamesfeshner/openmrs-module,ssmusoke/openmrs-core,iLoop2/openmrs-core,lilo2k/openmrs-core,jembi/openmrs-core,chethandeshpande/openmrs-core,jembi/openmrs-core,rbtracker/openmrs-core,kristopherschmidt/openmrs-core,siddharthkhabia/openmrs-core,sintjuri/openmrs-core,michaelhofer/openmrs-core,hoquangtruong/TestMylyn,kigsmtua/openmrs-core,donaldgavis/openmrs-core,jamesfeshner/openmrs-module,alexei-grigoriev/openmrs-core,koskedk/openmrs-core,Winbobob/openmrs-core,jamesfeshner/openmrs-module,preethi29/openmrs-core,naraink/openmrs-core,sintjuri/openmrs-core,jcantu1988/openmrs-core,nilusi/Legacy-UI,aj-jaswanth/openmrs-core,trsorsimoII/openmrs-core,Openmrs-joel/openmrs-core,milankarunarathne/openmrs-core,iLoop2/openmrs-core,dlahn/openmrs-core,spereverziev/openmrs-core,Negatu/openmrs-core,kckc/openmrs-core,joansmith/openmrs-core,sadhanvejella/openmrs,jvena1/openmrs-core,jcantu1988/openmrs-core,kabariyamilind/openMRSDEV,dcmul/openmrs-core,milankarunarathne/openmrs-core,sravanthi17/openmrs-core,trsorsimoII/openmrs-core,MitchellBot/openmrs-core,chethandeshpande/openmrs-core,vinayvenu/openmrs-core,ldf92/openmrs-core,maekstr/openmrs-core,kigsmtua/openmrs-core,joansmith/openmrs-core,MuhammadSafwan/Stop-Button-Ability,jembi/openmrs-core,michaelhofer/openmrs-core,kristopherschmidt/openmrs-core,vinayvenu/openmrs-core,aboutdata/openmrs-core,Winbobob/openmrs-core,kigsmtua/openmrs-core,kckc/openmrs-core,macorrales/openmrs-core,pselle/openmrs-core,macorrales/openmrs-core,maekstr/openmrs-core,jvena1/openmrs-core,shiangree/openmrs-core,spereverziev/openmrs-core,naraink/openmrs-core,dlahn/openmrs-core,jamesfeshner/openmrs-module,AbhijitParate/openmrs-core,dcmul/openmrs-core,MuhammadSafwan/Stop-Button-Ability,siddharthkhabia/openmrs-core,kckc/openmrs-core,preethi29/openmrs-core,jcantu1988/openmrs-core,lbl52001/openmrs-core,donaldgavis/openmrs-core,naraink/openmrs-core,alexei-grigoriev/openmrs-core,Negatu/openmrs-core,AbhijitParate/openmrs-core,foolchan2556/openmrs-core,Winbobob/openmrs-core,jembi/openmrs-core,AbhijitParate/openmrs-core,kigsmtua/openmrs-core,WANeves/openmrs-core,andyvand/OpenMRS,sadhanvejella/openmrs,kckc/openmrs-core,nilusi/Legacy-UI,michaelhofer/openmrs-core,geoff-wasilwa/openmrs-core,siddharthkhabia/openmrs-core,ern2/openmrs-core,sravanthi17/openmrs-core,Ch3ck/openmrs-core,siddharthkhabia/openmrs-core,trsorsimoII/openmrs-core,milankarunarathne/openmrs-core,joansmith/openmrs-core,donaldgavis/openmrs-core,foolchan2556/openmrs-core,ern2/openmrs-core,maekstr/openmrs-core,andyvand/OpenMRS,dcmul/openmrs-core,ssmusoke/openmrs-core,Openmrs-joel/openmrs-core,kristopherschmidt/openmrs-core,AbhijitParate/openmrs-core,pselle/openmrs-core,Ch3ck/openmrs-core,hoquangtruong/TestMylyn,WANeves/openmrs-core,asifur77/openmrs,andyvand/OpenMRS,MuhammadSafwan/Stop-Button-Ability,sadhanvejella/openmrs,geoff-wasilwa/openmrs-core,alexwind26/openmrs-core,andyvand/OpenMRS,joansmith/openmrs-core,trsorsimoII/openmrs-core,alexei-grigoriev/openmrs-core,Negatu/openmrs-core,kabariyamilind/openMRSDEV,lbl52001/openmrs-core,aboutdata/openmrs-core,kigsmtua/openmrs-core,maekstr/openmrs-core,koskedk/openmrs-core,maany/openmrs-core,jvena1/openmrs-core,aj-jaswanth/openmrs-core,Winbobob/openmrs-core,vinayvenu/openmrs-core,sravanthi17/openmrs-core,kabariyamilind/openMRSDEV,pselle/openmrs-core,macorrales/openmrs-core,jvena1/openmrs-core,sadhanvejella/openmrs,sadhanvejella/openmrs,sintjuri/openmrs-core,lbl52001/openmrs-core,pselle/openmrs-core,sintjuri/openmrs-core,milankarunarathne/openmrs-core,aboutdata/openmrs-core,koskedk/openmrs-core,WANeves/openmrs-core,asifur77/openmrs,geoff-wasilwa/openmrs-core,rbtracker/openmrs-core,jembi/openmrs-core,WANeves/openmrs-core,dlahn/openmrs-core,ern2/openmrs-core,WANeves/openmrs-core,maany/openmrs-core,prisamuel/openmrs-core,kristopherschmidt/openmrs-core,nilusi/Legacy-UI,asifur77/openmrs,nilusi/Legacy-UI,alexei-grigoriev/openmrs-core,MitchellBot/openmrs-core,sintjuri/openmrs-core,siddharthkhabia/openmrs-core,ldf92/openmrs-core,lbl52001/openmrs-core,Negatu/openmrs-core,MitchellBot/openmrs-core,sadhanvejella/openmrs,alexei-grigoriev/openmrs-core,hoquangtruong/TestMylyn,lilo2k/openmrs-core,ern2/openmrs-core,spereverziev/openmrs-core,MuhammadSafwan/Stop-Button-Ability,shiangree/openmrs-core,jvena1/openmrs-core,lbl52001/openmrs-core,ssmusoke/openmrs-core,michaelhofer/openmrs-core,iLoop2/openmrs-core,kigsmtua/openmrs-core,MuhammadSafwan/Stop-Button-Ability,milankarunarathne/openmrs-core,Ch3ck/openmrs-core,aboutdata/openmrs-core,dcmul/openmrs-core,chethandeshpande/openmrs-core,Openmrs-joel/openmrs-core,naraink/openmrs-core,aboutdata/openmrs-core,preethi29/openmrs-core,Winbobob/openmrs-core,aj-jaswanth/openmrs-core,spereverziev/openmrs-core,kckc/openmrs-core,iLoop2/openmrs-core,kristopherschmidt/openmrs-core,nilusi/Legacy-UI,maany/openmrs-core,naraink/openmrs-core,Openmrs-joel/openmrs-core,Ch3ck/openmrs-core,alexwind26/openmrs-core,sintjuri/openmrs-core,maany/openmrs-core,siddharthkhabia/openmrs-core,iLoop2/openmrs-core,koskedk/openmrs-core,foolchan2556/openmrs-core,spereverziev/openmrs-core,trsorsimoII/openmrs-core,asifur77/openmrs,donaldgavis/openmrs-core,dcmul/openmrs-core,dlahn/openmrs-core,dcmul/openmrs-core,alexwind26/openmrs-core,lbl52001/openmrs-core,MuhammadSafwan/Stop-Button-Ability,kabariyamilind/openMRSDEV,Negatu/openmrs-core,pselle/openmrs-core,rbtracker/openmrs-core,andyvand/OpenMRS,shiangree/openmrs-core,sravanthi17/openmrs-core,koskedk/openmrs-core,macorrales/openmrs-core,lilo2k/openmrs-core,michaelhofer/openmrs-core,macorrales/openmrs-core,lilo2k/openmrs-core,geoff-wasilwa/openmrs-core,AbhijitParate/openmrs-core,AbhijitParate/openmrs-core,preethi29/openmrs-core,ldf92/openmrs-core,kckc/openmrs-core,hoquangtruong/TestMylyn,maekstr/openmrs-core,prisamuel/openmrs-core,hoquangtruong/TestMylyn,shiangree/openmrs-core,nilusi/Legacy-UI,preethi29/openmrs-core,dlahn/openmrs-core,Ch3ck/openmrs-core,pselle/openmrs-core,MitchellBot/openmrs-core,ldf92/openmrs-core,maany/openmrs-core,ern2/openmrs-core,jcantu1988/openmrs-core,alexwind26/openmrs-core,shiangree/openmrs-core,chethandeshpande/openmrs-core,ssmusoke/openmrs-core,alexwind26/openmrs-core,Openmrs-joel/openmrs-core,aboutdata/openmrs-core,vinayvenu/openmrs-core,Winbobob/openmrs-core,foolchan2556/openmrs-core,jamesfeshner/openmrs-module,jembi/openmrs-core,prisamuel/openmrs-core,koskedk/openmrs-core,WANeves/openmrs-core,lilo2k/openmrs-core,sravanthi17/openmrs-core,aj-jaswanth/openmrs-core,alexei-grigoriev/openmrs-core,Negatu/openmrs-core,foolchan2556/openmrs-core,shiangree/openmrs-core,prisamuel/openmrs-core,vinayvenu/openmrs-core,ldf92/openmrs-core
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Vector; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.GlobalProperty; import org.openmrs.Privilege; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * This class will parse a file into an org.openmrs.module.Module object */ public class ModuleFileParser { private Log log = LogFactory.getLog(this.getClass()); private File moduleFile = null; /** * List out all of the possible version numbers for config files that openmrs has DTDs for. * These are usually stored at http://resources.openmrs.org/doctype/config-x.x.dt */ private static List<String> validConfigVersions = new ArrayList<String>(); static { validConfigVersions.add("1.0"); validConfigVersions.add("1.1"); validConfigVersions.add("1.2"); } /** * Constructor * * @param moduleFile the module (jar)file that will be parsed */ public ModuleFileParser(File moduleFile) { if (moduleFile == null) throw new ModuleException("Module file cannot be null"); if (!moduleFile.getName().endsWith(".omod")) throw new ModuleException("Module file does not have the correct .omod file extension", moduleFile.getName()); this.moduleFile = moduleFile; } /** * Get the module * * @return new module object */ public Module parse() throws ModuleException { Module module = null; JarFile jarfile = null; InputStream configStream = null; try { try { jarfile = new JarFile(moduleFile); } catch (IOException e) { throw new ModuleException("Unable to get jar file", moduleFile.getName(), e); } // look for config.xml in the root of the module ZipEntry config = jarfile.getEntry("config.xml"); if (config == null) throw new ModuleException("Error loading module. No config.xml found.", moduleFile.getName()); // get a config file stream try { configStream = jarfile.getInputStream(config); } catch (IOException e) { throw new ModuleException("Unable to get config file stream", moduleFile.getName(), e); } // turn the config file into an xml document Document configDoc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a // DTD) we return an InputSource // with no data at the end, causing the parser to ignore // the DTD. return new InputSource(new StringReader("")); } }); configDoc = db.parse(configStream); } catch (Exception e) { log.error("Error parsing config.xml: " + configStream.toString(), e); OutputStream out = null; String output = ""; try { out = new ByteArrayOutputStream(); // Now copy bytes from the URL to the output stream byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = configStream.read(buffer)) != -1) out.write(buffer, 0, bytes_read); output = out.toString(); } catch (Exception e2) { log.warn("Another error parsing config.xml", e2); } finally { try { out.close(); } catch (Exception e3) {} ; } log.error("config.xml content: " + output); throw new ModuleException("Error parsing module config.xml file", moduleFile.getName(), e); } Element rootNode = configDoc.getDocumentElement(); String configVersion = rootNode.getAttribute("configVersion"); if (!validConfigVersions.contains(configVersion)) throw new ModuleException("Invalid config version: " + configVersion, moduleFile.getName()); String name = getElement(rootNode, configVersion, "name"); String moduleId = getElement(rootNode, configVersion, "id"); String packageName = getElement(rootNode, configVersion, "package"); String author = getElement(rootNode, configVersion, "author"); String desc = getElement(rootNode, configVersion, "description"); String version = getElement(rootNode, configVersion, "version"); // do some validation if (name == null || name.length() == 0) throw new ModuleException("name cannot be empty", moduleFile.getName()); if (moduleId == null || moduleId.length() == 0) throw new ModuleException("module id cannot be empty", name); if (packageName == null || packageName.length() == 0) throw new ModuleException("package cannot be empty", name); // look for log4j.xml in the root of the module Document log4jDoc = null; try { ZipEntry log4j = jarfile.getEntry("log4j.xml"); if (log4j != null) { InputStream log4jStream = jarfile.getInputStream(log4j); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as // a // DTD) we return an InputSource // with no data at the end, causing the parser to // ignore // the DTD. return new InputSource(new StringReader("")); } }); log4jDoc = db.parse(log4jStream); } } catch (Exception e) {} // create the module object module = new Module(name, moduleId, packageName, author, desc, version); // find and load the activator class module.setActivatorName(getElement(rootNode, configVersion, "activator")); module.setRequireDatabaseVersion(getElement(rootNode, configVersion, "require_database_version")); module.setRequireOpenmrsVersion(getElement(rootNode, configVersion, "require_version")); module.setUpdateURL(getElement(rootNode, configVersion, "updateURL")); module.setRequiredModulesMap(getRequiredModules(rootNode, configVersion)); module.setAdvicePoints(getAdvice(rootNode, configVersion, module)); module.setExtensionNames(getExtensions(rootNode, configVersion)); module.setPrivileges(getPrivileges(rootNode, configVersion)); module.setGlobalProperties(getGlobalProperties(rootNode, configVersion)); module.setMessages(getMessages(rootNode, configVersion, jarfile)); module.setMappingFiles(getMappingFiles(rootNode, configVersion, jarfile)); module.setConfig(configDoc); module.setLog4j(log4jDoc); module.setFile(moduleFile); } finally { try { jarfile.close(); } catch (Exception e) { log.warn("Unable to close jarfile: " + jarfile, e); } if (configStream != null) { try { configStream.close(); } catch (Exception io) { log.error("Error while closing config stream for module: " + moduleFile.getAbsolutePath(), io); } } } return module; } /** * Generic method to get a module tag * * @param root * @param version * @param tag * @return */ private String getElement(Element root, String version, String tag) { if (root.getElementsByTagName(tag).getLength() > 0) return root.getElementsByTagName(tag).item(0).getTextContent(); return ""; } /** * load in required modules list * * @param root element in the xml doc object * @param version of the config file * @return map from module package name to required version */ private Map<String, String> getRequiredModules(Element root, String version) { NodeList requiredModulesParents = root.getElementsByTagName("require_modules"); Map<String, String> packageNamesToVersion = new HashMap<String, String>(); // TODO test require_modules section if (requiredModulesParents.getLength() > 0) { Node requiredModulesParent = requiredModulesParents.item(0); NodeList requiredModules = requiredModulesParent.getChildNodes(); int i = 0; while (i < requiredModules.getLength()) { Node n = requiredModules.item(i); if (n != null && "require_module".equals(n.getNodeName())) { NamedNodeMap attributes = n.getAttributes(); Node versionNode = attributes.getNamedItem("version"); String reqVersion = versionNode == null ? null : versionNode.getNodeValue(); packageNamesToVersion.put(n.getTextContent(), reqVersion); } i++; } } return packageNamesToVersion; } /** * load in advicePoints * * @param root * @param version * @return */ private List<AdvicePoint> getAdvice(Element root, String version, Module mod) { List<AdvicePoint> advicePoints = new Vector<AdvicePoint>(); NodeList advice = root.getElementsByTagName("advice"); if (advice.getLength() > 0) { log.debug("# advice: " + advice.getLength()); int i = 0; while (i < advice.getLength()) { Node node = advice.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String point = "", adviceClass = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("point".equals(childNode.getNodeName())) point = childNode.getTextContent(); else if ("class".equals(childNode.getNodeName())) adviceClass = childNode.getTextContent(); x++; } log.debug("point: " + point + " class: " + adviceClass); // point and class are required if (point.length() > 0 && adviceClass.length() > 0) { advicePoints.add(new AdvicePoint(mod, point, adviceClass)); } else log.warn("'point' and 'class' are required for advice. Given '" + point + "' and '" + adviceClass + "'"); i++; } } return advicePoints; } /** * load in extensions * * @param root * @param configVersion * @return */ private IdentityHashMap<String, String> getExtensions(Element root, String configVersion) { IdentityHashMap<String, String> extensions = new IdentityHashMap<String, String>(); NodeList extensionNodes = root.getElementsByTagName("extension"); if (extensionNodes.getLength() > 0) { log.debug("# extensions: " + extensionNodes.getLength()); int i = 0; while (i < extensionNodes.getLength()) { Node node = extensionNodes.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String point = "", extClass = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("point".equals(childNode.getNodeName())) point = childNode.getTextContent(); else if ("class".equals(childNode.getNodeName())) extClass = childNode.getTextContent(); x++; } log.debug("point: " + point + " class: " + extClass); // point and class are required if (point.length() > 0 && extClass.length() > 0) { if (point.indexOf(Extension.extensionIdSeparator) != -1) log.warn("Point id contains illegal character: '" + Extension.extensionIdSeparator + "'"); else { extensions.put(point, extClass); } } else log .warn("'point' and 'class' are required for extensions. Given '" + point + "' and '" + extClass + "'"); i++; } } return extensions; } /** * load in messages * * @param root * @param configVersion * @return */ private Map<String, Properties> getMessages(Element root, String configVersion, JarFile jarfile) { Map<String, Properties> messages = new HashMap<String, Properties>(); NodeList messageNodes = root.getElementsByTagName("messages"); if (messageNodes.getLength() > 0) { log.debug("# message nodes: " + messageNodes.getLength()); int i = 0; while (i < messageNodes.getLength()) { Node node = messageNodes.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String lang = "", file = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("lang".equals(childNode.getNodeName())) lang = childNode.getTextContent(); else if ("file".equals(childNode.getNodeName())) file = childNode.getTextContent(); x++; } log.debug("lang: " + lang + " file: " + file); // lang and file are required if (lang.length() > 0 && file.length() > 0) { InputStream inStream = null; try { ZipEntry entry = jarfile.getEntry(file); inStream = jarfile.getInputStream(entry); Properties props = new Properties(); props.load(inStream); messages.put(lang, props); } catch (IOException e) { log.warn("Unable to load properties: " + file); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException io) { log.error("Error while closing property input stream for module: " + moduleFile.getAbsolutePath(), io); } } } } else log.warn("'lang' and 'file' are required for extensions. Given '" + lang + "' and '" + file + "'"); i++; } } return messages; } /** * load in required privileges * * @param root * @param version * @return */ private List<Privilege> getPrivileges(Element root, String version) { List<Privilege> privileges = new Vector<Privilege>(); NodeList privNodes = root.getElementsByTagName("privilege"); if (privNodes.getLength() > 0) { log.debug("# privileges: " + privNodes.getLength()); int i = 0; while (i < privNodes.getLength()) { Node node = privNodes.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String name = "", description = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("name".equals(childNode.getNodeName())) name = childNode.getTextContent(); else if ("description".equals(childNode.getNodeName())) description = childNode.getTextContent(); x++; } log.debug("name: " + name + " description: " + description); // name and desc are required if (name.length() > 0 && description.length() > 0) privileges.add(new Privilege(name, description)); else log.warn("'name' and 'description' are required for privileges. Given '" + name + "' and '" + description + "'"); i++; } } return privileges; } /** * load in required global properties and defaults * * @param root * @param version * @return */ private List<GlobalProperty> getGlobalProperties(Element root, String version) { List<GlobalProperty> properties = new Vector<GlobalProperty>(); NodeList propNodes = root.getElementsByTagName("globalProperty"); if (propNodes.getLength() > 0) { log.debug("# global props: " + propNodes.getLength()); int i = 0; while (i < propNodes.getLength()) { Node node = propNodes.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String property = "", defaultValue = "", description = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("property".equals(childNode.getNodeName())) property = childNode.getTextContent(); else if ("defaultValue".equals(childNode.getNodeName())) defaultValue = childNode.getTextContent(); else if ("description".equals(childNode.getNodeName())) description = childNode.getTextContent(); x++; } log.debug("property: " + property + " defaultValue: " + defaultValue + " description: " + description); // remove tabs from description and trim start/end whitespace if (description != null) description = description.replaceAll(" ", "").trim(); // name is required if (property.length() > 0) properties.add(new GlobalProperty(property, defaultValue, description)); else log.warn("'property' is required for global properties. Given '" + property + "'"); i++; } } return properties; } /** * Load in the defined mapping file names * * @param rootNode * @param configVersion * @param jarfile * @return */ private List<String> getMappingFiles(Element rootNode, String configVersion, JarFile jarfile) { String mappingString = getElement(rootNode, configVersion, "mappingFiles"); List<String> mappings = new Vector<String>(); for (String s : mappingString.split("\\s")) { String s2 = s.trim(); if (s2.length() > 0) mappings.add(s2); } return mappings; } }
src/api/org/openmrs/module/ModuleFileParser.java
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Vector; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.GlobalProperty; import org.openmrs.Privilege; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * This class will parse a file into an org.openmrs.module.Module object */ public class ModuleFileParser { private Log log = LogFactory.getLog(this.getClass()); private File moduleFile = null; /** * Constructor * * @param moduleFile the module (jar)file that will be parsed */ public ModuleFileParser(File moduleFile) { if (moduleFile == null) throw new ModuleException("Module file cannot be null"); if (!moduleFile.getName().endsWith(".omod")) throw new ModuleException("Module file does not have the correct .omod file extension", moduleFile.getName()); this.moduleFile = moduleFile; } private List<String> validConfigVersions() { List<String> versions = new Vector<String>(); versions.add("1.0"); return versions; } /** * Get the module * * @return new module object */ public Module parse() throws ModuleException { Module module = null; JarFile jarfile = null; InputStream configStream = null; try { try { jarfile = new JarFile(moduleFile); } catch (IOException e) { throw new ModuleException("Unable to get jar file", moduleFile.getName(), e); } // look for config.xml in the root of the module ZipEntry config = jarfile.getEntry("config.xml"); if (config == null) throw new ModuleException("Error loading module. No config.xml found.", moduleFile.getName()); // get a config file stream try { configStream = jarfile.getInputStream(config); } catch (IOException e) { throw new ModuleException("Unable to get config file stream", moduleFile.getName(), e); } // turn the config file into an xml document Document configDoc = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as a // DTD) we return an InputSource // with no data at the end, causing the parser to ignore // the DTD. return new InputSource(new StringReader("")); } }); configDoc = db.parse(configStream); } catch (Exception e) { log.error("Error parsing config.xml: " + configStream.toString(), e); OutputStream out = null; String output = ""; try { out = new ByteArrayOutputStream(); // Now copy bytes from the URL to the output stream byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = configStream.read(buffer)) != -1) out.write(buffer, 0, bytes_read); output = out.toString(); } catch (Exception e2) { log.warn("Another error parsing config.xml", e2); } finally { try { out.close(); } catch (Exception e3) {} ; } log.error("config.xml content: " + output); throw new ModuleException("Error parsing module config.xml file", moduleFile.getName(), e); } Element rootNode = configDoc.getDocumentElement(); String configVersion = rootNode.getAttribute("configVersion"); if (!validConfigVersions().contains(configVersion)) throw new ModuleException("Invalid config version: " + configVersion, moduleFile.getName()); String name = getElement(rootNode, configVersion, "name"); String moduleId = getElement(rootNode, configVersion, "id"); String packageName = getElement(rootNode, configVersion, "package"); String author = getElement(rootNode, configVersion, "author"); String desc = getElement(rootNode, configVersion, "description"); String version = getElement(rootNode, configVersion, "version"); // do some validation if (name == null || name.length() == 0) throw new ModuleException("name cannot be empty", moduleFile.getName()); if (moduleId == null || moduleId.length() == 0) throw new ModuleException("module id cannot be empty", name); if (packageName == null || packageName.length() == 0) throw new ModuleException("package cannot be empty", name); // look for log4j.xml in the root of the module Document log4jDoc = null; try { ZipEntry log4j = jarfile.getEntry("log4j.xml"); if (log4j != null) { InputStream log4jStream = jarfile.getInputStream(log4j); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // When asked to resolve external entities (such as // a // DTD) we return an InputSource // with no data at the end, causing the parser to // ignore // the DTD. return new InputSource(new StringReader("")); } }); log4jDoc = db.parse(log4jStream); } } catch (Exception e) {} // create the module object module = new Module(name, moduleId, packageName, author, desc, version); // find and load the activator class module.setActivatorName(getElement(rootNode, configVersion, "activator")); module.setRequireDatabaseVersion(getElement(rootNode, configVersion, "require_database_version")); module.setRequireOpenmrsVersion(getElement(rootNode, configVersion, "require_version")); module.setUpdateURL(getElement(rootNode, configVersion, "updateURL")); module.setRequiredModulesMap(getRequiredModules(rootNode, configVersion)); module.setAdvicePoints(getAdvice(rootNode, configVersion, module)); module.setExtensionNames(getExtensions(rootNode, configVersion)); module.setPrivileges(getPrivileges(rootNode, configVersion)); module.setGlobalProperties(getGlobalProperties(rootNode, configVersion)); module.setMessages(getMessages(rootNode, configVersion, jarfile)); module.setMappingFiles(getMappingFiles(rootNode, configVersion, jarfile)); module.setConfig(configDoc); module.setLog4j(log4jDoc); module.setFile(moduleFile); } finally { try { jarfile.close(); } catch (Exception e) { log.warn("Unable to close jarfile: " + jarfile, e); } if (configStream != null) { try { configStream.close(); } catch (Exception io) { log.error("Error while closing config stream for module: " + moduleFile.getAbsolutePath(), io); } } } return module; } /** * Generic method to get a module tag * * @param root * @param version * @param tag * @return */ private String getElement(Element root, String version, String tag) { if (root.getElementsByTagName(tag).getLength() > 0) return root.getElementsByTagName(tag).item(0).getTextContent(); return ""; } /** * load in required modules list * * @param root element in the xml doc object * @param version of the config file * @return map from module package name to required version */ private Map<String, String> getRequiredModules(Element root, String version) { NodeList requiredModulesParents = root.getElementsByTagName("require_modules"); Map<String, String> packageNamesToVersion = new HashMap<String, String>(); // TODO test require_modules section if (requiredModulesParents.getLength() > 0) { Node requiredModulesParent = requiredModulesParents.item(0); NodeList requiredModules = requiredModulesParent.getChildNodes(); int i = 0; while (i < requiredModules.getLength()) { Node n = requiredModules.item(i); if (n != null && "require_module".equals(n.getNodeName())) { NamedNodeMap attributes = n.getAttributes(); Node versionNode = attributes.getNamedItem("version"); String reqVersion = versionNode == null ? null : versionNode.getNodeValue(); packageNamesToVersion.put(n.getTextContent(), reqVersion); } i++; } } return packageNamesToVersion; } /** * load in advicePoints * * @param root * @param version * @return */ private List<AdvicePoint> getAdvice(Element root, String version, Module mod) { List<AdvicePoint> advicePoints = new Vector<AdvicePoint>(); NodeList advice = root.getElementsByTagName("advice"); if (advice.getLength() > 0) { log.debug("# advice: " + advice.getLength()); int i = 0; while (i < advice.getLength()) { Node node = advice.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String point = "", adviceClass = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("point".equals(childNode.getNodeName())) point = childNode.getTextContent(); else if ("class".equals(childNode.getNodeName())) adviceClass = childNode.getTextContent(); x++; } log.debug("point: " + point + " class: " + adviceClass); // point and class are required if (point.length() > 0 && adviceClass.length() > 0) { advicePoints.add(new AdvicePoint(mod, point, adviceClass)); } else log.warn("'point' and 'class' are required for advice. Given '" + point + "' and '" + adviceClass + "'"); i++; } } return advicePoints; } /** * load in extensions * * @param root * @param configVersion * @return */ private IdentityHashMap<String, String> getExtensions(Element root, String configVersion) { IdentityHashMap<String, String> extensions = new IdentityHashMap<String, String>(); NodeList extensionNodes = root.getElementsByTagName("extension"); if (extensionNodes.getLength() > 0) { log.debug("# extensions: " + extensionNodes.getLength()); int i = 0; while (i < extensionNodes.getLength()) { Node node = extensionNodes.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String point = "", extClass = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("point".equals(childNode.getNodeName())) point = childNode.getTextContent(); else if ("class".equals(childNode.getNodeName())) extClass = childNode.getTextContent(); x++; } log.debug("point: " + point + " class: " + extClass); // point and class are required if (point.length() > 0 && extClass.length() > 0) { if (point.indexOf(Extension.extensionIdSeparator) != -1) log.warn("Point id contains illegal character: '" + Extension.extensionIdSeparator + "'"); else { extensions.put(point, extClass); } } else log .warn("'point' and 'class' are required for extensions. Given '" + point + "' and '" + extClass + "'"); i++; } } return extensions; } /** * load in messages * * @param root * @param configVersion * @return */ private Map<String, Properties> getMessages(Element root, String configVersion, JarFile jarfile) { Map<String, Properties> messages = new HashMap<String, Properties>(); NodeList messageNodes = root.getElementsByTagName("messages"); if (messageNodes.getLength() > 0) { log.debug("# message nodes: " + messageNodes.getLength()); int i = 0; while (i < messageNodes.getLength()) { Node node = messageNodes.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String lang = "", file = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("lang".equals(childNode.getNodeName())) lang = childNode.getTextContent(); else if ("file".equals(childNode.getNodeName())) file = childNode.getTextContent(); x++; } log.debug("lang: " + lang + " file: " + file); // lang and file are required if (lang.length() > 0 && file.length() > 0) { InputStream inStream = null; try { ZipEntry entry = jarfile.getEntry(file); inStream = jarfile.getInputStream(entry); Properties props = new Properties(); props.load(inStream); messages.put(lang, props); } catch (IOException e) { log.warn("Unable to load properties: " + file); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException io) { log.error("Error while closing property input stream for module: " + moduleFile.getAbsolutePath(), io); } } } } else log.warn("'lang' and 'file' are required for extensions. Given '" + lang + "' and '" + file + "'"); i++; } } return messages; } /** * load in required privileges * * @param root * @param version * @return */ private List<Privilege> getPrivileges(Element root, String version) { List<Privilege> privileges = new Vector<Privilege>(); NodeList privNodes = root.getElementsByTagName("privilege"); if (privNodes.getLength() > 0) { log.debug("# privileges: " + privNodes.getLength()); int i = 0; while (i < privNodes.getLength()) { Node node = privNodes.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String name = "", description = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("name".equals(childNode.getNodeName())) name = childNode.getTextContent(); else if ("description".equals(childNode.getNodeName())) description = childNode.getTextContent(); x++; } log.debug("name: " + name + " description: " + description); // name and desc are required if (name.length() > 0 && description.length() > 0) privileges.add(new Privilege(name, description)); else log.warn("'name' and 'description' are required for privileges. Given '" + name + "' and '" + description + "'"); i++; } } return privileges; } /** * load in required global properties and defaults * * @param root * @param version * @return */ private List<GlobalProperty> getGlobalProperties(Element root, String version) { List<GlobalProperty> properties = new Vector<GlobalProperty>(); NodeList propNodes = root.getElementsByTagName("globalProperty"); if (propNodes.getLength() > 0) { log.debug("# global props: " + propNodes.getLength()); int i = 0; while (i < propNodes.getLength()) { Node node = propNodes.item(i); NodeList nodes = node.getChildNodes(); int x = 0; String property = "", defaultValue = "", description = ""; while (x < nodes.getLength()) { Node childNode = nodes.item(x); if ("property".equals(childNode.getNodeName())) property = childNode.getTextContent(); else if ("defaultValue".equals(childNode.getNodeName())) defaultValue = childNode.getTextContent(); else if ("description".equals(childNode.getNodeName())) description = childNode.getTextContent(); x++; } log.debug("property: " + property + " defaultValue: " + defaultValue + " description: " + description); // remove tabs from description and trim start/end whitespace if (description != null) description = description.replaceAll(" ", "").trim(); // name is required if (property.length() > 0) properties.add(new GlobalProperty(property, defaultValue, description)); else log.warn("'property' is required for global properties. Given '" + property + "'"); i++; } } return properties; } /** * Load in the defined mapping file names * * @param rootNode * @param configVersion * @param jarfile * @return */ private List<String> getMappingFiles(Element rootNode, String configVersion, JarFile jarfile) { String mappingString = getElement(rootNode, configVersion, "mappingFiles"); List<String> mappings = new Vector<String>(); for (String s : mappingString.split("\\s")) { String s2 = s.trim(); if (s2.length() > 0) mappings.add(s2); } return mappings; } }
Added versions 1.1 and 1.2 to the valid config file versions -#1193 git-svn-id: ce3478dfdc990238714fcdf4fc6855b7489218cf@7272 5bac5841-c719-aa4e-b3fe-cce5062f897a
src/api/org/openmrs/module/ModuleFileParser.java
Added versions 1.1 and 1.2 to the valid config file versions -#1193
<ide><path>rc/api/org/openmrs/module/ModuleFileParser.java <ide> import java.io.InputStream; <ide> import java.io.OutputStream; <ide> import java.io.StringReader; <add>import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.IdentityHashMap; <ide> import java.util.List; <ide> private File moduleFile = null; <ide> <ide> /** <add> * List out all of the possible version numbers for config files that openmrs has DTDs for. <add> * These are usually stored at http://resources.openmrs.org/doctype/config-x.x.dt <add> */ <add> private static List<String> validConfigVersions = new ArrayList<String>(); <add> <add> static { <add> validConfigVersions.add("1.0"); <add> validConfigVersions.add("1.1"); <add> validConfigVersions.add("1.2"); <add> } <add> <add> /** <ide> * Constructor <ide> * <ide> * @param moduleFile the module (jar)file that will be parsed <ide> throw new ModuleException("Module file does not have the correct .omod file extension", moduleFile.getName()); <ide> <ide> this.moduleFile = moduleFile; <del> } <del> <del> private List<String> validConfigVersions() { <del> List<String> versions = new Vector<String>(); <del> versions.add("1.0"); <del> return versions; <ide> } <ide> <ide> /** <ide> <ide> String configVersion = rootNode.getAttribute("configVersion"); <ide> <del> if (!validConfigVersions().contains(configVersion)) <add> if (!validConfigVersions.contains(configVersion)) <ide> throw new ModuleException("Invalid config version: " + configVersion, moduleFile.getName()); <ide> <ide> String name = getElement(rootNode, configVersion, "name");
Java
mit
60f0885958c0600ee7eff0eaa0045694d2e89501
0
AfricasTalkingLtd/africastalking-java,AfricasTalkingLtd/africastalking-java,AfricasTalkingLtd/africastalking-java
package com.africastalking.example; import com.africastalking.*; import com.africastalking.payment.recipient.Consumer; import com.africastalking.voice.action.*; import com.google.gson.Gson; import java.io.IOException; import java.net.*; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import spark.ModelAndView; import spark.template.handlebars.HandlebarsTemplateEngine; import static spark.Spark.exception; import static spark.Spark.get; import static spark.Spark.port; import static spark.Spark.post; import static spark.Spark.staticFiles; public class App { private static final int HTTP_PORT = 8080; private static final int RPC_PORT = 35897; private static final String USERNAME = BuildConfig.USERNAME; private static final String API_KEY = BuildConfig.API_KEY; private static Gson gson = new Gson(); private static HandlebarsTemplateEngine hbs = new HandlebarsTemplateEngine("/views"); private static Server server; private static SmsService sms; private static AirtimeService airtime; private static PaymentService payment; private static void log(String message) { System.out.println(message); } private static void setupAfricastalking() throws IOException { // SDK Server AfricasTalking.initialize(USERNAME, API_KEY); AfricasTalking.setLogger(new Logger(){ @Override public void log(String message, Object... args) { System.out.println(message); } }); sms = AfricasTalking.getService(AfricasTalking.SERVICE_SMS); airtime = AfricasTalking.getService(AirtimeService.class); payment = AfricasTalking.getService(AfricasTalking.SERVICE_PAYMENT); server = new Server(); server.startInsecure(); } public static void main(String[] args) throws IOException { InetAddress host = Inet4Address.getLocalHost(); log("\n"); log(String.format("SDK Server: %s:%d", host.getHostAddress(), RPC_PORT)); log(String.format("HTTP Server: %s:%d", host.getHostAddress(), HTTP_PORT)); log("\n"); HashMap<String, String> states = new HashMap<>(); String baseUrl = "http://aksalj.ngrok.io"; String songUrl = "https://upload.wikimedia.org/wikipedia/commons/transcoded/4/49/National_Anthem_of_Kenya.ogg/National_Anthem_of_Kenya.ogg.mp3"; setupAfricastalking(); port(HTTP_PORT); staticFiles.location("/public"); exception(Exception.class, (e, req, res) -> e.printStackTrace()); // print all exceptions get("/", (req, res) -> { Map<String, Object> data = new HashMap<>(); data.put("req", req.pathInfo()); return render("index", data); }); // Send SMS post("/auth/register/:phone", (req, res) -> sms.send("Welcome to Awesome Company", "AT2FA", new String[] {req.params("phone")}, false), gson::toJson); // Send Airtime post("/airtime/:phone", (req, res) -> airtime.send(req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount"))), gson::toJson); // Mobile Checkout post("/mobile/checkout/:phone", (req, res) -> payment.mobileCheckout("TestProduct", req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount")), null, req.queryParams("providerChannel")), gson::toJson); // Mobile B2C post("/mobile/b2c/:phone", (req, res) -> payment.mobileB2C("TestProduct", Arrays.asList(new Consumer("Boby", req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount")), Consumer.REASON_SALARY))), gson::toJson); post("/voice", (req, res) -> { // Parse POST data String[] raw = URLDecoder.decode(req.body()).split("&"); Map<String, String> data = new HashMap<>(); for (String item: raw) { String [] kw = item.split("="); if (kw.length == 2) { data.put(kw[0], kw[1]); } } // Prep state boolean isActive = data.get("isActive").contentEquals("1"); String sessionId = data.get("sessionId"); String callerNumber = data.get("callerNumber"); String dtmf = data.get("dtmfDigits"); String state = isActive ? states.getOrDefault(sessionId, "menu") : ""; ActionBuilder response = new ActionBuilder(); switch (state) { case "menu": states.put(sessionId, "process"); response .say(new Say("Hello bot " + data.getOrDefault("callerNumber", "There"))) .getDigits(new GetDigits(new Say("Press 1 to listen to some song. Press 2 to tell me your name. Press 3 to talk to a human. Press 4 or hang up to quit"), 1, "#", null)); break; case "process": switch (dtmf) { case "1": states.put(sessionId, "menu"); response .play(new Play(new URL(songUrl))) .redirect(new Redirect(new URL(baseUrl + "/voice"))); break; case "2": states.put(sessionId, "name"); response.record(new Record(new Say("Please say your full name after the beep"), "#", 30, 0, true, true, null)); break; case "3": states.remove(sessionId); response .say(new Say("We are getting our resident human on the line for you, please wait while enjoying this nice tune. You have 30 seconds to enjoy a nice conversation with them")) .dial(new Dial(Arrays.asList("+254718769882"), false, false, null, new URL(songUrl), 30)); break; case "4": states.remove(sessionId); response.say(new Say("Bye Bye, Long Live Our Machine Overlords")).reject(new Reject()); break; default: states.put(sessionId, "menu"); response .say(new Say("Invalid choice, try again and you will be exterminated!")) .redirect(new Redirect(new URL(baseUrl + "/voice"))); break; } break; case "name": states.put(sessionId, "menu"); response .say(new Say("Your human name is")) .play(new Play(new URL(data.get("recordingUrl")))) .say(new Say("Now forget is, you new name is bot " + callerNumber)) .redirect(new Redirect(new URL(baseUrl + "/voice"))); break; default: response.say(new Say("Well, this is unexpected! Bye Bye, Long Live Our Machine Overlords")).reject(new Reject()); break; } return response.build(); }); } private static String render(String view, Map data) { return hbs.render(new ModelAndView(data, view + ".hbs")); } }
example/src/main/java/com/africastalking/example/App.java
package com.africastalking.example; import com.africastalking.*; import com.africastalking.payment.recipient.Consumer; import com.africastalking.voice.action.*; import com.google.gson.Gson; import java.io.IOException; import java.net.*; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import spark.ModelAndView; import spark.template.handlebars.HandlebarsTemplateEngine; import static spark.Spark.exception; import static spark.Spark.get; import static spark.Spark.port; import static spark.Spark.post; import static spark.Spark.staticFiles; public class App { private static final int HTTP_PORT = 8080; private static final int RPC_PORT = 35897; private static final String USERNAME = BuildConfig.USERNAME; private static final String API_KEY = BuildConfig.API_KEY; private static Gson gson = new Gson(); private static HandlebarsTemplateEngine hbs = new HandlebarsTemplateEngine("/views"); private static Server server; private static SmsService sms; private static AirtimeService airtime; private static PaymentService payment; private static void log(String message) { System.out.println(message); } private static void setupAfricastalking() throws IOException { // SDK Server AfricasTalking.initialize(USERNAME, API_KEY); AfricasTalking.setLogger(new Logger(){ @Override public void log(String message, Object... args) { System.out.println(message); } }); sms = AfricasTalking.getService(AfricasTalking.SERVICE_SMS); airtime = AfricasTalking.getService(AirtimeService.class); payment = AfricasTalking.getService(AfricasTalking.SERVICE_PAYMENT); server = new Server(); server.startInsecure(); } public static void main(String[] args) throws IOException { InetAddress host = Inet4Address.getLocalHost(); log("\n"); log(String.format("SDK Server: %s:%d", host.getHostAddress(), RPC_PORT)); log(String.format("HTTP Server: %s:%d", host.getHostAddress(), HTTP_PORT)); log("\n"); HashMap<String, String> states = new HashMap<>(); String baseUrl = "http://aksalj.ngrok.io"; String songUrl = "https://upload.wikimedia.org/wikipedia/commons/transcoded/4/49/National_Anthem_of_Kenya.ogg/National_Anthem_of_Kenya.ogg.mp3"; setupAfricastalking(); port(HTTP_PORT); staticFiles.location("/public"); exception(Exception.class, (e, req, res) -> e.printStackTrace()); // print all exceptions get("/", (req, res) -> { Map<String, Object> data = new HashMap<>(); data.put("req", req.pathInfo()); return render("index", data); }); // Send SMS post("/auth/register/:phone", (req, res) -> sms.send("Welcome to Awesome Company", "AT2FA", new String[] {req.params("phone")}, false), gson::toJson); // Send Airtime post("/airtime/:phone", (req, res) -> airtime.send(req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount"))), gson::toJson); // Mobile Checkout post("/mobile/checkout/:phone", (req, res) -> payment.mobileCheckout("TestProduct", req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount")), null), gson::toJson); // Mobile B2C post("/mobile/b2c/:phone", (req, res) -> payment.mobileB2C("TestProduct", Arrays.asList(new Consumer("Boby", req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount")), Consumer.REASON_SALARY))), gson::toJson); post("/voice", (req, res) -> { // Parse POST data String[] raw = URLDecoder.decode(req.body()).split("&"); Map<String, String> data = new HashMap<>(); for (String item: raw) { String [] kw = item.split("="); if (kw.length == 2) { data.put(kw[0], kw[1]); } } // Prep state boolean isActive = data.get("isActive").contentEquals("1"); String sessionId = data.get("sessionId"); String callerNumber = data.get("callerNumber"); String dtmf = data.get("dtmfDigits"); String state = isActive ? states.getOrDefault(sessionId, "menu") : ""; ActionBuilder response = new ActionBuilder(); switch (state) { case "menu": states.put(sessionId, "process"); response .say(new Say("Hello bot " + data.getOrDefault("callerNumber", "There"))) .getDigits(new GetDigits(new Say("Press 1 to listen to some song. Press 2 to tell me your name. Press 3 to talk to a human. Press 4 or hang up to quit"), 1, "#", null)); break; case "process": switch (dtmf) { case "1": states.put(sessionId, "menu"); response .play(new Play(new URL(songUrl))) .redirect(new Redirect(new URL(baseUrl + "/voice"))); break; case "2": states.put(sessionId, "name"); response.record(new Record(new Say("Please say your full name after the beep"), "#", 30, 0, true, true, null)); break; case "3": states.remove(sessionId); response .say(new Say("We are getting our resident human on the line for you, please wait while enjoying this nice tune. You have 30 seconds to enjoy a nice conversation with them")) .dial(new Dial(Arrays.asList("+254718769882"), false, false, null, new URL(songUrl), 30)); break; case "4": states.remove(sessionId); response.say(new Say("Bye Bye, Long Live Our Machine Overlords")).reject(new Reject()); break; default: states.put(sessionId, "menu"); response .say(new Say("Invalid choice, try again and you will be exterminated!")) .redirect(new Redirect(new URL(baseUrl + "/voice"))); break; } break; case "name": states.put(sessionId, "menu"); response .say(new Say("Your human name is")) .play(new Play(new URL(data.get("recordingUrl")))) .say(new Say("Now forget is, you new name is bot " + callerNumber)) .redirect(new Redirect(new URL(baseUrl + "/voice"))); break; default: response.say(new Say("Well, this is unexpected! Bye Bye, Long Live Our Machine Overlords")).reject(new Reject()); break; } return response.build(); }); } private static String render(String view, Map data) { return hbs.render(new ModelAndView(data, view + ".hbs")); } }
Update example App
example/src/main/java/com/africastalking/example/App.java
Update example App
<ide><path>xample/src/main/java/com/africastalking/example/App.java <ide> post("/airtime/:phone", (req, res) -> airtime.send(req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount"))), gson::toJson); <ide> <ide> // Mobile Checkout <del> post("/mobile/checkout/:phone", (req, res) -> payment.mobileCheckout("TestProduct", req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount")), null), gson::toJson); <add> post("/mobile/checkout/:phone", (req, res) -> payment.mobileCheckout("TestProduct", req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount")), null, req.queryParams("providerChannel")), gson::toJson); <ide> <ide> // Mobile B2C <ide> post("/mobile/b2c/:phone", (req, res) -> payment.mobileB2C("TestProduct", Arrays.asList(new Consumer("Boby", req.params("phone"), req.queryParams("currencyCode"), Float.parseFloat(req.queryParams("amount")), Consumer.REASON_SALARY))), gson::toJson);
Java
apache-2.0
09f656809fed47d4d8d5b263c194bb2ea0867bee
0
ol-loginov/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,signed/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,apixandru/intellij-community,allotria/intellij-community,vvv1559/intellij-community,caot/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,izonder/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,samthor/intellij-community,fitermay/intellij-community,allotria/intellij-community,izonder/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,adedayo/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,amith01994/intellij-community,izonder/intellij-community,blademainer/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,caot/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,caot/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,holmes/intellij-community,fnouama/intellij-community,clumsy/intellij-community,jagguli/intellij-community,kdwink/intellij-community,fitermay/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,xfournet/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,supersven/intellij-community,kool79/intellij-community,jagguli/intellij-community,asedunov/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,kdwink/intellij-community,xfournet/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,FHannes/intellij-community,da1z/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,amith01994/intellij-community,FHannes/intellij-community,supersven/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,samthor/intellij-community,holmes/intellij-community,diorcety/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,clumsy/intellij-community,kdwink/intellij-community,retomerz/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,slisson/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,xfournet/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,kool79/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,izonder/intellij-community,kdwink/intellij-community,holmes/intellij-community,gnuhub/intellij-community,caot/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,robovm/robovm-studio,apixandru/intellij-community,robovm/robovm-studio,supersven/intellij-community,clumsy/intellij-community,da1z/intellij-community,ibinti/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,signed/intellij-community,adedayo/intellij-community,da1z/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,ryano144/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,samthor/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,slisson/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,jagguli/intellij-community,kool79/intellij-community,semonte/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,supersven/intellij-community,nicolargo/intellij-community,caot/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,fnouama/intellij-community,robovm/robovm-studio,dslomov/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,samthor/intellij-community,xfournet/intellij-community,xfournet/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,blademainer/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,semonte/intellij-community,da1z/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,signed/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,vladmm/intellij-community,ibinti/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,signed/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,TangHao1987/intellij-community,signed/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,allotria/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,da1z/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,signed/intellij-community,slisson/intellij-community,hurricup/intellij-community,petteyg/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,caot/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,blademainer/intellij-community,dslomov/intellij-community,da1z/intellij-community,FHannes/intellij-community,hurricup/intellij-community,signed/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,semonte/intellij-community,adedayo/intellij-community,diorcety/intellij-community,blademainer/intellij-community,kool79/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,fnouama/intellij-community,blademainer/intellij-community,kool79/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,xfournet/intellij-community,kool79/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,da1z/intellij-community,samthor/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,asedunov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,semonte/intellij-community,supersven/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,slisson/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,signed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,allotria/intellij-community,hurricup/intellij-community,holmes/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,signed/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,robovm/robovm-studio,asedunov/intellij-community,ibinti/intellij-community,semonte/intellij-community,vladmm/intellij-community,robovm/robovm-studio,holmes/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,kool79/intellij-community,retomerz/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,caot/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,semonte/intellij-community,ryano144/intellij-community,slisson/intellij-community,nicolargo/intellij-community,holmes/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,retomerz/intellij-community,fitermay/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,hurricup/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,jagguli/intellij-community,apixandru/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,slisson/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,vladmm/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,allotria/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,supersven/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,signed/intellij-community,allotria/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,slisson/intellij-community,adedayo/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,ryano144/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,caot/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,kool79/intellij-community,kdwink/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,FHannes/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,signed/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,fitermay/intellij-community,slisson/intellij-community,hurricup/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,signed/intellij-community,amith01994/intellij-community,dslomov/intellij-community,kool79/intellij-community,samthor/intellij-community,da1z/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,adedayo/intellij-community,caot/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,fnouama/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,slisson/intellij-community,petteyg/intellij-community,caot/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,diorcety/intellij-community,supersven/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,petteyg/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.bytecodeAnalysis; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.NullableLazyValue; import com.intellij.util.indexing.DataIndexer; import com.intellij.util.indexing.FileContent; import org.jetbrains.annotations.NotNull; import org.jetbrains.org.objectweb.asm.*; import org.jetbrains.org.objectweb.asm.tree.MethodNode; import org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.intellij.codeInspection.bytecodeAnalysis.ProjectBytecodeAnalysis.LOG; /** * @author lambdamix */ public class ClassDataIndexer implements DataIndexer<HKey, HResult, FileContent> { @NotNull @Override public Map<HKey, HResult> map(@NotNull FileContent inputData) { HashMap<HKey, HResult> map = new HashMap<HKey, HResult>(); try { MessageDigest md = BytecodeAnalysisConverter.getMessageDigest(); ClassEquations rawEquations = processClass(new ClassReader(inputData.getContent()), inputData.getFile().getPresentableUrl()); List<Equation<Key, Value>> rawParameterEquations = rawEquations.parameterEquations; List<Equation<Key, Value>> rawContractEquations = rawEquations.contractEquations; for (Equation<Key, Value> rawParameterEquation: rawParameterEquations) { HEquation equation = BytecodeAnalysisConverter.convert(rawParameterEquation, md); map.put(equation.key, equation.result); } for (Equation<Key, Value> rawContractEquation: rawContractEquations) { HEquation equation = BytecodeAnalysisConverter.convert(rawContractEquation, md); map.put(equation.key, equation.result); } } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { // incorrect bytecode may result in Runtime exceptions during analysis // so here we suppose that exception is due to incorrect bytecode LOG.debug("Unexpected Error during indexing of bytecode", e); } return map; } private static class ClassEquations { final List<Equation<Key, Value>> parameterEquations; final List<Equation<Key, Value>> contractEquations; private ClassEquations(List<Equation<Key, Value>> parameterEquations, List<Equation<Key, Value>> contractEquations) { this.parameterEquations = parameterEquations; this.contractEquations = contractEquations; } } public static ClassEquations processClass(final ClassReader classReader, final String presentableUrl) { final List<Equation<Key, Value>> parameterEquations = new ArrayList<Equation<Key, Value>>(); final List<Equation<Key, Value>> contractEquations = new ArrayList<Equation<Key, Value>>(); classReader.accept(new ClassVisitor(Opcodes.ASM5) { private boolean stableClass; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { stableClass = (access & Opcodes.ACC_FINAL) != 0; super.visit(version, access, name, signature, superName, interfaces); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { final MethodNode node = new MethodNode(Opcodes.ASM5, access, name, desc, signature, exceptions); return new MethodVisitor(Opcodes.ASM5, node) { @Override public void visitEnd() { super.visitEnd(); processMethod(classReader.getClassName(), node, stableClass); } }; } void processMethod(final String className, final MethodNode methodNode, boolean stableClass) { ProgressManager.checkCanceled(); Type[] argumentTypes = Type.getArgumentTypes(methodNode.desc); Type resultType = Type.getReturnType(methodNode.desc); int resultSort = resultType.getSort(); boolean isReferenceResult = resultSort == Type.OBJECT || resultSort == Type.ARRAY; boolean isBooleanResult = Type.BOOLEAN_TYPE == resultType; boolean isInterestingResult = isReferenceResult || isBooleanResult; if (argumentTypes.length == 0 && !isInterestingResult) { return; } final Method method = new Method(className, methodNode.name, methodNode.desc); int access = methodNode.access; final boolean stable = stableClass || (access & Opcodes.ACC_FINAL) != 0 || (access & Opcodes.ACC_PRIVATE) != 0 || (access & Opcodes.ACC_STATIC) != 0 || "<init>".equals(methodNode.name); try { boolean added = false; final ControlFlowGraph graph = cfg.buildControlFlowGraph(className, methodNode); boolean maybeLeakingParameter = false; for (Type argType : argumentTypes) { int argSort = argType.getSort(); if (argSort == Type.OBJECT || argSort == Type.ARRAY || (isInterestingResult && Type.BOOLEAN_TYPE.equals(argType))) { maybeLeakingParameter = true; break; } } if (graph.transitions.length > 0) { final DFSTree dfs = cfg.buildDFSTree(graph.transitions); boolean reducible = dfs.back.isEmpty() || cfg.reducible(graph, dfs); if (reducible) { final NullableLazyValue<boolean[]> resultOrigins = new NullableLazyValue<boolean[]>() { @Override protected boolean[] compute() { try { return cfg.resultOrigins(className, methodNode); } catch (AnalyzerException e) { return null; } catch (LimitReachedException e) { return null; } } }; NotNullLazyValue<Equation<Key, Value>> resultEquation = new NotNullLazyValue<Equation<Key, Value>>() { @NotNull @Override protected Equation<Key, Value> compute() { boolean[] origins = resultOrigins.getValue(); if (origins != null) { try { return new InOutAnalysis(new RichControlFlow(graph, dfs), new Out(), origins, stable).analyze(); } catch (AnalyzerException ignored) { } } return new Equation<Key, Value>(new Key(method, new Out(), stable), new Final<Key, Value>(Value.Top)); } }; boolean[] leakingParameters = maybeLeakingParameter ? cfg.leakingParameters(className, methodNode) : null; if (isReferenceResult) { contractEquations.add(resultEquation.getValue()); } for (int i = 0; i < argumentTypes.length; i++) { Type argType = argumentTypes[i]; int argSort = argType.getSort(); boolean isReferenceArg = argSort == Type.OBJECT || argSort == Type.ARRAY; boolean isBooleanArg = Type.BOOLEAN_TYPE.equals(argType); boolean notNullParam = false; if (isReferenceArg) { if (leakingParameters[i]) { Equation<Key, Value> notNullParamEquation = new NonNullInAnalysis(new RichControlFlow(graph, dfs), new In(i), stable).analyze(); notNullParam = notNullParamEquation.rhs.equals(new Final<Key, Value>(Value.NotNull)); parameterEquations.add(notNullParamEquation); } else { // parameter is not leaking, so it is definitely NOT @NotNull parameterEquations.add(new Equation<Key, Value>(new Key(method, new In(i), stable), new Final<Key, Value>(Value.Top))); } } if (isReferenceArg && isInterestingResult) { if (leakingParameters[i]) { if (resultOrigins.getValue() != null) { // result origins analysis was ok if (!notNullParam) { // may be null on some branch contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.Null), resultOrigins.getValue(), stable).analyze()); } else { // definitely NPE -> bottom contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.Null), stable), new Final<Key, Value>(Value.Bot))); } contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.NotNull), resultOrigins.getValue(), stable).analyze()); } else { // result origins analysis failed, approximating to Top contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.Null), stable), new Final<Key, Value>(Value.Top))); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.NotNull), stable), new Final<Key, Value>(Value.Top))); } } else { // parameter is not leaking, so a contract is the same as for the whole method contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.Null), stable), resultEquation.getValue().rhs)); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.NotNull), stable), resultEquation.getValue().rhs)); } } if (isBooleanArg && isInterestingResult) { if (leakingParameters[i]) { if (resultOrigins.getValue() != null) { // result origins analysis was ok contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.False), resultOrigins.getValue(), stable).analyze()); contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.True), resultOrigins.getValue(), stable).analyze()); } else { // result origins analysis failed, approximating to Top contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.False), stable), new Final<Key, Value>(Value.Top))); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.True), stable), new Final<Key, Value>(Value.Top))); } } else { // parameter is not leaking, so a contract is the same as for the whole method contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.False), stable), resultEquation.getValue().rhs)); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.True), stable), resultEquation.getValue().rhs)); } } } added = true; } else { LOG.debug("CFG for " + method + " is not reducible"); } } if (!added) { if (isReferenceResult) { contractEquations.add(new Equation<Key, Value>(new Key(method, new Out(), stable), new Final<Key, Value>(Value.Top))); } for (int i = 0; i < argumentTypes.length; i++) { Type argType = argumentTypes[i]; int argSort = argType.getSort(); boolean isReferenceArg = argSort == Type.OBJECT || argSort == Type.ARRAY; boolean isBooleanArg = Type.BOOLEAN_TYPE.equals(argType); if (isReferenceArg) { parameterEquations.add(new Equation<Key, Value>(new Key(method, new In(i), stable), new Final<Key, Value>(Value.Top))); } if (isReferenceArg && isInterestingResult) { contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.Null), stable), new Final<Key, Value>(Value.Top))); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.NotNull), stable), new Final<Key, Value>(Value.Top))); } if (isBooleanArg && isInterestingResult) { contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.False), stable), new Final<Key, Value>(Value.Top))); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.True), stable), new Final<Key, Value>(Value.Top))); } } } } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { // incorrect bytecode may result in Runtime exceptions during analysis // so here we suppose that exception is due to incorrect bytecode LOG.debug("Unexpected Error during processing of " + method + " in " + presentableUrl, e); } } }, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); return new ClassEquations(parameterEquations, contractEquations); } }
java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/ClassDataIndexer.java
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.bytecodeAnalysis; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.NullableLazyValue; import com.intellij.util.indexing.DataIndexer; import com.intellij.util.indexing.FileContent; import org.jetbrains.annotations.NotNull; import org.jetbrains.org.objectweb.asm.*; import org.jetbrains.org.objectweb.asm.tree.MethodNode; import org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.intellij.codeInspection.bytecodeAnalysis.ProjectBytecodeAnalysis.LOG; /** * @author lambdamix */ public class ClassDataIndexer implements DataIndexer<HKey, HResult, FileContent> { @NotNull @Override public Map<HKey, HResult> map(@NotNull FileContent inputData) { HashMap<HKey, HResult> map = new HashMap<HKey, HResult>(); try { MessageDigest md = BytecodeAnalysisConverter.getMessageDigest(); ClassEquations rawEquations = processClass(new ClassReader(inputData.getContent()), inputData.getFile().getPresentableUrl()); List<Equation<Key, Value>> rawParameterEquations = rawEquations.parameterEquations; List<Equation<Key, Value>> rawContractEquations = rawEquations.contractEquations; for (Equation<Key, Value> rawParameterEquation: rawParameterEquations) { HEquation equation = BytecodeAnalysisConverter.convert(rawParameterEquation, md); map.put(equation.key, equation.result); } for (Equation<Key, Value> rawContractEquation: rawContractEquations) { HEquation equation = BytecodeAnalysisConverter.convert(rawContractEquation, md); map.put(equation.key, equation.result); } } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { // incorrect bytecode may result in Runtime exceptions during analysis // so here we suppose that exception is due to incorrect bytecode LOG.debug("Unexpected Error during indexing of bytecode", e); } return map; } private static class ClassEquations { final List<Equation<Key, Value>> parameterEquations; final List<Equation<Key, Value>> contractEquations; private ClassEquations(List<Equation<Key, Value>> parameterEquations, List<Equation<Key, Value>> contractEquations) { this.parameterEquations = parameterEquations; this.contractEquations = contractEquations; } } public static ClassEquations processClass(final ClassReader classReader, final String presentableUrl) { final List<Equation<Key, Value>> parameterEquations = new ArrayList<Equation<Key, Value>>(); final List<Equation<Key, Value>> contractEquations = new ArrayList<Equation<Key, Value>>(); classReader.accept(new ClassVisitor(Opcodes.ASM5) { private boolean stableClass; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { stableClass = (access & Opcodes.ACC_FINAL) != 0; super.visit(version, access, name, signature, superName, interfaces); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { final MethodNode node = new MethodNode(Opcodes.ASM5, access, name, desc, signature, exceptions); return new MethodVisitor(Opcodes.ASM5, node) { @Override public void visitEnd() { super.visitEnd(); processMethod(classReader.getClassName(), node, stableClass); } }; } void processMethod(final String className, final MethodNode methodNode, boolean stableClass) { ProgressManager.checkCanceled(); Type[] argumentTypes = Type.getArgumentTypes(methodNode.desc); Type resultType = Type.getReturnType(methodNode.desc); int resultSort = resultType.getSort(); boolean isReferenceResult = resultSort == Type.OBJECT || resultSort == Type.ARRAY; boolean isBooleanResult = Type.BOOLEAN_TYPE == resultType; boolean isInterestingResult = isReferenceResult || isBooleanResult; if (argumentTypes.length == 0 && !isInterestingResult) { return; } final Method method = new Method(className, methodNode.name, methodNode.desc); int access = methodNode.access; final boolean stable = stableClass || (access & Opcodes.ACC_FINAL) != 0 || (access & Opcodes.ACC_PRIVATE) != 0 || (access & Opcodes.ACC_STATIC) != 0 || "<init>".equals(methodNode.name); try { boolean added = false; final ControlFlowGraph graph = cfg.buildControlFlowGraph(className, methodNode); boolean maybeLeakingParameter = false; for (Type argType : argumentTypes) { int argSort = argType.getSort(); if (argSort == Type.OBJECT || argSort == Type.ARRAY || (isInterestingResult && Type.BOOLEAN_TYPE.equals(argType))) { maybeLeakingParameter = true; break; } } if (graph.transitions.length > 0) { final DFSTree dfs = cfg.buildDFSTree(graph.transitions); boolean reducible = dfs.back.isEmpty() || cfg.reducible(graph, dfs); if (reducible) { final NullableLazyValue<boolean[]> resultOrigins = new NullableLazyValue<boolean[]>() { @Override protected boolean[] compute() { try { return cfg.resultOrigins(className, methodNode); } catch (AnalyzerException e) { return null; } catch (LimitReachedException e) { return null; } } }; NotNullLazyValue<Equation<Key, Value>> resultEquation = new NotNullLazyValue<Equation<Key, Value>>() { @NotNull @Override protected Equation<Key, Value> compute() { boolean[] origins = resultOrigins.getValue(); if (origins != null) { try { return new InOutAnalysis(new RichControlFlow(graph, dfs), new Out(), origins, stable).analyze(); } catch (AnalyzerException ignored) { } } return new Equation<Key, Value>(new Key(method, new Out(), stable), new Final<Key, Value>(Value.Top)); } }; boolean[] leakingParameters = maybeLeakingParameter ? cfg.leakingParameters(className, methodNode) : null; if (isReferenceResult) { contractEquations.add(resultEquation.getValue()); } for (int i = 0; i < argumentTypes.length; i++) { Type argType = argumentTypes[i]; int argSort = argType.getSort(); boolean isReferenceArg = argSort == Type.OBJECT || argSort == Type.ARRAY; boolean isBooleanArg = Type.BOOLEAN_TYPE.equals(argType); if (isReferenceArg) { if (leakingParameters[i]) { parameterEquations.add(new NonNullInAnalysis(new RichControlFlow(graph, dfs), new In(i), stable).analyze()); } else { // parameter is not leaking, so it is definitely NOT @NotNull parameterEquations.add(new Equation<Key, Value>(new Key(method, new In(i), stable), new Final<Key, Value>(Value.Top))); } } if (isReferenceArg && isInterestingResult) { if (leakingParameters[i]) { if (resultOrigins.getValue() != null) { // result origins analysis was ok contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.Null), resultOrigins.getValue(), stable).analyze()); contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.NotNull), resultOrigins.getValue(), stable).analyze()); } else { // result origins analysis failed, approximating to Top contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.Null), stable), new Final<Key, Value>(Value.Top))); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.NotNull), stable), new Final<Key, Value>(Value.Top))); } } else { // parameter is not leaking, so a contract is the same as for the whole method contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.Null), stable), resultEquation.getValue().rhs)); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.NotNull), stable), resultEquation.getValue().rhs)); } } if (isBooleanArg && isInterestingResult) { if (leakingParameters[i]) { if (resultOrigins.getValue() != null) { // result origins analysis was ok contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.False), resultOrigins.getValue(), stable).analyze()); contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.True), resultOrigins.getValue(), stable).analyze()); } else { // result origins analysis failed, approximating to Top contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.False), stable), new Final<Key, Value>(Value.Top))); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.True), stable), new Final<Key, Value>(Value.Top))); } } else { // parameter is not leaking, so a contract is the same as for the whole method contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.False), stable), resultEquation.getValue().rhs)); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.True), stable), resultEquation.getValue().rhs)); } } } added = true; } else { LOG.debug("CFG for " + method + " is not reducible"); } } if (!added) { if (isReferenceResult) { contractEquations.add(new Equation<Key, Value>(new Key(method, new Out(), stable), new Final<Key, Value>(Value.Top))); } for (int i = 0; i < argumentTypes.length; i++) { Type argType = argumentTypes[i]; int argSort = argType.getSort(); boolean isReferenceArg = argSort == Type.OBJECT || argSort == Type.ARRAY; boolean isBooleanArg = Type.BOOLEAN_TYPE.equals(argType); if (isReferenceArg) { parameterEquations.add(new Equation<Key, Value>(new Key(method, new In(i), stable), new Final<Key, Value>(Value.Top))); } if (isReferenceArg && isInterestingResult) { contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.Null), stable), new Final<Key, Value>(Value.Top))); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.NotNull), stable), new Final<Key, Value>(Value.Top))); } if (isBooleanArg && isInterestingResult) { contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.False), stable), new Final<Key, Value>(Value.Top))); contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.True), stable), new Final<Key, Value>(Value.Top))); } } } } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { // incorrect bytecode may result in Runtime exceptions during analysis // so here we suppose that exception is due to incorrect bytecode LOG.debug("Unexpected Error during processing of " + method + " in " + presentableUrl, e); } } }, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); return new ClassEquations(parameterEquations, contractEquations); } }
optimization: no need to infer null->... if param is @NotNull
java/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/ClassDataIndexer.java
optimization: no need to infer null->... if param is @NotNull
<ide><path>ava/java-analysis-impl/src/com/intellij/codeInspection/bytecodeAnalysis/ClassDataIndexer.java <ide> int argSort = argType.getSort(); <ide> boolean isReferenceArg = argSort == Type.OBJECT || argSort == Type.ARRAY; <ide> boolean isBooleanArg = Type.BOOLEAN_TYPE.equals(argType); <add> boolean notNullParam = false; <ide> if (isReferenceArg) { <ide> if (leakingParameters[i]) { <del> parameterEquations.add(new NonNullInAnalysis(new RichControlFlow(graph, dfs), new In(i), stable).analyze()); <add> Equation<Key, Value> notNullParamEquation = new NonNullInAnalysis(new RichControlFlow(graph, dfs), new In(i), stable).analyze(); <add> notNullParam = notNullParamEquation.rhs.equals(new Final<Key, Value>(Value.NotNull)); <add> parameterEquations.add(notNullParamEquation); <ide> } <ide> else { <ide> // parameter is not leaking, so it is definitely NOT @NotNull <ide> if (leakingParameters[i]) { <ide> if (resultOrigins.getValue() != null) { <ide> // result origins analysis was ok <del> contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.Null), resultOrigins.getValue(), stable).analyze()); <add> if (!notNullParam) { <add> // may be null on some branch <add> contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.Null), resultOrigins.getValue(), stable).analyze()); <add> } else { <add> // definitely NPE -> bottom <add> contractEquations.add(new Equation<Key, Value>(new Key(method, new InOut(i, Value.Null), stable), new Final<Key, Value>(Value.Bot))); <add> } <ide> contractEquations.add(new InOutAnalysis(new RichControlFlow(graph, dfs), new InOut(i, Value.NotNull), resultOrigins.getValue(), stable).analyze()); <ide> } <ide> else {
Java
mit
173018a7cefff72bf352ff7bff9cc4b470696ba0
0
ev3dev-lang-java/ev3dev-lang-java,jabrena/ev3dev-lang-java
package ev3dev.utils; import org.slf4j.Logger; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The class responsible to interact with Sysfs on EV3Dev * * @author Juan Antonio Breña Moral * */ public class Sysfs { private static final Logger log = org.slf4j.LoggerFactory.getLogger(Sysfs.class); /** * Write a value in a file. * * @param filePath File path * @param value value to write * @return A boolean value if the operation was written or not. */ public static boolean writeString(final String filePath, final String value) { if(log.isTraceEnabled()) log.trace("echo " + value + " > " + filePath); try { final File file = new File(filePath); if(file.canWrite()) { //TODO Review if it possible to improve PrintWriter out = new PrintWriter(file); out.println(value); out.flush(); out.close(); //TODO Review }else { log.error("File: '{}' without write permissions.", filePath); return false; } } catch (IOException e) { log.error(e.getLocalizedMessage(), e); return false; } return true; } public static boolean writeInteger(final String filePath, final int value) { return writeString(filePath, new StringBuilder().append(value).toString()); } /** * Read an Attribute in the Sysfs with containing String values * @param filePath path * @return value from attribute */ public static String readString(final String filePath) { if(log.isTraceEnabled()) log.trace("cat " + filePath); try { final Path path = Paths.get(filePath); if(existFile(path) && Files.isReadable(path)){ final String result = Files.readAllLines(path, Charset.forName("UTF-8")).get(0); if(log.isTraceEnabled()) log.trace("value: {}", result); return result; } throw new IOException("Problem reading path: " + filePath); } catch (IOException e) { log.error(e.getLocalizedMessage(), e); throw new RuntimeException("Problem reading path: " + filePath, e); } } /** * Read an Attribute in the Sysfs with containing Integer values * @param filePath path * @return value from attribute */ public static int readInteger(final String filePath) { return Integer.parseInt(readString(filePath)); } public static float readFloat(final String filePath) { return Float.parseFloat(readString(filePath)); } /** * * @param filePath path * @return an List with options from a path */ public static List<File> getElements(final String filePath) { final File f = new File(filePath); if(existPath(filePath) && (f.listFiles().length > 0)) { return new ArrayList<>(Arrays.asList(f.listFiles())); }else { throw new RuntimeException("The path doesn't exist: " + filePath); } } /** * This method is used to detect folders in /sys/class/ * * @param filePath path * @return boolean */ public static boolean existPath(final String filePath){ if(log.isTraceEnabled()) log.trace("ls " + filePath); final File f = new File(filePath); return f.exists() && f.isDirectory(); } public static boolean existFile(Path pathToFind) { return Files.exists(pathToFind); } public static boolean writeBytes(final String path, final byte[] value) { try { Files.write(Paths.get(path), value, StandardOpenOption.WRITE); } catch (IOException e) { throw new RuntimeException("Unable to draw the LCD", e); } return true; } }
src/main/java/ev3dev/utils/Sysfs.java
package ev3dev.utils; import org.slf4j.Logger; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The class responsible to interact with Sysfs on EV3Dev * * @author Juan Antonio Breña Moral * */ public class Sysfs { private static final Logger log = org.slf4j.LoggerFactory.getLogger(Sysfs.class); /** * Write a value in a file. * * @param filePath File path * @param value value to write * @return A boolean value if the operation was written or not. */ public static boolean writeString(final String filePath, final String value) { if(log.isTraceEnabled()) log.trace("echo " + value + " > " + filePath); try { final File file = new File(filePath); if(file.canWrite()) { //TODO Review if it possible to improve PrintWriter out = new PrintWriter(file); out.println(value); out.flush(); out.close(); //TODO Review }else { log.error("File: '{}' without write permissions.", filePath); return false; } } catch (IOException e) { log.error(e.getLocalizedMessage(), e); return false; } return true; } public static boolean writeInteger(final String filePath, final int value) { return writeString(filePath, new StringBuilder().append(value).toString()); } /** * Read an Attribute in the Sysfs with containing String values * @param filePath path * @return value from attribute */ public static String readString(final String filePath) { if(log.isTraceEnabled()) log.trace("cat " + filePath); try { final Path path = Paths.get(filePath); if(existFile(path) && Files.isReadable(path)){ final String result = Files.readAllLines(path, Charset.forName("UTF-8")).get(0); if(log.isTraceEnabled()) log.trace("value: {}", result); return result; } throw new IOException("Problem reading path: " + filePath); } catch (IOException e) { log.error(e.getLocalizedMessage(), e); throw new RuntimeException("Problem reading path: " + filePath, e); } } /** * Read an Attribute in the Sysfs with containing Integer values * @param filePath path * @return value from attribute */ public static int readInteger(final String filePath) { return Integer.parseInt(readString(filePath)); } public static float readFloat(final String filePath) { return Float.parseFloat(readString(filePath)); } /** * * @param filePath path * @return an List with options from a path */ public static List<File> getElements(final String filePath) { final File f = new File(filePath); if(existPath(filePath) && (f.listFiles().length > 0)) { return new ArrayList<>(Arrays.asList(f.listFiles())); }else { throw new RuntimeException("The path doesn't exist: " + filePath); } } /** * This method is used to detect folders in /sys/class/ * * @param filePath path * @return boolean */ public static boolean existPath(final String filePath){ if(log.isTraceEnabled()) log.trace("ls " + filePath); final File f = new File(filePath); return f.exists() && f.isDirectory(); } public static boolean existFile(Path pathToFind) { return Files.exists(pathToFind); } public static boolean writeBytes(final String path, final byte[] value) { final File file = new File(path); try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) { out.write(value); out.flush(); out.close(); } catch (IOException e) { throw new RuntimeException("Unable to draw the LCD", e); } return true; } }
Use Files.write() for LCD write
src/main/java/ev3dev/utils/Sysfs.java
Use Files.write() for LCD write
<ide><path>rc/main/java/ev3dev/utils/Sysfs.java <ide> import java.nio.file.Files; <ide> import java.nio.file.Path; <ide> import java.nio.file.Paths; <add>import java.nio.file.StandardOpenOption; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.List; <ide> <ide> /** <ide> * The class responsible to interact with Sysfs on EV3Dev <del> * <add> * <ide> * @author Juan Antonio Breña Moral <ide> * <ide> */ <ide> <ide> /** <ide> * Write a value in a file. <del> * <add> * <ide> * @param filePath File path <ide> * @param value value to write <ide> * @return A boolean value if the operation was written or not. <ide> } <ide> return true; <ide> } <del> <add> <ide> public static boolean writeInteger(final String filePath, final int value) { <ide> return writeString(filePath, new StringBuilder().append(value).toString()); <ide> } <del> <add> <ide> /** <ide> * Read an Attribute in the Sysfs with containing String values <ide> * @param filePath path <ide> throw new RuntimeException("Problem reading path: " + filePath, e); <ide> } <ide> } <del> <add> <ide> /** <ide> * Read an Attribute in the Sysfs with containing Integer values <ide> * @param filePath path <ide> public static int readInteger(final String filePath) { <ide> return Integer.parseInt(readString(filePath)); <ide> } <del> <add> <ide> public static float readFloat(final String filePath) { <ide> return Float.parseFloat(readString(filePath)); <ide> } <del> <add> <ide> /** <del> * <add> * <ide> * @param filePath path <ide> * @return an List with options from a path <ide> */ <ide> } <ide> <ide> public static boolean writeBytes(final String path, final byte[] value) { <del> final File file = new File(path); <del> try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) { <del> out.write(value); <del> out.flush(); <del> out.close(); <add> try { <add> Files.write(Paths.get(path), value, StandardOpenOption.WRITE); <ide> } catch (IOException e) { <ide> throw new RuntimeException("Unable to draw the LCD", e); <ide> }
JavaScript
agpl-3.0
bef32cc48a6dec8d5fca37380c04d6d48dfd8d0d
0
fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID
/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */ /* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */ "use strict"; /* Only methods of the WebGLApplication object elicit a render. All other methods * do not, except for those that use continuations to load data (meshes) or to * compute with web workers (betweenness centrality shading). */ var WebGLApplication = function() { this.widgetID = this.registerInstance(); this.registerSource(); // Indicates whether init has been called this.initialized = false; // Listen to changes of the active node SkeletonAnnotations.on(SkeletonAnnotations.EVENT_ACTIVE_NODE_CHANGED, this.staticUpdateActiveNodePosition, this); }; WebGLApplication.prototype = {}; $.extend(WebGLApplication.prototype, new InstanceRegistry()); $.extend(WebGLApplication.prototype, new SkeletonSource()); WebGLApplication.prototype.init = function(canvasWidth, canvasHeight, divID) { if (this.initialized) { return; } this.divID = divID; this.container = document.getElementById(divID); this.stack = project.focusedStack; this.submit = new submitterFn(); this.options = new WebGLApplication.prototype.OPTIONS.clone(); this.space = new this.Space(canvasWidth, canvasHeight, this.container, this.stack); this.updateActiveNodePosition(); this.initialized = true; }; WebGLApplication.prototype.getName = function() { return "3D View " + this.widgetID; }; WebGLApplication.prototype.destroy = function() { SkeletonAnnotations.off(SkeletonAnnotations.EVENT_ACTIVE_NODE_CHANGED, this.staticUpdateActiveNodePosition); this.unregisterInstance(); this.unregisterSource(); this.space.destroy(); Object.keys(this).forEach(function(key) { delete this[key]; }, this); }; WebGLApplication.prototype.updateModels = function(models) { this.append(models); }; WebGLApplication.prototype.getSelectedSkeletons = function() { var skeletons = this.space.content.skeletons; return Object.keys(skeletons).filter(function(skid) { return skeletons[skid].visible; }).map(Number); }; WebGLApplication.prototype.getSkeletonModel = function(skeleton_id) { if (skeleton_id in this.space.content.skeletons) { return this.space.content.skeletons[skeleton_id].skeletonmodel.clone(); } return null; }; WebGLApplication.prototype.getSelectedSkeletonModels = function() { var skeletons = this.space.content.skeletons; return Object.keys(skeletons).reduce(function(m, skid) { var skeleton = skeletons[skid]; if (skeleton.visible) { m[skid] = skeleton.skeletonmodel.clone(); } return m; }, {}); }; WebGLApplication.prototype.highlight = function(skeleton_id) { // Do nothing, for now }; WebGLApplication.prototype.resizeView = function(w, h) { if (!this.space) { // WebGLView has not been initialized, can't resize! return; } var canvasWidth = w, canvasHeight = h; if (!THREEx.FullScreen.activated()) { $('#view_in_3d_webgl_widget' + this.widgetID).css('overflowY', 'hidden'); if(isNaN(h) && isNaN(w)) { canvasHeight = 800; canvasWidth = 600; } // use 4:3 if (isNaN(h)) { canvasHeight = canvasWidth / 4 * 3; } else if (isNaN(w)) { canvasHeight = canvasHeight - 100; canvasWidth = canvasHeight / 3 * 4; } if (canvasWidth < 80 || canvasHeight < 60) { canvasWidth = 80; canvasHeight = 60; } $('#viewer-3d-webgl-canvas' + this.widgetID).width(canvasWidth); $('#viewer-3d-webgl-canvas' + this.widgetID).height(canvasHeight); $('#viewer-3d-webgl-canvas' + this.widgetID).css("background-color", "#000000"); this.space.setSize(canvasWidth, canvasHeight); this.space.render(); } }; WebGLApplication.prototype.fullscreenWebGL = function() { if (THREEx.FullScreen.activated()){ var w = canvasWidth, h = canvasHeight; this.resizeView( w, h ); THREEx.FullScreen.cancel(); } else { THREEx.FullScreen.request(document.getElementById('viewer-3d-webgl-canvas' + this.widgetID)); var w = window.innerWidth, h = window.innerHeight; this.resizeView( w, h ); } this.space.render(); }; /** * Store the current view as PNG image. */ WebGLApplication.prototype.exportPNG = function() { this.space.render(); try { var imageData = this.space.view.getImageData(); var blob = dataURItoBlob(imageData); growlAlert("Information", "The exported PNG will have a transparent background"); saveAs(blob, "catmaid_3d_view.png"); } catch (e) { error("Could not export current 3D view, there was an error.", e); } }; /** * Store the current view as SVG image. */ WebGLApplication.prototype.exportSVG = function() { try { var svg = this.space.view.getSVGData(); var xml = new XMLSerializer().serializeToString(svg); var blob = new Blob([xml], {type: 'text/svg'}); saveAs(blob, "catmaid-3d-view.svg"); } catch (e) { error("Could not export current 3D view, there was an error.", e); } }; WebGLApplication.prototype.Options = function() { this.show_meshes = false; this.meshes_color = "#ffffff"; this.meshes_opacity = 0.2; this.show_missing_sections = false; this.missing_section_height = 20; this.show_active_node = true; this.show_floor = true; this.show_background = true; this.show_box = true; this.show_zplane = false; this.connector_filter = false; this.shading_method = 'none'; this.color_method = 'none'; this.tag_regex = ''; this.connector_color = 'cyan-red'; this.lean_mode = false; this.synapse_clustering_bandwidth = 5000; this.smooth_skeletons = false; this.smooth_skeletons_sigma = 200; // nm this.resample_skeletons = false; this.resampling_delta = 3000; // nm this.skeleton_line_width = 3; this.invert_shading = false; this.follow_active = false; }; WebGLApplication.prototype.Options.prototype = {}; WebGLApplication.prototype.Options.prototype.clone = function() { var src = this; return Object.keys(this).reduce( function(copy, key) { copy[key] = src[key]; return copy; }, new WebGLApplication.prototype.Options()); }; WebGLApplication.prototype.Options.prototype.createMeshMaterial = function(color, opacity) { color = color || new THREE.Color(this.meshes_color); if (typeof opacity === 'undefined') opacity = this.meshes_opacity; return new THREE.MeshBasicMaterial({color: color, opacity: opacity, transparent: opacity !== 1, wireframe: true}); }; /** Persistent options, get replaced every time the 'ok' button is pushed in the dialog. */ WebGLApplication.prototype.OPTIONS = new WebGLApplication.prototype.Options(); WebGLApplication.prototype.updateZPlane = function() { this.space.staticContent.updateZPlanePosition(this.stack); this.space.render(); }; WebGLApplication.prototype.staticUpdateZPlane = function() { this.getInstances().forEach(function(instance) { instance.updateZPlane(); }); }; /** Receives an extra argument (an event) which is ignored. */ WebGLApplication.prototype.updateColorMethod = function(colorMenu) { if ('downstream-of-tag' === colorMenu.value) { var dialog = new OptionsDialog("Type in tag"); dialog.appendMessage("Nodes downstream of tag: magenta.\nNodes upstream of tag: dark grey."); var input = dialog.appendField("Tag (regex): ", "tag_text", this.options.tag_regex); dialog.onOK = (function() { this.options.tag_regex = input.value; this.options.color_method = colorMenu.value; this.updateSkeletonColors(); }).bind(this); dialog.onCancel = function() { // Reset to default (can't know easily what was selected before). colorMenu.selectedIndex = 0; }; dialog.show(); return; } this.options.color_method = colorMenu.value; this.updateSkeletonColors(); }; WebGLApplication.prototype.updateSkeletonColors = function(callback) { var fnRecolor = (function() { Object.keys(this.space.content.skeletons).forEach(function(skeleton_id) { this.space.content.skeletons[skeleton_id].updateSkeletonColor(this.options); }, this); if (typeof callback === "function") { try { callback(); } catch (e) { alert(e); } } this.space.render(); }).bind(this); if (-1 !== this.options.color_method.indexOf('reviewed')) { var skeletons = this.space.content.skeletons; // Find the subset of skeletons that don't have their reviews loaded var skeleton_ids = Object.keys(skeletons).filter(function(skid) { return !skeletons[skid].reviews; }); // Will invoke fnRecolor even if the list of skeleton_ids is empty fetchSkeletons( skeleton_ids, function(skeleton_id) { return django_url + project.id + '/skeleton/' + skeleton_id + '/reviewed-nodes'; }, function(skeleton_id) { return {}; }, // post function(skeleton_id, json) { skeletons[skeleton_id].reviews = json; }, function(skeleton_id) { // Failed loading skeletons[skeleton_id].reviews = {}; // dummy console.log('ERROR: failed to load reviews for skeleton ' + skeleton_id); }, fnRecolor); } else if ('axon-and-dendrite' === this.options.color_method) { var skeletons = this.space.content.skeletons; // Find the subset of skeletons that don't have their axon loaded var skeleton_ids = Object.keys(skeletons).filter(function(skid) { return !skeletons[skid].axon; }); fetchSkeletons( skeleton_ids, function(skid) { return django_url + project.id + '/' + skid + '/0/1/0/compact-arbor'; }, function(skid) { return {}; }, // post function(skid, json) { skeletons[skid].axon = skeletons[skid].splitByFlowCentrality(json); }, function(skid) { // Failed loading skeletons[skid].axon = {}; // dummy console.log('ERROR: failed to load axon-and-dendrite for skeleton ' + skid); }, fnRecolor); } else { fnRecolor(); } }; WebGLApplication.prototype.XYView = function() { this.space.view.XY(); this.space.render(); }; WebGLApplication.prototype.XZView = function() { this.space.view.XZ(); this.space.render(); }; WebGLApplication.prototype.ZYView = function() { this.space.view.ZY(); this.space.render(); }; WebGLApplication.prototype.ZXView = function() { this.space.view.ZX(); this.space.render(); }; WebGLApplication.prototype._skeletonVizFn = function(field) { return function(skeleton_id, value) { var skeletons = this.space.content.skeletons; if (!skeletons.hasOwnProperty(skeleton_id)) return; skeletons[skeleton_id]['set' + field + 'Visibility'](value); this.space.render(); }; }; WebGLApplication.prototype.setSkeletonPreVisibility = WebGLApplication.prototype._skeletonVizFn('Pre'); WebGLApplication.prototype.setSkeletonPostVisibility = WebGLApplication.prototype._skeletonVizFn('Post'); WebGLApplication.prototype.setSkeletonTextVisibility = WebGLApplication.prototype._skeletonVizFn('Text'); WebGLApplication.prototype.toggleConnectors = function() { this.options.connector_filter = ! this.options.connector_filter; var f = this.options.connector_filter; var skeletons = this.space.content.skeletons; var skids = Object.keys(skeletons); skids.forEach(function(skid) { skeletons[skid].setPreVisibility( !f ); skeletons[skid].setPostVisibility( !f ); $('#skeletonpre-' + skid).attr('checked', !f ); $('#skeletonpost-' + skid).attr('checked', !f ); }); if (this.options.connector_filter) { this.refreshRestrictedConnectors(); } else { skids.forEach(function(skid) { skeletons[skid].remove_connector_selection(); }); this.space.render(); } }; WebGLApplication.prototype.refreshRestrictedConnectors = function() { if (!this.options.connector_filter) return; // Find all connector IDs referred to by more than one skeleton // but only for visible skeletons var skeletons = this.space.content.skeletons; var visible_skeletons = Object.keys(skeletons).filter(function(skeleton_id) { return skeletons[skeleton_id].visible; }); var synapticTypes = this.space.Skeleton.prototype.synapticTypes; var counts = visible_skeletons.reduce(function(counts, skeleton_id) { return synapticTypes.reduce(function(counts, type) { var vertices = skeletons[skeleton_id].geometry[type].vertices; // Vertices is an array of Vector3, every two a pair, the first at the connector and the second at the node for (var i=vertices.length-2; i>-1; i-=2) { var connector_id = vertices[i].node_id; if (!counts.hasOwnProperty(connector_id)) { counts[connector_id] = {}; } counts[connector_id][skeleton_id] = null; } return counts; }, counts); }, {}); var common = {}; for (var connector_id in counts) { if (counts.hasOwnProperty(connector_id) && Object.keys(counts[connector_id]).length > 1) { common[connector_id] = null; // null, just to add something } } var visible_set = visible_skeletons.reduce(function(o, skeleton_id) { o[skeleton_id] = null; return o; }, {}); for (var skeleton_id in skeletons) { if (skeletons.hasOwnProperty(skeleton_id)) { skeletons[skeleton_id].remove_connector_selection(); if (skeleton_id in visible_set) { skeletons[skeleton_id].create_connector_selection( common ); } } } this.space.render(); }; WebGLApplication.prototype.set_shading_method = function() { // Set the shading of all skeletons based on the state of the "Shading" pop-up menu. this.options.shading_method = $('#skeletons_shading' + this.widgetID + ' :selected').attr("value"); var skeletons = this.space.content.skeletons; try { $.blockUI(); Object.keys(skeletons).forEach(function(skid) { skeletons[skid].updateSkeletonColor(this.options); }, this); } catch (e) { console.log(e, e.stack); alert(e); } $.unblockUI(); this.space.render(); }; WebGLApplication.prototype.look_at_active_node = function() { this.space.content.active_node.updatePosition(this.space, this.options); this.space.view.controls.target = this.space.content.active_node.mesh.position.clone(); this.space.render(); }; WebGLApplication.prototype.updateActiveNodePosition = function() { this.space.content.active_node.updatePosition(this.space, this.options); if (this.space.content.active_node.mesh.visible) { this.space.render(); } }; WebGLApplication.prototype.staticUpdateActiveNodePosition = function() { this.getInstances().map(function(instance) { instance.updateActiveNodePosition(); // Center the active node, if wanted if (instance.options.follow_active) { instance.look_at_active_node(); } }); }; WebGLApplication.prototype.has_skeleton = function(skeleton_id) { return this.space.content.skeletons.hasOwnProperty(skeleton_id); }; /** Reload only if present. */ WebGLApplication.prototype.staticReloadSkeletons = function(skeleton_ids) { this.getInstances().forEach(function(instance) { var models = skeleton_ids.filter(instance.hasSkeleton, instance) .reduce(function(m, skid) { if (instance.hasSkeleton(skid)) m[skid] = instance.getSkeletonModel(skid); return m; }, {}); instance.space.removeSkeletons(skeleton_ids); instance.updateModels(models); }); }; /** Fetch skeletons one by one, and render just once at the end. */ WebGLApplication.prototype.addSkeletons = function(models, callback) { // Update skeleton properties for existing skeletons, and remove them from models var skeleton_ids = Object.keys(models).filter(function(skid) { if (skid in this.space.content.skeletons) { var model = models[skid], skeleton = this.space.content.skeletons[skid]; skeleton.skeletonmodel = model; skeleton.setActorVisibility(model.selected); skeleton.setPreVisibility(model.pre_visible); skeleton.setPostVisibility(model.post_visible); skeleton.setTextVisibility(model.text_visible); skeleton.actorColor = model.color.clone(); skeleton.opacity = model.opacity; skeleton.updateSkeletonColor(this.options); return false; } return true; }, this); if (0 === skeleton_ids.length) return; var options = this.options; var url1 = django_url + project.id + '/', lean = options.lean_mode ? 0 : 1, url2 = '/' + lean + '/' + lean + '/compact-skeleton'; fetchSkeletons( skeleton_ids, function(skeleton_id) { return url1 + skeleton_id + url2; }, function(skeleton_id) { return {}; // the post }, (function(skeleton_id, json) { var sk = this.space.updateSkeleton(models[skeleton_id], json, options); if (sk) sk.show(this.options); }).bind(this), function(skeleton_id) { // Failed loading: will be handled elsewhere via fnMissing in fetchCompactSkeletons }, (function() { this.updateSkeletonColors( (function() { if (this.options.connector_filter) this.refreshRestrictedConnectors(); if (typeof callback === "function") { try { callback(); } catch (e) { alert(e); } } }).bind(this)); }).bind(this)); }; /** Reload skeletons from database. */ WebGLApplication.prototype.updateSkeletons = function() { var models = this.getSelectedSkeletonModels(); // visible ones this.clear(); this.append(models); }; WebGLApplication.prototype.append = function(models) { if (0 === Object.keys(models).length) { growlAlert("Info", "No skeletons selected!"); return; } this.addSkeletons(models, false); if (this.options.connector_filter) { this.refreshRestrictedConnectors(); } else { this.space.render(); } }; WebGLApplication.prototype.clear = function() { this.removeSkeletons(Object.keys(this.space.content.skeletons)); this.space.render(); }; WebGLApplication.prototype.getSkeletonColor = function( skeleton_id ) { if (skeleton_id in this.space.content.skeletons) { return this.space.content.skeletons[skeleton_id].actorColor.clone(); } return new THREE.Color().setRGB(1, 0, 1); }; WebGLApplication.prototype.hasSkeleton = function(skeleton_id) { return skeleton_id in this.space.content.skeletons; }; WebGLApplication.prototype.removeSkeletons = function(skeleton_ids) { if (!this.space) return; this.space.removeSkeletons(skeleton_ids); if (this.options.connector_filter) this.refreshRestrictedConnectors(); else this.space.render(); }; WebGLApplication.prototype.changeSkeletonColors = function(skeleton_ids, colors) { var skeletons = this.space.content.skeletons; skeleton_ids.forEach(function(skeleton_id, index) { if (!skeletons.hasOwnProperty(skeleton_id)) { console.log("Skeleton "+skeleton_id+" does not exist."); } if (undefined === colors) skeletons[skeleton_id].updateSkeletonColor(this.options); else skeletons[skeleton_id].changeColor(colors[index], this.options); }, this); this.space.render(); return true; }; // TODO obsolete code from segmentationtool.js WebGLApplication.prototype.addActiveObjectToStagingArea = function() { alert("The function 'addActiveObjectToStagingArea' is no longer in use."); }; WebGLApplication.prototype.showActiveNode = function() { this.space.content.active_node.setVisible(true); }; WebGLApplication.prototype.configureParameters = function() { var space = this.space; var options = this.options; var updateSkeletons = this.updateSkeletons.bind(this); var dialog = document.createElement('div'); dialog.setAttribute("id", "dialog-confirm"); dialog.setAttribute("title", "Configuration"); var msg = document.createElement('p'); msg.innerHTML = "Missing sections height [0,100]:"; dialog.appendChild(msg); var missingsectionheight = document.createElement('input'); missingsectionheight.setAttribute("type", "text"); missingsectionheight.setAttribute("id", "missing-section-height"); missingsectionheight.setAttribute("value", options.missing_section_height); dialog.appendChild(missingsectionheight); dialog.appendChild(document.createElement("br")); var bzplane = document.createElement('input'); bzplane.setAttribute("type", "checkbox"); bzplane.setAttribute("id", "enable_z_plane"); bzplane.setAttribute("value", "Enable z-plane"); if ( options.show_zplane ) bzplane.setAttribute("checked", "true"); dialog.appendChild(bzplane); dialog.appendChild(document.createTextNode('Enable z-plane')); dialog.appendChild(document.createElement("br")); var bmeshes = document.createElement('input'); bmeshes.setAttribute("type", "checkbox"); bmeshes.setAttribute("id", "show_meshes"); bmeshes.setAttribute("value", "Show meshes"); if( options.show_meshes ) bmeshes.setAttribute("checked", "true"); dialog.appendChild(bmeshes); dialog.appendChild(document.createTextNode('Show meshes, with color: ')); var c = $(document.createElement("button")).attr({ id: 'meshes-color', value: 'color' }) .css('background-color', options.meshes_color) .click( function( event ) { var sel = $('#meshes-colorwheel'); if (sel.is(':hidden')) { var cw = Raphael.colorwheel(sel[0], 150); cw.color($('#meshes-color').css('background-color'), $('#meshes-opacity').text()); cw.onchange(function(color, alpha) { color = new THREE.Color().setRGB(parseInt(color.r) / 255.0, parseInt(color.g) / 255.0, parseInt(color.b) / 255.0); $('#meshes-color').css('background-color', color.getStyle()); $('#meshes-opacity').text(alpha.toFixed(2)); if (options.show_meshes) { var material = options.createMeshMaterial(color, alpha); space.content.meshes.forEach(function(mesh) { mesh.material = material; }); space.render(); } }); sel.show(); } else { sel.hide(); sel.empty(); } }) .text('color') .get(0); dialog.appendChild(c); dialog.appendChild($( '<span>(Opacity: <span id="meshes-opacity">' + options.meshes_opacity + '</span>)</span>').get(0)); dialog.appendChild($('<div id="meshes-colorwheel">').hide().get(0)); dialog.appendChild(document.createElement("br")); var bactive = document.createElement('input'); bactive.setAttribute("type", "checkbox"); bactive.setAttribute("id", "enable_active_node"); bactive.setAttribute("value", "Enable active node"); if( options.show_active_node ) bactive.setAttribute("checked", "true"); dialog.appendChild(bactive); dialog.appendChild(document.createTextNode('Enable active node')); dialog.appendChild(document.createElement("br")); var bmissing = document.createElement('input'); bmissing.setAttribute("type", "checkbox"); bmissing.setAttribute("id", "enable_missing_sections"); bmissing.setAttribute("value", "Missing sections"); if( options.show_missing_sections ) bmissing.setAttribute("checked", "true"); dialog.appendChild(bmissing); dialog.appendChild(document.createTextNode('Missing sections')); dialog.appendChild(document.createElement("br")); /*var bortho = document.createElement('input'); bortho.setAttribute("type", "checkbox"); bortho.setAttribute("id", "toggle_ortho"); bortho.setAttribute("value", "Toggle Ortho"); container.appendChild(bortho); container.appendChild(document.createTextNode('Toggle Ortho'));*/ var bfloor = document.createElement('input'); bfloor.setAttribute("type", "checkbox"); bfloor.setAttribute("id", "toggle_floor"); bfloor.setAttribute("value", "Toggle Floor"); if( options.show_floor ) bfloor.setAttribute("checked", "true"); dialog.appendChild(bfloor); dialog.appendChild(document.createTextNode('Toggle floor')); dialog.appendChild(document.createElement("br")); var bbox = document.createElement('input'); bbox.setAttribute("type", "checkbox"); bbox.setAttribute("id", "toggle_aabb"); bbox.setAttribute("value", "Toggle Bounding Box"); if( options.show_box ) bbox.setAttribute("checked", "true"); dialog.appendChild(bbox); dialog.appendChild(document.createTextNode('Toggle Bounding Box')); dialog.appendChild(document.createElement("br")); var bbackground = document.createElement('input'); bbackground.setAttribute("type", "checkbox"); bbackground.setAttribute("id", "toggle_bgcolor"); bbackground.setAttribute("value", "Toggle Background Color"); if( options.show_background ) bbackground.setAttribute("checked", "true"); dialog.appendChild(bbackground); dialog.appendChild(document.createTextNode('Toggle Background Color')); dialog.appendChild(document.createElement("br")); var blean = document.createElement('input'); blean.setAttribute("type", "checkbox"); blean.setAttribute("id", "toggle_lean"); if( options.lean_mode ) blean.setAttribute("checked", "true"); dialog.appendChild(blean); dialog.appendChild(document.createTextNode('Toggle lean mode (no synapses, no tags)')); dialog.appendChild(document.createElement("br")); dialog.appendChild(document.createTextNode('Synapse clustering bandwidth: ')); var ibandwidth = document.createElement('input'); ibandwidth.setAttribute('type', 'text'); ibandwidth.setAttribute('id', 'synapse-clustering-bandwidth'); ibandwidth.setAttribute('value', options.synapse_clustering_bandwidth); ibandwidth.setAttribute('size', '7'); dialog.appendChild(ibandwidth); dialog.appendChild(document.createTextNode(' nm.')); dialog.appendChild(document.createElement("br")); var optionField = function(label, units, size, checkboxKey, valueKey) { var checkbox; if (checkboxKey) { checkbox = document.createElement('input'); checkbox.setAttribute("type", "checkbox"); if (options[checkboxKey]) checkbox.setAttribute("checked", true); dialog.appendChild(checkbox); } dialog.appendChild(document.createTextNode(label)); var number = document.createElement('input'); number.setAttribute('type', 'text'); number.setAttribute('value', options[valueKey]); number.setAttribute('size', size); dialog.appendChild(number); dialog.appendChild(document.createTextNode(units)); dialog.appendChild(document.createElement("br")); return [checkbox, number]; }; var smooth = optionField('Toggle smoothing skeletons by Gaussian convolution of the slabs, with sigma: ', ' nm.', 5, 'smooth_skeletons', 'smooth_skeletons_sigma'); var resample = optionField('Toogle resampling skeleton slabs, with delta: ', ' nm.', 5, 'resample_skeletons', 'resampling_delta'); var linewidth = optionField('Skeleton rendering line width: ', ' pixels.', 5, null, 'skeleton_line_width'); var submit = this.submit; $(dialog).dialog({ height: 440, width: 600, modal: true, buttons: { "Cancel": function() { $(this).dialog("close"); }, "OK": function() { var missing_section_height = missingsectionheight.value; try { missing_section_height = parseInt(missing_section_height); if (missing_section_height < 0) missing_section_height = 20; } catch (e) { alert("Invalid value for the height of missing sections!"); } options.missing_section_height = missing_section_height; options.show_zplane = bzplane.checked; options.show_missing_sections = bmissing.checked; options.show_floor = bfloor.checked; options.show_box = bbox.checked; options.show_background = bbackground.checked; options.show_active_node = bactive.checked; options.show_meshes = bmeshes.checked; options.meshes_color = $('#meshes-color').css('background-color').replace(/\s/g, ''); options.meshes_opacity = $('#meshes-opacity').text(); options.lean_mode = blean.checked; var read = function(checkbox, checkboxKey, valueField, valueKey) { var old_value = options[checkboxKey]; if (checkbox) options[checkboxKey] = checkbox.checked; try { var new_value = parseInt(valueField.value); if (new_value > 0) { options[valueKey] = new_value; return old_value != new_value; } else alert("'" + valueKey + "' must be larger than zero."); } catch (e) { alert("Invalid value for '" + valueKey + "': " + valueField.value); } return false; }; var changed_sigma = read(smooth[0], 'smooth_skeletons', smooth[1], 'smooth_skeletons_sigma'), changed_bandwidth = read(null, null, ibandwidth, 'synapse_clustering_bandwidth', null), changed_delta = read(resample[0], 'resample_skeletons', resample[1], 'resampling_delta'), changed_line_width = read(null, null, linewidth[1], 'skeleton_line_width', null); space.staticContent.adjust(options, space); space.content.adjust(options, space, submit, changed_bandwidth, changed_line_width); // Copy WebGLApplication.prototype.OPTIONS = options.clone(); if (changed_sigma || changed_delta) updateSkeletons(); else space.render(); $(this).dialog("close"); } }, close: function(event, ui) { $('#dialog-confirm').remove(); // Remove the binding $(document).off('keyup', "#meshes-color"); } }); }; /** Defines the properties of the 3d space and also its static members like the bounding box and the missing sections. */ WebGLApplication.prototype.Space = function( w, h, container, stack ) { this.stack = stack; this.container = container; // used by MouseControls this.canvasWidth = w; this.canvasHeight = h; this.yDimension = stack.dimension.y * stack.resolution.y; // Absolute center in Space coordinates (not stack coordinates) this.center = this.createCenter(); this.dimensions = new THREE.Vector3(stack.dimension.x * stack.resolution.x, stack.dimension.y * stack.resolution.y, stack.dimension.z * stack.resolution.z); // WebGL space this.scene = new THREE.Scene(); this.view = new this.View(this); this.lights = this.createLights(stack.dimension, stack.resolution, this.view.camera); this.lights.forEach(this.scene.add, this.scene); // Content this.staticContent = new this.StaticContent(this.dimensions, stack, this.center); this.scene.add(this.staticContent.box); this.scene.add(this.staticContent.floor); this.content = new this.Content(); this.scene.add(this.content.active_node.mesh); }; WebGLApplication.prototype.Space.prototype = {}; WebGLApplication.prototype.Space.prototype.setSize = function(canvasWidth, canvasHeight) { this.canvasWidth = canvasWidth; this.canvasHeight = canvasHeight; this.view.camera.setSize(canvasWidth, canvasHeight); this.view.camera.toPerspective(); // invokes update of camera matrices this.view.renderer.setSize(canvasWidth, canvasHeight); }; /** Transform a THREE.Vector3d from stack coordinates to Space coordinates. In other words, transform coordinates from CATMAID coordinate system to WebGL coordinate system: x->x, y->y+dy, z->-z */ WebGLApplication.prototype.Space.prototype.toSpace = function(v3) { v3.y = this.yDimension - v3.y; v3.z = -v3.z; return v3; }; /** Transform axes but do not scale. */ WebGLApplication.prototype.Space.prototype.coordsToUnscaledSpace = function(x, y, z) { return [x, this.yDimension - y, -z]; }; /** Starting at i, edit i, i+1 and i+2, which represent x, y, z of a 3d point. */ WebGLApplication.prototype.Space.prototype.coordsToUnscaledSpace2 = function(vertices, i) { // vertices[i] equal vertices[i+1] = this.yDimension -vertices[i+1]; vertices[i+2] = -vertices[i+2]; }; WebGLApplication.prototype.Space.prototype.createCenter = function() { var d = this.stack.dimension, r = this.stack.resolution, t = this.stack.translation, center = new THREE.Vector3((d.x * r.x) / 2.0 + t.x, (d.y * r.y) / 2.0 + t.y, (d.z * r.z) / 2.0 + t.z); // Bring the stack center to Space coordinates this.toSpace(center); return center; }; WebGLApplication.prototype.Space.prototype.createLights = function(dimension, resolution, camera) { var ambientLight = new THREE.AmbientLight( 0x505050 ); var pointLight = new THREE.PointLight( 0xffaa00 ); pointLight.position.set(dimension.x * resolution.x, dimension.y * resolution.y, 50); var light = new THREE.SpotLight( 0xffffff, 1.5 ); light.position.set(dimension.x * resolution.x / 2, dimension.y * resolution.y / 2, 50); light.castShadow = true; light.shadowCameraNear = 200; light.shadowCameraFar = camera.far; light.shadowCameraFov = 50; light.shadowBias = -0.00022; light.shadowDarkness = 0.5; light.shadowMapWidth = 2048; light.shadowMapHeight = 2048; return [ambientLight, pointLight, light]; }; WebGLApplication.prototype.Space.prototype.add = function(mesh) { this.scene.add(mesh); }; WebGLApplication.prototype.Space.prototype.remove = function(mesh) { this.scene.remove(mesh); }; WebGLApplication.prototype.Space.prototype.render = function() { this.view.render(); }; WebGLApplication.prototype.Space.prototype.destroy = function() { // remove active_node and project-wise meshes this.scene.remove(this.content.active_node.mesh); this.content.meshes.forEach(this.scene.remove, this.scene); // dispose active_node and meshes this.content.dispose(); // dispose and remove skeletons this.removeSkeletons(Object.keys(this.content.skeletons)); this.lights.forEach(this.scene.remove, this.scene); // dispose meshes and materials this.staticContent.dispose(); // remove meshes this.scene.remove(this.staticContent.box); this.scene.remove(this.staticContent.floor); if (this.staticContent.zplane) this.scene.remove(this.staticContent.zplane); this.staticContent.missing_sections.forEach(this.scene.remove, this.scene); this.view.destroy(); Object.keys(this).forEach(function(key) { delete this[key]; }, this); }; WebGLApplication.prototype.Space.prototype.removeSkeletons = function(skeleton_ids) { skeleton_ids.forEach(this.removeSkeleton, this); }; WebGLApplication.prototype.Space.prototype.removeSkeleton = function(skeleton_id) { if (skeleton_id in this.content.skeletons) { this.content.skeletons[skeleton_id].destroy(); delete this.content.skeletons[skeleton_id]; } }; WebGLApplication.prototype.Space.prototype.updateSplitShading = function(old_skeleton_id, new_skeleton_id, options) { if ('active_node_split' === options.shading_method) { if (old_skeleton_id !== new_skeleton_id) { if (old_skeleton_id && old_skeleton_id in this.content.skeletons) this.content.skeletons[old_skeleton_id].updateSkeletonColor(options); } if (new_skeleton_id && new_skeleton_id in this.content.skeletons) this.content.skeletons[new_skeleton_id].updateSkeletonColor(options); } }; WebGLApplication.prototype.Space.prototype.TextGeometryCache = function() { this.geometryCache = {}; this.getTagGeometry = function(tagString) { if (tagString in this.geometryCache) { var e = this.geometryCache[tagString]; e.refs += 1; return e.geometry; } // Else create, store, and return a new one: var text3d = new THREE.TextGeometry( tagString, { size: 100, height: 20, curveSegments: 1, font: "helvetiker" }); text3d.computeBoundingBox(); text3d.tagString = tagString; this.geometryCache[tagString] = {geometry: text3d, refs: 1}; return text3d; }; this.releaseTagGeometry = function(tagString) { if (tagString in this.geometryCache) { var e = this.geometryCache[tagString]; e.refs -= 1; if (0 === e.refs) { delete this.geometryCache[tagString].geometry; delete this.geometryCache[tagString]; } } }; this.createTextMesh = function(tagString, material) { var text = new THREE.Mesh(this.getTagGeometry(tagString), material); text.visible = true; return text; }; this.destroy = function() { Object.keys(this.geometryCache).forEach(function(entry) { entry.geometry.dispose(); }); delete this.geometryCache; }; }; WebGLApplication.prototype.Space.prototype.StaticContent = function(dimensions, stack, center) { // Space elements this.box = this.createBoundingBox(center, stack.dimension, stack.resolution); this.floor = this.createFloor(center, dimensions); this.zplane = null; this.missing_sections = []; // Shared across skeletons this.labelspheregeometry = new THREE.OctahedronGeometry( 130, 3); this.radiusSphere = new THREE.OctahedronGeometry( 40, 3); this.icoSphere = new THREE.IcosahedronGeometry(1, 2); this.cylinder = new THREE.CylinderGeometry(1, 1, 1, 10, 1, false); this.textMaterial = new THREE.MeshNormalMaterial( { color: 0xffffff, overdraw: true } ); // Mesh materials for spheres on nodes tagged with 'uncertain end', 'undertain continuation' or 'TODO' this.labelColors = {uncertain: new THREE.MeshBasicMaterial({color: 0xff8000, opacity:0.6, transparent: true}), todo: new THREE.MeshBasicMaterial({color: 0xff0000, opacity:0.6, transparent: true})}; this.textGeometryCache = new WebGLApplication.prototype.Space.prototype.TextGeometryCache(); this.synapticColors = [new THREE.MeshBasicMaterial( { color: 0xff0000, opacity:0.6, transparent:false } ), new THREE.MeshBasicMaterial( { color: 0x00f6ff, opacity:0.6, transparent:false } )]; this.connectorLineColors = {'presynaptic_to': new THREE.LineBasicMaterial({color: 0xff0000, opacity: 1.0, linewidth: 6}), 'postsynaptic_to': new THREE.LineBasicMaterial({color: 0x00f6ff, opacity: 1.0, linewidth: 6})}; }; WebGLApplication.prototype.Space.prototype.StaticContent.prototype = {}; WebGLApplication.prototype.Space.prototype.StaticContent.prototype.dispose = function() { // dispose ornaments this.box.geometry.dispose(); this.box.material.dispose(); this.floor.geometry.dispose(); this.floor.material.dispose(); this.missing_sections.forEach(function(s) { s.geometry.dispose(); s.material.dispose(); // it is ok to call more than once }); if (this.zplane) { this.zplane.geometry.dispose(); this.zplane.material.dispose(); } // dispose shared geometries [this.labelspheregeometry, this.radiusSphere, this.icoSphere, this.cylinder].forEach(function(g) { g.dispose(); }); this.textGeometryCache.destroy(); // dispose shared materials this.textMaterial.dispose(); this.labelColors.uncertain.dispose(); this.labelColors.todo.dispose(); this.synapticColors[0].dispose(); this.synapticColors[1].dispose(); }; WebGLApplication.prototype.Space.prototype.StaticContent.prototype.createBoundingBox = function(center, dimension, resolution) { var w2 = (dimension.x * resolution.x) / 2; var h2 = (dimension.y * resolution.y) / 2; var d2 = (dimension.z * resolution.z) / 2; var geometry = new THREE.Geometry(); geometry.vertices.push( new THREE.Vector3(-w2, -h2, -d2), new THREE.Vector3(-w2, h2, -d2), new THREE.Vector3(-w2, h2, -d2), new THREE.Vector3( w2, h2, -d2), new THREE.Vector3( w2, h2, -d2), new THREE.Vector3( w2, -h2, -d2), new THREE.Vector3( w2, -h2, -d2), new THREE.Vector3(-w2, -h2, -d2), new THREE.Vector3(-w2, -h2, d2), new THREE.Vector3(-w2, h2, d2), new THREE.Vector3(-w2, h2, d2), new THREE.Vector3( w2, h2, d2), new THREE.Vector3( w2, h2, d2), new THREE.Vector3( w2, -h2, d2), new THREE.Vector3( w2, -h2, d2), new THREE.Vector3(-w2, -h2, d2), new THREE.Vector3(-w2, -h2, -d2), new THREE.Vector3(-w2, -h2, d2), new THREE.Vector3(-w2, h2, -d2), new THREE.Vector3(-w2, h2, d2), new THREE.Vector3( w2, h2, -d2), new THREE.Vector3( w2, h2, d2), new THREE.Vector3( w2, -h2, -d2), new THREE.Vector3( w2, -h2, d2) ); geometry.computeLineDistances(); var material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); var mesh = new THREE.Line( geometry, material, THREE.LinePieces ); mesh.position.set(center.x, center.y, center.z); return mesh; }; /** * Creates a THREE.js line object that represents a floor grid. By default, it * extents around the bounding box by about twice the height of it. The grid * cells are placed so that they are divide the bouning box floor evenly. By * default, there are ten cells in each dimension within the bounding box. It is * positioned around the center of the dimensions. These settings can be * overridden with the options parameter. */ WebGLApplication.prototype.Space.prototype.StaticContent.prototype.createFloor = function(center, dimensions, options) { var o = options || {}; var floor = o['floor'] || 0.0; // 10 steps in each dimension of the bounding box var nBaseLines = o['nBaseLines'] || 10.0; var xStep = dimensions.x / nBaseLines; var zStep = dimensions.z / nBaseLines; // Extend this around the bounding box var xExtent = o['xExtent'] || Math.ceil(2.0 * dimensions.y / xStep); var zExtent = o['zExtent'] || Math.ceil(2.0 * dimensions.y / zStep); // Offset from origin var xOffset = dimensions.x * 0.5 - center.x; var zOffset = dimensions.z * 0.5 + center.z; // Get min and max coordinates of grid var min_x = -1.0 * xExtent * xStep + xOffset, max_x = dimensions.x + (xExtent * xStep) + xOffset; var min_z = -1.0 * dimensions.z - zExtent * zStep + zOffset, max_z = zExtent * zStep + zOffset; // Create planar mesh for floor var xLines = nBaseLines + 2 * xExtent; var zLines = nBaseLines + 2 * zExtent; var width = max_x - min_x; var height = max_z - min_z; var geometry = new THREE.Geometry(); for (var x=0; x<=xLines; ++x) { for (var z=0; z<=zLines; ++z) { geometry.vertices.push( new THREE.Vector3(min_x, floor, min_z + z*zStep), new THREE.Vector3(max_x, floor, min_z + z*zStep), new THREE.Vector3(min_x + x*xStep, floor, min_z), new THREE.Vector3(min_x + x*xStep, floor, max_z) ); } } geometry.computeLineDistances(); var material = new THREE.LineBasicMaterial({ color: o['color'] || 0x535353 }); var mesh = new THREE.Line( geometry, material, THREE.LinePieces ); mesh.position.set(min_x + 0.5 * width, floor, min_z + 0.5 * height); return mesh; }; /** Adjust visibility of static content according to the persistent options. */ WebGLApplication.prototype.Space.prototype.StaticContent.prototype.adjust = function(options, space) { if (options.show_missing_sections) { if (0 === this.missing_sections.length) { this.missing_sections = this.createMissingSections(space, options.missing_section_height); this.missing_sections.forEach(space.scene.add, space.scene); } } else { this.missing_sections.forEach(space.scene.remove, space.scene); this.missing_sections = []; } if (options.show_background) { space.view.renderer.setClearColor(0x000000, 1); } else { space.view.renderer.setClearColor(0xffffff, 1); } this.floor.visible = options.show_floor; this.box.visible = options.show_box; if (this.zplane) space.scene.remove(this.zplane); if (options.show_zplane) { this.zplane = this.createZPlane(space.stack); this.updateZPlanePosition(space.stack); space.scene.add(this.zplane); } else { this.zplane = null; } }; WebGLApplication.prototype.Space.prototype.StaticContent.prototype.createZPlane = function(stack) { var geometry = new THREE.Geometry(), xwidth = stack.dimension.x * stack.resolution.x, ywidth = stack.dimension.y * stack.resolution.y, material = new THREE.MeshBasicMaterial( { color: 0x151349, side: THREE.DoubleSide } ); geometry.vertices.push( new THREE.Vector3( 0,0,0 ) ); geometry.vertices.push( new THREE.Vector3( xwidth,0,0 ) ); geometry.vertices.push( new THREE.Vector3( 0,ywidth,0 ) ); geometry.vertices.push( new THREE.Vector3( xwidth,ywidth,0 ) ); geometry.faces.push( new THREE.Face4( 0, 1, 3, 2 ) ); return new THREE.Mesh( geometry, material ); }; WebGLApplication.prototype.Space.prototype.StaticContent.prototype.updateZPlanePosition = function(stack) { if (this.zplane) { this.zplane.position.z = (-stack.z * stack.resolution.z - stack.translation.z); } }; /** Returns an array of meshes representing the missing sections. */ WebGLApplication.prototype.Space.prototype.StaticContent.prototype.createMissingSections = function(space, missing_section_height) { var d = space.stack.dimension, r = space.stack.resolution, t = space.stack.translation, geometry = new THREE.Geometry(), xwidth = d.x * r.x, ywidth = d.y * r.y * missing_section_height / 100.0, materials = [new THREE.MeshBasicMaterial( { color: 0x151349, opacity:0.6, transparent: true, side: THREE.DoubleSide } ), new THREE.MeshBasicMaterial( { color: 0x00ffff, wireframe: true, wireframeLinewidth: 5, side: THREE.DoubleSide } )]; geometry.vertices.push( new THREE.Vector3( 0,0,0 ) ); geometry.vertices.push( new THREE.Vector3( xwidth,0,0 ) ); geometry.vertices.push( new THREE.Vector3( 0,ywidth,0 ) ); geometry.vertices.push( new THREE.Vector3( xwidth,ywidth,0 ) ); geometry.faces.push( new THREE.Face4( 0, 1, 3, 2 ) ); return space.stack.broken_slices.reduce(function(missing_sections, sliceZ) { var z = -sliceZ * r.z - t.z; return missing_sections.concat(materials.map(function(material) { var mesh = new THREE.Mesh(geometry, material); mesh.position.z = z; return mesh; })); }, []); }; WebGLApplication.prototype.Space.prototype.Content = function() { // Scene content this.active_node = new this.ActiveNode(); this.meshes = []; this.skeletons = {}; }; WebGLApplication.prototype.Space.prototype.Content.prototype = {}; WebGLApplication.prototype.Space.prototype.Content.prototype.dispose = function() { this.active_node.mesh.geometry.dispose(); this.active_node.mesh.material.dispose(); this.meshes.forEach(function(mesh) { mesh.geometry.dispose(); mesh.material.dispose(); }); }; WebGLApplication.prototype.Space.prototype.Content.prototype.loadMeshes = function(space, submit, material) { submit(django_url + project.id + "/stack/" + space.stack.id + "/models", {}, function (models) { var ids = Object.keys(models); if (0 === ids.length) return; var loader = space.content.newJSONLoader(); ids.forEach(function(id) { var vs = models[id].vertices; for (var i=0; i < vs.length; i+=3) { space.coordsToUnscaledSpace2(vs, i); } var geometry = loader.parse(models[id]).geometry; var mesh = space.content.newMesh(geometry, material); mesh.position.set(0, 0, 0); mesh.rotation.set(0, 0, 0); space.content.meshes.push(mesh); space.add(mesh); }); space.render(); }); }; WebGLApplication.prototype.Space.prototype.Content.prototype.newMesh = function(geometry, material) { return new THREE.Mesh(geometry, material); }; WebGLApplication.prototype.Space.prototype.Content.prototype.newJSONLoader = function() { return new THREE.JSONLoader(true); }; /** Adjust content according to the persistent options. */ WebGLApplication.prototype.Space.prototype.Content.prototype.adjust = function(options, space, submit, changed_bandwidth, changed_line_width) { if (options.show_meshes) { if (0 === this.meshes.length) { this.loadMeshes(space, submit, options.createMeshMaterial()); } } else { this.meshes.forEach(space.scene.remove, space.scene); this.meshes = []; } this.active_node.setVisible(options.show_active_node); if (changed_bandwidth && 'synapse-clustering' === options.connector_color) { space.updateConnectorColors(options, Object.keys(this.skeletons).map(function(skid) { return this.skeletons[skid]; }, this)); } if (changed_line_width) { Object.keys(this.skeletons).forEach(function(skid) { this.skeletons[skid].changeSkeletonLineWidth(options.skeleton_line_width); }, this); } }; WebGLApplication.prototype.Space.prototype.View = function(space) { this.space = space; this.init(); // Initial view this.XY(); }; WebGLApplication.prototype.Space.prototype.View.prototype = {}; WebGLApplication.prototype.Space.prototype.View.prototype.init = function() { /* Create a camera which generates a picture fitting in our canvas. The * frustum's far culling plane is three times the longest size of the * displayed space. The near plan starts at one. */ var d = this.space.dimensions; var fov = 75; var near = 1; var far = 3 * Math.max(d.x, Math.max(d.y, d.z)); var orthoNear = 1; var orthoFar = far; this.camera = new THREE.CombinedCamera(-this.space.canvasWidth, -this.space.canvasHeight, fov, near, far, orthoNear, orthoFar); this.camera.frustumCulled = false; this.projector = new THREE.Projector(); this.renderer = this.createRenderer('webgl'); this.controls = this.createControls(); this.space.container.appendChild(this.renderer.domElement); this.mouse = {position: new THREE.Vector2(), is_mouse_down: false}; this.mouseControls = new this.MouseControls(); this.mouseControls.attach(this, this.renderer.domElement); // Add handlers for WebGL context lost and restore events this.renderer.context.canvas.addEventListener('webglcontextlost', function(e) { e.preventDefault(); // Notify user about reload error("Due to limited system resources the 3D display can't be shown " + "right now. Please try and restart the widget containing the 3D " + "viewer."); }, false); this.renderer.context.canvas.addEventListener('webglcontextrestored', (function(e) { // TODO: Calling init() isn't enough, but one can manually restart // the widget. }).bind(this), false); }; /** * Crate and setup a WebGL or SVG renderer. */ WebGLApplication.prototype.Space.prototype.View.prototype.createRenderer = function(type) { var renderer = null; if ('webgl' === type) { renderer = new THREE.WebGLRenderer({ antialias: true }); } else if ('svg' === type) { renderer = new THREE.SVGRenderer(); } else { error("Unknon renderer type: " + type); return null; } renderer.sortObjects = false; renderer.setSize( this.space.canvasWidth, this.space.canvasHeight ); return renderer; }; WebGLApplication.prototype.Space.prototype.View.prototype.destroy = function() { this.controls.removeListeners(); this.mouseControls.detach(this.renderer.domElement); this.space.container.removeChild(this.renderer.domElement); Object.keys(this).forEach(function(key) { delete this[key]; }, this); }; WebGLApplication.prototype.Space.prototype.View.prototype.createControls = function() { var controls = new THREE.TrackballControls( this.camera, this.space.container ); controls.rotateSpeed = 1.0; controls.zoomSpeed = 3.2; controls.panSpeed = 1.5; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.target = this.space.center.clone(); return controls; }; WebGLApplication.prototype.Space.prototype.View.prototype.render = function() { this.controls.update(); if (this.renderer) { this.renderer.clear(); this.renderer.render(this.space.scene, this.camera); } }; /** * Get the toDataURL() image data of the renderer in PNG format. */ WebGLApplication.prototype.Space.prototype.View.prototype.getImageData = function() { return this.renderer.domElement.toDataURL("image/png"); }; /** * Return SVG data of the rendered image. */ WebGLApplication.prototype.Space.prototype.View.prototype.getSVGData = function() { var svgRenderer = this.createRenderer('svg'); svgRenderer.clear(); svgRenderer.render(this.space.scene, this.camera); return svgRenderer.domElement; }; /** * Set camera position so that the whole XY side of the bounding box facing +Z * can just be seen. */ WebGLApplication.prototype.Space.prototype.View.prototype.XY = function() { var center = this.space.center, dimensions = this.space.dimensions, vFOV = this.camera.fov * Math.PI / 180, bbDistance; if (this.height > this.width) { var hFOV = 2 * Math.atan( Math.tan( vFOV * 0.5 ) * this.width / this.height ); bbDistance = dimensions.x * 0.5 / Math.tan(hFOV * 0.5); } else { bbDistance = dimensions.y * 0.5 / Math.tan(vFOV * 0.5); } this.controls.target = center; this.camera.position.x = center.x; this.camera.position.y = center.y; this.camera.position.z = center.z + (dimensions.z / 2) + bbDistance; this.camera.up.set(0, 1, 0); }; /** * Set camera position so that the whole XZ side of the bounding box facing +Y * can just be seen. */ WebGLApplication.prototype.Space.prototype.View.prototype.XZ = function() { var center = this.space.center, dimensions = this.space.dimensions, vFOV = this.camera.fov * Math.PI / 180, bbDistance; if (this.height > this.width) { var hFOV = 2 * Math.atan( Math.tan( vFOV * 0.5 ) * this.width / this.height ); bbDistance = dimensions.x * 0.5 / Math.tan(hFOV * 0.5); } else { bbDistance = dimensions.z * 0.5 / Math.tan(vFOV * 0.5); } this.controls.target = center; this.camera.position.x = center.x; this.camera.position.y = center.y + (dimensions.y / 2) + bbDistance; this.camera.position.z = center.z; this.camera.up.set(0, 0, 1); }; /** * Set camera position so that the whole ZY side of the bounding box facing +X * can just be seen. */ WebGLApplication.prototype.Space.prototype.View.prototype.ZY = function() { var center = this.space.center, dimensions = this.space.dimensions, vFOV = this.camera.fov * Math.PI / 180, bbDistance; if (this.height > this.width) { var hFOV = 2 * Math.atan( Math.tan( vFOV * 0.5 ) * this.width / this.height ); bbDistance = dimensions.z * 0.5 / Math.tan(hFOV * 0.5); } else { bbDistance = dimensions.y * 0.5 / Math.tan(vFOV * 0.5); } this.controls.target = center; this.camera.position.x = center.x + (dimensions.x / 2) + bbDistance; this.camera.position.y = center.y; this.camera.position.z = center.z; this.camera.up.set(0, 1, 0); }; /** * Set camera position so that the whole ZX side of the bounding box facing +Y * can just be seen. */ WebGLApplication.prototype.Space.prototype.View.prototype.ZX = function() { var center = this.space.center, dimensions = this.space.dimensions, vFOV = this.camera.fov * Math.PI / 180, bbDistance; if (this.height > this.width) { var hFOV = 2 * Math.atan( Math.tan( vFOV * 0.5 ) * this.width / this.height ); bbDistance = dimensions.z * 0.5 / Math.tan(hFOV * 0.5); } else { bbDistance = dimensions.x * 0.5 / Math.tan(vFOV * 0.5); } this.controls.target = center; this.camera.position.x = center.x; this.camera.position.y = center.y + (dimensions.y / 2) + bbDistance; this.camera.position.z = center.z; this.camera.up.set(-1, 0, 0); }; /** Construct mouse controls as objects, so that no context is retained. */ WebGLApplication.prototype.Space.prototype.View.prototype.MouseControls = function() { this.attach = function(view, domElement) { domElement.CATMAID_view = view; domElement.addEventListener('mousewheel', this.MouseWheel, false); domElement.addEventListener('mousemove', this.MouseMove, false); domElement.addEventListener('mouseup', this.MouseUp, false); domElement.addEventListener('mousedown', this.MouseDown, false); }; this.detach = function(domElement) { domElement.CATMAID_view = null; delete domElement.CATMAID_view; domElement.removeEventListener('mousewheel', this.MouseWheel, false); domElement.removeEventListener('mousemove', this.MouseMove, false); domElement.removeEventListener('mouseup', this.MouseUp, false); domElement.removeEventListener('mousedown', this.MouseDown, false); Object.keys(this).forEach(function(key) { delete this[key]; }, this); }; this.MouseWheel = function(ev) { this.CATMAID_view.space.render(); }; this.MouseMove = function(ev) { var mouse = this.CATMAID_view.mouse, space = this.CATMAID_view.space; mouse.position.x = ( ev.offsetX / space.canvasWidth ) * 2 -1; mouse.position.y = -( ev.offsetY / space.canvasHeight ) * 2 +1; if (mouse.is_mouse_down) { space.render(); } space.container.style.cursor = 'pointer'; }; this.MouseUp = function(ev) { var mouse = this.CATMAID_view.mouse, controls = this.CATMAID_view.controls, space = this.CATMAID_view.space; mouse.is_mouse_down = false; controls.enabled = true; space.render(); // May need another render on occasions }; this.MouseDown = function(ev) { var mouse = this.CATMAID_view.mouse, space = this.CATMAID_view.space, camera = this.CATMAID_view.camera, projector = this.CATMAID_view.projector; mouse.is_mouse_down = true; if (!ev.shiftKey) return; // Find object under the mouse var vector = new THREE.Vector3(mouse.position.x, mouse.position.y, 0.5); projector.unprojectVector(vector, camera); var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); // Attempt to intersect visible skeleton spheres, stopping at the first found var fields = ['specialTagSpheres', 'synapticSpheres', 'radiusVolumes']; var skeletons = space.content.skeletons; if (Object.keys(skeletons).some(function(skeleton_id) { var skeleton = skeletons[skeleton_id]; if (!skeleton.visible) return false; var all_spheres = fields.map(function(field) { return skeleton[field]; }) .reduce(function(a, spheres) { return Object.keys(spheres).reduce(function(a, id) { a.push(spheres[id]); return a; }, a); }, []); var intersects = raycaster.intersectObjects(all_spheres, true); if (intersects.length > 0) { return all_spheres.some(function(sphere) { if (sphere.id !== intersects[0].object.id) return false; SkeletonAnnotations.staticMoveToAndSelectNode(sphere.node_id); return true; }); } return false; })) { return; } growlAlert("Oops", "Couldn't find any intersectable object under the mouse."); }; }; WebGLApplication.prototype.Space.prototype.Content.prototype.ActiveNode = function() { this.skeleton_id = null; this.mesh = new THREE.Mesh( new THREE.IcosahedronGeometry(1, 2), new THREE.MeshBasicMaterial( { color: 0x00ff00, opacity:0.8, transparent:true } ) ); this.mesh.scale.x = this.mesh.scale.y = this.mesh.scale.z = 160; }; WebGLApplication.prototype.Space.prototype.Content.prototype.ActiveNode.prototype = {}; WebGLApplication.prototype.Space.prototype.Content.prototype.ActiveNode.prototype.setVisible = function(visible) { this.mesh.visible = visible ? true : false; }; WebGLApplication.prototype.Space.prototype.Content.prototype.ActiveNode.prototype.updatePosition = function(space, options) { var pos = SkeletonAnnotations.getActiveNodePosition(); if (!pos) { space.updateSplitShading(this.skeleton_id, null, options); this.skeleton_id = null; return; } var skeleton_id = SkeletonAnnotations.getActiveSkeletonId(); space.updateSplitShading(this.skeleton_id, skeleton_id, options); this.skeleton_id = skeleton_id; // Get world coordinates of active node var c = new THREE.Vector3(pos.x, pos.y, pos.z); space.toSpace(c); this.mesh.position.set(c.x, c.y, c.z); }; WebGLApplication.prototype.Space.prototype.updateSkeleton = function(skeletonmodel, json, options) { if (!this.content.skeletons.hasOwnProperty(skeletonmodel.id)) { this.content.skeletons[skeletonmodel.id] = new this.Skeleton(this, skeletonmodel); } this.content.skeletons[skeletonmodel.id].reinit_actor(skeletonmodel, json, options); return this.content.skeletons[skeletonmodel.id]; }; /** An object to represent a skeleton in the WebGL space. * The skeleton consists of three geometries: * (1) one for the edges between nodes, represented as a list of contiguous pairs of points; * (2) one for the edges representing presynaptic relations to connectors; * (3) one for the edges representing postsynaptic relations to connectors. * Each geometry has its own mesh material and can be switched independently. * In addition, each skeleton node with a pre- or postsynaptic relation to a connector * gets a clickable sphere to represent it. * Nodes with an 'uncertain' or 'todo' in their text tags also get a sphere. * * When visualizing only the connectors among the skeletons visible in the WebGL space, the geometries of the pre- and postsynaptic edges are hidden away, and a new pair of geometries are created to represent just the edges that converge onto connectors also related to by the other skeletons. * */ WebGLApplication.prototype.Space.prototype.Skeleton = function(space, skeletonmodel) { // TODO id, baseName, actorColor are all redundant with the skeletonmodel this.space = space; this.id = skeletonmodel.id; this.baseName = skeletonmodel.baseName; this.synapticColors = space.staticContent.synapticColors; this.skeletonmodel = skeletonmodel; this.opacity = skeletonmodel.opacity; // This is an index mapping treenode IDs to lists of reviewers. Attaching them // directly to the nodes is too much of a performance hit. // Gets loaded dynamically, and erased when refreshing (because a new Skeleton is instantiated with the same model). this.reviews = null; // A map of nodeID vs true for nodes that belong to the axon, as computed by splitByFlowCentrality. Loaded dynamically, and erased when refreshing like this.reviews. this.axon = null; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype = {}; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.CTYPES = ['neurite', 'presynaptic_to', 'postsynaptic_to']; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.synapticTypes = ['presynaptic_to', 'postsynaptic_to']; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.initialize_objects = function(options) { this.visible = true; if (undefined === this.skeletonmodel) { console.log('Can not initialize skeleton object'); return; } this.actorColor = this.skeletonmodel.color.clone(); var CTYPES = this.CTYPES; this.line_material = new THREE.LineBasicMaterial({color: 0xffff00, opacity: 1.0, linewidth: options.skeleton_line_width}); this.geometry = {}; this.geometry[CTYPES[0]] = new THREE.Geometry(); this.geometry[CTYPES[1]] = new THREE.Geometry(); this.geometry[CTYPES[2]] = new THREE.Geometry(); this.actor = {}; // has three keys (the CTYPES), each key contains the edges of each type this.actor[CTYPES[0]] = new THREE.Line(this.geometry[CTYPES[0]], this.line_material, THREE.LinePieces); this.actor[CTYPES[1]] = new THREE.Line(this.geometry[CTYPES[1]], this.space.staticContent.connectorLineColors[CTYPES[1]], THREE.LinePieces); this.actor[CTYPES[2]] = new THREE.Line(this.geometry[CTYPES[2]], this.space.staticContent.connectorLineColors[CTYPES[2]], THREE.LinePieces); this.specialTagSpheres = {}; this.synapticSpheres = {}; this.radiusVolumes = {}; // contains spheres and cylinders this.textlabels = {}; // Used only with restricted connectors this.connectoractor = {}; this.connectorgeometry = {}; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.destroy = function() { this.removeActorFromScene(); [this.actor, this.geometry, this.connectorgeometry, this.connectoractor, this.specialTagSpheres, this.synapticSpheres, this.radiusVolumes, this.textlabels].forEach(function(ob) { if (ob) { for (var key in ob) { if (ob.hasOwnProperty(key)) delete ob[key]; } } }); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.removeActorFromScene = function() { // Dispose of both geometry and material, unique to this Skeleton this.actor[this.CTYPES[0]].geometry.dispose(); this.actor[this.CTYPES[0]].material.dispose(); // Dispose only of the geometries. Materials for connectors are shared this.actor[this.CTYPES[1]].geometry.dispose(); this.actor[this.CTYPES[2]].geometry.dispose(); [this.actor, this.synapticSpheres, this.radiusVolumes, this.specialTagSpheres].forEach(function(ob) { if (ob) { for (var key in ob) { if (ob.hasOwnProperty(key)) this.space.remove(ob[key]); } } }, this); this.remove_connector_selection(); this.removeTextMeshes(); }; /** Set the visibility of the skeleton, radius spheres and label spheres. Does not set the visibility of the synaptic spheres or edges. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setActorVisibility = function(vis) { this.visible = vis; this.visibilityCompositeActor('neurite', vis); // radiusVolumes: the spheres where nodes have a radius larger than zero // specialTagSpheres: the spheres at special tags like 'TODO', 'Uncertain end', etc. [this.radiusVolumes, this.specialTagSpheres].forEach(function(ob) { for (var idx in ob) { if (ob.hasOwnProperty(idx)) ob[idx].visible = vis; } }); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setSynapticVisibilityFn = function(type) { return function(vis) { this.visibilityCompositeActor(type, vis); for (var idx in this.synapticSpheres) { if (this.synapticSpheres.hasOwnProperty(idx) && this.synapticSpheres[idx].type === type) { this.synapticSpheres[idx].visible = vis; } } }; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setPreVisibility = WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setSynapticVisibilityFn('presynaptic_to'); WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setPostVisibility = WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setSynapticVisibilityFn('postsynaptic_to'); WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createTextMeshes = function() { // Sort out tags by node: some nodes may have more than one var nodeIDTags = {}; for (var tag in this.tags) { if (this.tags.hasOwnProperty(tag)) { this.tags[tag].forEach(function(nodeID) { if (nodeIDTags.hasOwnProperty(nodeID)) { nodeIDTags[nodeID].push(tag); } else { nodeIDTags[nodeID] = [tag]; } }); } } // Sort and convert to string the array of tags of each node for (var nodeID in nodeIDTags) { if (nodeIDTags.hasOwnProperty(nodeID)) { nodeIDTags[nodeID] = nodeIDTags[nodeID].sort().join(); } } // Group nodes by common tag string var tagNodes = {}; for (var nodeID in nodeIDTags) { if (nodeIDTags.hasOwnProperty(nodeID)) { var tagString = nodeIDTags[nodeID]; if (tagNodes.hasOwnProperty(tagString)) { tagNodes[tagString].push(nodeID); } else { tagNodes[tagString] = [nodeID]; } } } // Find Vector3 of tagged nodes var vs = this.geometry['neurite'].vertices.reduce(function(o, v) { if (v.node_id in nodeIDTags) o[v.node_id] = v; return o; }, {}); // Create meshes for the tags for all nodes that need them, reusing the geometries var cache = this.space.staticContent.textGeometryCache, textMaterial = this.space.staticContent.textMaterial; for (var tagString in tagNodes) { if (tagNodes.hasOwnProperty(tagString)) { tagNodes[tagString].forEach(function(nodeID) { var text = cache.createTextMesh(tagString, textMaterial); var v = vs[nodeID]; text.position.x = v.x; text.position.y = v.y; text.position.z = v.z; this.textlabels[nodeID] = text; this.space.add(text); }, this); } } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.removeTextMeshes = function() { var cache = this.space.staticContent.textGeometryCache; for (var k in this.textlabels) { if (this.textlabels.hasOwnProperty(k)) { this.space.remove(this.textlabels[k]); cache.releaseTagGeometry(this.textlabels[k].tagString); delete this.textlabels[k]; } } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setTextVisibility = function( vis ) { // Create text meshes if not there, or destroy them if to be hidden if (vis && 0 === Object.keys(this.textlabels).length) { this.createTextMeshes(); } else if (!vis) { this.removeTextMeshes(); } }; /* Unused WebGLApplication.prototype.Space.prototype.Skeleton.prototype.translate = function( dx, dy, dz ) { for ( var i=0; i<CTYPES.length; ++i ) { if( dx ) { this.actor[CTYPES[i]].translateX( dx ); } if( dy ) { this.actor[CTYPES[i]].translateY( dy ); } if( dz ) { this.actor[CTYPES[i]].translateZ( dz ); } } }; */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createSynapseClustering = function(bandwidth) { var locations = this.geometry['neurite'].vertices.reduce(function(vs, v) { vs[v.node_id] = v.clone(); return vs; }, {}); return new SynapseClustering(this.createArbor(), locations, this.createSynapseCounts(), bandwidth); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createSynapseCounts = function() { return this.synapticTypes.reduce((function(o, type, k) { var vs = this.geometry[type].vertices; for (var i=0, l=vs.length; i<l; i+=2) { var treenode_id = vs[i+1].node_id, count = o[treenode_id]; if (count) o[treenode_id] = count + 1; else o[treenode_id] = 1; } return o; }).bind(this), {}); }; /** Return a map with 4 elements: * {presynaptic_to: {}, // map of node ID vs count of presynaptic sites * postsynaptic_to: {}, // map of node ID vs count of postsynaptic sites * presynaptic_to_count: N, * postsynaptic_to_count: M} */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createPrePostCounts = function() { return this.synapticTypes.reduce((function(o, type, k) { var vs = this.geometry[type].vertices, syn = {}; for (var i=0, l=vs.length; i<l; i+=2) { var treenode_id = vs[i+1].node_id, count = syn[treenode_id]; if (count) syn[treenode_id] = count + 1; else syn[treenode_id] = 1; } o[type] = syn; o[type + "_count"] = vs.length / 2; return o; }).bind(this), {}); }; /** Returns a map of treenode ID keys and lists of {type, connectorID} as values, * where type 0 is presynaptic and type 1 is postsynaptic. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createSynapseMap = function() { return this.synapticTypes.reduce((function(o, type, k) { var vs = this.geometry[type].vertices; for (var i=0, l=vs.length; i<l; i+=2) { var connector_id = vs[i].node_id, treenode_id = vs[i+1].node_id, list = o[treenode_id], synapse = {type: k, connector_id: connector_id}; if (list) list.push(synapse); else o[treenode_id] = [synapse]; } return o; }).bind(this), {}); }; /** Returns a map of connector ID keys and a list of treenode ID values. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createInverseSynapseMap = function() { return this.synapticTypes.reduce((function(o, type) { var vs = this.geometry[type].vertices; for (var i=0, l=vs.length; i<l; i+=2) { var connector_id = vs[i].node_id, treenode_id = vs[i+1].node_id, list = o[connector_id]; if (list) { list.push(connector_id); } else { o[connector_id] = [treenode_id]; } } return o; }).bind(this), {}); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createArbor = function() { return new Arbor().addEdges(this.geometry['neurite'].vertices, function(v) { return v.node_id; }); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.getPositions = function() { var vs = this.geometry['neurite'].vertices, p = {}; for (var i=0; i<vs.length; ++i) { var v = vs[i]; p[v.node_id] = v; } return p; }; /** Determine the nodes that belong to the axon by computing the centrifugal flow * centrality. * Takes as argument the json of compact-arbor, but uses only index 1: the inputs and outputs, parseable by the ArborParser.synapse function. * If only one node has the soma tag and it is not the root, will reroot at it. * Returns a map of node ID vs true for nodes that belong to the axon. * When the flowCentrality cannot be computed, returns null. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.splitByFlowCentrality = function(json) { var arbor = this.createArbor(); if (this.tags && this.tags['soma'] && 1 === this.tags['soma'].length) { var soma = this.tags['soma'][0]; if (arbor.root != soma) arbor.reroot(soma); } var ap = new ArborParser(); ap.arbor = arbor; ap.synapses(json[1]); var axon = SynapseClustering.prototype.findAxon(ap, 0.9, this.getPositions()); return axon ? axon.nodes() : null; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.updateSkeletonColor = function(options) { var node_weights, arbor; if ('none' === options.shading_method) { node_weights = null; } else { arbor = this.createArbor(); if (-1 !== options.shading_method.lastIndexOf('centrality')) { // Darken the skeleton based on the betweenness calculation. var c; if (0 === options.shading_method.indexOf('betweenness')) { c = arbor.betweennessCentrality(true); } else if (0 === options.shading_method.indexOf('slab')) { c = arbor.slabCentrality(true); // branch centrality } else { // Flow centrality var io = this.createPrePostCounts(); if (0 === io.postsynaptic_to_count || 0 === io.presynaptic_to_count) { growlAlert('WARNING', 'Neuron "' + this.skeletonmodel.baseName + '" lacks input or output synapses.'); c = arbor.nodesArray().reduce(function(o, node) { // All the same o[node] = 1; return o; }, {}); } else { var key = 'sum'; if (0 === options.shading_method.indexOf('centrifugal')) { key = 'centrifugal'; } else if (0 === options.shading_method.indexOf('centripetal')) { key = 'centripetal'; } var fc = arbor.flowCentrality(io.presynaptic_to, io.postsynaptic_to, io.presynaptic_to_count, io.postsynaptic_to_count), c = {}, nodes = Object.keys(fc); for (var i=0; i<nodes.length; ++i) { var node = nodes[i]; c[node] = fc[node][key]; } } } var node_ids = Object.keys(c), max = node_ids.reduce(function(a, node_id) { return Math.max(a, c[node_id]); }, 0); // Normalize c in place node_ids.forEach(function(node_id) { c[node_id] = c[node_id] / max; }); node_weights = c; } else if ('distance_to_root' === options.shading_method) { var locations = this.geometry['neurite'].vertices.reduce(function(vs, v) { vs[v.node_id] = v; return vs; }, {}); var distanceFn = (function(child, paren) { return this[child].distanceTo(this[paren]); }).bind(locations); var dr = arbor.nodesDistanceTo(arbor.root, distanceFn), distances = dr.distances, max = dr.max; // Normalize by max in place Object.keys(distances).forEach(function(node) { distances[node] = 1 - (distances[node] / max); }); node_weights = distances; } else if ('downstream_amount' === options.shading_method) { var locations = this.geometry['neurite'].vertices.reduce(function(vs, v) { vs[v.node_id] = v; return vs; }, {}); var distanceFn = (function(paren, child) { return this[child].distanceTo(this[paren]); }).bind(locations); node_weights = arbor.downstreamAmount(distanceFn, true); } else if ('active_node_split' === options.shading_method) { var atn = SkeletonAnnotations.getActiveNodeId(); if (arbor.contains(atn)) { node_weights = {}; var sub = arbor.subArbor(atn), up = 1, down = 0.5; if (options.invert_shading) { up = 0.5; down = 0; } arbor.nodesArray().forEach(function(node) { node_weights[node] = sub.contains(node) ? down : up; }); } else { // Don't shade any node_weights = {}; } } else if ('partitions' === options.shading_method) { // Shade by euclidian length, relative to the longest branch var locations = this.geometry['neurite'].vertices.reduce(function(vs, v) { vs[v.node_id] = v; return vs; }, {}); var partitions = arbor.partitionSorted(); node_weights = partitions.reduce(function(o, seq, i) { var loc1 = locations[seq[0]], loc2, plen = 0; for (var i=1, len=seq.length; i<len; ++i) { loc2 = locations[seq[i]]; plen += loc1.distanceTo(loc2); loc1 = loc2; } return seq.reduce(function(o, node) { o[node] = plen; return o; }, o); }, {}); // Normalize by the length of the longest partition, which ends at root var max_length = node_weights[arbor.root]; Object.keys(node_weights).forEach(function(node) { node_weights[node] /= max_length; }); } else if (-1 !== options.shading_method.indexOf('strahler')) { node_weights = arbor.strahlerAnalysis(); var max = node_weights[arbor.root]; Object.keys(node_weights).forEach(function(node) { node_weights[node] /= max; }); } } if (options.invert_shading && node_weights) { // All weights are values between 0 and 1 Object.keys(node_weights).forEach(function(node) { node_weights[node] = 1 - node_weights[node]; }); } if (node_weights || 'none' !== options.color_method) { // The skeleton colors need to be set per-vertex. this.line_material.vertexColors = THREE.VertexColors; this.line_material.needsUpdate = true; var pickColor; var actorColor = this.actorColor; var unreviewedColor = new THREE.Color().setRGB(0.2, 0.2, 0.2); var reviewedColor = new THREE.Color().setRGB(1.0, 0.0, 1.0); var axonColor = new THREE.Color().setRGB(0, 1, 0), dendriteColor = new THREE.Color().setRGB(0, 0, 1), notComputable = new THREE.Color().setRGB(0.4, 0.4, 0.4); if ('creator' === options.color_method) { pickColor = function(vertex) { return User(vertex.user_id).color; }; } else if ('all-reviewed' === options.color_method) { pickColor = this.reviews ? (function(vertex) { var reviewers = this.reviews[vertex.node_id]; return reviewers && reviewers.length > 0 ? reviewedColor : unreviewedColor; }).bind(this) : function() { return notComputable; }; } else if ('own-reviewed' === options.color_method) { pickColor = this.reviews ? (function(vertex) { var reviewers = this.reviews[vertex.node_id]; return reviewers && -1 !== reviewers.indexOf(session.userid) ? reviewedColor : unreviewedColor; }).bind(this) : function() { return notComputable; }; } else if ('axon-and-dendrite' === options.color_method) { pickColor = this.axon ? (function(vertex) { return this.axon[vertex.node_id] ? axonColor : dendriteColor; }).bind(this) : function() { return notComputable; }; } else if ('downstream-of-tag' === options.color_method) { var tags = this.tags, regex = new RegExp(options.tag_regex), cuts = Object.keys(tags).filter(function(tag) { return tag.match(regex); }).reduce(function(o, tag) { return tags[tag].reduce(function(o, nodeID) { o[nodeID] = true; return o;}, o); }, {}); if (!arbor) arbor = this.createArbor(); var upstream = arbor.upstreamArbor(cuts); pickColor = function(vertex) { return upstream.contains(vertex.node_id) ? unreviewedColor : actorColor; }; } else { pickColor = function() { return actorColor; }; } // When not using shading, but using creator or reviewer: if (!node_weights) node_weights = {}; var seen = {}; this.geometry['neurite'].colors = this.geometry['neurite'].vertices.map(function(vertex) { var node_id = vertex.node_id, color = seen[node_id]; if (color) return color; var weight = node_weights[node_id]; weight = undefined === weight? 1.0 : weight * 0.9 + 0.1; var baseColor = pickColor(vertex); color = new THREE.Color().setRGB(baseColor.r * weight, baseColor.g * weight, baseColor.b * weight); seen[node_id] = color; // Side effect: color a volume at the node, if any var mesh = this.radiusVolumes[node_id]; if (mesh) { var material = mesh.material.clone(); material.color = color; mesh.setMaterial(material); } return color; }, this); this.geometry['neurite'].colorsNeedUpdate = true; this.actor['neurite'].material.color = new THREE.Color().setHex(0xffffff); this.actor['neurite'].material.opacity = 1; this.actor['neurite'].material.transparent = false; this.actor['neurite'].material.needsUpdate = true; // TODO repeated, it's the line_material } else { // Display the entire skeleton with a single color. this.geometry['neurite'].colors = []; this.line_material.vertexColors = THREE.NoColors; this.line_material.needsUpdate = true; this.actor['neurite'].material.color = this.actorColor; this.actor['neurite'].material.opacity = this.opacity; this.actor['neurite'].material.transparent = this.opacity !== 1; this.actor['neurite'].material.needsUpdate = true; // TODO repeated it's the line_material var material = new THREE.MeshBasicMaterial({color: this.actorColor, opacity:1.0, transparent:false}); for (var k in this.radiusVolumes) { if (this.radiusVolumes.hasOwnProperty(k)) { this.radiusVolumes[k].setMaterial(material); } } } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.changeSkeletonLineWidth = function(width) { this.actor['neurite'].material.linewidth = width; this.actor['neurite'].material.needsUpdate = true; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.changeColor = function(color, options) { this.actorColor = color; if (options.color_method === 'manual') { this.updateSkeletonColor(options); } }; WebGLApplication.prototype.updateConnectorColors = function(select) { this.options.connector_color = select.value; var skeletons = Object.keys(this.space.content.skeletons).map(function(skid) { return this.space.content.skeletons[skid]; }, this); this.space.updateConnectorColors(this.options, skeletons, this.space.render.bind(this.space)); }; WebGLApplication.prototype.Space.prototype.updateConnectorColors = function(options, skeletons, callback) { if ('cyan-red' === options.connector_color) { var pre = this.staticContent.synapticColors[0], post = this.staticContent.synapticColors[1]; pre.color.setRGB(1, 0, 0); // red pre.vertexColors = THREE.NoColors; pre.needsUpdate = true; post.color.setRGB(0, 1, 1); // cyan post.vertexColors = THREE.NoColors; post.needsUpdate = true; skeletons.forEach(function(skeleton) { skeleton.completeUpdateConnectorColor(options); }); if (callback) callback(); } else if ('by-amount' === options.connector_color) { var skids = skeletons.map(function(skeleton) { return skeleton.id; }); if (skids.length > 1) $.blockUI(); requestQueue.register(django_url + project.id + "/skeleton/connectors-by-partner", "POST", {skids: skids}, (function(status, text) { try { if (200 !== status) return; var json = $.parseJSON(text); if (json.error) return alert(json.error); skeletons.forEach(function(skeleton) { skeleton.completeUpdateConnectorColor(options, json[skeleton.id]); }); if (callback) callback(); } catch (e) { console.log(e, e.stack); alert(e); } $.unblockUI(); }).bind(this)); } else if ('synapse-clustering' === options.connector_color) { if (skeletons.length > 1) $.blockUI(); try { skeletons.forEach(function(skeleton) { skeleton.completeUpdateConnectorColor(options); }); if (callback) callback(); } catch (e) { console.log(e, e.stack); alert(e); } $.unblockUI(); } else if ('axon-and-dendrite' === options.connector_color) { fetchSkeletons( skeletons.map(function(skeleton) { return skeleton.id; }), function(skid) { return django_url + project.id + '/' + skid + '/0/1/0/compact-arbor'; }, function(skid) { return {}; }, (function(skid, json) { this.content.skeletons[skid].completeUpdateConnectorColor(options, json); }).bind(this), function(skid) { growlAlert("Error", "Failed to load synapses for: " + skid); }, (function() { this.render(); }).bind(this)); } }; /** Operates in conjunction with updateConnectorColors above. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.completeUpdateConnectorColor = function(options, json) { if ('cyan-red' === options.connector_color) { this.CTYPES.slice(1).forEach(function(type, i) { this.geometry[type].colors = []; this.geometry[type].colorsNeedUpdate = true; this.actor[type].material.vertexColors = THREE.NoColors; this.actor[type].material.color = this.synapticColors[this.CTYPES[1] === type ? 0 : 1].color; this.actor[type].material.needsUpdate = true; }, this); Object.keys(this.synapticSpheres).forEach(function(idx) { var mesh = this.synapticSpheres[idx]; mesh.material = this.synapticColors[this.CTYPES[1] === mesh.type ? 0 : 1]; }, this); } else if ('by-amount' === options.connector_color) { var ranges = {}; ranges[this.CTYPES[1]] = function(ratio) { return 0.66 + 0.34 * ratio; // 0.66 (blue) to 1 (red) }; ranges[this.CTYPES[2]] = function(ratio) { return 0.16 + 0.34 * (1 - ratio); // 0.5 (cyan) to 0.16 (yellow) }; this.CTYPES.slice(1).forEach(function(type) { var partners = json[type]; if (!partners) return; var connectors = Object.keys(partners).reduce(function(o, skid) { return partners[skid].reduce(function(a, connector_id, i, arr) { a[connector_id] = arr.length; return a; }, o); }, {}), max = Object.keys(connectors).reduce(function(m, connector_id) { return Math.max(m, connectors[connector_id]); }, 0), range = ranges[type]; var fnConnectorValue = function(node_id, connector_id) { var value = connectors[connector_id]; if (!value) value = 1; // connector without partner skeleton return value; }; var fnMakeColor = function(value) { return new THREE.Color().setHSL(1 === max ? range(0) : range((value -1) / (max -1)), 1, 0.5); }; this._colorConnectorsBy(type, fnConnectorValue, fnMakeColor); }, this); } else if ('synapse-clustering' === options.connector_color) { var sc = this.createSynapseClustering(options.synapse_clustering_bandwidth), density_hill_map = sc.densityHillMap(), clusters = sc.clusterMaps(density_hill_map), colorizer = d3.scale.category10(), synapse_treenodes = Object.keys(sc.synapses); // Remove bogus cluster - TODO fix this bogus cluster in SynapseClustering delete clusters[undefined]; // Filter out clusters without synapses var clusterIDs = Object.keys(clusters).filter(function(id) { var treenodes = clusters[id]; for (var k=0; k<synapse_treenodes.length; ++k) { if (treenodes[synapse_treenodes[k]]) return true; } return false; }); var cluster_colors = clusterIDs .map(function(cid) { return [cid, clusters[cid]]; }) .sort(function(a, b) { var la = a[1].length, lb = b[1].length; return la === lb ? 0 : (la > lb ? -1 : 1); }) .reduce(function(o, c, i) { o[c[0]] = new THREE.Color().set(colorizer(i)); return o; }, {}); var fnConnectorValue = function(node_id, connector_id) { return density_hill_map[node_id]; }; var fnMakeColor = function(value) { return cluster_colors[value]; }; this.synapticTypes.forEach(function(type) { this._colorConnectorsBy(type, fnConnectorValue, fnMakeColor); }, this); } else if ('axon-and-dendrite' === options.connector_color) { var axon = this.splitByFlowCentrality(json), fnMakeColor, fnConnectorValue; if (axon) { var colors = [new THREE.Color().setRGB(0, 1, 0), // axon: green new THREE.Color().setRGB(0, 0, 1)]; // dendrite: blue fnConnectorValue = function(node_id, connector_id) { return axon[node_id] ? 0 : 1; }; fnMakeColor = function(value) { return colors[value]; }; } else { // Not computable fnMakeColor = function() { return new THREE.Color().setRGB(0.4, 0.4, 0.4); }; fnConnectorValue = function() { return 0; }; } this.synapticTypes.forEach(function(type) { this._colorConnectorsBy(type, fnConnectorValue, fnMakeColor); }, this); } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype._colorConnectorsBy = function(type, fnConnectorValue, fnMakeColor) { // Set colors per-vertex var seen = {}, seen_materials = {}, colors = [], vertices = this.geometry[type].vertices; for (var i=0; i<vertices.length; i+=2) { var connector_id = vertices[i].node_id, node_id = vertices[i+1].node_id, value = fnConnectorValue(node_id, connector_id); var color = seen[value]; if (!color) { color = fnMakeColor(value); seen[value] = color; } // twice: for treenode and for connector colors.push(color); colors.push(color); var mesh = this.synapticSpheres[node_id]; if (mesh) { mesh.material.color = color; mesh.material.needsUpdate = true; var material = seen_materials[value]; if (!material) { material = mesh.material.clone(); material.color = color; seen_materials[value] = material; } mesh.setMaterial(material); } } this.geometry[type].colors = colors; this.geometry[type].colorsNeedUpdate = true; var material = new THREE.LineBasicMaterial({color: 0xffffff, opacity: 1.0, linewidth: 6}); material.vertexColors = THREE.VertexColors; material.needsUpdate = true; this.actor[type].material = material; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.addCompositeActorToScene = function() { this.CTYPES.forEach(function(t) { this.space.add(this.actor[t]); }, this); }; /** Three possible types of actors: 'neurite', 'presynaptic_to', and 'postsynaptic_to', each consisting, respectibly, of the edges of the skeleton, the edges of the presynaptic sites and the edges of the postsynaptic sites. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.visibilityCompositeActor = function(type, visible) { this.actor[type].visible = visible; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.getActorColorAsHTMLHex = function () { return this.actorColor.getHexString(); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.getActorColorAsHex = function() { return this.actorColor.getHex(); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.remove_connector_selection = function() { if (this.connectoractor) { for (var i=0; i<2; ++i) { var ca = this.connectoractor[this.synapticTypes[i]]; if (ca) { ca.geometry.dispose(); // do not dispose material, it is shared this.space.remove(ca); delete this.connectoractor[this.synapticTypes[i]]; } } this.connectoractor = null; } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.create_connector_selection = function( common_connector_IDs ) { this.connectoractor = {}; this.connectorgeometry = {}; this.connectorgeometry[this.CTYPES[1]] = new THREE.Geometry(); this.connectorgeometry[this.CTYPES[2]] = new THREE.Geometry(); this.synapticTypes.forEach(function(type) { // Vertices is an array of Vector3, every two a pair, the first at the connector and the second at the node var vertices1 = this.geometry[type].vertices; var vertices2 = this.connectorgeometry[type].vertices; for (var i=vertices1.length-2; i>-1; i-=2) { var v = vertices1[i]; if (common_connector_IDs.hasOwnProperty(v.node_id)) { vertices2.push(vertices1[i+1]); vertices2.push(v); } } this.connectoractor[type] = new THREE.Line( this.connectorgeometry[type], this.space.staticContent.connectorLineColors[type], THREE.LinePieces ); this.space.add( this.connectoractor[type] ); }, this); }; /** Place a colored sphere at the node. Used for highlighting special tags like 'uncertain end' and 'todo'. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createLabelSphere = function(v, material) { if (this.specialTagSpheres.hasOwnProperty(v.node_id)) { // There already is a tag sphere at the node return; } var mesh = new THREE.Mesh( this.space.staticContent.labelspheregeometry, material ); mesh.position.set( v.x, v.y, v.z ); mesh.node_id = v.node_id; this.specialTagSpheres[v.node_id] = mesh; this.space.add( mesh ); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createEdge = function(v1, v2, type) { // Create edge between child (id1) and parent (id2) nodes: // Takes the coordinates of each node, transforms them into the space, // and then adds them to the parallel lists of vertices and vertexIDs var vs = this.geometry[type].vertices; vs.push(v1); vs.push(v2); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createNodeSphere = function(v, radius, material) { if (this.radiusVolumes.hasOwnProperty(v.node_id)) { // There already is a sphere or cylinder at the node return; } // Reuse geometry: an icoSphere of radius 1.0 var mesh = new THREE.Mesh(this.space.staticContent.icoSphere, material); // Scale the mesh to bring about the correct radius mesh.scale.x = mesh.scale.y = mesh.scale.z = radius; mesh.position.set( v.x, v.y, v.z ); mesh.node_id = v.node_id; this.radiusVolumes[v.node_id] = mesh; this.space.add(mesh); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createCylinder = function(v1, v2, radius, material) { if (this.radiusVolumes.hasOwnProperty(v1.node_id)) { // There already is a sphere or cylinder at the node return; } var mesh = new THREE.Mesh(this.space.staticContent.cylinder, material); // BE CAREFUL with side effects: all functions on a Vector3 alter the vector and return it (rather than returning an altered copy) var direction = new THREE.Vector3().subVectors(v2, v1); mesh.scale.x = radius; mesh.scale.y = direction.length(); mesh.scale.z = radius; var arrow = new THREE.ArrowHelper(direction.clone().normalize(), v1); mesh.rotation = new THREE.Vector3().setEulerFromQuaternion(arrow.quaternion); mesh.position = new THREE.Vector3().addVectors(v1, direction.multiplyScalar(0.5)); mesh.node_id = v1.node_id; this.radiusVolumes[v1.node_id] = mesh; this.space.add(mesh); }; /* The itype is 0 (pre) or 1 (post), and chooses from the two arrays: synapticTypes and synapticColors. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createSynapticSphere = function(v, itype) { if (this.synapticSpheres.hasOwnProperty(v.node_id)) { // There already is a synaptic sphere at the node return; } var mesh = new THREE.Mesh( this.space.staticContent.radiusSphere, this.synapticColors[itype] ); mesh.position.set( v.x, v.y, v.z ); mesh.node_id = v.node_id; mesh.type = this.synapticTypes[itype]; this.synapticSpheres[v.node_id] = mesh; this.space.add( mesh ); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.reinit_actor = function(skeletonmodel, json, options) { if (this.actor) { this.destroy(); } this.skeletonmodel = skeletonmodel; this.initialize_objects(options); var nodes = json[0]; var connectors = json[1]; var tags = json[2]; var lean = options.lean_mode; // Map of node ID vs node properties array var nodeProps = nodes.reduce(function(ob, node) { ob[node[0]] = node; return ob; }, {}); // Store for creation when requested // TODO could request them from the server when necessary this.tags = tags; // Cache for reusing Vector3d instances var vs = {}; // Reused for all meshes var material = new THREE.MeshBasicMaterial( { color: this.getActorColorAsHex(), opacity:1.0, transparent:false } ); material.opacity = this.skeletonmodel.opacity; material.transparent = material.opacity !== 1; // Create edges between all skeleton nodes // and a sphere on the node if radius > 0 nodes.forEach(function(node) { // node[0]: treenode ID // node[1]: parent ID // node[2]: user ID // 3,4,5: x,y,z // node[6]: radius // node[7]: confidence // If node has a parent var v1; if (node[1]) { var p = nodeProps[node[1]]; v1 = vs[node[0]]; if (!v1) { v1 = this.space.toSpace(new THREE.Vector3(node[3], node[4], node[5])); v1.node_id = node[0]; v1.user_id = node[2]; vs[node[0]] = v1; } var v2 = vs[p[0]]; if (!v2) { v2 = this.space.toSpace(new THREE.Vector3(p[3], p[4], p[5])); v2.node_id = p[0]; v2.user_id = p[2]; vs[p[0]] = v2; } var nodeID = node[0]; if (node[6] > 0 && p[6] > 0) { // Create cylinder using the node's radius only (not the parent) so that the geometry can be reused this.createCylinder(v1, v2, node[6], material); // Create skeleton line as well this.createEdge(v1, v2, 'neurite'); } else { // Create line this.createEdge(v1, v2, 'neurite'); // Create sphere if (node[6] > 0) { this.createNodeSphere(v1, node[6], material); } } } else { // For the root node, which must be added to vs v1 = vs[node[0]]; if (!v1) { v1 = this.space.toSpace(new THREE.Vector3(node[3], node[4], node[5])); v1.node_id = node[0]; v1.user_id = node[2]; vs[node[0]] = v1; } if (node[6] > 0) { // Clear the slot for a sphere at the root var mesh = this.radiusVolumes[v1.node_id]; if (mesh) { this.space.remove(mesh); delete this.radiusVolumes[v1.node_id]; } this.createNodeSphere(v1, node[6], material); } } if (!lean && node[7] < 5) { // Edge with confidence lower than 5 this.createLabelSphere(v1, this.space.staticContent.labelColors.uncertain); } }, this); if (options.smooth_skeletons) { var smoothed = this.createArbor().smoothPositions(vs, options.smooth_skeletons_sigma); Object.keys(vs).forEach(function(node_id) { vs[node_id].copy(smoothed[node_id]); }); } // Create edges between all connector nodes and their associated skeleton nodes, // appropriately colored as pre- or postsynaptic. // If not yet there, create as well the sphere for the node related to the connector connectors.forEach(function(con) { // con[0]: treenode ID // con[1]: connector ID // con[2]: 0 for pre, 1 for post // indices 3,4,5 are x,y,z for connector // indices 4,5,6 are x,y,z for node var v1 = this.space.toSpace(new THREE.Vector3(con[3], con[4], con[5])); v1.node_id = con[1]; var v2 = vs[con[0]]; this.createEdge(v1, v2, this.synapticTypes[con[2]]); this.createSynapticSphere(v2, con[2]); }, this); // Place spheres on nodes with special labels, if they don't have a sphere there already for (var tag in this.tags) { if (this.tags.hasOwnProperty(tag)) { var tagLC = tag.toLowerCase(); if (-1 !== tagLC.indexOf('todo')) { this.tags[tag].forEach(function(nodeID) { if (!this.specialTagSpheres[nodeID]) { this.createLabelSphere(vs[nodeID], this.space.staticContent.labelColors.todo); } }, this); } else if (-1 !== tagLC.indexOf('uncertain')) { this.tags[tag].forEach(function(nodeID) { if (!this.specialTagSpheres[nodeID]) { this.createLabelSphere(vs[nodeID], this.space.staticContent.labelColors.uncertain); } }, this); } } } if (options.resample_skeletons) { // WARNING: node IDs no longer resemble actual skeleton IDs. // All node IDs will now have negative values to avoid accidental similarities. var res = this.createArbor().resampleSlabs(vs, options.smooth_skeletons_sigma, options.resampling_delta, 2); var vs = this.geometry['neurite'].vertices; // Remove existing lines vs.length = 0; // Add all new lines var edges = res.arbor.edges, positions = res.positions; Object.keys(edges).forEach(function(nodeID) { // Fix up Vector3 instances var v_child = positions[nodeID]; v_child.user_id = -1; v_child.node_id = -nodeID; // Add line vs.push(v_child); vs.push(positions[edges[nodeID]]); // parent }); // Fix up root var v_root = positions[res.arbor.root]; v_root.user_id = -1; v_root.node_id = -res.arbor.root; } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.show = function(options) { this.addCompositeActorToScene(); this.setActorVisibility( this.skeletonmodel.selected ); // the skeleton, radius spheres and label spheres if (options.connector_filter) { this.setPreVisibility( false ); // the presynaptic edges and spheres this.setPostVisibility( false ); // the postsynaptic edges and spheres } else { this.setPreVisibility( this.skeletonmodel.pre_visible ); // the presynaptic edges and spheres this.setPostVisibility( this.skeletonmodel.post_visible ); // the postsynaptic edges and spheres } this.setTextVisibility( this.skeletonmodel.text_visible ); // the text labels //this.updateSkeletonColor(options); // Will query the server if ('cyan-red' !== options.connector_color) this.space.updateConnectorColors(options, [this]); }; /** * Toggles the display of a JQuery UI dialog that shows which user has which * color assigned. */ WebGLApplication.prototype.toggle_usercolormap_dialog = function() { // In case a color dialog exists already, close it and return. if ($('#user-colormap-dialog').length > 0) { $('#user-colormap-dialog').remove(); return; } // Create a new color dialog var dialog = document.createElement('div'); dialog.setAttribute("id", "user-colormap-dialog"); dialog.setAttribute("title", "User colormap"); var tab = document.createElement('table'); tab.setAttribute("id", "usercolormap-table"); tab.innerHTML = '<thead>' + '<tr>' + '<th>login</th>' + '<th>name</th>' + '<th>color</th>' + '</tr>' + '</thead>' + '<tbody></tbody>'; dialog.appendChild(tab); $(dialog).dialog({ height: 440, width: 340, modal: false, dialogClass: "no-close", buttons: { "OK": function() { $(this).dialog("close"); } }, close: function(event, ui) { $('#user-colormap-dialog').remove(); } }); var users = User.all(); for (var userID in users) { if (users.hasOwnProperty(userID) && userID !== "-1") { var user = users[userID]; var rowElement = $('<tr/>'); rowElement.append( $('<td/>').text( user.login ) ); rowElement.append( $('<td/>').text( user.fullName ) ); rowElement.append( $('<div/>').css('width', '100px').css('height', '20px').css('background-color', '#' + user.color.getHexString()) ); $('#usercolormap-table > tbody:last').append( rowElement ); } } }; WebGLApplication.prototype.toggleInvertShading = function() { this.options.invert_shading = !this.options.invert_shading; if (this.options.shading_method === 'none') return; this.set_shading_method(); }; WebGLApplication.prototype.setFollowActive = function(value) { this.options.follow_active = value ? true : false; this.space.render(); };
django/applications/catmaid/static/js/webglapp.js
/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */ /* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */ "use strict"; /* Only methods of the WebGLApplication object elicit a render. All other methods * do not, except for those that use continuations to load data (meshes) or to * compute with web workers (betweenness centrality shading). */ var WebGLApplication = function() { this.widgetID = this.registerInstance(); this.registerSource(); // Indicates whether init has been called this.initialized = false; // Listen to changes of the active node SkeletonAnnotations.on(SkeletonAnnotations.EVENT_ACTIVE_NODE_CHANGED, this.staticUpdateActiveNodePosition, this); }; WebGLApplication.prototype = {}; $.extend(WebGLApplication.prototype, new InstanceRegistry()); $.extend(WebGLApplication.prototype, new SkeletonSource()); WebGLApplication.prototype.init = function(canvasWidth, canvasHeight, divID) { if (this.initialized) { return; } this.divID = divID; this.container = document.getElementById(divID); this.stack = project.focusedStack; this.submit = new submitterFn(); this.options = new WebGLApplication.prototype.OPTIONS.clone(); this.space = new this.Space(canvasWidth, canvasHeight, this.container, this.stack); this.updateActiveNodePosition(); this.initialized = true; }; WebGLApplication.prototype.getName = function() { return "3D View " + this.widgetID; }; WebGLApplication.prototype.destroy = function() { SkeletonAnnotations.off(SkeletonAnnotations.EVENT_ACTIVE_NODE_CHANGED, this.staticUpdateActiveNodePosition); this.unregisterInstance(); this.unregisterSource(); this.space.destroy(); Object.keys(this).forEach(function(key) { delete this[key]; }, this); }; WebGLApplication.prototype.updateModels = function(models) { this.append(models); }; WebGLApplication.prototype.getSelectedSkeletons = function() { var skeletons = this.space.content.skeletons; return Object.keys(skeletons).filter(function(skid) { return skeletons[skid].visible; }).map(Number); }; WebGLApplication.prototype.getSkeletonModel = function(skeleton_id) { if (skeleton_id in this.space.content.skeletons) { return this.space.content.skeletons[skeleton_id].skeletonmodel.clone(); } return null; }; WebGLApplication.prototype.getSelectedSkeletonModels = function() { var skeletons = this.space.content.skeletons; return Object.keys(skeletons).reduce(function(m, skid) { var skeleton = skeletons[skid]; if (skeleton.visible) { m[skid] = skeleton.skeletonmodel.clone(); } return m; }, {}); }; WebGLApplication.prototype.highlight = function(skeleton_id) { // Do nothing, for now }; WebGLApplication.prototype.resizeView = function(w, h) { if (!this.space) { // WebGLView has not been initialized, can't resize! return; } var canvasWidth = w, canvasHeight = h; if (!THREEx.FullScreen.activated()) { $('#view_in_3d_webgl_widget' + this.widgetID).css('overflowY', 'hidden'); if(isNaN(h) && isNaN(w)) { canvasHeight = 800; canvasWidth = 600; } // use 4:3 if (isNaN(h)) { canvasHeight = canvasWidth / 4 * 3; } else if (isNaN(w)) { canvasHeight = canvasHeight - 100; canvasWidth = canvasHeight / 3 * 4; } if (canvasWidth < 80 || canvasHeight < 60) { canvasWidth = 80; canvasHeight = 60; } $('#viewer-3d-webgl-canvas' + this.widgetID).width(canvasWidth); $('#viewer-3d-webgl-canvas' + this.widgetID).height(canvasHeight); $('#viewer-3d-webgl-canvas' + this.widgetID).css("background-color", "#000000"); this.space.setSize(canvasWidth, canvasHeight); this.space.render(); } }; WebGLApplication.prototype.fullscreenWebGL = function() { if (THREEx.FullScreen.activated()){ var w = canvasWidth, h = canvasHeight; this.resizeView( w, h ); THREEx.FullScreen.cancel(); } else { THREEx.FullScreen.request(document.getElementById('viewer-3d-webgl-canvas' + this.widgetID)); var w = window.innerWidth, h = window.innerHeight; this.resizeView( w, h ); } this.space.render(); }; /** * Store the current view as PNG image. */ WebGLApplication.prototype.exportPNG = function() { this.space.render(); try { var imageData = this.space.view.getImageData(); var blob = dataURItoBlob(imageData); growlAlert("Information", "The exported PNG will have a transparent background"); saveAs(blob, "catmaid_3d_view.png"); } catch (e) { error("Could not export current 3D view, there was an error.", e); } }; /** * Store the current view as SVG image. */ WebGLApplication.prototype.exportSVG = function() { try { var svg = this.space.view.getSVGData(); var xml = new XMLSerializer().serializeToString(svg); var blob = new Blob([xml], {type: 'text/svg'}); saveAs(blob, "catmaid-3d-view.svg"); } catch (e) { error("Could not export current 3D view, there was an error.", e); } }; WebGLApplication.prototype.Options = function() { this.show_meshes = false; this.meshes_color = "#ffffff"; this.meshes_opacity = 0.2; this.show_missing_sections = false; this.missing_section_height = 20; this.show_active_node = true; this.show_floor = true; this.show_background = true; this.show_box = true; this.show_zplane = false; this.connector_filter = false; this.shading_method = 'none'; this.color_method = 'none'; this.tag_regex = ''; this.connector_color = 'cyan-red'; this.lean_mode = false; this.synapse_clustering_bandwidth = 5000; this.smooth_skeletons = false; this.smooth_skeletons_sigma = 200; // nm this.resample_skeletons = false; this.resampling_delta = 3000; // nm this.skeleton_line_width = 3; this.invert_shading = false; this.follow_active = false; }; WebGLApplication.prototype.Options.prototype = {}; WebGLApplication.prototype.Options.prototype.clone = function() { var src = this; return Object.keys(this).reduce( function(copy, key) { copy[key] = src[key]; return copy; }, new WebGLApplication.prototype.Options()); }; WebGLApplication.prototype.Options.prototype.createMeshMaterial = function(color, opacity) { color = color || new THREE.Color(this.meshes_color); if (typeof opacity === 'undefined') opacity = this.meshes_opacity; return new THREE.MeshBasicMaterial({color: color, opacity: opacity, transparent: opacity !== 1, wireframe: true}); }; /** Persistent options, get replaced every time the 'ok' button is pushed in the dialog. */ WebGLApplication.prototype.OPTIONS = new WebGLApplication.prototype.Options(); WebGLApplication.prototype.updateZPlane = function() { this.space.staticContent.updateZPlanePosition(this.stack); this.space.render(); }; WebGLApplication.prototype.staticUpdateZPlane = function() { this.getInstances().forEach(function(instance) { instance.updateZPlane(); }); }; /** Receives an extra argument (an event) which is ignored. */ WebGLApplication.prototype.updateColorMethod = function(colorMenu) { if ('downstream-of-tag' === colorMenu.value) { var dialog = new OptionsDialog("Type in tag"); dialog.appendMessage("Nodes downstream of tag: magenta.\nNodes upstream of tag: dark grey."); var input = dialog.appendField("Tag (regex): ", "tag_text", this.options.tag_regex); dialog.onOK = (function() { this.options.tag_regex = input.value; this.options.color_method = colorMenu.value; this.updateSkeletonColors(); }).bind(this); dialog.onCancel = function() { // Reset to default (can't know easily what was selected before). colorMenu.selectedIndex = 0; }; dialog.show(); return; } this.options.color_method = colorMenu.value; this.updateSkeletonColors(); }; WebGLApplication.prototype.updateSkeletonColors = function(callback) { var fnRecolor = (function() { Object.keys(this.space.content.skeletons).forEach(function(skeleton_id) { this.space.content.skeletons[skeleton_id].updateSkeletonColor(this.options); }, this); if (typeof callback === "function") { try { callback(); } catch (e) { alert(e); } } this.space.render(); }).bind(this); if (-1 !== this.options.color_method.indexOf('reviewed')) { var skeletons = this.space.content.skeletons; // Find the subset of skeletons that don't have their reviews loaded var skeleton_ids = Object.keys(skeletons).filter(function(skid) { return !skeletons[skid].reviews; }); // Will invoke fnRecolor even if the list of skeleton_ids is empty fetchSkeletons( skeleton_ids, function(skeleton_id) { return django_url + project.id + '/skeleton/' + skeleton_id + '/reviewed-nodes'; }, function(skeleton_id) { return {}; }, // post function(skeleton_id, json) { skeletons[skeleton_id].reviews = json; }, function(skeleton_id) { // Failed loading skeletons[skeleton_id].reviews = {}; // dummy console.log('ERROR: failed to load reviews for skeleton ' + skeleton_id); }, fnRecolor); } else if ('axon-and-dendrite' === this.options.color_method) { var skeletons = this.space.content.skeletons; // Find the subset of skeletons that don't have their axon loaded var skeleton_ids = Object.keys(skeletons).filter(function(skid) { return !skeletons[skid].axon; }); fetchSkeletons( skeleton_ids, function(skid) { return django_url + project.id + '/' + skid + '/0/1/0/compact-arbor'; }, function(skid) { return {}; }, // post function(skid, json) { skeletons[skid].axon = skeletons[skid].splitByFlowCentrality(json); }, function(skid) { // Failed loading skeletons[skid].axon = {}; // dummy console.log('ERROR: failed to load axon-and-dendrite for skeleton ' + skid); }, fnRecolor); } else { fnRecolor(); } }; WebGLApplication.prototype.XYView = function() { this.space.view.XY(); this.space.render(); }; WebGLApplication.prototype.XZView = function() { this.space.view.XZ(); this.space.render(); }; WebGLApplication.prototype.ZYView = function() { this.space.view.ZY(); this.space.render(); }; WebGLApplication.prototype.ZXView = function() { this.space.view.ZX(); this.space.render(); }; WebGLApplication.prototype._skeletonVizFn = function(field) { return function(skeleton_id, value) { var skeletons = this.space.content.skeletons; if (!skeletons.hasOwnProperty(skeleton_id)) return; skeletons[skeleton_id]['set' + field + 'Visibility'](value); this.space.render(); }; }; WebGLApplication.prototype.setSkeletonPreVisibility = WebGLApplication.prototype._skeletonVizFn('Pre'); WebGLApplication.prototype.setSkeletonPostVisibility = WebGLApplication.prototype._skeletonVizFn('Post'); WebGLApplication.prototype.setSkeletonTextVisibility = WebGLApplication.prototype._skeletonVizFn('Text'); WebGLApplication.prototype.toggleConnectors = function() { this.options.connector_filter = ! this.options.connector_filter; var f = this.options.connector_filter; var skeletons = this.space.content.skeletons; var skids = Object.keys(skeletons); skids.forEach(function(skid) { skeletons[skid].setPreVisibility( !f ); skeletons[skid].setPostVisibility( !f ); $('#skeletonpre-' + skid).attr('checked', !f ); $('#skeletonpost-' + skid).attr('checked', !f ); }); if (this.options.connector_filter) { this.refreshRestrictedConnectors(); } else { skids.forEach(function(skid) { skeletons[skid].remove_connector_selection(); }); this.space.render(); } }; WebGLApplication.prototype.refreshRestrictedConnectors = function() { if (!this.options.connector_filter) return; // Find all connector IDs referred to by more than one skeleton // but only for visible skeletons var skeletons = this.space.content.skeletons; var visible_skeletons = Object.keys(skeletons).filter(function(skeleton_id) { return skeletons[skeleton_id].visible; }); var synapticTypes = this.space.Skeleton.prototype.synapticTypes; var counts = visible_skeletons.reduce(function(counts, skeleton_id) { return synapticTypes.reduce(function(counts, type) { var vertices = skeletons[skeleton_id].geometry[type].vertices; // Vertices is an array of Vector3, every two a pair, the first at the connector and the second at the node for (var i=vertices.length-2; i>-1; i-=2) { var connector_id = vertices[i].node_id; if (!counts.hasOwnProperty(connector_id)) { counts[connector_id] = {}; } counts[connector_id][skeleton_id] = null; } return counts; }, counts); }, {}); var common = {}; for (var connector_id in counts) { if (counts.hasOwnProperty(connector_id) && Object.keys(counts[connector_id]).length > 1) { common[connector_id] = null; // null, just to add something } } var visible_set = visible_skeletons.reduce(function(o, skeleton_id) { o[skeleton_id] = null; return o; }, {}); for (var skeleton_id in skeletons) { if (skeletons.hasOwnProperty(skeleton_id)) { skeletons[skeleton_id].remove_connector_selection(); if (skeleton_id in visible_set) { skeletons[skeleton_id].create_connector_selection( common ); } } } this.space.render(); }; WebGLApplication.prototype.set_shading_method = function() { // Set the shading of all skeletons based on the state of the "Shading" pop-up menu. this.options.shading_method = $('#skeletons_shading' + this.widgetID + ' :selected').attr("value"); var skeletons = this.space.content.skeletons; try { $.blockUI(); Object.keys(skeletons).forEach(function(skid) { skeletons[skid].updateSkeletonColor(this.options); }, this); } catch (e) { console.log(e, e.stack); alert(e); } $.unblockUI(); this.space.render(); }; WebGLApplication.prototype.look_at_active_node = function() { this.space.content.active_node.updatePosition(this.space, this.options); this.space.view.controls.target = this.space.content.active_node.mesh.position.clone(); this.space.render(); }; WebGLApplication.prototype.updateActiveNodePosition = function() { this.space.content.active_node.updatePosition(this.space, this.options); if (this.space.content.active_node.mesh.visible) { this.space.render(); } }; WebGLApplication.prototype.staticUpdateActiveNodePosition = function() { this.getInstances().map(function(instance) { instance.updateActiveNodePosition(); // Center the active node, if wanted if (instance.options.follow_active) { instance.look_at_active_node(); } }); }; WebGLApplication.prototype.has_skeleton = function(skeleton_id) { return this.space.content.skeletons.hasOwnProperty(skeleton_id); }; /** Reload only if present. */ WebGLApplication.prototype.staticReloadSkeletons = function(skeleton_ids) { this.getInstances().forEach(function(instance) { var models = skeleton_ids.filter(instance.hasSkeleton, instance) .reduce(function(m, skid) { if (instance.hasSkeleton(skid)) m[skid] = instance.getSkeletonModel(skid); return m; }, {}); instance.space.removeSkeletons(skeleton_ids); instance.updateModels(models); }); }; /** Fetch skeletons one by one, and render just once at the end. */ WebGLApplication.prototype.addSkeletons = function(models, callback) { // Update skeleton properties for existing skeletons, and remove them from models var skeleton_ids = Object.keys(models).filter(function(skid) { if (skid in this.space.content.skeletons) { var model = models[skid], skeleton = this.space.content.skeletons[skid]; skeleton.skeletonmodel = model; skeleton.setActorVisibility(model.selected); skeleton.setPreVisibility(model.pre_visible); skeleton.setPostVisibility(model.post_visible); skeleton.setTextVisibility(model.text_visible); skeleton.actorColor = model.color.clone(); skeleton.opacity = model.opacity; skeleton.updateSkeletonColor(this.options); return false; } return true; }, this); if (0 === skeleton_ids.length) return; var options = this.options; var url1 = django_url + project.id + '/', lean = options.lean_mode ? 0 : 1, url2 = '/' + lean + '/' + lean + '/compact-skeleton'; fetchSkeletons( skeleton_ids, function(skeleton_id) { return url1 + skeleton_id + url2; }, function(skeleton_id) { return {}; // the post }, (function(skeleton_id, json) { var sk = this.space.updateSkeleton(models[skeleton_id], json, options); if (sk) sk.show(this.options); }).bind(this), function(skeleton_id) { // Failed loading: will be handled elsewhere via fnMissing in fetchCompactSkeletons }, (function() { this.updateSkeletonColors( (function() { if (this.options.connector_filter) this.refreshRestrictedConnectors(); if (typeof callback === "function") { try { callback(); } catch (e) { alert(e); } } }).bind(this)); }).bind(this)); }; /** Reload skeletons from database. */ WebGLApplication.prototype.updateSkeletons = function() { var models = this.getSelectedSkeletonModels(); // visible ones this.clear(); this.append(models); }; WebGLApplication.prototype.append = function(models) { if (0 === Object.keys(models).length) { growlAlert("Info", "No skeletons selected!"); return; } this.addSkeletons(models, false); if (this.options.connector_filter) { this.refreshRestrictedConnectors(); } else { this.space.render(); } }; WebGLApplication.prototype.clear = function() { this.removeSkeletons(Object.keys(this.space.content.skeletons)); this.space.render(); }; WebGLApplication.prototype.getSkeletonColor = function( skeleton_id ) { if (skeleton_id in this.space.content.skeletons) { return this.space.content.skeletons[skeleton_id].actorColor.clone(); } return new THREE.Color().setRGB(1, 0, 1); }; WebGLApplication.prototype.hasSkeleton = function(skeleton_id) { return skeleton_id in this.space.content.skeletons; }; WebGLApplication.prototype.removeSkeletons = function(skeleton_ids) { if (!this.space) return; this.space.removeSkeletons(skeleton_ids); if (this.options.connector_filter) this.refreshRestrictedConnectors(); else this.space.render(); }; WebGLApplication.prototype.changeSkeletonColors = function(skeleton_ids, colors) { var skeletons = this.space.content.skeletons; skeleton_ids.forEach(function(skeleton_id, index) { if (!skeletons.hasOwnProperty(skeleton_id)) { console.log("Skeleton "+skeleton_id+" does not exist."); } if (undefined === colors) skeletons[skeleton_id].updateSkeletonColor(this.options); else skeletons[skeleton_id].changeColor(colors[index], this.options); }, this); this.space.render(); return true; }; // TODO obsolete code from segmentationtool.js WebGLApplication.prototype.addActiveObjectToStagingArea = function() { alert("The function 'addActiveObjectToStagingArea' is no longer in use."); }; WebGLApplication.prototype.showActiveNode = function() { this.space.content.active_node.setVisible(true); }; WebGLApplication.prototype.configureParameters = function() { var space = this.space; var options = this.options; var updateSkeletons = this.updateSkeletons.bind(this); var dialog = document.createElement('div'); dialog.setAttribute("id", "dialog-confirm"); dialog.setAttribute("title", "Configuration"); var msg = document.createElement('p'); msg.innerHTML = "Missing sections height [0,100]:"; dialog.appendChild(msg); var missingsectionheight = document.createElement('input'); missingsectionheight.setAttribute("type", "text"); missingsectionheight.setAttribute("id", "missing-section-height"); missingsectionheight.setAttribute("value", options.missing_section_height); dialog.appendChild(missingsectionheight); dialog.appendChild(document.createElement("br")); var bzplane = document.createElement('input'); bzplane.setAttribute("type", "checkbox"); bzplane.setAttribute("id", "enable_z_plane"); bzplane.setAttribute("value", "Enable z-plane"); if ( options.show_zplane ) bzplane.setAttribute("checked", "true"); dialog.appendChild(bzplane); dialog.appendChild(document.createTextNode('Enable z-plane')); dialog.appendChild(document.createElement("br")); var bmeshes = document.createElement('input'); bmeshes.setAttribute("type", "checkbox"); bmeshes.setAttribute("id", "show_meshes"); bmeshes.setAttribute("value", "Show meshes"); if( options.show_meshes ) bmeshes.setAttribute("checked", "true"); dialog.appendChild(bmeshes); dialog.appendChild(document.createTextNode('Show meshes, with color: ')); var c = $(document.createElement("button")).attr({ id: 'meshes-color', value: 'color' }) .css('background-color', options.meshes_color) .click( function( event ) { var sel = $('#meshes-colorwheel'); if (sel.is(':hidden')) { var cw = Raphael.colorwheel(sel[0], 150); cw.color($('#meshes-color').css('background-color'), $('#meshes-opacity').text()); cw.onchange(function(color, alpha) { color = new THREE.Color().setRGB(parseInt(color.r) / 255.0, parseInt(color.g) / 255.0, parseInt(color.b) / 255.0); $('#meshes-color').css('background-color', color.getStyle()); $('#meshes-opacity').text(alpha.toFixed(2)); if (options.show_meshes) { var material = options.createMeshMaterial(color, alpha); space.content.meshes.forEach(function(mesh) { mesh.material = material; }); space.render(); } }); sel.show(); } else { sel.hide(); sel.empty(); } }) .text('color') .get(0); dialog.appendChild(c); dialog.appendChild($( '<span>(Opacity: <span id="meshes-opacity">' + options.meshes_opacity + '</span>)</span>').get(0)); dialog.appendChild($('<div id="meshes-colorwheel">').hide().get(0)); dialog.appendChild(document.createElement("br")); var bactive = document.createElement('input'); bactive.setAttribute("type", "checkbox"); bactive.setAttribute("id", "enable_active_node"); bactive.setAttribute("value", "Enable active node"); if( options.show_active_node ) bactive.setAttribute("checked", "true"); dialog.appendChild(bactive); dialog.appendChild(document.createTextNode('Enable active node')); dialog.appendChild(document.createElement("br")); var bmissing = document.createElement('input'); bmissing.setAttribute("type", "checkbox"); bmissing.setAttribute("id", "enable_missing_sections"); bmissing.setAttribute("value", "Missing sections"); if( options.show_missing_sections ) bmissing.setAttribute("checked", "true"); dialog.appendChild(bmissing); dialog.appendChild(document.createTextNode('Missing sections')); dialog.appendChild(document.createElement("br")); /*var bortho = document.createElement('input'); bortho.setAttribute("type", "checkbox"); bortho.setAttribute("id", "toggle_ortho"); bortho.setAttribute("value", "Toggle Ortho"); container.appendChild(bortho); container.appendChild(document.createTextNode('Toggle Ortho'));*/ var bfloor = document.createElement('input'); bfloor.setAttribute("type", "checkbox"); bfloor.setAttribute("id", "toggle_floor"); bfloor.setAttribute("value", "Toggle Floor"); if( options.show_floor ) bfloor.setAttribute("checked", "true"); dialog.appendChild(bfloor); dialog.appendChild(document.createTextNode('Toggle floor')); dialog.appendChild(document.createElement("br")); var bbox = document.createElement('input'); bbox.setAttribute("type", "checkbox"); bbox.setAttribute("id", "toggle_aabb"); bbox.setAttribute("value", "Toggle Bounding Box"); if( options.show_box ) bbox.setAttribute("checked", "true"); dialog.appendChild(bbox); dialog.appendChild(document.createTextNode('Toggle Bounding Box')); dialog.appendChild(document.createElement("br")); var bbackground = document.createElement('input'); bbackground.setAttribute("type", "checkbox"); bbackground.setAttribute("id", "toggle_bgcolor"); bbackground.setAttribute("value", "Toggle Background Color"); if( options.show_background ) bbackground.setAttribute("checked", "true"); dialog.appendChild(bbackground); dialog.appendChild(document.createTextNode('Toggle Background Color')); dialog.appendChild(document.createElement("br")); var blean = document.createElement('input'); blean.setAttribute("type", "checkbox"); blean.setAttribute("id", "toggle_lean"); if( options.lean_mode ) blean.setAttribute("checked", "true"); dialog.appendChild(blean); dialog.appendChild(document.createTextNode('Toggle lean mode (no synapses, no tags)')); dialog.appendChild(document.createElement("br")); dialog.appendChild(document.createTextNode('Synapse clustering bandwidth: ')); var ibandwidth = document.createElement('input'); ibandwidth.setAttribute('type', 'text'); ibandwidth.setAttribute('id', 'synapse-clustering-bandwidth'); ibandwidth.setAttribute('value', options.synapse_clustering_bandwidth); ibandwidth.setAttribute('size', '7'); dialog.appendChild(ibandwidth); dialog.appendChild(document.createTextNode(' nm.')); dialog.appendChild(document.createElement("br")); var optionField = function(label, units, size, checkboxKey, valueKey) { var checkbox; if (checkboxKey) { checkbox = document.createElement('input'); checkbox.setAttribute("type", "checkbox"); if (options[checkboxKey]) checkbox.setAttribute("checked", true); dialog.appendChild(checkbox); } dialog.appendChild(document.createTextNode(label)); var number = document.createElement('input'); number.setAttribute('type', 'text'); number.setAttribute('value', options[valueKey]); number.setAttribute('size', size); dialog.appendChild(number); dialog.appendChild(document.createTextNode(units)); dialog.appendChild(document.createElement("br")); return [checkbox, number]; }; var smooth = optionField('Toggle smoothing skeletons by Gaussian convolution of the slabs, with sigma: ', ' nm.', 5, 'smooth_skeletons', 'smooth_skeletons_sigma'); var resample = optionField('Toogle resampling skeleton slabs, with delta: ', ' nm.', 5, 'resample_skeletons', 'resampling_delta'); var linewidth = optionField('Skeleton rendering line width: ', ' pixels.', 5, null, 'skeleton_line_width'); var submit = this.submit; $(dialog).dialog({ height: 440, width: 600, modal: true, buttons: { "Cancel": function() { $(this).dialog("close"); }, "OK": function() { var missing_section_height = missingsectionheight.value; try { missing_section_height = parseInt(missing_section_height); if (missing_section_height < 0) missing_section_height = 20; } catch (e) { alert("Invalid value for the height of missing sections!"); } options.missing_section_height = missing_section_height; options.show_zplane = bzplane.checked; options.show_missing_sections = bmissing.checked; options.show_floor = bfloor.checked; options.show_box = bbox.checked; options.show_background = bbackground.checked; options.show_active_node = bactive.checked; options.show_meshes = bmeshes.checked; options.meshes_color = $('#meshes-color').css('background-color').replace(/\s/g, ''); options.meshes_opacity = $('#meshes-opacity').text(); options.lean_mode = blean.checked; var read = function(checkbox, checkboxKey, valueField, valueKey) { var old_value = options[checkboxKey]; if (checkbox) options[checkboxKey] = checkbox.checked; try { var new_value = parseInt(valueField.value); if (new_value > 0) { options[valueKey] = new_value; return old_value != new_value; } else alert("'" + valueKey + "' must be larger than zero."); } catch (e) { alert("Invalid value for '" + valueKey + "': " + valueField.value); } return false; }; var changed_sigma = read(smooth[0], 'smooth_skeletons', smooth[1], 'smooth_skeletons_sigma'), changed_bandwidth = read(null, null, ibandwidth, 'synapse_clustering_bandwidth', null), changed_delta = read(resample[0], 'resample_skeletons', resample[1], 'resampling_delta'), changed_line_width = read(null, null, linewidth[1], 'skeleton_line_width', null); space.staticContent.adjust(options, space); space.content.adjust(options, space, submit, changed_bandwidth, changed_line_width); // Copy WebGLApplication.prototype.OPTIONS = options.clone(); if (changed_sigma || changed_delta) updateSkeletons(); else space.render(); $(this).dialog("close"); } }, close: function(event, ui) { $('#dialog-confirm').remove(); // Remove the binding $(document).off('keyup', "#meshes-color"); } }); }; /** Defines the properties of the 3d space and also its static members like the bounding box and the missing sections. */ WebGLApplication.prototype.Space = function( w, h, container, stack ) { this.stack = stack; this.container = container; // used by MouseControls this.canvasWidth = w; this.canvasHeight = h; this.yDimension = stack.dimension.y * stack.resolution.y; // Absolute center in Space coordinates (not stack coordinates) this.center = this.createCenter(); this.dimensions = new THREE.Vector3(stack.dimension.x * stack.resolution.x, stack.dimension.y * stack.resolution.y, stack.dimension.z * stack.resolution.z); // WebGL space this.scene = new THREE.Scene(); this.view = new this.View(this); this.lights = this.createLights(stack.dimension, stack.resolution, this.view.camera); this.lights.forEach(this.scene.add, this.scene); // Content this.staticContent = new this.StaticContent(this.dimensions, stack, this.center); this.scene.add(this.staticContent.box); this.scene.add(this.staticContent.floor); this.content = new this.Content(); this.scene.add(this.content.active_node.mesh); }; WebGLApplication.prototype.Space.prototype = {}; WebGLApplication.prototype.Space.prototype.setSize = function(canvasWidth, canvasHeight) { this.canvasWidth = canvasWidth; this.canvasHeight = canvasHeight; this.view.camera.setSize(canvasWidth, canvasHeight); this.view.camera.toPerspective(); // invokes update of camera matrices this.view.renderer.setSize(canvasWidth, canvasHeight); }; /** Transform a THREE.Vector3d from stack coordinates to Space coordinates. In other words, transform coordinates from CATMAID coordinate system to WebGL coordinate system: x->x, y->y+dy, z->-z */ WebGLApplication.prototype.Space.prototype.toSpace = function(v3) { v3.y = this.yDimension - v3.y; v3.z = -v3.z; return v3; }; /** Transform axes but do not scale. */ WebGLApplication.prototype.Space.prototype.coordsToUnscaledSpace = function(x, y, z) { return [x, this.yDimension - y, -z]; }; /** Starting at i, edit i, i+1 and i+2, which represent x, y, z of a 3d point. */ WebGLApplication.prototype.Space.prototype.coordsToUnscaledSpace2 = function(vertices, i) { // vertices[i] equal vertices[i+1] = this.yDimension -vertices[i+1]; vertices[i+2] = -vertices[i+2]; }; WebGLApplication.prototype.Space.prototype.createCenter = function() { var d = this.stack.dimension, r = this.stack.resolution, t = this.stack.translation, center = new THREE.Vector3((d.x * r.x) / 2.0 + t.x, (d.y * r.y) / 2.0 + t.y, (d.z * r.z) / 2.0 + t.z); // Bring the stack center to Space coordinates this.toSpace(center); return center; }; WebGLApplication.prototype.Space.prototype.createLights = function(dimension, resolution, camera) { var ambientLight = new THREE.AmbientLight( 0x505050 ); var pointLight = new THREE.PointLight( 0xffaa00 ); pointLight.position.set(dimension.x * resolution.x, dimension.y * resolution.y, 50); var light = new THREE.SpotLight( 0xffffff, 1.5 ); light.position.set(dimension.x * resolution.x / 2, dimension.y * resolution.y / 2, 50); light.castShadow = true; light.shadowCameraNear = 200; light.shadowCameraFar = camera.far; light.shadowCameraFov = 50; light.shadowBias = -0.00022; light.shadowDarkness = 0.5; light.shadowMapWidth = 2048; light.shadowMapHeight = 2048; return [ambientLight, pointLight, light]; }; WebGLApplication.prototype.Space.prototype.add = function(mesh) { this.scene.add(mesh); }; WebGLApplication.prototype.Space.prototype.remove = function(mesh) { this.scene.remove(mesh); }; WebGLApplication.prototype.Space.prototype.render = function() { this.view.render(); }; WebGLApplication.prototype.Space.prototype.destroy = function() { // remove active_node and project-wise meshes this.scene.remove(this.content.active_node.mesh); this.content.meshes.forEach(this.scene.remove, this.scene); // dispose active_node and meshes this.content.dispose(); // dispose and remove skeletons this.removeSkeletons(Object.keys(this.content.skeletons)); this.lights.forEach(this.scene.remove, this.scene); // dispose meshes and materials this.staticContent.dispose(); // remove meshes this.scene.remove(this.staticContent.box); this.scene.remove(this.staticContent.floor); if (this.staticContent.zplane) this.scene.remove(this.staticContent.zplane); this.staticContent.missing_sections.forEach(this.scene.remove, this.scene); this.view.destroy(); Object.keys(this).forEach(function(key) { delete this[key]; }, this); }; WebGLApplication.prototype.Space.prototype.removeSkeletons = function(skeleton_ids) { skeleton_ids.forEach(this.removeSkeleton, this); }; WebGLApplication.prototype.Space.prototype.removeSkeleton = function(skeleton_id) { if (skeleton_id in this.content.skeletons) { this.content.skeletons[skeleton_id].destroy(); delete this.content.skeletons[skeleton_id]; } }; WebGLApplication.prototype.Space.prototype.updateSplitShading = function(old_skeleton_id, new_skeleton_id, options) { if ('active_node_split' === options.shading_method) { if (old_skeleton_id !== new_skeleton_id) { if (old_skeleton_id && old_skeleton_id in this.content.skeletons) this.content.skeletons[old_skeleton_id].updateSkeletonColor(options); } if (new_skeleton_id && new_skeleton_id in this.content.skeletons) this.content.skeletons[new_skeleton_id].updateSkeletonColor(options); } }; WebGLApplication.prototype.Space.prototype.TextGeometryCache = function() { this.geometryCache = {}; this.getTagGeometry = function(tagString) { if (tagString in this.geometryCache) { var e = this.geometryCache[tagString]; e.refs += 1; return e.geometry; } // Else create, store, and return a new one: var text3d = new THREE.TextGeometry( tagString, { size: 100, height: 20, curveSegments: 1, font: "helvetiker" }); text3d.computeBoundingBox(); text3d.tagString = tagString; this.geometryCache[tagString] = {geometry: text3d, refs: 1}; return text3d; }; this.releaseTagGeometry = function(tagString) { if (tagString in this.geometryCache) { var e = this.geometryCache[tagString]; e.refs -= 1; if (0 === e.refs) { delete this.geometryCache[tagString].geometry; delete this.geometryCache[tagString]; } } }; this.createTextMesh = function(tagString, material) { var text = new THREE.Mesh(this.getTagGeometry(tagString), material); text.visible = true; return text; }; this.destroy = function() { Object.keys(this.geometryCache).forEach(function(entry) { entry.geometry.dispose(); }); delete this.geometryCache; }; }; WebGLApplication.prototype.Space.prototype.StaticContent = function(dimensions, stack, center) { // Space elements this.box = this.createBoundingBox(center, stack.dimension, stack.resolution); this.floor = this.createFloor(center, dimensions); this.zplane = null; this.missing_sections = []; // Shared across skeletons this.labelspheregeometry = new THREE.OctahedronGeometry( 130, 3); this.radiusSphere = new THREE.OctahedronGeometry( 40, 3); this.icoSphere = new THREE.IcosahedronGeometry(1, 2); this.cylinder = new THREE.CylinderGeometry(1, 1, 1, 10, 1, false); this.textMaterial = new THREE.MeshNormalMaterial( { color: 0xffffff, overdraw: true } ); // Mesh materials for spheres on nodes tagged with 'uncertain end', 'undertain continuation' or 'TODO' this.labelColors = {uncertain: new THREE.MeshBasicMaterial({color: 0xff8000, opacity:0.6, transparent: true}), todo: new THREE.MeshBasicMaterial({color: 0xff0000, opacity:0.6, transparent: true})}; this.textGeometryCache = new WebGLApplication.prototype.Space.prototype.TextGeometryCache(); this.synapticColors = [new THREE.MeshBasicMaterial( { color: 0xff0000, opacity:0.6, transparent:false } ), new THREE.MeshBasicMaterial( { color: 0x00f6ff, opacity:0.6, transparent:false } )]; this.connectorLineColors = {'presynaptic_to': new THREE.LineBasicMaterial({color: 0xff0000, opacity: 1.0, linewidth: 6}), 'postsynaptic_to': new THREE.LineBasicMaterial({color: 0x00f6ff, opacity: 1.0, linewidth: 6})}; }; WebGLApplication.prototype.Space.prototype.StaticContent.prototype = {}; WebGLApplication.prototype.Space.prototype.StaticContent.prototype.dispose = function() { // dispose ornaments this.box.geometry.dispose(); this.box.material.dispose(); this.floor.geometry.dispose(); this.floor.material.dispose(); this.missing_sections.forEach(function(s) { s.geometry.dispose(); s.material.dispose(); // it is ok to call more than once }); if (this.zplane) { this.zplane.geometry.dispose(); this.zplane.material.dispose(); } // dispose shared geometries [this.labelspheregeometry, this.radiusSphere, this.icoSphere, this.cylinder].forEach(function(g) { g.dispose(); }); this.textGeometryCache.destroy(); // dispose shared materials this.textMaterial.dispose(); this.labelColors.uncertain.dispose(); this.labelColors.todo.dispose(); this.synapticColors[0].dispose(); this.synapticColors[1].dispose(); }; WebGLApplication.prototype.Space.prototype.StaticContent.prototype.createBoundingBox = function(center, dimension, resolution) { var w2 = (dimension.x * resolution.x) / 2; var h2 = (dimension.y * resolution.y) / 2; var d2 = (dimension.z * resolution.z) / 2; var geometry = new THREE.Geometry(); geometry.vertices.push( new THREE.Vector3(-w2, -h2, -d2), new THREE.Vector3(-w2, h2, -d2), new THREE.Vector3(-w2, h2, -d2), new THREE.Vector3( w2, h2, -d2), new THREE.Vector3( w2, h2, -d2), new THREE.Vector3( w2, -h2, -d2), new THREE.Vector3( w2, -h2, -d2), new THREE.Vector3(-w2, -h2, -d2), new THREE.Vector3(-w2, -h2, d2), new THREE.Vector3(-w2, h2, d2), new THREE.Vector3(-w2, h2, d2), new THREE.Vector3( w2, h2, d2), new THREE.Vector3( w2, h2, d2), new THREE.Vector3( w2, -h2, d2), new THREE.Vector3( w2, -h2, d2), new THREE.Vector3(-w2, -h2, d2), new THREE.Vector3(-w2, -h2, -d2), new THREE.Vector3(-w2, -h2, d2), new THREE.Vector3(-w2, h2, -d2), new THREE.Vector3(-w2, h2, d2), new THREE.Vector3( w2, h2, -d2), new THREE.Vector3( w2, h2, d2), new THREE.Vector3( w2, -h2, -d2), new THREE.Vector3( w2, -h2, d2) ); geometry.computeLineDistances(); var material = new THREE.LineBasicMaterial( { color: 0xff0000 } ); var mesh = new THREE.Line( geometry, material, THREE.LinePieces ); mesh.position.set(center.x, center.y, center.z); return mesh; }; /** * Creates a THREE.js line object that represents a floor grid. By default, it * extents around the bounding box by about twice the height of it. The grid * cells are placed so that they are divide the bouning box floor evenly. By * default, there are ten cells in each dimension within the bounding box. It is * positioned around the center of the dimensions. These settings can be * overridden with the options parameter. */ WebGLApplication.prototype.Space.prototype.StaticContent.prototype.createFloor = function(center, dimensions, options) { var o = options || {}; var floor = o['floor'] || 0.0; // 10 steps in each dimension of the bounding box var nBaseLines = o['nBaseLines'] || 10.0; var xStep = dimensions.x / nBaseLines; var zStep = dimensions.z / nBaseLines; // Extend this around the bounding box var xExtent = o['xExtent'] || Math.ceil(2.0 * dimensions.y / xStep); var zExtent = o['zExtent'] || Math.ceil(2.0 * dimensions.y / zStep); // Offset from origin var xOffset = dimensions.x * 0.5 - center.x; var zOffset = dimensions.z * 0.5 + center.z; // Get min and max coordinates of grid var min_x = -1.0 * xExtent * xStep + xOffset, max_x = dimensions.x + (xExtent * xStep) + xOffset; var min_z = -1.0 * dimensions.z - zExtent * zStep + zOffset, max_z = zExtent * zStep + zOffset; // Create planar mesh for floor var xLines = nBaseLines + 2 * xExtent; var zLines = nBaseLines + 2 * zExtent; var width = max_x - min_x; var height = max_z - min_z; var plane = new THREE.PlaneGeometry(width, height, xLines, zLines); var material = new THREE.MeshBasicMaterial({ color: o['color'] || 0x535353, wireframe: true, side: THREE.DoubleSide, transparent: true }); var mesh = new THREE.Mesh(plane, material); // Center the mesh and rotate it to be XZ parallel mesh.position.set(min_x + 0.5 * width, floor, min_z + 0.5 * height); mesh.rotation.x = Math.PI * 0.5; return mesh; }; /** Adjust visibility of static content according to the persistent options. */ WebGLApplication.prototype.Space.prototype.StaticContent.prototype.adjust = function(options, space) { if (options.show_missing_sections) { if (0 === this.missing_sections.length) { this.missing_sections = this.createMissingSections(space, options.missing_section_height); this.missing_sections.forEach(space.scene.add, space.scene); } } else { this.missing_sections.forEach(space.scene.remove, space.scene); this.missing_sections = []; } if (options.show_background) { space.view.renderer.setClearColor(0x000000, 1); } else { space.view.renderer.setClearColor(0xffffff, 1); } this.floor.visible = options.show_floor; this.box.visible = options.show_box; if (this.zplane) space.scene.remove(this.zplane); if (options.show_zplane) { this.zplane = this.createZPlane(space.stack); this.updateZPlanePosition(space.stack); space.scene.add(this.zplane); } else { this.zplane = null; } }; WebGLApplication.prototype.Space.prototype.StaticContent.prototype.createZPlane = function(stack) { var geometry = new THREE.Geometry(), xwidth = stack.dimension.x * stack.resolution.x, ywidth = stack.dimension.y * stack.resolution.y, material = new THREE.MeshBasicMaterial( { color: 0x151349, side: THREE.DoubleSide } ); geometry.vertices.push( new THREE.Vector3( 0,0,0 ) ); geometry.vertices.push( new THREE.Vector3( xwidth,0,0 ) ); geometry.vertices.push( new THREE.Vector3( 0,ywidth,0 ) ); geometry.vertices.push( new THREE.Vector3( xwidth,ywidth,0 ) ); geometry.faces.push( new THREE.Face4( 0, 1, 3, 2 ) ); return new THREE.Mesh( geometry, material ); }; WebGLApplication.prototype.Space.prototype.StaticContent.prototype.updateZPlanePosition = function(stack) { if (this.zplane) { this.zplane.position.z = (-stack.z * stack.resolution.z - stack.translation.z); } }; /** Returns an array of meshes representing the missing sections. */ WebGLApplication.prototype.Space.prototype.StaticContent.prototype.createMissingSections = function(space, missing_section_height) { var d = space.stack.dimension, r = space.stack.resolution, t = space.stack.translation, geometry = new THREE.Geometry(), xwidth = d.x * r.x, ywidth = d.y * r.y * missing_section_height / 100.0, materials = [new THREE.MeshBasicMaterial( { color: 0x151349, opacity:0.6, transparent: true, side: THREE.DoubleSide } ), new THREE.MeshBasicMaterial( { color: 0x00ffff, wireframe: true, wireframeLinewidth: 5, side: THREE.DoubleSide } )]; geometry.vertices.push( new THREE.Vector3( 0,0,0 ) ); geometry.vertices.push( new THREE.Vector3( xwidth,0,0 ) ); geometry.vertices.push( new THREE.Vector3( 0,ywidth,0 ) ); geometry.vertices.push( new THREE.Vector3( xwidth,ywidth,0 ) ); geometry.faces.push( new THREE.Face4( 0, 1, 3, 2 ) ); return space.stack.broken_slices.reduce(function(missing_sections, sliceZ) { var z = -sliceZ * r.z - t.z; return missing_sections.concat(materials.map(function(material) { var mesh = new THREE.Mesh(geometry, material); mesh.position.z = z; return mesh; })); }, []); }; WebGLApplication.prototype.Space.prototype.Content = function() { // Scene content this.active_node = new this.ActiveNode(); this.meshes = []; this.skeletons = {}; }; WebGLApplication.prototype.Space.prototype.Content.prototype = {}; WebGLApplication.prototype.Space.prototype.Content.prototype.dispose = function() { this.active_node.mesh.geometry.dispose(); this.active_node.mesh.material.dispose(); this.meshes.forEach(function(mesh) { mesh.geometry.dispose(); mesh.material.dispose(); }); }; WebGLApplication.prototype.Space.prototype.Content.prototype.loadMeshes = function(space, submit, material) { submit(django_url + project.id + "/stack/" + space.stack.id + "/models", {}, function (models) { var ids = Object.keys(models); if (0 === ids.length) return; var loader = space.content.newJSONLoader(); ids.forEach(function(id) { var vs = models[id].vertices; for (var i=0; i < vs.length; i+=3) { space.coordsToUnscaledSpace2(vs, i); } var geometry = loader.parse(models[id]).geometry; var mesh = space.content.newMesh(geometry, material); mesh.position.set(0, 0, 0); mesh.rotation.set(0, 0, 0); space.content.meshes.push(mesh); space.add(mesh); }); space.render(); }); }; WebGLApplication.prototype.Space.prototype.Content.prototype.newMesh = function(geometry, material) { return new THREE.Mesh(geometry, material); }; WebGLApplication.prototype.Space.prototype.Content.prototype.newJSONLoader = function() { return new THREE.JSONLoader(true); }; /** Adjust content according to the persistent options. */ WebGLApplication.prototype.Space.prototype.Content.prototype.adjust = function(options, space, submit, changed_bandwidth, changed_line_width) { if (options.show_meshes) { if (0 === this.meshes.length) { this.loadMeshes(space, submit, options.createMeshMaterial()); } } else { this.meshes.forEach(space.scene.remove, space.scene); this.meshes = []; } this.active_node.setVisible(options.show_active_node); if (changed_bandwidth && 'synapse-clustering' === options.connector_color) { space.updateConnectorColors(options, Object.keys(this.skeletons).map(function(skid) { return this.skeletons[skid]; }, this)); } if (changed_line_width) { Object.keys(this.skeletons).forEach(function(skid) { this.skeletons[skid].changeSkeletonLineWidth(options.skeleton_line_width); }, this); } }; WebGLApplication.prototype.Space.prototype.View = function(space) { this.space = space; this.init(); // Initial view this.XY(); }; WebGLApplication.prototype.Space.prototype.View.prototype = {}; WebGLApplication.prototype.Space.prototype.View.prototype.init = function() { /* Create a camera which generates a picture fitting in our canvas. The * frustum's far culling plane is three times the longest size of the * displayed space. The near plan starts at one. */ var d = this.space.dimensions; var fov = 75; var near = 1; var far = 3 * Math.max(d.x, Math.max(d.y, d.z)); var orthoNear = 1; var orthoFar = far; this.camera = new THREE.CombinedCamera(-this.space.canvasWidth, -this.space.canvasHeight, fov, near, far, orthoNear, orthoFar); this.camera.frustumCulled = false; this.projector = new THREE.Projector(); this.renderer = this.createRenderer('webgl'); this.controls = this.createControls(); this.space.container.appendChild(this.renderer.domElement); this.mouse = {position: new THREE.Vector2(), is_mouse_down: false}; this.mouseControls = new this.MouseControls(); this.mouseControls.attach(this, this.renderer.domElement); // Add handlers for WebGL context lost and restore events this.renderer.context.canvas.addEventListener('webglcontextlost', function(e) { e.preventDefault(); // Notify user about reload error("Due to limited system resources the 3D display can't be shown " + "right now. Please try and restart the widget containing the 3D " + "viewer."); }, false); this.renderer.context.canvas.addEventListener('webglcontextrestored', (function(e) { // TODO: Calling init() isn't enough, but one can manually restart // the widget. }).bind(this), false); }; /** * Crate and setup a WebGL or SVG renderer. */ WebGLApplication.prototype.Space.prototype.View.prototype.createRenderer = function(type) { var renderer = null; if ('webgl' === type) { renderer = new THREE.WebGLRenderer({ antialias: true }); } else if ('svg' === type) { renderer = new THREE.SVGRenderer(); } else { error("Unknon renderer type: " + type); return null; } renderer.sortObjects = false; renderer.setSize( this.space.canvasWidth, this.space.canvasHeight ); return renderer; }; WebGLApplication.prototype.Space.prototype.View.prototype.destroy = function() { this.controls.removeListeners(); this.mouseControls.detach(this.renderer.domElement); this.space.container.removeChild(this.renderer.domElement); Object.keys(this).forEach(function(key) { delete this[key]; }, this); }; WebGLApplication.prototype.Space.prototype.View.prototype.createControls = function() { var controls = new THREE.TrackballControls( this.camera, this.space.container ); controls.rotateSpeed = 1.0; controls.zoomSpeed = 3.2; controls.panSpeed = 1.5; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.target = this.space.center.clone(); return controls; }; WebGLApplication.prototype.Space.prototype.View.prototype.render = function() { this.controls.update(); if (this.renderer) { this.renderer.clear(); this.renderer.render(this.space.scene, this.camera); } }; /** * Get the toDataURL() image data of the renderer in PNG format. */ WebGLApplication.prototype.Space.prototype.View.prototype.getImageData = function() { return this.renderer.domElement.toDataURL("image/png"); }; /** * Return SVG data of the rendered image. */ WebGLApplication.prototype.Space.prototype.View.prototype.getSVGData = function() { var svgRenderer = this.createRenderer('svg'); svgRenderer.clear(); svgRenderer.render(this.space.scene, this.camera); return svgRenderer.domElement; }; /** * Set camera position so that the whole XY side of the bounding box facing +Z * can just be seen. */ WebGLApplication.prototype.Space.prototype.View.prototype.XY = function() { var center = this.space.center, dimensions = this.space.dimensions, vFOV = this.camera.fov * Math.PI / 180, bbDistance; if (this.height > this.width) { var hFOV = 2 * Math.atan( Math.tan( vFOV * 0.5 ) * this.width / this.height ); bbDistance = dimensions.x * 0.5 / Math.tan(hFOV * 0.5); } else { bbDistance = dimensions.y * 0.5 / Math.tan(vFOV * 0.5); } this.controls.target = center; this.camera.position.x = center.x; this.camera.position.y = center.y; this.camera.position.z = center.z + (dimensions.z / 2) + bbDistance; this.camera.up.set(0, 1, 0); }; /** * Set camera position so that the whole XZ side of the bounding box facing +Y * can just be seen. */ WebGLApplication.prototype.Space.prototype.View.prototype.XZ = function() { var center = this.space.center, dimensions = this.space.dimensions, vFOV = this.camera.fov * Math.PI / 180, bbDistance; if (this.height > this.width) { var hFOV = 2 * Math.atan( Math.tan( vFOV * 0.5 ) * this.width / this.height ); bbDistance = dimensions.x * 0.5 / Math.tan(hFOV * 0.5); } else { bbDistance = dimensions.z * 0.5 / Math.tan(vFOV * 0.5); } this.controls.target = center; this.camera.position.x = center.x; this.camera.position.y = center.y + (dimensions.y / 2) + bbDistance; this.camera.position.z = center.z; this.camera.up.set(0, 0, 1); }; /** * Set camera position so that the whole ZY side of the bounding box facing +X * can just be seen. */ WebGLApplication.prototype.Space.prototype.View.prototype.ZY = function() { var center = this.space.center, dimensions = this.space.dimensions, vFOV = this.camera.fov * Math.PI / 180, bbDistance; if (this.height > this.width) { var hFOV = 2 * Math.atan( Math.tan( vFOV * 0.5 ) * this.width / this.height ); bbDistance = dimensions.z * 0.5 / Math.tan(hFOV * 0.5); } else { bbDistance = dimensions.y * 0.5 / Math.tan(vFOV * 0.5); } this.controls.target = center; this.camera.position.x = center.x + (dimensions.x / 2) + bbDistance; this.camera.position.y = center.y; this.camera.position.z = center.z; this.camera.up.set(0, 1, 0); }; /** * Set camera position so that the whole ZX side of the bounding box facing +Y * can just be seen. */ WebGLApplication.prototype.Space.prototype.View.prototype.ZX = function() { var center = this.space.center, dimensions = this.space.dimensions, vFOV = this.camera.fov * Math.PI / 180, bbDistance; if (this.height > this.width) { var hFOV = 2 * Math.atan( Math.tan( vFOV * 0.5 ) * this.width / this.height ); bbDistance = dimensions.z * 0.5 / Math.tan(hFOV * 0.5); } else { bbDistance = dimensions.x * 0.5 / Math.tan(vFOV * 0.5); } this.controls.target = center; this.camera.position.x = center.x; this.camera.position.y = center.y + (dimensions.y / 2) + bbDistance; this.camera.position.z = center.z; this.camera.up.set(-1, 0, 0); }; /** Construct mouse controls as objects, so that no context is retained. */ WebGLApplication.prototype.Space.prototype.View.prototype.MouseControls = function() { this.attach = function(view, domElement) { domElement.CATMAID_view = view; domElement.addEventListener('mousewheel', this.MouseWheel, false); domElement.addEventListener('mousemove', this.MouseMove, false); domElement.addEventListener('mouseup', this.MouseUp, false); domElement.addEventListener('mousedown', this.MouseDown, false); }; this.detach = function(domElement) { domElement.CATMAID_view = null; delete domElement.CATMAID_view; domElement.removeEventListener('mousewheel', this.MouseWheel, false); domElement.removeEventListener('mousemove', this.MouseMove, false); domElement.removeEventListener('mouseup', this.MouseUp, false); domElement.removeEventListener('mousedown', this.MouseDown, false); Object.keys(this).forEach(function(key) { delete this[key]; }, this); }; this.MouseWheel = function(ev) { this.CATMAID_view.space.render(); }; this.MouseMove = function(ev) { var mouse = this.CATMAID_view.mouse, space = this.CATMAID_view.space; mouse.position.x = ( ev.offsetX / space.canvasWidth ) * 2 -1; mouse.position.y = -( ev.offsetY / space.canvasHeight ) * 2 +1; if (mouse.is_mouse_down) { space.render(); } space.container.style.cursor = 'pointer'; }; this.MouseUp = function(ev) { var mouse = this.CATMAID_view.mouse, controls = this.CATMAID_view.controls, space = this.CATMAID_view.space; mouse.is_mouse_down = false; controls.enabled = true; space.render(); // May need another render on occasions }; this.MouseDown = function(ev) { var mouse = this.CATMAID_view.mouse, space = this.CATMAID_view.space, camera = this.CATMAID_view.camera, projector = this.CATMAID_view.projector; mouse.is_mouse_down = true; if (!ev.shiftKey) return; // Find object under the mouse var vector = new THREE.Vector3(mouse.position.x, mouse.position.y, 0.5); projector.unprojectVector(vector, camera); var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); // Attempt to intersect visible skeleton spheres, stopping at the first found var fields = ['specialTagSpheres', 'synapticSpheres', 'radiusVolumes']; var skeletons = space.content.skeletons; if (Object.keys(skeletons).some(function(skeleton_id) { var skeleton = skeletons[skeleton_id]; if (!skeleton.visible) return false; var all_spheres = fields.map(function(field) { return skeleton[field]; }) .reduce(function(a, spheres) { return Object.keys(spheres).reduce(function(a, id) { a.push(spheres[id]); return a; }, a); }, []); var intersects = raycaster.intersectObjects(all_spheres, true); if (intersects.length > 0) { return all_spheres.some(function(sphere) { if (sphere.id !== intersects[0].object.id) return false; SkeletonAnnotations.staticMoveToAndSelectNode(sphere.node_id); return true; }); } return false; })) { return; } growlAlert("Oops", "Couldn't find any intersectable object under the mouse."); }; }; WebGLApplication.prototype.Space.prototype.Content.prototype.ActiveNode = function() { this.skeleton_id = null; this.mesh = new THREE.Mesh( new THREE.IcosahedronGeometry(1, 2), new THREE.MeshBasicMaterial( { color: 0x00ff00, opacity:0.8, transparent:true } ) ); this.mesh.scale.x = this.mesh.scale.y = this.mesh.scale.z = 160; }; WebGLApplication.prototype.Space.prototype.Content.prototype.ActiveNode.prototype = {}; WebGLApplication.prototype.Space.prototype.Content.prototype.ActiveNode.prototype.setVisible = function(visible) { this.mesh.visible = visible ? true : false; }; WebGLApplication.prototype.Space.prototype.Content.prototype.ActiveNode.prototype.updatePosition = function(space, options) { var pos = SkeletonAnnotations.getActiveNodePosition(); if (!pos) { space.updateSplitShading(this.skeleton_id, null, options); this.skeleton_id = null; return; } var skeleton_id = SkeletonAnnotations.getActiveSkeletonId(); space.updateSplitShading(this.skeleton_id, skeleton_id, options); this.skeleton_id = skeleton_id; // Get world coordinates of active node var c = new THREE.Vector3(pos.x, pos.y, pos.z); space.toSpace(c); this.mesh.position.set(c.x, c.y, c.z); }; WebGLApplication.prototype.Space.prototype.updateSkeleton = function(skeletonmodel, json, options) { if (!this.content.skeletons.hasOwnProperty(skeletonmodel.id)) { this.content.skeletons[skeletonmodel.id] = new this.Skeleton(this, skeletonmodel); } this.content.skeletons[skeletonmodel.id].reinit_actor(skeletonmodel, json, options); return this.content.skeletons[skeletonmodel.id]; }; /** An object to represent a skeleton in the WebGL space. * The skeleton consists of three geometries: * (1) one for the edges between nodes, represented as a list of contiguous pairs of points; * (2) one for the edges representing presynaptic relations to connectors; * (3) one for the edges representing postsynaptic relations to connectors. * Each geometry has its own mesh material and can be switched independently. * In addition, each skeleton node with a pre- or postsynaptic relation to a connector * gets a clickable sphere to represent it. * Nodes with an 'uncertain' or 'todo' in their text tags also get a sphere. * * When visualizing only the connectors among the skeletons visible in the WebGL space, the geometries of the pre- and postsynaptic edges are hidden away, and a new pair of geometries are created to represent just the edges that converge onto connectors also related to by the other skeletons. * */ WebGLApplication.prototype.Space.prototype.Skeleton = function(space, skeletonmodel) { // TODO id, baseName, actorColor are all redundant with the skeletonmodel this.space = space; this.id = skeletonmodel.id; this.baseName = skeletonmodel.baseName; this.synapticColors = space.staticContent.synapticColors; this.skeletonmodel = skeletonmodel; this.opacity = skeletonmodel.opacity; // This is an index mapping treenode IDs to lists of reviewers. Attaching them // directly to the nodes is too much of a performance hit. // Gets loaded dynamically, and erased when refreshing (because a new Skeleton is instantiated with the same model). this.reviews = null; // A map of nodeID vs true for nodes that belong to the axon, as computed by splitByFlowCentrality. Loaded dynamically, and erased when refreshing like this.reviews. this.axon = null; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype = {}; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.CTYPES = ['neurite', 'presynaptic_to', 'postsynaptic_to']; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.synapticTypes = ['presynaptic_to', 'postsynaptic_to']; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.initialize_objects = function(options) { this.visible = true; if (undefined === this.skeletonmodel) { console.log('Can not initialize skeleton object'); return; } this.actorColor = this.skeletonmodel.color.clone(); var CTYPES = this.CTYPES; this.line_material = new THREE.LineBasicMaterial({color: 0xffff00, opacity: 1.0, linewidth: options.skeleton_line_width}); this.geometry = {}; this.geometry[CTYPES[0]] = new THREE.Geometry(); this.geometry[CTYPES[1]] = new THREE.Geometry(); this.geometry[CTYPES[2]] = new THREE.Geometry(); this.actor = {}; // has three keys (the CTYPES), each key contains the edges of each type this.actor[CTYPES[0]] = new THREE.Line(this.geometry[CTYPES[0]], this.line_material, THREE.LinePieces); this.actor[CTYPES[1]] = new THREE.Line(this.geometry[CTYPES[1]], this.space.staticContent.connectorLineColors[CTYPES[1]], THREE.LinePieces); this.actor[CTYPES[2]] = new THREE.Line(this.geometry[CTYPES[2]], this.space.staticContent.connectorLineColors[CTYPES[2]], THREE.LinePieces); this.specialTagSpheres = {}; this.synapticSpheres = {}; this.radiusVolumes = {}; // contains spheres and cylinders this.textlabels = {}; // Used only with restricted connectors this.connectoractor = {}; this.connectorgeometry = {}; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.destroy = function() { this.removeActorFromScene(); [this.actor, this.geometry, this.connectorgeometry, this.connectoractor, this.specialTagSpheres, this.synapticSpheres, this.radiusVolumes, this.textlabels].forEach(function(ob) { if (ob) { for (var key in ob) { if (ob.hasOwnProperty(key)) delete ob[key]; } } }); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.removeActorFromScene = function() { // Dispose of both geometry and material, unique to this Skeleton this.actor[this.CTYPES[0]].geometry.dispose(); this.actor[this.CTYPES[0]].material.dispose(); // Dispose only of the geometries. Materials for connectors are shared this.actor[this.CTYPES[1]].geometry.dispose(); this.actor[this.CTYPES[2]].geometry.dispose(); [this.actor, this.synapticSpheres, this.radiusVolumes, this.specialTagSpheres].forEach(function(ob) { if (ob) { for (var key in ob) { if (ob.hasOwnProperty(key)) this.space.remove(ob[key]); } } }, this); this.remove_connector_selection(); this.removeTextMeshes(); }; /** Set the visibility of the skeleton, radius spheres and label spheres. Does not set the visibility of the synaptic spheres or edges. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setActorVisibility = function(vis) { this.visible = vis; this.visibilityCompositeActor('neurite', vis); // radiusVolumes: the spheres where nodes have a radius larger than zero // specialTagSpheres: the spheres at special tags like 'TODO', 'Uncertain end', etc. [this.radiusVolumes, this.specialTagSpheres].forEach(function(ob) { for (var idx in ob) { if (ob.hasOwnProperty(idx)) ob[idx].visible = vis; } }); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setSynapticVisibilityFn = function(type) { return function(vis) { this.visibilityCompositeActor(type, vis); for (var idx in this.synapticSpheres) { if (this.synapticSpheres.hasOwnProperty(idx) && this.synapticSpheres[idx].type === type) { this.synapticSpheres[idx].visible = vis; } } }; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setPreVisibility = WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setSynapticVisibilityFn('presynaptic_to'); WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setPostVisibility = WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setSynapticVisibilityFn('postsynaptic_to'); WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createTextMeshes = function() { // Sort out tags by node: some nodes may have more than one var nodeIDTags = {}; for (var tag in this.tags) { if (this.tags.hasOwnProperty(tag)) { this.tags[tag].forEach(function(nodeID) { if (nodeIDTags.hasOwnProperty(nodeID)) { nodeIDTags[nodeID].push(tag); } else { nodeIDTags[nodeID] = [tag]; } }); } } // Sort and convert to string the array of tags of each node for (var nodeID in nodeIDTags) { if (nodeIDTags.hasOwnProperty(nodeID)) { nodeIDTags[nodeID] = nodeIDTags[nodeID].sort().join(); } } // Group nodes by common tag string var tagNodes = {}; for (var nodeID in nodeIDTags) { if (nodeIDTags.hasOwnProperty(nodeID)) { var tagString = nodeIDTags[nodeID]; if (tagNodes.hasOwnProperty(tagString)) { tagNodes[tagString].push(nodeID); } else { tagNodes[tagString] = [nodeID]; } } } // Find Vector3 of tagged nodes var vs = this.geometry['neurite'].vertices.reduce(function(o, v) { if (v.node_id in nodeIDTags) o[v.node_id] = v; return o; }, {}); // Create meshes for the tags for all nodes that need them, reusing the geometries var cache = this.space.staticContent.textGeometryCache, textMaterial = this.space.staticContent.textMaterial; for (var tagString in tagNodes) { if (tagNodes.hasOwnProperty(tagString)) { tagNodes[tagString].forEach(function(nodeID) { var text = cache.createTextMesh(tagString, textMaterial); var v = vs[nodeID]; text.position.x = v.x; text.position.y = v.y; text.position.z = v.z; this.textlabels[nodeID] = text; this.space.add(text); }, this); } } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.removeTextMeshes = function() { var cache = this.space.staticContent.textGeometryCache; for (var k in this.textlabels) { if (this.textlabels.hasOwnProperty(k)) { this.space.remove(this.textlabels[k]); cache.releaseTagGeometry(this.textlabels[k].tagString); delete this.textlabels[k]; } } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.setTextVisibility = function( vis ) { // Create text meshes if not there, or destroy them if to be hidden if (vis && 0 === Object.keys(this.textlabels).length) { this.createTextMeshes(); } else if (!vis) { this.removeTextMeshes(); } }; /* Unused WebGLApplication.prototype.Space.prototype.Skeleton.prototype.translate = function( dx, dy, dz ) { for ( var i=0; i<CTYPES.length; ++i ) { if( dx ) { this.actor[CTYPES[i]].translateX( dx ); } if( dy ) { this.actor[CTYPES[i]].translateY( dy ); } if( dz ) { this.actor[CTYPES[i]].translateZ( dz ); } } }; */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createSynapseClustering = function(bandwidth) { var locations = this.geometry['neurite'].vertices.reduce(function(vs, v) { vs[v.node_id] = v.clone(); return vs; }, {}); return new SynapseClustering(this.createArbor(), locations, this.createSynapseCounts(), bandwidth); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createSynapseCounts = function() { return this.synapticTypes.reduce((function(o, type, k) { var vs = this.geometry[type].vertices; for (var i=0, l=vs.length; i<l; i+=2) { var treenode_id = vs[i+1].node_id, count = o[treenode_id]; if (count) o[treenode_id] = count + 1; else o[treenode_id] = 1; } return o; }).bind(this), {}); }; /** Return a map with 4 elements: * {presynaptic_to: {}, // map of node ID vs count of presynaptic sites * postsynaptic_to: {}, // map of node ID vs count of postsynaptic sites * presynaptic_to_count: N, * postsynaptic_to_count: M} */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createPrePostCounts = function() { return this.synapticTypes.reduce((function(o, type, k) { var vs = this.geometry[type].vertices, syn = {}; for (var i=0, l=vs.length; i<l; i+=2) { var treenode_id = vs[i+1].node_id, count = syn[treenode_id]; if (count) syn[treenode_id] = count + 1; else syn[treenode_id] = 1; } o[type] = syn; o[type + "_count"] = vs.length / 2; return o; }).bind(this), {}); }; /** Returns a map of treenode ID keys and lists of {type, connectorID} as values, * where type 0 is presynaptic and type 1 is postsynaptic. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createSynapseMap = function() { return this.synapticTypes.reduce((function(o, type, k) { var vs = this.geometry[type].vertices; for (var i=0, l=vs.length; i<l; i+=2) { var connector_id = vs[i].node_id, treenode_id = vs[i+1].node_id, list = o[treenode_id], synapse = {type: k, connector_id: connector_id}; if (list) list.push(synapse); else o[treenode_id] = [synapse]; } return o; }).bind(this), {}); }; /** Returns a map of connector ID keys and a list of treenode ID values. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createInverseSynapseMap = function() { return this.synapticTypes.reduce((function(o, type) { var vs = this.geometry[type].vertices; for (var i=0, l=vs.length; i<l; i+=2) { var connector_id = vs[i].node_id, treenode_id = vs[i+1].node_id, list = o[connector_id]; if (list) { list.push(connector_id); } else { o[connector_id] = [treenode_id]; } } return o; }).bind(this), {}); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createArbor = function() { return new Arbor().addEdges(this.geometry['neurite'].vertices, function(v) { return v.node_id; }); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.getPositions = function() { var vs = this.geometry['neurite'].vertices, p = {}; for (var i=0; i<vs.length; ++i) { var v = vs[i]; p[v.node_id] = v; } return p; }; /** Determine the nodes that belong to the axon by computing the centrifugal flow * centrality. * Takes as argument the json of compact-arbor, but uses only index 1: the inputs and outputs, parseable by the ArborParser.synapse function. * If only one node has the soma tag and it is not the root, will reroot at it. * Returns a map of node ID vs true for nodes that belong to the axon. * When the flowCentrality cannot be computed, returns null. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.splitByFlowCentrality = function(json) { var arbor = this.createArbor(); if (this.tags && this.tags['soma'] && 1 === this.tags['soma'].length) { var soma = this.tags['soma'][0]; if (arbor.root != soma) arbor.reroot(soma); } var ap = new ArborParser(); ap.arbor = arbor; ap.synapses(json[1]); var axon = SynapseClustering.prototype.findAxon(ap, 0.9, this.getPositions()); return axon ? axon.nodes() : null; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.updateSkeletonColor = function(options) { var node_weights, arbor; if ('none' === options.shading_method) { node_weights = null; } else { arbor = this.createArbor(); if (-1 !== options.shading_method.lastIndexOf('centrality')) { // Darken the skeleton based on the betweenness calculation. var c; if (0 === options.shading_method.indexOf('betweenness')) { c = arbor.betweennessCentrality(true); } else if (0 === options.shading_method.indexOf('slab')) { c = arbor.slabCentrality(true); // branch centrality } else { // Flow centrality var io = this.createPrePostCounts(); if (0 === io.postsynaptic_to_count || 0 === io.presynaptic_to_count) { growlAlert('WARNING', 'Neuron "' + this.skeletonmodel.baseName + '" lacks input or output synapses.'); c = arbor.nodesArray().reduce(function(o, node) { // All the same o[node] = 1; return o; }, {}); } else { var key = 'sum'; if (0 === options.shading_method.indexOf('centrifugal')) { key = 'centrifugal'; } else if (0 === options.shading_method.indexOf('centripetal')) { key = 'centripetal'; } var fc = arbor.flowCentrality(io.presynaptic_to, io.postsynaptic_to, io.presynaptic_to_count, io.postsynaptic_to_count), c = {}, nodes = Object.keys(fc); for (var i=0; i<nodes.length; ++i) { var node = nodes[i]; c[node] = fc[node][key]; } } } var node_ids = Object.keys(c), max = node_ids.reduce(function(a, node_id) { return Math.max(a, c[node_id]); }, 0); // Normalize c in place node_ids.forEach(function(node_id) { c[node_id] = c[node_id] / max; }); node_weights = c; } else if ('distance_to_root' === options.shading_method) { var locations = this.geometry['neurite'].vertices.reduce(function(vs, v) { vs[v.node_id] = v; return vs; }, {}); var distanceFn = (function(child, paren) { return this[child].distanceTo(this[paren]); }).bind(locations); var dr = arbor.nodesDistanceTo(arbor.root, distanceFn), distances = dr.distances, max = dr.max; // Normalize by max in place Object.keys(distances).forEach(function(node) { distances[node] = 1 - (distances[node] / max); }); node_weights = distances; } else if ('downstream_amount' === options.shading_method) { var locations = this.geometry['neurite'].vertices.reduce(function(vs, v) { vs[v.node_id] = v; return vs; }, {}); var distanceFn = (function(paren, child) { return this[child].distanceTo(this[paren]); }).bind(locations); node_weights = arbor.downstreamAmount(distanceFn, true); } else if ('active_node_split' === options.shading_method) { var atn = SkeletonAnnotations.getActiveNodeId(); if (arbor.contains(atn)) { node_weights = {}; var sub = arbor.subArbor(atn), up = 1, down = 0.5; if (options.invert_shading) { up = 0.5; down = 0; } arbor.nodesArray().forEach(function(node) { node_weights[node] = sub.contains(node) ? down : up; }); } else { // Don't shade any node_weights = {}; } } else if ('partitions' === options.shading_method) { // Shade by euclidian length, relative to the longest branch var locations = this.geometry['neurite'].vertices.reduce(function(vs, v) { vs[v.node_id] = v; return vs; }, {}); var partitions = arbor.partitionSorted(); node_weights = partitions.reduce(function(o, seq, i) { var loc1 = locations[seq[0]], loc2, plen = 0; for (var i=1, len=seq.length; i<len; ++i) { loc2 = locations[seq[i]]; plen += loc1.distanceTo(loc2); loc1 = loc2; } return seq.reduce(function(o, node) { o[node] = plen; return o; }, o); }, {}); // Normalize by the length of the longest partition, which ends at root var max_length = node_weights[arbor.root]; Object.keys(node_weights).forEach(function(node) { node_weights[node] /= max_length; }); } else if (-1 !== options.shading_method.indexOf('strahler')) { node_weights = arbor.strahlerAnalysis(); var max = node_weights[arbor.root]; Object.keys(node_weights).forEach(function(node) { node_weights[node] /= max; }); } } if (options.invert_shading && node_weights) { // All weights are values between 0 and 1 Object.keys(node_weights).forEach(function(node) { node_weights[node] = 1 - node_weights[node]; }); } if (node_weights || 'none' !== options.color_method) { // The skeleton colors need to be set per-vertex. this.line_material.vertexColors = THREE.VertexColors; this.line_material.needsUpdate = true; var pickColor; var actorColor = this.actorColor; var unreviewedColor = new THREE.Color().setRGB(0.2, 0.2, 0.2); var reviewedColor = new THREE.Color().setRGB(1.0, 0.0, 1.0); var axonColor = new THREE.Color().setRGB(0, 1, 0), dendriteColor = new THREE.Color().setRGB(0, 0, 1), notComputable = new THREE.Color().setRGB(0.4, 0.4, 0.4); if ('creator' === options.color_method) { pickColor = function(vertex) { return User(vertex.user_id).color; }; } else if ('all-reviewed' === options.color_method) { pickColor = this.reviews ? (function(vertex) { var reviewers = this.reviews[vertex.node_id]; return reviewers && reviewers.length > 0 ? reviewedColor : unreviewedColor; }).bind(this) : function() { return notComputable; }; } else if ('own-reviewed' === options.color_method) { pickColor = this.reviews ? (function(vertex) { var reviewers = this.reviews[vertex.node_id]; return reviewers && -1 !== reviewers.indexOf(session.userid) ? reviewedColor : unreviewedColor; }).bind(this) : function() { return notComputable; }; } else if ('axon-and-dendrite' === options.color_method) { pickColor = this.axon ? (function(vertex) { return this.axon[vertex.node_id] ? axonColor : dendriteColor; }).bind(this) : function() { return notComputable; }; } else if ('downstream-of-tag' === options.color_method) { var tags = this.tags, regex = new RegExp(options.tag_regex), cuts = Object.keys(tags).filter(function(tag) { return tag.match(regex); }).reduce(function(o, tag) { return tags[tag].reduce(function(o, nodeID) { o[nodeID] = true; return o;}, o); }, {}); if (!arbor) arbor = this.createArbor(); var upstream = arbor.upstreamArbor(cuts); pickColor = function(vertex) { return upstream.contains(vertex.node_id) ? unreviewedColor : actorColor; }; } else { pickColor = function() { return actorColor; }; } // When not using shading, but using creator or reviewer: if (!node_weights) node_weights = {}; var seen = {}; this.geometry['neurite'].colors = this.geometry['neurite'].vertices.map(function(vertex) { var node_id = vertex.node_id, color = seen[node_id]; if (color) return color; var weight = node_weights[node_id]; weight = undefined === weight? 1.0 : weight * 0.9 + 0.1; var baseColor = pickColor(vertex); color = new THREE.Color().setRGB(baseColor.r * weight, baseColor.g * weight, baseColor.b * weight); seen[node_id] = color; // Side effect: color a volume at the node, if any var mesh = this.radiusVolumes[node_id]; if (mesh) { var material = mesh.material.clone(); material.color = color; mesh.setMaterial(material); } return color; }, this); this.geometry['neurite'].colorsNeedUpdate = true; this.actor['neurite'].material.color = new THREE.Color().setHex(0xffffff); this.actor['neurite'].material.opacity = 1; this.actor['neurite'].material.transparent = false; this.actor['neurite'].material.needsUpdate = true; // TODO repeated, it's the line_material } else { // Display the entire skeleton with a single color. this.geometry['neurite'].colors = []; this.line_material.vertexColors = THREE.NoColors; this.line_material.needsUpdate = true; this.actor['neurite'].material.color = this.actorColor; this.actor['neurite'].material.opacity = this.opacity; this.actor['neurite'].material.transparent = this.opacity !== 1; this.actor['neurite'].material.needsUpdate = true; // TODO repeated it's the line_material var material = new THREE.MeshBasicMaterial({color: this.actorColor, opacity:1.0, transparent:false}); for (var k in this.radiusVolumes) { if (this.radiusVolumes.hasOwnProperty(k)) { this.radiusVolumes[k].setMaterial(material); } } } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.changeSkeletonLineWidth = function(width) { this.actor['neurite'].material.linewidth = width; this.actor['neurite'].material.needsUpdate = true; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.changeColor = function(color, options) { this.actorColor = color; if (options.color_method === 'manual') { this.updateSkeletonColor(options); } }; WebGLApplication.prototype.updateConnectorColors = function(select) { this.options.connector_color = select.value; var skeletons = Object.keys(this.space.content.skeletons).map(function(skid) { return this.space.content.skeletons[skid]; }, this); this.space.updateConnectorColors(this.options, skeletons, this.space.render.bind(this.space)); }; WebGLApplication.prototype.Space.prototype.updateConnectorColors = function(options, skeletons, callback) { if ('cyan-red' === options.connector_color) { var pre = this.staticContent.synapticColors[0], post = this.staticContent.synapticColors[1]; pre.color.setRGB(1, 0, 0); // red pre.vertexColors = THREE.NoColors; pre.needsUpdate = true; post.color.setRGB(0, 1, 1); // cyan post.vertexColors = THREE.NoColors; post.needsUpdate = true; skeletons.forEach(function(skeleton) { skeleton.completeUpdateConnectorColor(options); }); if (callback) callback(); } else if ('by-amount' === options.connector_color) { var skids = skeletons.map(function(skeleton) { return skeleton.id; }); if (skids.length > 1) $.blockUI(); requestQueue.register(django_url + project.id + "/skeleton/connectors-by-partner", "POST", {skids: skids}, (function(status, text) { try { if (200 !== status) return; var json = $.parseJSON(text); if (json.error) return alert(json.error); skeletons.forEach(function(skeleton) { skeleton.completeUpdateConnectorColor(options, json[skeleton.id]); }); if (callback) callback(); } catch (e) { console.log(e, e.stack); alert(e); } $.unblockUI(); }).bind(this)); } else if ('synapse-clustering' === options.connector_color) { if (skeletons.length > 1) $.blockUI(); try { skeletons.forEach(function(skeleton) { skeleton.completeUpdateConnectorColor(options); }); if (callback) callback(); } catch (e) { console.log(e, e.stack); alert(e); } $.unblockUI(); } else if ('axon-and-dendrite' === options.connector_color) { fetchSkeletons( skeletons.map(function(skeleton) { return skeleton.id; }), function(skid) { return django_url + project.id + '/' + skid + '/0/1/0/compact-arbor'; }, function(skid) { return {}; }, (function(skid, json) { this.content.skeletons[skid].completeUpdateConnectorColor(options, json); }).bind(this), function(skid) { growlAlert("Error", "Failed to load synapses for: " + skid); }, (function() { this.render(); }).bind(this)); } }; /** Operates in conjunction with updateConnectorColors above. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.completeUpdateConnectorColor = function(options, json) { if ('cyan-red' === options.connector_color) { this.CTYPES.slice(1).forEach(function(type, i) { this.geometry[type].colors = []; this.geometry[type].colorsNeedUpdate = true; this.actor[type].material.vertexColors = THREE.NoColors; this.actor[type].material.color = this.synapticColors[this.CTYPES[1] === type ? 0 : 1].color; this.actor[type].material.needsUpdate = true; }, this); Object.keys(this.synapticSpheres).forEach(function(idx) { var mesh = this.synapticSpheres[idx]; mesh.material = this.synapticColors[this.CTYPES[1] === mesh.type ? 0 : 1]; }, this); } else if ('by-amount' === options.connector_color) { var ranges = {}; ranges[this.CTYPES[1]] = function(ratio) { return 0.66 + 0.34 * ratio; // 0.66 (blue) to 1 (red) }; ranges[this.CTYPES[2]] = function(ratio) { return 0.16 + 0.34 * (1 - ratio); // 0.5 (cyan) to 0.16 (yellow) }; this.CTYPES.slice(1).forEach(function(type) { var partners = json[type]; if (!partners) return; var connectors = Object.keys(partners).reduce(function(o, skid) { return partners[skid].reduce(function(a, connector_id, i, arr) { a[connector_id] = arr.length; return a; }, o); }, {}), max = Object.keys(connectors).reduce(function(m, connector_id) { return Math.max(m, connectors[connector_id]); }, 0), range = ranges[type]; var fnConnectorValue = function(node_id, connector_id) { var value = connectors[connector_id]; if (!value) value = 1; // connector without partner skeleton return value; }; var fnMakeColor = function(value) { return new THREE.Color().setHSL(1 === max ? range(0) : range((value -1) / (max -1)), 1, 0.5); }; this._colorConnectorsBy(type, fnConnectorValue, fnMakeColor); }, this); } else if ('synapse-clustering' === options.connector_color) { var sc = this.createSynapseClustering(options.synapse_clustering_bandwidth), density_hill_map = sc.densityHillMap(), clusters = sc.clusterMaps(density_hill_map), colorizer = d3.scale.category10(), synapse_treenodes = Object.keys(sc.synapses); // Remove bogus cluster - TODO fix this bogus cluster in SynapseClustering delete clusters[undefined]; // Filter out clusters without synapses var clusterIDs = Object.keys(clusters).filter(function(id) { var treenodes = clusters[id]; for (var k=0; k<synapse_treenodes.length; ++k) { if (treenodes[synapse_treenodes[k]]) return true; } return false; }); var cluster_colors = clusterIDs .map(function(cid) { return [cid, clusters[cid]]; }) .sort(function(a, b) { var la = a[1].length, lb = b[1].length; return la === lb ? 0 : (la > lb ? -1 : 1); }) .reduce(function(o, c, i) { o[c[0]] = new THREE.Color().set(colorizer(i)); return o; }, {}); var fnConnectorValue = function(node_id, connector_id) { return density_hill_map[node_id]; }; var fnMakeColor = function(value) { return cluster_colors[value]; }; this.synapticTypes.forEach(function(type) { this._colorConnectorsBy(type, fnConnectorValue, fnMakeColor); }, this); } else if ('axon-and-dendrite' === options.connector_color) { var axon = this.splitByFlowCentrality(json), fnMakeColor, fnConnectorValue; if (axon) { var colors = [new THREE.Color().setRGB(0, 1, 0), // axon: green new THREE.Color().setRGB(0, 0, 1)]; // dendrite: blue fnConnectorValue = function(node_id, connector_id) { return axon[node_id] ? 0 : 1; }; fnMakeColor = function(value) { return colors[value]; }; } else { // Not computable fnMakeColor = function() { return new THREE.Color().setRGB(0.4, 0.4, 0.4); }; fnConnectorValue = function() { return 0; }; } this.synapticTypes.forEach(function(type) { this._colorConnectorsBy(type, fnConnectorValue, fnMakeColor); }, this); } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype._colorConnectorsBy = function(type, fnConnectorValue, fnMakeColor) { // Set colors per-vertex var seen = {}, seen_materials = {}, colors = [], vertices = this.geometry[type].vertices; for (var i=0; i<vertices.length; i+=2) { var connector_id = vertices[i].node_id, node_id = vertices[i+1].node_id, value = fnConnectorValue(node_id, connector_id); var color = seen[value]; if (!color) { color = fnMakeColor(value); seen[value] = color; } // twice: for treenode and for connector colors.push(color); colors.push(color); var mesh = this.synapticSpheres[node_id]; if (mesh) { mesh.material.color = color; mesh.material.needsUpdate = true; var material = seen_materials[value]; if (!material) { material = mesh.material.clone(); material.color = color; seen_materials[value] = material; } mesh.setMaterial(material); } } this.geometry[type].colors = colors; this.geometry[type].colorsNeedUpdate = true; var material = new THREE.LineBasicMaterial({color: 0xffffff, opacity: 1.0, linewidth: 6}); material.vertexColors = THREE.VertexColors; material.needsUpdate = true; this.actor[type].material = material; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.addCompositeActorToScene = function() { this.CTYPES.forEach(function(t) { this.space.add(this.actor[t]); }, this); }; /** Three possible types of actors: 'neurite', 'presynaptic_to', and 'postsynaptic_to', each consisting, respectibly, of the edges of the skeleton, the edges of the presynaptic sites and the edges of the postsynaptic sites. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.visibilityCompositeActor = function(type, visible) { this.actor[type].visible = visible; }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.getActorColorAsHTMLHex = function () { return this.actorColor.getHexString(); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.getActorColorAsHex = function() { return this.actorColor.getHex(); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.remove_connector_selection = function() { if (this.connectoractor) { for (var i=0; i<2; ++i) { var ca = this.connectoractor[this.synapticTypes[i]]; if (ca) { ca.geometry.dispose(); // do not dispose material, it is shared this.space.remove(ca); delete this.connectoractor[this.synapticTypes[i]]; } } this.connectoractor = null; } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.create_connector_selection = function( common_connector_IDs ) { this.connectoractor = {}; this.connectorgeometry = {}; this.connectorgeometry[this.CTYPES[1]] = new THREE.Geometry(); this.connectorgeometry[this.CTYPES[2]] = new THREE.Geometry(); this.synapticTypes.forEach(function(type) { // Vertices is an array of Vector3, every two a pair, the first at the connector and the second at the node var vertices1 = this.geometry[type].vertices; var vertices2 = this.connectorgeometry[type].vertices; for (var i=vertices1.length-2; i>-1; i-=2) { var v = vertices1[i]; if (common_connector_IDs.hasOwnProperty(v.node_id)) { vertices2.push(vertices1[i+1]); vertices2.push(v); } } this.connectoractor[type] = new THREE.Line( this.connectorgeometry[type], this.space.staticContent.connectorLineColors[type], THREE.LinePieces ); this.space.add( this.connectoractor[type] ); }, this); }; /** Place a colored sphere at the node. Used for highlighting special tags like 'uncertain end' and 'todo'. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createLabelSphere = function(v, material) { if (this.specialTagSpheres.hasOwnProperty(v.node_id)) { // There already is a tag sphere at the node return; } var mesh = new THREE.Mesh( this.space.staticContent.labelspheregeometry, material ); mesh.position.set( v.x, v.y, v.z ); mesh.node_id = v.node_id; this.specialTagSpheres[v.node_id] = mesh; this.space.add( mesh ); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createEdge = function(v1, v2, type) { // Create edge between child (id1) and parent (id2) nodes: // Takes the coordinates of each node, transforms them into the space, // and then adds them to the parallel lists of vertices and vertexIDs var vs = this.geometry[type].vertices; vs.push(v1); vs.push(v2); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createNodeSphere = function(v, radius, material) { if (this.radiusVolumes.hasOwnProperty(v.node_id)) { // There already is a sphere or cylinder at the node return; } // Reuse geometry: an icoSphere of radius 1.0 var mesh = new THREE.Mesh(this.space.staticContent.icoSphere, material); // Scale the mesh to bring about the correct radius mesh.scale.x = mesh.scale.y = mesh.scale.z = radius; mesh.position.set( v.x, v.y, v.z ); mesh.node_id = v.node_id; this.radiusVolumes[v.node_id] = mesh; this.space.add(mesh); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createCylinder = function(v1, v2, radius, material) { if (this.radiusVolumes.hasOwnProperty(v1.node_id)) { // There already is a sphere or cylinder at the node return; } var mesh = new THREE.Mesh(this.space.staticContent.cylinder, material); // BE CAREFUL with side effects: all functions on a Vector3 alter the vector and return it (rather than returning an altered copy) var direction = new THREE.Vector3().subVectors(v2, v1); mesh.scale.x = radius; mesh.scale.y = direction.length(); mesh.scale.z = radius; var arrow = new THREE.ArrowHelper(direction.clone().normalize(), v1); mesh.rotation = new THREE.Vector3().setEulerFromQuaternion(arrow.quaternion); mesh.position = new THREE.Vector3().addVectors(v1, direction.multiplyScalar(0.5)); mesh.node_id = v1.node_id; this.radiusVolumes[v1.node_id] = mesh; this.space.add(mesh); }; /* The itype is 0 (pre) or 1 (post), and chooses from the two arrays: synapticTypes and synapticColors. */ WebGLApplication.prototype.Space.prototype.Skeleton.prototype.createSynapticSphere = function(v, itype) { if (this.synapticSpheres.hasOwnProperty(v.node_id)) { // There already is a synaptic sphere at the node return; } var mesh = new THREE.Mesh( this.space.staticContent.radiusSphere, this.synapticColors[itype] ); mesh.position.set( v.x, v.y, v.z ); mesh.node_id = v.node_id; mesh.type = this.synapticTypes[itype]; this.synapticSpheres[v.node_id] = mesh; this.space.add( mesh ); }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.reinit_actor = function(skeletonmodel, json, options) { if (this.actor) { this.destroy(); } this.skeletonmodel = skeletonmodel; this.initialize_objects(options); var nodes = json[0]; var connectors = json[1]; var tags = json[2]; var lean = options.lean_mode; // Map of node ID vs node properties array var nodeProps = nodes.reduce(function(ob, node) { ob[node[0]] = node; return ob; }, {}); // Store for creation when requested // TODO could request them from the server when necessary this.tags = tags; // Cache for reusing Vector3d instances var vs = {}; // Reused for all meshes var material = new THREE.MeshBasicMaterial( { color: this.getActorColorAsHex(), opacity:1.0, transparent:false } ); material.opacity = this.skeletonmodel.opacity; material.transparent = material.opacity !== 1; // Create edges between all skeleton nodes // and a sphere on the node if radius > 0 nodes.forEach(function(node) { // node[0]: treenode ID // node[1]: parent ID // node[2]: user ID // 3,4,5: x,y,z // node[6]: radius // node[7]: confidence // If node has a parent var v1; if (node[1]) { var p = nodeProps[node[1]]; v1 = vs[node[0]]; if (!v1) { v1 = this.space.toSpace(new THREE.Vector3(node[3], node[4], node[5])); v1.node_id = node[0]; v1.user_id = node[2]; vs[node[0]] = v1; } var v2 = vs[p[0]]; if (!v2) { v2 = this.space.toSpace(new THREE.Vector3(p[3], p[4], p[5])); v2.node_id = p[0]; v2.user_id = p[2]; vs[p[0]] = v2; } var nodeID = node[0]; if (node[6] > 0 && p[6] > 0) { // Create cylinder using the node's radius only (not the parent) so that the geometry can be reused this.createCylinder(v1, v2, node[6], material); // Create skeleton line as well this.createEdge(v1, v2, 'neurite'); } else { // Create line this.createEdge(v1, v2, 'neurite'); // Create sphere if (node[6] > 0) { this.createNodeSphere(v1, node[6], material); } } } else { // For the root node, which must be added to vs v1 = vs[node[0]]; if (!v1) { v1 = this.space.toSpace(new THREE.Vector3(node[3], node[4], node[5])); v1.node_id = node[0]; v1.user_id = node[2]; vs[node[0]] = v1; } if (node[6] > 0) { // Clear the slot for a sphere at the root var mesh = this.radiusVolumes[v1.node_id]; if (mesh) { this.space.remove(mesh); delete this.radiusVolumes[v1.node_id]; } this.createNodeSphere(v1, node[6], material); } } if (!lean && node[7] < 5) { // Edge with confidence lower than 5 this.createLabelSphere(v1, this.space.staticContent.labelColors.uncertain); } }, this); if (options.smooth_skeletons) { var smoothed = this.createArbor().smoothPositions(vs, options.smooth_skeletons_sigma); Object.keys(vs).forEach(function(node_id) { vs[node_id].copy(smoothed[node_id]); }); } // Create edges between all connector nodes and their associated skeleton nodes, // appropriately colored as pre- or postsynaptic. // If not yet there, create as well the sphere for the node related to the connector connectors.forEach(function(con) { // con[0]: treenode ID // con[1]: connector ID // con[2]: 0 for pre, 1 for post // indices 3,4,5 are x,y,z for connector // indices 4,5,6 are x,y,z for node var v1 = this.space.toSpace(new THREE.Vector3(con[3], con[4], con[5])); v1.node_id = con[1]; var v2 = vs[con[0]]; this.createEdge(v1, v2, this.synapticTypes[con[2]]); this.createSynapticSphere(v2, con[2]); }, this); // Place spheres on nodes with special labels, if they don't have a sphere there already for (var tag in this.tags) { if (this.tags.hasOwnProperty(tag)) { var tagLC = tag.toLowerCase(); if (-1 !== tagLC.indexOf('todo')) { this.tags[tag].forEach(function(nodeID) { if (!this.specialTagSpheres[nodeID]) { this.createLabelSphere(vs[nodeID], this.space.staticContent.labelColors.todo); } }, this); } else if (-1 !== tagLC.indexOf('uncertain')) { this.tags[tag].forEach(function(nodeID) { if (!this.specialTagSpheres[nodeID]) { this.createLabelSphere(vs[nodeID], this.space.staticContent.labelColors.uncertain); } }, this); } } } if (options.resample_skeletons) { // WARNING: node IDs no longer resemble actual skeleton IDs. // All node IDs will now have negative values to avoid accidental similarities. var res = this.createArbor().resampleSlabs(vs, options.smooth_skeletons_sigma, options.resampling_delta, 2); var vs = this.geometry['neurite'].vertices; // Remove existing lines vs.length = 0; // Add all new lines var edges = res.arbor.edges, positions = res.positions; Object.keys(edges).forEach(function(nodeID) { // Fix up Vector3 instances var v_child = positions[nodeID]; v_child.user_id = -1; v_child.node_id = -nodeID; // Add line vs.push(v_child); vs.push(positions[edges[nodeID]]); // parent }); // Fix up root var v_root = positions[res.arbor.root]; v_root.user_id = -1; v_root.node_id = -res.arbor.root; } }; WebGLApplication.prototype.Space.prototype.Skeleton.prototype.show = function(options) { this.addCompositeActorToScene(); this.setActorVisibility( this.skeletonmodel.selected ); // the skeleton, radius spheres and label spheres if (options.connector_filter) { this.setPreVisibility( false ); // the presynaptic edges and spheres this.setPostVisibility( false ); // the postsynaptic edges and spheres } else { this.setPreVisibility( this.skeletonmodel.pre_visible ); // the presynaptic edges and spheres this.setPostVisibility( this.skeletonmodel.post_visible ); // the postsynaptic edges and spheres } this.setTextVisibility( this.skeletonmodel.text_visible ); // the text labels //this.updateSkeletonColor(options); // Will query the server if ('cyan-red' !== options.connector_color) this.space.updateConnectorColors(options, [this]); }; /** * Toggles the display of a JQuery UI dialog that shows which user has which * color assigned. */ WebGLApplication.prototype.toggle_usercolormap_dialog = function() { // In case a color dialog exists already, close it and return. if ($('#user-colormap-dialog').length > 0) { $('#user-colormap-dialog').remove(); return; } // Create a new color dialog var dialog = document.createElement('div'); dialog.setAttribute("id", "user-colormap-dialog"); dialog.setAttribute("title", "User colormap"); var tab = document.createElement('table'); tab.setAttribute("id", "usercolormap-table"); tab.innerHTML = '<thead>' + '<tr>' + '<th>login</th>' + '<th>name</th>' + '<th>color</th>' + '</tr>' + '</thead>' + '<tbody></tbody>'; dialog.appendChild(tab); $(dialog).dialog({ height: 440, width: 340, modal: false, dialogClass: "no-close", buttons: { "OK": function() { $(this).dialog("close"); } }, close: function(event, ui) { $('#user-colormap-dialog').remove(); } }); var users = User.all(); for (var userID in users) { if (users.hasOwnProperty(userID) && userID !== "-1") { var user = users[userID]; var rowElement = $('<tr/>'); rowElement.append( $('<td/>').text( user.login ) ); rowElement.append( $('<td/>').text( user.fullName ) ); rowElement.append( $('<div/>').css('width', '100px').css('height', '20px').css('background-color', '#' + user.color.getHexString()) ); $('#usercolormap-table > tbody:last').append( rowElement ); } } }; WebGLApplication.prototype.toggleInvertShading = function() { this.options.invert_shading = !this.options.invert_shading; if (this.options.shading_method === 'none') return; this.set_shading_method(); }; WebGLApplication.prototype.setFollowActive = function(value) { this.options.follow_active = value ? true : false; this.space.render(); };
3D viewer: explicitely define floor edges This makes the Three.js update easier, because Face4 was removed.
django/applications/catmaid/static/js/webglapp.js
3D viewer: explicitely define floor edges
<ide><path>jango/applications/catmaid/static/js/webglapp.js <ide> var zLines = nBaseLines + 2 * zExtent; <ide> var width = max_x - min_x; <ide> var height = max_z - min_z; <del> var plane = new THREE.PlaneGeometry(width, height, xLines, zLines); <del> var material = new THREE.MeshBasicMaterial({ <del> color: o['color'] || 0x535353, <del> wireframe: true, <del> side: THREE.DoubleSide, <del> transparent: true <add> <add> var geometry = new THREE.Geometry(); <add> for (var x=0; x<=xLines; ++x) { <add> for (var z=0; z<=zLines; ++z) { <add> geometry.vertices.push( <add> new THREE.Vector3(min_x, floor, min_z + z*zStep), <add> new THREE.Vector3(max_x, floor, min_z + z*zStep), <add> new THREE.Vector3(min_x + x*xStep, floor, min_z), <add> new THREE.Vector3(min_x + x*xStep, floor, max_z) <add> ); <add> } <add> } <add> <add> geometry.computeLineDistances(); <add> <add> var material = new THREE.LineBasicMaterial({ <add> color: o['color'] || 0x535353 <ide> }); <del> var mesh = new THREE.Mesh(plane, material); <del> // Center the mesh and rotate it to be XZ parallel <add> var mesh = new THREE.Line( geometry, material, THREE.LinePieces ); <add> <ide> mesh.position.set(min_x + 0.5 * width, floor, min_z + 0.5 * height); <del> mesh.rotation.x = Math.PI * 0.5; <ide> <ide> return mesh; <ide> };
Java
bsd-2-clause
f4dd4159d444313c1293036ce363fd33aa4e1bee
0
scifio/scifio
// // TiffParser.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.tiff; import java.io.IOException; import java.util.TreeSet; import java.util.Vector; import loci.common.DataTools; import loci.common.RandomAccessInputStream; import loci.common.Region; import loci.formats.FormatException; import loci.formats.codec.BitBuffer; import loci.formats.codec.CodecOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Parses TIFF data from an input source. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/tiff/TiffParser.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/tiff/TiffParser.java">SVN</a></dd></dl> * * @author Curtis Rueden ctrueden at wisc.edu * @author Eric Kjellman egkjellman at wisc.edu * @author Melissa Linkert linkert at wisc.edu * @author Chris Allan callan at blackcat.ca */ public class TiffParser { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(TiffParser.class); // -- Fields -- /** Input source from which to parse TIFF data. */ protected RandomAccessInputStream in; /** Cached tile buffer to avoid re-allocations when reading tiles. */ private byte[] cachedTileBuffer; /** Whether or not the TIFF file contains BigTIFF data. */ private boolean bigTiff; private boolean doCaching; /** Cached list of IFDs in the current file. */ private IFDList ifdList; /** Cached first IFD in the current file. */ private IFD firstIFD; // -- Constructors -- /** Constructs a new TIFF parser from the given file name. */ public TiffParser(String filename) throws IOException { this(new RandomAccessInputStream(filename)); } /** Constructs a new TIFF parser from the given input source. */ public TiffParser(RandomAccessInputStream in) { this.in = in; doCaching = true; } // -- TiffParser methods -- /** Sets whether or not IFD entries should be cached. */ public void setDoCaching(boolean doCaching) { this.doCaching = doCaching; } /** Gets the stream from which TIFF data is being parsed. */ public RandomAccessInputStream getStream() { return in; } /** Tests this stream to see if it represents a TIFF file. */ public boolean isValidHeader() { try { return checkHeader() != null; } catch (IOException e) { return false; } } /** * Checks the TIFF header. * * @return true if little-endian, * false if big-endian, * or null if not a TIFF. */ public Boolean checkHeader() throws IOException { if (in.length() < 4) return null; // byte order must be II or MM in.seek(0); int endianOne = in.read(); int endianTwo = in.read(); boolean littleEndian = endianOne == TiffConstants.LITTLE && endianTwo == TiffConstants.LITTLE; // II boolean bigEndian = endianOne == TiffConstants.BIG && endianTwo == TiffConstants.BIG; // MM if (!littleEndian && !bigEndian) return null; // check magic number (42) in.order(littleEndian); short magic = in.readShort(); bigTiff = magic == TiffConstants.BIG_TIFF_MAGIC_NUMBER; if (magic != TiffConstants.MAGIC_NUMBER && magic != TiffConstants.BIG_TIFF_MAGIC_NUMBER) { return null; } return new Boolean(littleEndian); } /** Returns whether or not the current TIFF file contains BigTIFF data. */ public boolean isBigTiff() { return bigTiff; } // -- TiffParser methods - IFD parsing -- /** Returns all IFDs in the file. */ public IFDList getIFDs() throws IOException { if (ifdList != null) return ifdList; long[] offsets = getIFDOffsets(); IFDList ifds = new IFDList(); for (long offset : offsets) { IFD ifd = getIFD(offset); if (ifd == null) continue; ifds.add(ifd); long[] subOffsets = null; try { subOffsets = ifd.getIFDLongArray(IFD.SUB_IFD); } catch (FormatException e) { } if (subOffsets != null) { for (long subOffset : subOffsets) { IFD sub = getIFD(subOffset); if (sub != null) { ifds.add(sub); } } } } if (doCaching) ifdList = ifds; return ifds; } /** Returns thumbnail IFDs. */ public IFDList getThumbnailIFDs() throws IOException { IFDList ifds = getIFDs(); IFDList thumbnails = new IFDList(); for (IFD ifd : ifds) { Number subfile = (Number) ifd.getIFDValue(IFD.NEW_SUBFILE_TYPE); int subfileType = subfile == null ? 0 : subfile.intValue(); if (subfileType == 1) { thumbnails.add(ifd); } } return thumbnails; } /** Returns non-thumbnail IFDs. */ public IFDList getNonThumbnailIFDs() throws IOException { IFDList ifds = getIFDs(); IFDList nonThumbs = new IFDList(); for (IFD ifd : ifds) { Number subfile = (Number) ifd.getIFDValue(IFD.NEW_SUBFILE_TYPE); int subfileType = subfile == null ? 0 : subfile.intValue(); if (subfileType != 1 || ifds.size() <= 1) { nonThumbs.add(ifd); } } return nonThumbs; } /** Returns EXIF IFDs. */ public IFDList getExifIFDs() throws FormatException, IOException { IFDList ifds = getIFDs(); IFDList exif = new IFDList(); for (IFD ifd : ifds) { long offset = ifd.getIFDLongValue(IFD.EXIF, 0); if (offset != 0) { IFD exifIFD = getIFD(offset); if (exifIFD != null) { exif.add(exifIFD); } } } return exif; } /** Gets the offsets to every IFD in the file. */ public long[] getIFDOffsets() throws IOException { // check TIFF header int bytesPerEntry = bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY; Vector<Long> offsets = new Vector<Long>(); long offset = getFirstOffset(); while (offset > 0 && offset < in.length()) { in.seek(offset); offsets.add(offset); int nEntries = bigTiff ? (int) in.readLong() : in.readUnsignedShort(); in.skipBytes(nEntries * bytesPerEntry); offset = getNextOffset(offset); } long[] f = new long[offsets.size()]; for (int i=0; i<f.length; i++) { f[i] = offsets.get(i).longValue(); } return f; } /** * Gets the first IFD within the TIFF file, or null * if the input source is not a valid TIFF file. */ public IFD getFirstIFD() throws IOException { if (firstIFD != null) return firstIFD; long offset = getFirstOffset(); IFD ifd = getIFD(offset); if (doCaching) firstIFD = ifd; return ifd; } /** * Retrieve a given entry from the first IFD in the stream. * * @param tag the tag of the entry to be retrieved. * @return an object representing the entry's fields. * @throws IOException when there is an error accessing the stream. * @throws IllegalArgumentException when the tag number is unknown. */ // TODO : Try to remove this method. It is only being used by // loci.formats.in.MetamorphReader. public TiffIFDEntry getFirstIFDEntry(int tag) throws IOException { // Get the offset of the first IFD long offset = getFirstOffset(); if (offset < 0) return null; // The following loosely resembles the logic of getIFD()... in.seek(offset); long numEntries = bigTiff ? in.readLong() : in.readUnsignedShort(); for (int i = 0; i < numEntries; i++) { in.seek(offset + // The beginning of the IFD (bigTiff ? 8 : 2) + // The width of the initial numEntries field (bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY) * i); TiffIFDEntry entry = readTiffIFDEntry(); if (entry.getTag() == tag) { return entry; } } throw new IllegalArgumentException("Unknown tag: " + tag); } /** * Gets offset to the first IFD, or -1 if stream is not TIFF. */ public long getFirstOffset() throws IOException { Boolean header = checkHeader(); if (header == null) return -1; if (bigTiff) in.skipBytes(4); return getNextOffset(0); } /** Gets the IFD stored at the given offset. */ public IFD getIFD(long offset) throws IOException { if (offset < 0 || offset >= in.length()) return null; IFD ifd = new IFD(); // save little-endian flag to internal LITTLE_ENDIAN tag ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(in.isLittleEndian())); ifd.put(new Integer(IFD.BIG_TIFF), new Boolean(bigTiff)); // read in directory entries for this IFD LOGGER.debug("getIFDs: seeking IFD at {}", offset); in.seek(offset); long numEntries = bigTiff ? in.readLong() : in.readUnsignedShort(); LOGGER.debug("getIFDs: {} directory entries to read", numEntries); if (numEntries == 0 || numEntries == 1) return ifd; int bytesPerEntry = bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY; int baseOffset = bigTiff ? 8 : 2; for (int i=0; i<numEntries; i++) { in.seek(offset + baseOffset + bytesPerEntry * i); TiffIFDEntry entry = readTiffIFDEntry(); int count = entry.getValueCount(); int tag = entry.getTag(); long pointer = entry.getValueOffset(); int bpe = entry.getType().getBytesPerElement(); if (count < 0 || bpe <= 0) { // invalid data in.skipBytes(bytesPerEntry - 4 - (bigTiff ? 8 : 4)); continue; } Object value = null; long inputLen = in.length(); if (count * bpe + pointer > inputLen) { int oldCount = count; count = (int) ((inputLen - pointer) / bpe); LOGGER.debug("getIFDs: truncated {} array elements for tag {}", (oldCount - count), tag); } if (count < 0 || count > in.length()) break; if (pointer != in.getFilePointer() && !doCaching) { value = entry; } else value = getIFDValue(entry); if (value != null && !ifd.containsKey(new Integer(tag))) { ifd.put(new Integer(tag), value); } } in.seek(offset + baseOffset + bytesPerEntry * numEntries); return ifd; } /** Fill in IFD entries that are stored at an arbitrary offset. */ public void fillInIFD(IFD ifd) throws IOException { TreeSet<TiffIFDEntry> entries = new TreeSet<TiffIFDEntry>(); for (Object key : ifd.keySet()) { if (ifd.get(key) instanceof TiffIFDEntry) { entries.add((TiffIFDEntry) ifd.get(key)); } } for (TiffIFDEntry entry : entries) { ifd.put(new Integer(entry.getTag()), getIFDValue(entry)); } } /** Retrieve the value corresponding to the given TiffIFDEntry. */ public Object getIFDValue(TiffIFDEntry entry) throws IOException { IFDType type = entry.getType(); int count = entry.getValueCount(); long offset = entry.getValueOffset(); LOGGER.debug("Reading entry {} from {}; type={}, count={}", new Object[] {entry.getTag(), offset, type, count}); if (offset != in.getFilePointer()) { in.seek(offset); } if (type == IFDType.BYTE) { // 8-bit unsigned integer if (count == 1) return new Short(in.readByte()); byte[] bytes = new byte[count]; in.readFully(bytes); // bytes are unsigned, so use shorts short[] shorts = new short[count]; for (int j=0; j<count; j++) shorts[j] = (short) (bytes[j] & 0xff); return shorts; } else if (type == IFDType.ASCII) { // 8-bit byte that contain a 7-bit ASCII code; // the last byte must be NUL (binary zero) byte[] ascii = new byte[count]; in.read(ascii); // count number of null terminators int nullCount = 0; for (int j=0; j<count; j++) { if (ascii[j] == 0 || j == count - 1) nullCount++; } // convert character array to array of strings String[] strings = nullCount == 1 ? null : new String[nullCount]; String s = null; int c = 0, ndx = -1; for (int j=0; j<count; j++) { if (ascii[j] == 0) { s = new String(ascii, ndx + 1, j - ndx - 1); ndx = j; } else if (j == count - 1) { // handle non-null-terminated strings s = new String(ascii, ndx + 1, j - ndx); } else s = null; if (strings != null && s != null) strings[c++] = s; } return strings == null ? (Object) s : strings; } else if (type == IFDType.SHORT) { // 16-bit (2-byte) unsigned integer if (count == 1) return new Integer(in.readUnsignedShort()); int[] shorts = new int[count]; for (int j=0; j<count; j++) { shorts[j] = in.readUnsignedShort(); } return shorts; } else if (type == IFDType.LONG || type == IFDType.IFD) { // 32-bit (4-byte) unsigned integer if (count == 1) return new Long(in.readInt()); long[] longs = new long[count]; for (int j=0; j<count; j++) { if (in.getFilePointer() + 4 <= in.length()) { longs[j] = in.readInt(); } } return longs; } else if (type == IFDType.LONG8 || type == IFDType.SLONG8 || type == IFDType.IFD8) { if (count == 1) return new Long(in.readLong()); long[] longs = new long[count]; for (int j=0; j<count; j++) longs[j] = in.readLong(); return longs; } else if (type == IFDType.RATIONAL || type == IFDType.SRATIONAL) { // Two LONGs or SLONGs: the first represents the numerator // of a fraction; the second, the denominator if (count == 1) return new TiffRational(in.readInt(), in.readInt()); TiffRational[] rationals = new TiffRational[count]; for (int j=0; j<count; j++) { rationals[j] = new TiffRational(in.readInt(), in.readInt()); } return rationals; } else if (type == IFDType.SBYTE || type == IFDType.UNDEFINED) { // SBYTE: An 8-bit signed (twos-complement) integer // UNDEFINED: An 8-bit byte that may contain anything, // depending on the definition of the field if (count == 1) return new Byte(in.readByte()); byte[] sbytes = new byte[count]; in.read(sbytes); return sbytes; } else if (type == IFDType.SSHORT) { // A 16-bit (2-byte) signed (twos-complement) integer if (count == 1) return new Short(in.readShort()); short[] sshorts = new short[count]; for (int j=0; j<count; j++) sshorts[j] = in.readShort(); return sshorts; } else if (type == IFDType.SLONG) { // A 32-bit (4-byte) signed (twos-complement) integer if (count == 1) return new Integer(in.readInt()); int[] slongs = new int[count]; for (int j=0; j<count; j++) slongs[j] = in.readInt(); return slongs; } else if (type == IFDType.FLOAT) { // Single precision (4-byte) IEEE format if (count == 1) return new Float(in.readFloat()); float[] floats = new float[count]; for (int j=0; j<count; j++) floats[j] = in.readFloat(); return floats; } else if (type == IFDType.DOUBLE) { // Double precision (8-byte) IEEE format if (count == 1) return new Double(in.readDouble()); double[] doubles = new double[count]; for (int j=0; j<count; j++) { doubles[j] = in.readDouble(); } return doubles; } return null; } /** Convenience method for obtaining a stream's first ImageDescription. */ public String getComment() throws IOException { IFD firstIFD = getFirstIFD(); return firstIFD == null ? null : firstIFD.getComment(); } // -- TiffParser methods - image reading -- public byte[] getTile(IFD ifd, byte[] buf, int row, int col) throws FormatException, IOException { byte[] jpegTable = (byte[]) ifd.getIFDValue(IFD.JPEG_TABLES); CodecOptions options = new CodecOptions(); options.interleaved = true; options.littleEndian = ifd.isLittleEndian(); long tileWidth = ifd.getTileWidth(); long tileLength = ifd.getTileLength(); int samplesPerPixel = ifd.getSamplesPerPixel(); int planarConfig = ifd.getPlanarConfiguration(); TiffCompression compression = ifd.getCompression(); long numTileCols = ifd.getTilesPerRow(); int pixel = ifd.getBytesPerSample()[0]; int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel; long[] stripOffsets = ifd.getStripOffsets(); long[] stripByteCounts = ifd.getStripByteCounts(); long[] rowsPerStrip = ifd.getRowsPerStrip(); int tileNumber = (int) (row * numTileCols + col); if (stripByteCounts[tileNumber] == (rowsPerStrip[0] * tileWidth) && pixel > 1) { stripByteCounts[tileNumber] *= pixel; } int size = (int) (tileWidth * tileLength * pixel * effectiveChannels); if (buf == null) buf = new byte[size]; if (stripByteCounts[tileNumber] == 0 || stripOffsets[tileNumber] >= in.length()) { return buf; } byte[] tile = new byte[(int) stripByteCounts[tileNumber]]; in.seek(stripOffsets[tileNumber]); in.read(tile); options.maxBytes = size; if (jpegTable != null) { byte[] q = new byte[jpegTable.length + tile.length - 4]; System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2); System.arraycopy(tile, 2, q, jpegTable.length - 2, tile.length - 2); tile = compression.decompress(q, options); } else tile = compression.decompress(tile, options); TiffCompression.undifference(tile, ifd); unpackBytes(buf, 0, tile, ifd); return buf; } public byte[] getSamples(IFD ifd, byte[] buf) throws FormatException, IOException { long width = ifd.getImageWidth(); long length = ifd.getImageLength(); return getSamples(ifd, buf, 0, 0, width, length); } public byte[] getSamples(IFD ifd, byte[] buf, int x, int y, long width, long height) throws FormatException, IOException { LOGGER.debug("parsing IFD entries"); // get internal non-IFD entries boolean littleEndian = ifd.isLittleEndian(); in.order(littleEndian); // get relevant IFD entries int samplesPerPixel = ifd.getSamplesPerPixel(); long tileWidth = ifd.getTileWidth(); long tileLength = ifd.getTileLength(); if (tileLength <= 0) { LOGGER.debug("Tile length is {}; setting it to {}", tileLength, height); tileLength = height; } long numTileRows = ifd.getTilesPerColumn(); long numTileCols = ifd.getTilesPerRow(); PhotoInterp photoInterp = ifd.getPhotometricInterpretation(); int planarConfig = ifd.getPlanarConfiguration(); int pixel = ifd.getBytesPerSample()[0]; int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel; ifd.printIFD(); if (width * height > Integer.MAX_VALUE) { throw new FormatException("Sorry, ImageWidth x ImageLength > " + Integer.MAX_VALUE + " is not supported (" + width + " x " + height + ")"); } if (width * height * effectiveChannels * pixel > Integer.MAX_VALUE) { throw new FormatException("Sorry, ImageWidth x ImageLength x " + "SamplesPerPixel x BitsPerSample > " + Integer.MAX_VALUE + " is not supported (" + width + " x " + height + " x " + samplesPerPixel + " x " + (pixel * 8) + ")"); } // casting to int is safe because we have already determined that // width * height is less than Integer.MAX_VALUE int numSamples = (int) (width * height); // read in image strips LOGGER.debug("reading image data (samplesPerPixel={}; numSamples={})", samplesPerPixel, numSamples); TiffCompression compression = ifd.getCompression(); // special case: if we only need one tile, and that tile doesn't need // any special handling, then we can just read it directly and return if ((x % tileWidth) == 0 && (y % tileLength) == 0 && width == tileWidth && height == tileLength && samplesPerPixel == 1 && (ifd.getBitsPerSample()[0] % 8) == 0 && photoInterp != PhotoInterp.WHITE_IS_ZERO && photoInterp != PhotoInterp.CMYK && photoInterp != PhotoInterp.Y_CB_CR && compression == TiffCompression.UNCOMPRESSED) { long[] stripOffsets = ifd.getStripOffsets(); long[] stripByteCounts = ifd.getStripByteCounts(); int tile = (int) ((y / tileLength) * numTileCols + (x / tileWidth)); if (stripByteCounts[tile] == numSamples && pixel > 1) { stripByteCounts[tile] *= pixel; } in.seek(stripOffsets[tile]); in.read(buf, 0, (int) Math.min(buf.length, stripByteCounts[tile])); return buf; } long nrows = numTileRows; if (planarConfig == 2) numTileRows *= samplesPerPixel; Region imageBounds = new Region(x, y, (int) width, (int) (height * (samplesPerPixel / effectiveChannels))); int endX = (int) width + x; int endY = (int) height + y; int rowLen = pixel * (int) tileWidth; int tileSize = (int) (rowLen * tileLength); int planeSize = (int) (width * height * pixel); int outputRowLen = (int) (pixel * width); int bufferSizeSamplesPerPixel = samplesPerPixel; if (ifd.getPlanarConfiguration() == 2) bufferSizeSamplesPerPixel = 1; int bpp = ifd.getBytesPerSample()[0]; int bufferSize = (int) tileWidth * (int) tileLength * bufferSizeSamplesPerPixel * bpp; if (cachedTileBuffer == null || cachedTileBuffer.length != bufferSize) { cachedTileBuffer = new byte[bufferSize]; } Region tileBounds = new Region(0, 0, (int) tileWidth, (int) tileLength); for (int row=0; row<numTileRows; row++) { for (int col=0; col<numTileCols; col++) { tileBounds.x = col * (int) tileWidth; tileBounds.y = row * (int) tileLength; if (!imageBounds.intersects(tileBounds)) continue; if (planarConfig == 2) { tileBounds.y = (int) ((row % nrows) * tileLength); } getTile(ifd, cachedTileBuffer, row, col); // adjust tile bounds, if necessary int tileX = (int) Math.max(tileBounds.x, x); int tileY = (int) Math.max(tileBounds.y, y); int realX = tileX % (int) tileWidth; int realY = tileY % (int) tileLength; int twidth = (int) Math.min(endX - tileX, tileWidth - realX); int theight = (int) Math.min(endY - tileY, tileLength - realY); // copy appropriate portion of the tile to the output buffer int copy = pixel * twidth; realX *= pixel; realY *= rowLen; for (int q=0; q<effectiveChannels; q++) { int src = (int) (q * tileSize) + realX + realY; int dest = (int) (q * planeSize) + pixel * (tileX - x) + outputRowLen * (tileY - y); if (planarConfig == 2) dest += (planeSize * (row / nrows)); for (int tileRow=0; tileRow<theight; tileRow++) { System.arraycopy(cachedTileBuffer, src, buf, dest, copy); src += rowLen; dest += outputRowLen; } } } } return buf; } // -- Utility methods - byte stream decoding -- /** * Extracts pixel information from the given byte array according to the * bits per sample, photometric interpretation and color map IFD directory * entry values, and the specified byte ordering. * No error checking is performed. */ public static void unpackBytes(byte[] samples, int startIndex, byte[] bytes, IFD ifd) throws FormatException { boolean planar = ifd.getPlanarConfiguration() == 2; TiffCompression compression = ifd.getCompression(); PhotoInterp photoInterp = ifd.getPhotometricInterpretation(); if (compression == TiffCompression.JPEG) photoInterp = PhotoInterp.RGB; int[] bitsPerSample = ifd.getBitsPerSample(); int nChannels = bitsPerSample.length; int sampleCount = (8 * bytes.length) / (nChannels * bitsPerSample[0]); if (photoInterp == PhotoInterp.Y_CB_CR) sampleCount *= 3; if (planar) { sampleCount *= nChannels; nChannels = 1; } LOGGER.debug( "unpacking {} samples (startIndex={}; totalBits={}; numBytes={})", new Object[] {sampleCount, startIndex, nChannels * bitsPerSample[0], bytes.length}); long imageWidth = ifd.getImageWidth(); long imageHeight = ifd.getImageLength(); int bps0 = bitsPerSample[0]; int numBytes = ifd.getBytesPerSample()[0]; int nSamples = samples.length / (nChannels * numBytes); boolean noDiv8 = bps0 % 8 != 0; boolean bps8 = bps0 == 8; boolean bps16 = bps0 == 16; boolean littleEndian = ifd.isLittleEndian(); BitBuffer bb = new BitBuffer(bytes); // Hyper optimisation that takes any 8-bit or 16-bit data, where there is // only one channel, the source byte buffer's size is less than or equal to // that of the destination buffer and for which no special unpacking is // required and performs a simple array copy. Over the course of reading // semi-large datasets this can save **billions** of method calls. // Wed Aug 5 19:04:59 BST 2009 // Chris Allan <[email protected]> if ((bps8 || bps16) && bytes.length <= samples.length && nChannels == 1 && photoInterp != PhotoInterp.WHITE_IS_ZERO && photoInterp != PhotoInterp.CMYK && photoInterp != PhotoInterp.Y_CB_CR) { System.arraycopy(bytes, 0, samples, 0, bytes.length); return; } long maxValue = (long) Math.pow(2, bps0) - 1; if (photoInterp == PhotoInterp.CMYK) maxValue = Integer.MAX_VALUE; int skipBits = (int) (8 - ((imageWidth * bps0 * nChannels) % 8)); if (skipBits == 8 || (bytes.length * 8 < bps0 * (nChannels * imageWidth + imageHeight))) { skipBits = 0; } // set up YCbCr-specific values float lumaRed = PhotoInterp.LUMA_RED; float lumaGreen = PhotoInterp.LUMA_GREEN; float lumaBlue = PhotoInterp.LUMA_BLUE; int[] reference = ifd.getIFDIntArray(IFD.REFERENCE_BLACK_WHITE); if (reference == null) { reference = new int[] {0, 0, 0, 0, 0, 0}; } int[] subsampling = ifd.getIFDIntArray(IFD.Y_CB_CR_SUB_SAMPLING); TiffRational[] coefficients = (TiffRational[]) ifd.getIFDValue(IFD.Y_CB_CR_COEFFICIENTS); if (coefficients != null) { lumaRed = coefficients[0].floatValue(); lumaGreen = coefficients[1].floatValue(); lumaBlue = coefficients[2].floatValue(); } int subX = subsampling == null ? 2 : subsampling[0]; int subY = subsampling == null ? 2 : subsampling[1]; int block = subX * subY; int nTiles = (int) (imageWidth / subX); // unpack pixels for (int sample=0; sample<sampleCount; sample++) { int ndx = startIndex + sample; if (ndx >= nSamples) break; for (int channel=0; channel<nChannels; channel++) { int index = numBytes * (sample * nChannels + channel); int outputIndex = (channel * nSamples + ndx) * numBytes; // unpack non-YCbCr samples if (photoInterp != PhotoInterp.Y_CB_CR) { long value = 0; if (noDiv8) { // bits per sample is not a multiple of 8 if ((channel == 0 && photoInterp == PhotoInterp.RGB_PALETTE) || (photoInterp != PhotoInterp.CFA_ARRAY && photoInterp != PhotoInterp.RGB_PALETTE)) { value = bb.getBits(bps0) & 0xffff; if ((ndx % imageWidth) == imageWidth - 1) { bb.skipBits(skipBits); } } } else { value = DataTools.bytesToLong(bytes, index, numBytes, littleEndian); } if (photoInterp == PhotoInterp.WHITE_IS_ZERO || photoInterp == PhotoInterp.CMYK) { value = maxValue - value; } if (outputIndex + numBytes <= samples.length) { DataTools.unpackBytes(value, samples, outputIndex, numBytes, littleEndian); } } else { // unpack YCbCr samples; these need special handling, as each of // the RGB components depends upon two or more of the YCbCr components if (channel == nChannels - 1) { int lumaIndex = sample + (2 * (sample / block)); int chromaIndex = (sample / block) * (block + 2) + block; if (chromaIndex + 1 >= bytes.length) break; int tile = ndx / block; int pixel = ndx % block; long r = subY * (tile / nTiles) + (pixel / subX); long c = subX * (tile % nTiles) + (pixel % subX); int idx = (int) (r * imageWidth + c); if (idx < nSamples) { int y = (bytes[lumaIndex] & 0xff) - reference[0]; int cb = (bytes[chromaIndex] & 0xff) - reference[2]; int cr = (bytes[chromaIndex + 1] & 0xff) - reference[4]; int red = (int) (cr * (2 - 2 * lumaRed) + y); int blue = (int) (cb * (2 - 2 * lumaBlue) + y); int green = (int) ((y - lumaBlue * blue - lumaRed * red) / lumaGreen); samples[idx] = (byte) (red & 0xff); samples[nSamples + idx] = (byte) (green & 0xff); samples[2*nSamples + idx] = (byte) (blue & 0xff); } } } } } } /** * Read a file offset. * For bigTiff, a 64-bit number is read. For other Tiffs, a 32-bit number * is read and possibly adjusted for a possible carry-over from the previous * offset. */ long getNextOffset(long previous) throws IOException { if (bigTiff) { return in.readLong(); } long offset = (previous & ~0xffffffffL) | (in.readInt() & 0xffffffffL); // Only adjust the offset if we know that the file is too large for 32-bit // offsets to be accurate; otherwise, we're making the incorrect assumption // that IFDs are stored sequentially. if (offset < previous && offset != 0 && in.length() > Integer.MAX_VALUE) { offset += 0x100000000L; } return offset; } TiffIFDEntry readTiffIFDEntry() throws IOException { int entryTag = in.readUnsignedShort(); // Parse the entry's "Type" IFDType entryType = IFDType.get(in.readUnsignedShort()); // Parse the entry's "ValueCount" int valueCount = bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt(); if (valueCount < 0) { throw new RuntimeException("Count of '" + valueCount + "' unexpected."); } int nValueBytes = valueCount * entryType.getBytesPerElement(); int threshhold = bigTiff ? 8 : 4; long offset = nValueBytes > threshhold ? getNextOffset(0) : in.getFilePointer(); return new TiffIFDEntry(entryTag, entryType, valueCount, offset); } }
components/bio-formats/src/loci/formats/tiff/TiffParser.java
// // TiffParser.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.tiff; import java.io.IOException; import java.util.TreeSet; import java.util.Vector; import loci.common.DataTools; import loci.common.RandomAccessInputStream; import loci.common.Region; import loci.formats.FormatException; import loci.formats.codec.BitBuffer; import loci.formats.codec.CodecOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Parses TIFF data from an input source. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/tiff/TiffParser.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/tiff/TiffParser.java">SVN</a></dd></dl> * * @author Curtis Rueden ctrueden at wisc.edu * @author Eric Kjellman egkjellman at wisc.edu * @author Melissa Linkert linkert at wisc.edu * @author Chris Allan callan at blackcat.ca */ public class TiffParser { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(TiffParser.class); // -- Fields -- /** Input source from which to parse TIFF data. */ protected RandomAccessInputStream in; /** Cached tile buffer to avoid re-allocations when reading tiles. */ private byte[] cachedTileBuffer; /** Whether or not the TIFF file contains BigTIFF data. */ private boolean bigTiff; private boolean doCaching; /** Cached list of IFDs in the current file. */ private IFDList ifdList; /** Cached first IFD in the current file. */ private IFD firstIFD; // -- Constructors -- /** Constructs a new TIFF parser from the given file name. */ public TiffParser(String filename) throws IOException { this(new RandomAccessInputStream(filename)); } /** Constructs a new TIFF parser from the given input source. */ public TiffParser(RandomAccessInputStream in) { this.in = in; doCaching = true; } // -- TiffParser methods -- /** Sets whether or not IFD entries should be cached. */ public void setDoCaching(boolean doCaching) { this.doCaching = doCaching; } /** Gets the stream from which TIFF data is being parsed. */ public RandomAccessInputStream getStream() { return in; } /** Tests this stream to see if it represents a TIFF file. */ public boolean isValidHeader() { try { return checkHeader() != null; } catch (IOException e) { return false; } } /** * Checks the TIFF header. * * @return true if little-endian, * false if big-endian, * or null if not a TIFF. */ public Boolean checkHeader() throws IOException { if (in.length() < 4) return null; // byte order must be II or MM in.seek(0); int endianOne = in.read(); int endianTwo = in.read(); boolean littleEndian = endianOne == TiffConstants.LITTLE && endianTwo == TiffConstants.LITTLE; // II boolean bigEndian = endianOne == TiffConstants.BIG && endianTwo == TiffConstants.BIG; // MM if (!littleEndian && !bigEndian) return null; // check magic number (42) in.order(littleEndian); short magic = in.readShort(); bigTiff = magic == TiffConstants.BIG_TIFF_MAGIC_NUMBER; if (magic != TiffConstants.MAGIC_NUMBER && magic != TiffConstants.BIG_TIFF_MAGIC_NUMBER) { return null; } return new Boolean(littleEndian); } /** Returns whether or not the current TIFF file contains BigTIFF data. */ public boolean isBigTiff() { return bigTiff; } // -- TiffParser methods - IFD parsing -- /** Returns all IFDs in the file. */ public IFDList getIFDs() throws IOException { if (ifdList != null) return ifdList; long[] offsets = getIFDOffsets(); IFDList ifds = new IFDList(); for (long offset : offsets) { IFD ifd = getIFD(offset); if (ifd == null) continue; ifds.add(ifd); long[] subOffsets = null; try { subOffsets = ifd.getIFDLongArray(IFD.SUB_IFD); } catch (FormatException e) { } if (subOffsets != null) { for (long subOffset : subOffsets) { IFD sub = getIFD(subOffset); if (sub != null) { ifds.add(sub); } } } } if (doCaching) ifdList = ifds; return ifds; } /** Returns thumbnail IFDs. */ public IFDList getThumbnailIFDs() throws IOException { IFDList ifds = getIFDs(); IFDList thumbnails = new IFDList(); for (IFD ifd : ifds) { Number subfile = (Number) ifd.getIFDValue(IFD.NEW_SUBFILE_TYPE); int subfileType = subfile == null ? 0 : subfile.intValue(); if (subfileType == 1) { thumbnails.add(ifd); } } return thumbnails; } /** Returns non-thumbnail IFDs. */ public IFDList getNonThumbnailIFDs() throws IOException { IFDList ifds = getIFDs(); IFDList nonThumbs = new IFDList(); for (IFD ifd : ifds) { Number subfile = (Number) ifd.getIFDValue(IFD.NEW_SUBFILE_TYPE); int subfileType = subfile == null ? 0 : subfile.intValue(); if (subfileType != 1 || ifds.size() <= 1) { nonThumbs.add(ifd); } } return nonThumbs; } /** Returns EXIF IFDs. */ public IFDList getExifIFDs() throws FormatException, IOException { IFDList ifds = getIFDs(); IFDList exif = new IFDList(); for (IFD ifd : ifds) { long offset = ifd.getIFDLongValue(IFD.EXIF, 0); if (offset != 0) { IFD exifIFD = getIFD(offset); if (exifIFD != null) { exif.add(exifIFD); } } } return exif; } /** Gets the offsets to every IFD in the file. */ public long[] getIFDOffsets() throws IOException { // check TIFF header int bytesPerEntry = bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY; Vector<Long> offsets = new Vector<Long>(); long offset = getFirstOffset(); while (offset > 0 && offset < in.length()) { in.seek(offset); offsets.add(offset); int nEntries = bigTiff ? (int) in.readLong() : in.readUnsignedShort(); in.skipBytes(nEntries * bytesPerEntry); offset = getNextOffset(offset); } long[] f = new long[offsets.size()]; for (int i=0; i<f.length; i++) { f[i] = offsets.get(i).longValue(); } return f; } /** * Gets the first IFD within the TIFF file, or null * if the input source is not a valid TIFF file. */ public IFD getFirstIFD() throws IOException { if (firstIFD != null) return firstIFD; long offset = getFirstOffset(); IFD ifd = getIFD(offset); if (doCaching) firstIFD = ifd; return ifd; } /** * Retrieve a given entry from the first IFD in the stream. * * @param tag the tag of the entry to be retrieved. * @return an object representing the entry's fields. * @throws IOException when there is an error accessing the stream. * @throws IllegalArgumentException when the tag number is unknown. */ // TODO : Try to remove this method. It is only being used by // loci.formats.in.MetamorphReader. public TiffIFDEntry getFirstIFDEntry(int tag) throws IOException { // Get the offset of the first IFD long offset = getFirstOffset(); if (offset < 0) return null; // The following loosely resembles the logic of getIFD()... in.seek(offset); long numEntries = bigTiff ? in.readLong() : in.readUnsignedShort(); for (int i = 0; i < numEntries; i++) { in.seek(offset + // The beginning of the IFD (bigTiff ? 8 : 2) + // The width of the initial numEntries field (bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY) * i); TiffIFDEntry entry = readTiffIFDEntry(); if (entry.getTag() == tag) { return entry; } } throw new IllegalArgumentException("Unknown tag: " + tag); } /** * Gets offset to the first IFD, or -1 if stream is not TIFF. */ public long getFirstOffset() throws IOException { Boolean header = checkHeader(); if (header == null) return -1; if (bigTiff) in.skipBytes(4); return getNextOffset(0); } /** Gets the IFD stored at the given offset. */ public IFD getIFD(long offset) throws IOException { if (offset < 0) return null; IFD ifd = new IFD(); // save little-endian flag to internal LITTLE_ENDIAN tag ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(in.isLittleEndian())); ifd.put(new Integer(IFD.BIG_TIFF), new Boolean(bigTiff)); // read in directory entries for this IFD LOGGER.debug("getIFDs: seeking IFD at {}", offset); in.seek(offset); long numEntries = bigTiff ? in.readLong() : in.readUnsignedShort(); LOGGER.debug("getIFDs: {} directory entries to read", numEntries); if (numEntries == 0 || numEntries == 1) return ifd; int bytesPerEntry = bigTiff ? TiffConstants.BIG_TIFF_BYTES_PER_ENTRY : TiffConstants.BYTES_PER_ENTRY; int baseOffset = bigTiff ? 8 : 2; for (int i=0; i<numEntries; i++) { in.seek(offset + baseOffset + bytesPerEntry * i); TiffIFDEntry entry = readTiffIFDEntry(); int count = entry.getValueCount(); int tag = entry.getTag(); long pointer = entry.getValueOffset(); int bpe = entry.getType().getBytesPerElement(); if (count < 0 || bpe <= 0) { // invalid data in.skipBytes(bytesPerEntry - 4 - (bigTiff ? 8 : 4)); continue; } Object value = null; long inputLen = in.length(); if (count * bpe + pointer > inputLen) { int oldCount = count; count = (int) ((inputLen - pointer) / bpe); LOGGER.debug("getIFDs: truncated {} array elements for tag {}", (oldCount - count), tag); } if (count < 0 || count > in.length()) break; if (pointer != in.getFilePointer() && !doCaching) { value = entry; } else value = getIFDValue(entry); if (value != null && !ifd.containsKey(new Integer(tag))) { ifd.put(new Integer(tag), value); } } in.seek(offset + baseOffset + bytesPerEntry * numEntries); return ifd; } /** Fill in IFD entries that are stored at an arbitrary offset. */ public void fillInIFD(IFD ifd) throws IOException { TreeSet<TiffIFDEntry> entries = new TreeSet<TiffIFDEntry>(); for (Object key : ifd.keySet()) { if (ifd.get(key) instanceof TiffIFDEntry) { entries.add((TiffIFDEntry) ifd.get(key)); } } for (TiffIFDEntry entry : entries) { ifd.put(new Integer(entry.getTag()), getIFDValue(entry)); } } /** Retrieve the value corresponding to the given TiffIFDEntry. */ public Object getIFDValue(TiffIFDEntry entry) throws IOException { IFDType type = entry.getType(); int count = entry.getValueCount(); long offset = entry.getValueOffset(); LOGGER.debug("Reading entry {} from {}; type={}, count={}", new Object[] {entry.getTag(), offset, type, count}); if (offset != in.getFilePointer()) { in.seek(offset); } if (type == IFDType.BYTE) { // 8-bit unsigned integer if (count == 1) return new Short(in.readByte()); byte[] bytes = new byte[count]; in.readFully(bytes); // bytes are unsigned, so use shorts short[] shorts = new short[count]; for (int j=0; j<count; j++) shorts[j] = (short) (bytes[j] & 0xff); return shorts; } else if (type == IFDType.ASCII) { // 8-bit byte that contain a 7-bit ASCII code; // the last byte must be NUL (binary zero) byte[] ascii = new byte[count]; in.read(ascii); // count number of null terminators int nullCount = 0; for (int j=0; j<count; j++) { if (ascii[j] == 0 || j == count - 1) nullCount++; } // convert character array to array of strings String[] strings = nullCount == 1 ? null : new String[nullCount]; String s = null; int c = 0, ndx = -1; for (int j=0; j<count; j++) { if (ascii[j] == 0) { s = new String(ascii, ndx + 1, j - ndx - 1); ndx = j; } else if (j == count - 1) { // handle non-null-terminated strings s = new String(ascii, ndx + 1, j - ndx); } else s = null; if (strings != null && s != null) strings[c++] = s; } return strings == null ? (Object) s : strings; } else if (type == IFDType.SHORT) { // 16-bit (2-byte) unsigned integer if (count == 1) return new Integer(in.readUnsignedShort()); int[] shorts = new int[count]; for (int j=0; j<count; j++) { shorts[j] = in.readUnsignedShort(); } return shorts; } else if (type == IFDType.LONG || type == IFDType.IFD) { // 32-bit (4-byte) unsigned integer if (count == 1) return new Long(in.readInt()); long[] longs = new long[count]; for (int j=0; j<count; j++) { if (in.getFilePointer() + 4 <= in.length()) { longs[j] = in.readInt(); } } return longs; } else if (type == IFDType.LONG8 || type == IFDType.SLONG8 || type == IFDType.IFD8) { if (count == 1) return new Long(in.readLong()); long[] longs = new long[count]; for (int j=0; j<count; j++) longs[j] = in.readLong(); return longs; } else if (type == IFDType.RATIONAL || type == IFDType.SRATIONAL) { // Two LONGs or SLONGs: the first represents the numerator // of a fraction; the second, the denominator if (count == 1) return new TiffRational(in.readInt(), in.readInt()); TiffRational[] rationals = new TiffRational[count]; for (int j=0; j<count; j++) { rationals[j] = new TiffRational(in.readInt(), in.readInt()); } return rationals; } else if (type == IFDType.SBYTE || type == IFDType.UNDEFINED) { // SBYTE: An 8-bit signed (twos-complement) integer // UNDEFINED: An 8-bit byte that may contain anything, // depending on the definition of the field if (count == 1) return new Byte(in.readByte()); byte[] sbytes = new byte[count]; in.read(sbytes); return sbytes; } else if (type == IFDType.SSHORT) { // A 16-bit (2-byte) signed (twos-complement) integer if (count == 1) return new Short(in.readShort()); short[] sshorts = new short[count]; for (int j=0; j<count; j++) sshorts[j] = in.readShort(); return sshorts; } else if (type == IFDType.SLONG) { // A 32-bit (4-byte) signed (twos-complement) integer if (count == 1) return new Integer(in.readInt()); int[] slongs = new int[count]; for (int j=0; j<count; j++) slongs[j] = in.readInt(); return slongs; } else if (type == IFDType.FLOAT) { // Single precision (4-byte) IEEE format if (count == 1) return new Float(in.readFloat()); float[] floats = new float[count]; for (int j=0; j<count; j++) floats[j] = in.readFloat(); return floats; } else if (type == IFDType.DOUBLE) { // Double precision (8-byte) IEEE format if (count == 1) return new Double(in.readDouble()); double[] doubles = new double[count]; for (int j=0; j<count; j++) { doubles[j] = in.readDouble(); } return doubles; } return null; } /** Convenience method for obtaining a stream's first ImageDescription. */ public String getComment() throws IOException { IFD firstIFD = getFirstIFD(); return firstIFD == null ? null : firstIFD.getComment(); } // -- TiffParser methods - image reading -- public byte[] getTile(IFD ifd, byte[] buf, int row, int col) throws FormatException, IOException { byte[] jpegTable = (byte[]) ifd.getIFDValue(IFD.JPEG_TABLES); CodecOptions options = new CodecOptions(); options.interleaved = true; options.littleEndian = ifd.isLittleEndian(); long tileWidth = ifd.getTileWidth(); long tileLength = ifd.getTileLength(); int samplesPerPixel = ifd.getSamplesPerPixel(); int planarConfig = ifd.getPlanarConfiguration(); TiffCompression compression = ifd.getCompression(); long numTileCols = ifd.getTilesPerRow(); int pixel = ifd.getBytesPerSample()[0]; int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel; long[] stripOffsets = ifd.getStripOffsets(); long[] stripByteCounts = ifd.getStripByteCounts(); long[] rowsPerStrip = ifd.getRowsPerStrip(); int tileNumber = (int) (row * numTileCols + col); if (stripByteCounts[tileNumber] == (rowsPerStrip[0] * tileWidth) && pixel > 1) { stripByteCounts[tileNumber] *= pixel; } int size = (int) (tileWidth * tileLength * pixel * effectiveChannels); if (buf == null) buf = new byte[size]; if (stripByteCounts[tileNumber] == 0 || stripOffsets[tileNumber] >= in.length()) { return buf; } byte[] tile = new byte[(int) stripByteCounts[tileNumber]]; in.seek(stripOffsets[tileNumber]); in.read(tile); options.maxBytes = size; if (jpegTable != null) { byte[] q = new byte[jpegTable.length + tile.length - 4]; System.arraycopy(jpegTable, 0, q, 0, jpegTable.length - 2); System.arraycopy(tile, 2, q, jpegTable.length - 2, tile.length - 2); tile = compression.decompress(q, options); } else tile = compression.decompress(tile, options); TiffCompression.undifference(tile, ifd); unpackBytes(buf, 0, tile, ifd); return buf; } public byte[] getSamples(IFD ifd, byte[] buf) throws FormatException, IOException { long width = ifd.getImageWidth(); long length = ifd.getImageLength(); return getSamples(ifd, buf, 0, 0, width, length); } public byte[] getSamples(IFD ifd, byte[] buf, int x, int y, long width, long height) throws FormatException, IOException { LOGGER.debug("parsing IFD entries"); // get internal non-IFD entries boolean littleEndian = ifd.isLittleEndian(); in.order(littleEndian); // get relevant IFD entries int samplesPerPixel = ifd.getSamplesPerPixel(); long tileWidth = ifd.getTileWidth(); long tileLength = ifd.getTileLength(); if (tileLength <= 0) { LOGGER.debug("Tile length is {}; setting it to {}", tileLength, height); tileLength = height; } long numTileRows = ifd.getTilesPerColumn(); long numTileCols = ifd.getTilesPerRow(); PhotoInterp photoInterp = ifd.getPhotometricInterpretation(); int planarConfig = ifd.getPlanarConfiguration(); int pixel = ifd.getBytesPerSample()[0]; int effectiveChannels = planarConfig == 2 ? 1 : samplesPerPixel; ifd.printIFD(); if (width * height > Integer.MAX_VALUE) { throw new FormatException("Sorry, ImageWidth x ImageLength > " + Integer.MAX_VALUE + " is not supported (" + width + " x " + height + ")"); } if (width * height * effectiveChannels * pixel > Integer.MAX_VALUE) { throw new FormatException("Sorry, ImageWidth x ImageLength x " + "SamplesPerPixel x BitsPerSample > " + Integer.MAX_VALUE + " is not supported (" + width + " x " + height + " x " + samplesPerPixel + " x " + (pixel * 8) + ")"); } // casting to int is safe because we have already determined that // width * height is less than Integer.MAX_VALUE int numSamples = (int) (width * height); // read in image strips LOGGER.debug("reading image data (samplesPerPixel={}; numSamples={})", samplesPerPixel, numSamples); TiffCompression compression = ifd.getCompression(); // special case: if we only need one tile, and that tile doesn't need // any special handling, then we can just read it directly and return if ((x % tileWidth) == 0 && (y % tileLength) == 0 && width == tileWidth && height == tileLength && samplesPerPixel == 1 && (ifd.getBitsPerSample()[0] % 8) == 0 && photoInterp != PhotoInterp.WHITE_IS_ZERO && photoInterp != PhotoInterp.CMYK && photoInterp != PhotoInterp.Y_CB_CR && compression == TiffCompression.UNCOMPRESSED) { long[] stripOffsets = ifd.getStripOffsets(); long[] stripByteCounts = ifd.getStripByteCounts(); int tile = (int) ((y / tileLength) * numTileCols + (x / tileWidth)); if (stripByteCounts[tile] == numSamples && pixel > 1) { stripByteCounts[tile] *= pixel; } in.seek(stripOffsets[tile]); in.read(buf, 0, (int) Math.min(buf.length, stripByteCounts[tile])); return buf; } long nrows = numTileRows; if (planarConfig == 2) numTileRows *= samplesPerPixel; Region imageBounds = new Region(x, y, (int) width, (int) (height * (samplesPerPixel / effectiveChannels))); int endX = (int) width + x; int endY = (int) height + y; int rowLen = pixel * (int) tileWidth; int tileSize = (int) (rowLen * tileLength); int planeSize = (int) (width * height * pixel); int outputRowLen = (int) (pixel * width); int bufferSizeSamplesPerPixel = samplesPerPixel; if (ifd.getPlanarConfiguration() == 2) bufferSizeSamplesPerPixel = 1; int bpp = ifd.getBytesPerSample()[0]; int bufferSize = (int) tileWidth * (int) tileLength * bufferSizeSamplesPerPixel * bpp; if (cachedTileBuffer == null || cachedTileBuffer.length != bufferSize) { cachedTileBuffer = new byte[bufferSize]; } Region tileBounds = new Region(0, 0, (int) tileWidth, (int) tileLength); for (int row=0; row<numTileRows; row++) { for (int col=0; col<numTileCols; col++) { tileBounds.x = col * (int) tileWidth; tileBounds.y = row * (int) tileLength; if (!imageBounds.intersects(tileBounds)) continue; if (planarConfig == 2) { tileBounds.y = (int) ((row % nrows) * tileLength); } getTile(ifd, cachedTileBuffer, row, col); // adjust tile bounds, if necessary int tileX = (int) Math.max(tileBounds.x, x); int tileY = (int) Math.max(tileBounds.y, y); int realX = tileX % (int) tileWidth; int realY = tileY % (int) tileLength; int twidth = (int) Math.min(endX - tileX, tileWidth - realX); int theight = (int) Math.min(endY - tileY, tileLength - realY); // copy appropriate portion of the tile to the output buffer int copy = pixel * twidth; realX *= pixel; realY *= rowLen; for (int q=0; q<effectiveChannels; q++) { int src = (int) (q * tileSize) + realX + realY; int dest = (int) (q * planeSize) + pixel * (tileX - x) + outputRowLen * (tileY - y); if (planarConfig == 2) dest += (planeSize * (row / nrows)); for (int tileRow=0; tileRow<theight; tileRow++) { System.arraycopy(cachedTileBuffer, src, buf, dest, copy); src += rowLen; dest += outputRowLen; } } } } return buf; } // -- Utility methods - byte stream decoding -- /** * Extracts pixel information from the given byte array according to the * bits per sample, photometric interpretation and color map IFD directory * entry values, and the specified byte ordering. * No error checking is performed. */ public static void unpackBytes(byte[] samples, int startIndex, byte[] bytes, IFD ifd) throws FormatException { boolean planar = ifd.getPlanarConfiguration() == 2; TiffCompression compression = ifd.getCompression(); PhotoInterp photoInterp = ifd.getPhotometricInterpretation(); if (compression == TiffCompression.JPEG) photoInterp = PhotoInterp.RGB; int[] bitsPerSample = ifd.getBitsPerSample(); int nChannels = bitsPerSample.length; int sampleCount = (8 * bytes.length) / (nChannels * bitsPerSample[0]); if (photoInterp == PhotoInterp.Y_CB_CR) sampleCount *= 3; if (planar) { sampleCount *= nChannels; nChannels = 1; } LOGGER.debug( "unpacking {} samples (startIndex={}; totalBits={}; numBytes={})", new Object[] {sampleCount, startIndex, nChannels * bitsPerSample[0], bytes.length}); long imageWidth = ifd.getImageWidth(); long imageHeight = ifd.getImageLength(); int bps0 = bitsPerSample[0]; int numBytes = ifd.getBytesPerSample()[0]; int nSamples = samples.length / (nChannels * numBytes); boolean noDiv8 = bps0 % 8 != 0; boolean bps8 = bps0 == 8; boolean bps16 = bps0 == 16; boolean littleEndian = ifd.isLittleEndian(); BitBuffer bb = new BitBuffer(bytes); // Hyper optimisation that takes any 8-bit or 16-bit data, where there is // only one channel, the source byte buffer's size is less than or equal to // that of the destination buffer and for which no special unpacking is // required and performs a simple array copy. Over the course of reading // semi-large datasets this can save **billions** of method calls. // Wed Aug 5 19:04:59 BST 2009 // Chris Allan <[email protected]> if ((bps8 || bps16) && bytes.length <= samples.length && nChannels == 1 && photoInterp != PhotoInterp.WHITE_IS_ZERO && photoInterp != PhotoInterp.CMYK && photoInterp != PhotoInterp.Y_CB_CR) { System.arraycopy(bytes, 0, samples, 0, bytes.length); return; } long maxValue = (long) Math.pow(2, bps0) - 1; if (photoInterp == PhotoInterp.CMYK) maxValue = Integer.MAX_VALUE; int skipBits = (int) (8 - ((imageWidth * bps0 * nChannels) % 8)); if (skipBits == 8 || (bytes.length * 8 < bps0 * (nChannels * imageWidth + imageHeight))) { skipBits = 0; } // set up YCbCr-specific values float lumaRed = PhotoInterp.LUMA_RED; float lumaGreen = PhotoInterp.LUMA_GREEN; float lumaBlue = PhotoInterp.LUMA_BLUE; int[] reference = ifd.getIFDIntArray(IFD.REFERENCE_BLACK_WHITE); if (reference == null) { reference = new int[] {0, 0, 0, 0, 0, 0}; } int[] subsampling = ifd.getIFDIntArray(IFD.Y_CB_CR_SUB_SAMPLING); TiffRational[] coefficients = (TiffRational[]) ifd.getIFDValue(IFD.Y_CB_CR_COEFFICIENTS); if (coefficients != null) { lumaRed = coefficients[0].floatValue(); lumaGreen = coefficients[1].floatValue(); lumaBlue = coefficients[2].floatValue(); } int subX = subsampling == null ? 2 : subsampling[0]; int subY = subsampling == null ? 2 : subsampling[1]; int block = subX * subY; int nTiles = (int) (imageWidth / subX); // unpack pixels for (int sample=0; sample<sampleCount; sample++) { int ndx = startIndex + sample; if (ndx >= nSamples) break; for (int channel=0; channel<nChannels; channel++) { int index = numBytes * (sample * nChannels + channel); int outputIndex = (channel * nSamples + ndx) * numBytes; // unpack non-YCbCr samples if (photoInterp != PhotoInterp.Y_CB_CR) { long value = 0; if (noDiv8) { // bits per sample is not a multiple of 8 if ((channel == 0 && photoInterp == PhotoInterp.RGB_PALETTE) || (photoInterp != PhotoInterp.CFA_ARRAY && photoInterp != PhotoInterp.RGB_PALETTE)) { value = bb.getBits(bps0) & 0xffff; if ((ndx % imageWidth) == imageWidth - 1) { bb.skipBits(skipBits); } } } else { value = DataTools.bytesToLong(bytes, index, numBytes, littleEndian); } if (photoInterp == PhotoInterp.WHITE_IS_ZERO || photoInterp == PhotoInterp.CMYK) { value = maxValue - value; } if (outputIndex + numBytes <= samples.length) { DataTools.unpackBytes(value, samples, outputIndex, numBytes, littleEndian); } } else { // unpack YCbCr samples; these need special handling, as each of // the RGB components depends upon two or more of the YCbCr components if (channel == nChannels - 1) { int lumaIndex = sample + (2 * (sample / block)); int chromaIndex = (sample / block) * (block + 2) + block; if (chromaIndex + 1 >= bytes.length) break; int tile = ndx / block; int pixel = ndx % block; long r = subY * (tile / nTiles) + (pixel / subX); long c = subX * (tile % nTiles) + (pixel % subX); int idx = (int) (r * imageWidth + c); if (idx < nSamples) { int y = (bytes[lumaIndex] & 0xff) - reference[0]; int cb = (bytes[chromaIndex] & 0xff) - reference[2]; int cr = (bytes[chromaIndex + 1] & 0xff) - reference[4]; int red = (int) (cr * (2 - 2 * lumaRed) + y); int blue = (int) (cb * (2 - 2 * lumaBlue) + y); int green = (int) ((y - lumaBlue * blue - lumaRed * red) / lumaGreen); samples[idx] = (byte) (red & 0xff); samples[nSamples + idx] = (byte) (green & 0xff); samples[2*nSamples + idx] = (byte) (blue & 0xff); } } } } } } /** * Read a file offset. * For bigTiff, a 64-bit number is read. For other Tiffs, a 32-bit number * is read and possibly adjusted for a possible carry-over from the previous * offset. */ long getNextOffset(long previous) throws IOException { if (bigTiff) { return in.readLong(); } long offset = (previous & ~0xffffffffL) | (in.readInt() & 0xffffffffL); // Only adjust the offset if we know that the file is too large for 32-bit // offsets to be accurate; otherwise, we're making the incorrect assumption // that IFDs are stored sequentially. if (offset < previous && offset != 0 && in.length() > Integer.MAX_VALUE) { offset += 0x100000000L; } return offset; } TiffIFDEntry readTiffIFDEntry() throws IOException { int entryTag = in.readUnsignedShort(); // Parse the entry's "Type" IFDType entryType = IFDType.get(in.readUnsignedShort()); // Parse the entry's "ValueCount" int valueCount = bigTiff ? (int) (in.readLong() & 0xffffffff) : in.readInt(); if (valueCount < 0) { throw new RuntimeException("Count of '" + valueCount + "' unexpected."); } int nValueBytes = valueCount * entryType.getBytesPerElement(); int threshhold = bigTiff ? 8 : 4; long offset = nValueBytes > threshhold ? getNextOffset(0) : in.getFilePointer(); return new TiffIFDEntry(entryTag, entryType, valueCount, offset); } }
Don't attempt to read IFDs with offsets beyond the end of the file.
components/bio-formats/src/loci/formats/tiff/TiffParser.java
Don't attempt to read IFDs with offsets beyond the end of the file.
<ide><path>omponents/bio-formats/src/loci/formats/tiff/TiffParser.java <ide> <ide> /** Gets the IFD stored at the given offset. */ <ide> public IFD getIFD(long offset) throws IOException { <del> if (offset < 0) return null; <add> if (offset < 0 || offset >= in.length()) return null; <ide> IFD ifd = new IFD(); <ide> <ide> // save little-endian flag to internal LITTLE_ENDIAN tag
Java
mit
error: pathspec 'src/main/java/com/carpoolbuddy/data/dao/DaoResult.java' did not match any file(s) known to git
7ae3030396ae009d20afed9129ce8d7c54c73093
1
ceilfors/experian-hackathon-0,ceilfors/experian-hackathon-0
package com.carpoolbuddy.data.dao; /** * Created with IntelliJ IDEA. * User: alexus * Date: 11/4/13 * Time: 3:14 PM * To change this template use File | Settings | File Templates. */ public enum DaoResult { RECORD_ALREADY_EXIST, RECORD_CREATED_SUCCESSFULLY, RECORD_CREATION_FAILED }
src/main/java/com/carpoolbuddy/data/dao/DaoResult.java
Add DaoResult back in
src/main/java/com/carpoolbuddy/data/dao/DaoResult.java
Add DaoResult back in
<ide><path>rc/main/java/com/carpoolbuddy/data/dao/DaoResult.java <add>package com.carpoolbuddy.data.dao; <add> <add>/** <add> * Created with IntelliJ IDEA. <add> * User: alexus <add> * Date: 11/4/13 <add> * Time: 3:14 PM <add> * To change this template use File | Settings | File Templates. <add> */ <add>public enum DaoResult { <add> RECORD_ALREADY_EXIST, <add> RECORD_CREATED_SUCCESSFULLY, <add> RECORD_CREATION_FAILED <add>}
Java
bsd-3-clause
ea4434c9d32a6e16e741fe94c291c0a8f980ed33
0
e-mission/e-mission-data-collection,e-mission/e-mission-data-collection,e-mission/e-mission-data-collection
package edu.berkeley.eecs.emission.cordova.tracker; import edu.berkeley.eecs.emission.R; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.preference.PreferenceManager; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.location.LocationRequest; import com.google.gson.Gson; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import edu.berkeley.eecs.emission.*; import edu.berkeley.eecs.emission.cordova.tracker.location.TripDiaryStateMachineService; import edu.berkeley.eecs.emission.cordova.tracker.location.TripDiaryStateMachineForegroundService; import edu.berkeley.eecs.emission.cordova.tracker.location.TripDiaryStateMachineReceiver; import edu.berkeley.eecs.emission.cordova.tracker.wrapper.ConsentConfig; import edu.berkeley.eecs.emission.cordova.tracker.wrapper.LocationTrackingConfig; import edu.berkeley.eecs.emission.cordova.tracker.wrapper.StatsEvent; import edu.berkeley.eecs.emission.cordova.tracker.verification.SensorControlForegroundDelegate; import edu.berkeley.eecs.emission.cordova.unifiedlogger.Log; import edu.berkeley.eecs.emission.cordova.usercache.BuiltinUserCache; public class DataCollectionPlugin extends CordovaPlugin { public static final String TAG = "DataCollectionPlugin"; private SensorControlForegroundDelegate mControlDelegate = null; @Override public void pluginInitialize() { mControlDelegate = new SensorControlForegroundDelegate(this, cordova); final Activity myActivity = cordova.getActivity(); BuiltinUserCache.getDatabase(myActivity).putMessage(R.string.key_usercache_client_nav_event, new StatsEvent(myActivity, R.string.app_launched)); TripDiaryStateMachineReceiver.initOnUpgrade(myActivity); } @Override public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) throws JSONException { if (action.equals("launchInit")) { Log.d(cordova.getActivity(), TAG, "application launched, init is nop on android"); callbackContext.success(); return true; } else if (action.equals("markConsented")) { Log.d(cordova.getActivity(), TAG, "marking consent as done"); Context ctxt = cordova.getActivity(); JSONObject newConsent = data.getJSONObject(0); ConsentConfig cfg = new Gson().fromJson(newConsent.toString(), ConsentConfig.class); ConfigManager.setConsented(ctxt, cfg); // TripDiaryStateMachineForegroundService.startProperly(cordova.getActivity().getApplication()); // Now, really initialize the state machine // Note that we don't call initOnUpgrade so that we can handle the case where the // user deleted the consent and re-consented, but didn't upgrade the app // mControlDelegate.checkAndPromptPermissions(); ctxt.sendBroadcast(new ExplicitIntent(ctxt, R.string.transition_initialize)); // TripDiaryStateMachineReceiver.restartCollection(ctxt); callbackContext.success(); return true; } else if (action.equals("fixLocationSettings")) { Log.d(cordova.getActivity(), TAG, "fixing location settings"); mControlDelegate.checkAndPromptLocationSettings(callbackContext); return true; } else if (action.equals("isValidLocationSettings")) { Log.d(cordova.getActivity(), TAG, "checking location settings"); mControlDelegate.checkLocationSettings(callbackContext); return true; } else if (action.equals("fixLocationPermissions")) { Log.d(cordova.getActivity(), TAG, "fixing location permissions"); mControlDelegate.checkAndPromptLocationPermissions(callbackContext); return true; } else if (action.equals("isValidLocationPermissions")) { Log.d(cordova.getActivity(), TAG, "checking location permissions"); mControlDelegate.checkLocationPermissions(callbackContext); return true; } else if (action.equals("fixFitnessPermissions")) { Log.d(cordova.getActivity(), TAG, "fixing fitness permissions"); mControlDelegate.checkAndPromptMotionActivityPermissions(callbackContext); return true; } else if (action.equals("isValidFitnessPermissions")) { Log.d(cordova.getActivity(), TAG, "checking fitness permissions"); mControlDelegate.checkMotionActivityPermissions(callbackContext); return true; } else if (action.equals("fixShowNotifications")) { Log.d(cordova.getActivity(), TAG, "fixing notification enable"); mControlDelegate.checkAndPromptShowNotificationsEnabled(callbackContext); return true; } else if (action.equals("isValidShowNotifications")) { Log.d(cordova.getActivity(), TAG, "checking notification enable"); mControlDelegate.checkShowNotificationsEnabled(callbackContext); return true; } else if (action.equals("isNotificationsUnpaused")) { Log.d(cordova.getActivity(), TAG, "checking notification unpause"); mControlDelegate.checkPausedNotifications(callbackContext); return true; } else if (action.equals("fixUnusedAppRestrictions")) { Log.d(cordova.getActivity(), TAG, "fixing unused app restrictions"); mControlDelegate.checkAndPromptUnusedAppsUnrestricted(callbackContext); return true; } else if (action.equals("isUnusedAppUnrestricted")) { Log.d(cordova.getActivity(), TAG, "checking unused app restrictions"); mControlDelegate.checkUnusedAppsUnrestricted(callbackContext); return true; } else if (action.equals("storeBatteryLevel")) { Context ctxt = cordova.getActivity(); TripDiaryStateMachineReceiver.saveBatteryAndSimulateUser(ctxt); callbackContext.success(); } else if (action.equals("getConfig")) { Context ctxt = cordova.getActivity(); LocationTrackingConfig cfg = ConfigManager.getConfig(ctxt); // Gson.toJson() represents a string and we are expecting an object in the interface callbackContext.success(new JSONObject(new Gson().toJson(cfg))); return true; } else if (action.equals("setConfig")) { Context ctxt = cordova.getActivity(); JSONObject newConfig = data.getJSONObject(0); LocationTrackingConfig cfg = new Gson().fromJson(newConfig.toString(), LocationTrackingConfig.class); ConfigManager.updateConfig(ctxt, cfg); TripDiaryStateMachineReceiver.restartCollection(ctxt); callbackContext.success(); return true; } else if (action.equals("getState")) { Context ctxt = cordova.getActivity(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctxt); String state = prefs.getString(ctxt.getString(R.string.curr_state_key), ctxt.getString(R.string.state_start)); callbackContext.success(state); return true; } else if (action.equals("forceTransition")) { // we want to run this in a background thread because it might sometimes wait to get // the current location final String generalTransition = data.getString(0); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { Context ctxt = cordova.getActivity(); Map<String, String> transitionMap = getTransitionMap(ctxt); if (transitionMap.containsKey(generalTransition)) { String androidTransition = transitionMap.get(generalTransition); ctxt.sendBroadcast(new ExplicitIntent(ctxt, androidTransition)); callbackContext.success(androidTransition); } else { callbackContext.error(generalTransition + " not supported, ignoring"); } } }); return true; } else if (action.equals("handleSilentPush")) { throw new UnsupportedOperationException("silent push handling not supported for android"); } else if (action.equals("getAccuracyOptions")) { JSONObject retVal = new JSONObject(); retVal.put("PRIORITY_HIGH_ACCURACY", LocationRequest.PRIORITY_HIGH_ACCURACY); retVal.put("PRIORITY_BALANCED_POWER_ACCURACY", LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); retVal.put("PRIORITY_LOW_POWER", LocationRequest.PRIORITY_LOW_POWER); retVal.put("PRIORITY_NO_POWER", LocationRequest.PRIORITY_NO_POWER); callbackContext.success(retVal); return true; } return false; } private static Map<String, String> getTransitionMap(Context ctxt) { Map<String, String> retVal = new HashMap<String, String>(); retVal.put("INITIALIZE", ctxt.getString(R.string.transition_initialize)); retVal.put("EXITED_GEOFENCE", ctxt.getString(R.string.transition_exited_geofence)); retVal.put("STOPPED_MOVING", ctxt.getString(R.string.transition_stopped_moving)); retVal.put("STOP_TRACKING", ctxt.getString(R.string.transition_stop_tracking)); retVal.put("START_TRACKING", ctxt.getString(R.string.transition_start_tracking)); return retVal; } @Override public void onNewIntent(Intent intent) { Context mAct = cordova.getActivity(); Log.d(mAct, TAG, "onNewIntent(" + intent.getAction() + ")"); Log.d(mAct, TAG, "Found extras " + intent.getExtras()); // this is will be NOP if we are not handling the right intent mControlDelegate.onNewIntent(intent); // This is where we can add other intent handlers } @Override public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { // This will be a NOP if we are not requesting the right permission mControlDelegate.onRequestPermissionResult(requestCode, permissions, grantResults); // This is where we can add other permission callbacks } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (data == null) { Log.d(cordova.getActivity(), TAG, "received onActivityResult(" + requestCode + "," + resultCode + "," + "null data" + ")"); } else { Log.d(cordova.getActivity(), TAG, "received onActivityResult("+requestCode+","+ resultCode+","+data.getDataString()+")"); } // This will be a NOP if we are not handling the correct activity intent mControlDelegate.onActivityResult(requestCode, resultCode, data); /* This is where we would handle other cases for activity results switch (requestCode) { default: Log.d(cordova.getActivity(), TAG, "Got unsupported request code "+requestCode+ " , ignoring..."); } */ } }
src/android/DataCollectionPlugin.java
package edu.berkeley.eecs.emission.cordova.tracker; import edu.berkeley.eecs.emission.R; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.preference.PreferenceManager; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.location.LocationRequest; import com.google.gson.Gson; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import edu.berkeley.eecs.emission.*; import edu.berkeley.eecs.emission.cordova.tracker.location.TripDiaryStateMachineService; import edu.berkeley.eecs.emission.cordova.tracker.location.TripDiaryStateMachineForegroundService; import edu.berkeley.eecs.emission.cordova.tracker.location.TripDiaryStateMachineReceiver; import edu.berkeley.eecs.emission.cordova.tracker.wrapper.ConsentConfig; import edu.berkeley.eecs.emission.cordova.tracker.wrapper.LocationTrackingConfig; import edu.berkeley.eecs.emission.cordova.tracker.wrapper.StatsEvent; import edu.berkeley.eecs.emission.cordova.tracker.verification.SensorControlForegroundDelegate; import edu.berkeley.eecs.emission.cordova.unifiedlogger.Log; import edu.berkeley.eecs.emission.cordova.usercache.BuiltinUserCache; public class DataCollectionPlugin extends CordovaPlugin { public static final String TAG = "DataCollectionPlugin"; private SensorControlForegroundDelegate mControlDelegate = null; @Override public void pluginInitialize() { mControlDelegate = new SensorControlForegroundDelegate(this, cordova); final Activity myActivity = cordova.getActivity(); BuiltinUserCache.getDatabase(myActivity).putMessage(R.string.key_usercache_client_nav_event, new StatsEvent(myActivity, R.string.app_launched)); TripDiaryStateMachineReceiver.initOnUpgrade(myActivity); } @Override public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) throws JSONException { if (action.equals("launchInit")) { Log.d(cordova.getActivity(), TAG, "application launched, init is nop on android"); callbackContext.success(); return true; } else if (action.equals("markConsented")) { Log.d(cordova.getActivity(), TAG, "marking consent as done"); Context ctxt = cordova.getActivity(); JSONObject newConsent = data.getJSONObject(0); ConsentConfig cfg = new Gson().fromJson(newConsent.toString(), ConsentConfig.class); ConfigManager.setConsented(ctxt, cfg); TripDiaryStateMachineForegroundService.startProperly(cordova.getActivity().getApplication()); // Now, really initialize the state machine // Note that we don't call initOnUpgrade so that we can handle the case where the // user deleted the consent and re-consented, but didn't upgrade the app // mControlDelegate.checkAndPromptPermissions(); // ctxt.sendBroadcast(new ExplicitIntent(ctxt, R.string.transition_initialize)); // TripDiaryStateMachineReceiver.restartCollection(ctxt); callbackContext.success(); return true; } else if (action.equals("fixLocationSettings")) { Log.d(cordova.getActivity(), TAG, "fixing location settings"); mControlDelegate.checkAndPromptLocationSettings(callbackContext); return true; } else if (action.equals("isValidLocationSettings")) { Log.d(cordova.getActivity(), TAG, "checking location settings"); mControlDelegate.checkLocationSettings(callbackContext); return true; } else if (action.equals("fixLocationPermissions")) { Log.d(cordova.getActivity(), TAG, "fixing location permissions"); mControlDelegate.checkAndPromptLocationPermissions(callbackContext); return true; } else if (action.equals("isValidLocationPermissions")) { Log.d(cordova.getActivity(), TAG, "checking location permissions"); mControlDelegate.checkLocationPermissions(callbackContext); return true; } else if (action.equals("fixFitnessPermissions")) { Log.d(cordova.getActivity(), TAG, "fixing fitness permissions"); mControlDelegate.checkAndPromptMotionActivityPermissions(callbackContext); return true; } else if (action.equals("isValidFitnessPermissions")) { Log.d(cordova.getActivity(), TAG, "checking fitness permissions"); mControlDelegate.checkMotionActivityPermissions(callbackContext); return true; } else if (action.equals("fixShowNotifications")) { Log.d(cordova.getActivity(), TAG, "fixing notification enable"); mControlDelegate.checkAndPromptShowNotificationsEnabled(callbackContext); return true; } else if (action.equals("isValidShowNotifications")) { Log.d(cordova.getActivity(), TAG, "checking notification enable"); mControlDelegate.checkShowNotificationsEnabled(callbackContext); return true; } else if (action.equals("isNotificationsUnpaused")) { Log.d(cordova.getActivity(), TAG, "checking notification unpause"); mControlDelegate.checkPausedNotifications(callbackContext); return true; } else if (action.equals("fixUnusedAppRestrictions")) { Log.d(cordova.getActivity(), TAG, "fixing unused app restrictions"); mControlDelegate.checkAndPromptUnusedAppsUnrestricted(callbackContext); return true; } else if (action.equals("isUnusedAppUnrestricted")) { Log.d(cordova.getActivity(), TAG, "checking unused app restrictions"); mControlDelegate.checkUnusedAppsUnrestricted(callbackContext); return true; } else if (action.equals("storeBatteryLevel")) { Context ctxt = cordova.getActivity(); TripDiaryStateMachineReceiver.saveBatteryAndSimulateUser(ctxt); callbackContext.success(); } else if (action.equals("getConfig")) { Context ctxt = cordova.getActivity(); LocationTrackingConfig cfg = ConfigManager.getConfig(ctxt); // Gson.toJson() represents a string and we are expecting an object in the interface callbackContext.success(new JSONObject(new Gson().toJson(cfg))); return true; } else if (action.equals("setConfig")) { Context ctxt = cordova.getActivity(); JSONObject newConfig = data.getJSONObject(0); LocationTrackingConfig cfg = new Gson().fromJson(newConfig.toString(), LocationTrackingConfig.class); ConfigManager.updateConfig(ctxt, cfg); TripDiaryStateMachineReceiver.restartCollection(ctxt); callbackContext.success(); return true; } else if (action.equals("getState")) { Context ctxt = cordova.getActivity(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctxt); String state = prefs.getString(ctxt.getString(R.string.curr_state_key), ctxt.getString(R.string.state_start)); callbackContext.success(state); return true; } else if (action.equals("forceTransition")) { // we want to run this in a background thread because it might sometimes wait to get // the current location final String generalTransition = data.getString(0); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { Context ctxt = cordova.getActivity(); Map<String, String> transitionMap = getTransitionMap(ctxt); if (transitionMap.containsKey(generalTransition)) { String androidTransition = transitionMap.get(generalTransition); ctxt.sendBroadcast(new ExplicitIntent(ctxt, androidTransition)); callbackContext.success(androidTransition); } else { callbackContext.error(generalTransition + " not supported, ignoring"); } } }); return true; } else if (action.equals("handleSilentPush")) { throw new UnsupportedOperationException("silent push handling not supported for android"); } else if (action.equals("getAccuracyOptions")) { JSONObject retVal = new JSONObject(); retVal.put("PRIORITY_HIGH_ACCURACY", LocationRequest.PRIORITY_HIGH_ACCURACY); retVal.put("PRIORITY_BALANCED_POWER_ACCURACY", LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); retVal.put("PRIORITY_LOW_POWER", LocationRequest.PRIORITY_LOW_POWER); retVal.put("PRIORITY_NO_POWER", LocationRequest.PRIORITY_NO_POWER); callbackContext.success(retVal); return true; } return false; } private static Map<String, String> getTransitionMap(Context ctxt) { Map<String, String> retVal = new HashMap<String, String>(); retVal.put("INITIALIZE", ctxt.getString(R.string.transition_initialize)); retVal.put("EXITED_GEOFENCE", ctxt.getString(R.string.transition_exited_geofence)); retVal.put("STOPPED_MOVING", ctxt.getString(R.string.transition_stopped_moving)); retVal.put("STOP_TRACKING", ctxt.getString(R.string.transition_stop_tracking)); retVal.put("START_TRACKING", ctxt.getString(R.string.transition_start_tracking)); return retVal; } @Override public void onNewIntent(Intent intent) { Context mAct = cordova.getActivity(); Log.d(mAct, TAG, "onNewIntent(" + intent.getAction() + ")"); Log.d(mAct, TAG, "Found extras " + intent.getExtras()); // this is will be NOP if we are not handling the right intent mControlDelegate.onNewIntent(intent); // This is where we can add other intent handlers } @Override public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { // This will be a NOP if we are not requesting the right permission mControlDelegate.onRequestPermissionResult(requestCode, permissions, grantResults); // This is where we can add other permission callbacks } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (data == null) { Log.d(cordova.getActivity(), TAG, "received onActivityResult(" + requestCode + "," + resultCode + "," + "null data" + ")"); } else { Log.d(cordova.getActivity(), TAG, "received onActivityResult("+requestCode+","+ resultCode+","+data.getDataString()+")"); } // This will be a NOP if we are not handling the correct activity intent mControlDelegate.onActivityResult(requestCode, resultCode, data); /* This is where we would handle other cases for activity results switch (requestCode) { default: Log.d(cordova.getActivity(), TAG, "Got unsupported request code "+requestCode+ " , ignoring..."); } */ } }
Fix incorrect initialization during onboarding when `markConsented` is called This fixes https://github.com/e-mission/e-mission-docs/issues/680#issuecomment-971953421 **Behavior before the change:** Receive initialize as part of plugin creation ``` public void pluginInitialize() { ... TripDiaryStateMachineReceiver.initOnUpgrade(myActivity); } public static void initOnUpgrade(Context ctxt) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctxt); System.out.println("All preferences are "+sp.getAll()); int currentCompleteVersion = sp.getInt(SETUP_COMPLETE_KEY, 0); Log.d(ctxt, TAG, "Comparing installed version "+currentCompleteVersion + " with new version " + BuildConfig.VERSION_CODE); if(currentCompleteVersion != BuildConfig.VERSION_CODE) { Log.d(ctxt, TAG, "Setup not complete, sending initialize"); ... ctxt.sendBroadcast(new ExplicitIntent(ctxt, R.string.transition_initialize)); ``` ``` 2022-02-01 18:04:08.152 25551-25551/edu.berkeley.eecs.emission D/TripDiaryStateMachineRcvr: Setup not complete, sending initialize ``` But because the intro is not done, we exit early ``` if (introDoneResult != null) { Log.i(context, TAG, reqConsent + " is not the current consented version, skipping init..."); NotificationHelper.createNotification(context, STARTUP_IN_NUMBERS, null, context.getString(R.string.new_data_collection_terms)); return; } else { Log.i(context, TAG, "onboarding is not complete, skipping prompt"); return; } ``` So far so good. We could add a check in initOnUpgrade that only generates the initialize if the intro is not done, but that is an optimization. Next: UI calls `markConsented` - calls `TripDiaryStateMachineForegroundService.startProperly` - calls `startForegroundService` with `getForegroundServiceIntent` - calls `onStartCommand` which calls `humanizeState` ``` String message = humanizeState(this, TripDiaryStateMachineService.getState(this)); ``` The default state (since we have not initialized) is the start state, so the humanized message is `Cannot start app, see next pop up` We don't call `initialize` after that during the onboarding process. Let's dig a bit deeper into this. The current data collection plugin code currently has the line `ctxt.sendBroadcast(new ExplicitIntent(ctxt, R.string.transition_initialize));` but it was commented out as part of https://github.com/e-mission/e-mission-data-collection/commit/3e94966d4fd597bbf33273e99a421a91585d6e96 in which it was replaced by `checkAndPromptPermissions();`. The new function calls `restartFSMIfStartState` if we have the location permission. ``` private void checkAndPromptPermissions() { if(cordova.hasPermission(LOCATION_PERMISSION)) { TripDiaryStateMachineService.restartFSMIfStartState(cordova.getActivity()); } else { cordova.requestPermission(this, ENABLE_LOCATION_PERMISSION, LOCATION_PERMISSION); } } ``` and `restartFSMIfStartState` in turn generates the initialize transition. In this refactoring, we have commented out both `mControlDelegate.checkAndPromptPermissions` and `ctxt.sendBroadcast(new ExplicitIntent(ctxt, R.string.transition_initialize));` so the FSM is never initialized and the app stays in the start state. I can confirm that if I `initialize`, the FSM starts up correctly and the message is changed. The obvious fix is to go back to generating `initialize`. Note that there are some checks around `intro_done` and we haven't actually finished the intro at this point. However those checks are only triggered if the user did not consent. Since we are in `markConsented`, those checks are not even invoked. **New fixed flow:** - initial `initialize` from `initOnUpgrade`, ignored since no consent and no intro_done - `markConsented` called. This calls `setConsented` and then sends an `initialize` event - `initalize` is received, consent is true, intro_done checks are skipped and foreground service `startProperly` is called - foreground `startService` is called and the function returns - foreground service `onStartCommand` is called, message is "Cannot start app, see next pop up", also shown in UI - handle the `initialize` in the FSM - calls `handleStart`, which sets the state to `waiting_for_trip_start` - State Machine `setNewState` -> ForegroundServiceComm `setNewState` -> foreground service `setStateMessage` - message is now "Ready for your next trip" both in the debugger and in the UI - `checkAppState` is called from State Machine `setNewState`, but the app state is fine - after onboarding, state is `waiting_for_trip_start`
src/android/DataCollectionPlugin.java
Fix incorrect initialization during onboarding when `markConsented` is called
<ide><path>rc/android/DataCollectionPlugin.java <ide> JSONObject newConsent = data.getJSONObject(0); <ide> ConsentConfig cfg = new Gson().fromJson(newConsent.toString(), ConsentConfig.class); <ide> ConfigManager.setConsented(ctxt, cfg); <del> TripDiaryStateMachineForegroundService.startProperly(cordova.getActivity().getApplication()); <add> // TripDiaryStateMachineForegroundService.startProperly(cordova.getActivity().getApplication()); <ide> // Now, really initialize the state machine <ide> // Note that we don't call initOnUpgrade so that we can handle the case where the <ide> // user deleted the consent and re-consented, but didn't upgrade the app <ide> // mControlDelegate.checkAndPromptPermissions(); <del> // ctxt.sendBroadcast(new ExplicitIntent(ctxt, R.string.transition_initialize)); <add> ctxt.sendBroadcast(new ExplicitIntent(ctxt, R.string.transition_initialize)); <ide> // TripDiaryStateMachineReceiver.restartCollection(ctxt); <ide> callbackContext.success(); <ide> return true;
Java
apache-2.0
549bbc33a21a056ea877df36c72dfa8f9f40d72a
0
laverca/laverca
package fi.laverca.samples; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Formatter; import java.util.LinkedList; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.util.encoders.Base64; import org.etsi.uri.TS102204.v1_1_2.Service; import fi.laverca.FiComAdditionalServices; import fi.laverca.FiComClient; import fi.laverca.FiComRequest; import fi.laverca.FiComResponse; import fi.laverca.FiComResponseHandler; import fi.laverca.JvmSsl; import fi.laverca.FiComAdditionalServices.PersonIdAttribute; public class SignData { private static final Log log = LogFactory.getLog(SignData.class); private static FiComRequest req; private static JTextArea responseBox = new JTextArea(); /** * Connects to MSSP using SSL and waits for response. * @param phoneNumber * @param selectedFile */ private static void estamblishConnection(String phoneNumber, final File selectedFile) { log.info("setting up ssl"); JvmSsl.setSSL("etc/laverca-truststore", "changeit", "etc/laverca-keystore", "changeit", "JKS"); String apId = "http://laverca-eval.fi"; String apPwd = "pfkpfk"; String aeMsspIdUri = "http://dev-ae.mssp.dna.fi"; //TODO: TeliaSonera //TODO: Elisa String msspSignatureUrl = "https://dev-ae.mssp.dna.fi/soap/services/MSS_SignaturePort"; String msspStatusUrl = "https://dev-ae.mssp.dna.fi/soap/services/MSS_StatusQueryPort"; String msspReceiptUrl = "https://dev-ae.mssp.dna.fi/soap/services/MSS_ReceiptPort"; log.info("creating FiComClient"); FiComClient fiComClient = new FiComClient(apId, apPwd, aeMsspIdUri, msspSignatureUrl, msspStatusUrl, msspReceiptUrl); final byte[] output = generateSHA1(selectedFile); String apTransId = "A"+System.currentTimeMillis(); Service noSpamService = FiComAdditionalServices.createNoSpamService("A12", false); LinkedList<Service> additionalServices = new LinkedList<Service>(); LinkedList<String> attributeNames = new LinkedList<String>(); attributeNames.add(FiComAdditionalServices.PERSON_ID_VALIDUNTIL); Service personIdService = FiComAdditionalServices.createPersonIdService(attributeNames); additionalServices.add(personIdService); try { log.info("calling signData"); req = fiComClient.signData(apTransId, output, phoneNumber, noSpamService, additionalServices, new FiComResponseHandler() { @Override public void onResponse(FiComRequest req, FiComResponse resp) { log.info("got resp"); printSHA1(output); responseBox.setText("File path: " + selectedFile.getAbsolutePath() + "\n" + responseBox.getText()); try { responseBox.setText("MSS Signature: " + new String(Base64.encode(resp.getMSS_StatusResp(). getMSS_Signature().getBase64Signature()), "ASCII") + "\nSigner: " + resp.getPkcs7Signature().getSignerCn() + "\n" + responseBox.getText()); for(PersonIdAttribute a : resp.getPersonIdAttributes()) { log.info(a.getName() + " " + a.getStringValue()); responseBox.setText(a.getStringValue() + "\n" + responseBox.getText()); } } catch (UnsupportedEncodingException e) { log.info("Unsupported encoding", e); } catch (NullPointerException e){ log.info("PersonIDAttributes = null", e); } } @Override public void onError(FiComRequest req, Throwable throwable) { log.info("got error", throwable); } }); } catch (IOException e) { log.info("error establishing connection", e); } fiComClient.shutdown(); } /** * Generates SHA1 hash from a file and asks for a user to sign it. * @param args */ public static void main(String[] args) { final JFrame frame = new JFrame("Sign data"); Container pane = frame.getContentPane(); frame.setSize(380, 380); final JFileChooser fc = new JFileChooser(); fc.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { printSHA1(generateSHA1(fc.getSelectedFile())); } }); fc.showOpenDialog(frame); /*JButton browse = new JButton("Browse"); browse.setPreferredSize(new Dimension(80, 10)); browse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fc.showOpenDialog(frame); } }); pane.add(browse, BorderLayout.WEST);*/ JButton cancel = new JButton("Cancel"); cancel.setPreferredSize(new Dimension(80, 10)); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { req.cancel(); responseBox.setText("Canceled\n" + responseBox.getText()); } }); pane.add(cancel, BorderLayout.WEST); pane.add(new JLabel("Phone number"), BorderLayout.PAGE_START); final JTextField number = new JTextField("+35847001001"); number.setPreferredSize(new Dimension(230, 10)); pane.add(number, BorderLayout.CENTER); JButton send = new JButton("Send"); send.setPreferredSize(new Dimension(70, 10)); pane.add(send, BorderLayout.EAST); responseBox.setPreferredSize(new Dimension(200, 300)); send.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { estamblishConnection(number.getText(), fc.getSelectedFile()); } }); pane.add(responseBox, BorderLayout.PAGE_END); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /** * * @param selectedFile * @return */ public static byte[] generateSHA1(final File selectedFile) { byte[] output = null; try { InputStream is = new FileInputStream(selectedFile); byte[] buffer = new byte[1024]; MessageDigest md = MessageDigest.getInstance("SHA1"); int numRead; do { numRead = is.read(buffer); if (numRead > 0) { md.update(buffer, 0, numRead); } } while (numRead != -1); output = md.digest(); } catch (NoSuchAlgorithmException e) { log.info("error finding algorithm", e); } catch (FileNotFoundException e) { log.info("error finding file", e); } catch (IOException e) { log.info("i/o error", e); } return output; } /** * Prints SHA1 to the <code>responseBox</code>. * @param buf */ public static void printSHA1(byte[] buf) { Formatter formatter = new Formatter(); for (byte b : buf) formatter.format("%02x", b); // Cuts first 8 characters of a hash because first 8 characters should be cut from a receiver. String sha1 = formatter.toString().substring(8).toUpperCase(); String shaTmp = new String(); for (int i = 0; i < sha1.length()/4; i++){ shaTmp += " " + sha1.substring(i*4, i*4+4); } responseBox.setText("SHA1: " + shaTmp + "\n\n" + responseBox.getText()); } }
samples-src/fi/laverca/samples/SignData.java
package fi.laverca.samples; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Formatter; import java.util.LinkedList; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bouncycastle.util.encoders.Base64; import org.etsi.uri.TS102204.v1_1_2.Service; import fi.laverca.FiComAdditionalServices; import fi.laverca.FiComClient; import fi.laverca.FiComRequest; import fi.laverca.FiComResponse; import fi.laverca.FiComResponseHandler; import fi.laverca.JvmSsl; import fi.laverca.FiComAdditionalServices.PersonIdAttribute; public class SignData { private static final Log log = LogFactory.getLog(SignData.class); private static JTextArea responseBox = new JTextArea(); /** * Connects to MSSP using SSL and waits for response. * @param phoneNumber * @param selectedFile */ private static void estamblishConnection(String phoneNumber, final File selectedFile) { log.info("setting up ssl"); JvmSsl.setSSL("etc/laverca-truststore", "changeit", "etc/laverca-keystore", "changeit", "JKS"); String apId = "http://laverca-eval.fi"; String apPwd = "pfkpfk"; String aeMsspIdUri = "http://dev-ae.mssp.dna.fi"; //TODO: TeliaSonera //TODO: Elisa String msspSignatureUrl = "https://dev-ae.mssp.dna.fi/soap/services/MSS_SignaturePort"; String msspStatusUrl = "https://dev-ae.mssp.dna.fi/soap/services/MSS_StatusQueryPort"; String msspReceiptUrl = "https://dev-ae.mssp.dna.fi/soap/services/MSS_ReceiptPort"; log.info("creating FiComClient"); FiComClient fiComClient = new FiComClient(apId, apPwd, aeMsspIdUri, msspSignatureUrl, msspStatusUrl, msspReceiptUrl); final byte[] output = generateSHA1(selectedFile); String apTransId = "A"+System.currentTimeMillis(); Service noSpamService = FiComAdditionalServices.createNoSpamService("A12", false); LinkedList<Service> additionalServices = new LinkedList<Service>(); LinkedList<String> attributeNames = new LinkedList<String>(); attributeNames.add(FiComAdditionalServices.PERSON_ID_VALIDUNTIL); Service personIdService = FiComAdditionalServices.createPersonIdService(attributeNames); additionalServices.add(personIdService); try { log.info("calling signData"); fiComClient.signData(apTransId, output, phoneNumber, noSpamService, additionalServices, new FiComResponseHandler() { @Override public void onResponse(FiComRequest req, FiComResponse resp) { log.info("got resp"); printSHA1(output); responseBox.setText("File path: " + selectedFile.getAbsolutePath() + "\n" + responseBox.getText()); try { responseBox.setText("MSS Signature: " + new String(Base64.encode(resp.getMSS_StatusResp(). getMSS_Signature().getBase64Signature()), "ASCII") + "\nSigner: " + resp.getPkcs7Signature().getSignerCn() + "\n" + responseBox.getText()); for(PersonIdAttribute a : resp.getPersonIdAttributes()) { log.info(a.getName() + " " + a.getStringValue()); responseBox.setText(a.getStringValue() + "\n" + responseBox.getText()); } } catch (UnsupportedEncodingException e) { log.info("Unsupported encoding", e); } catch (NullPointerException e){ log.info("PersonIDAttributes = null", e); } } @Override public void onError(FiComRequest req, Throwable throwable) { log.info("got error", throwable); } }); } catch (IOException e) { log.info("error establishing connection", e); } fiComClient.shutdown(); } /** * Generates SHA1 hash from a file and asks for a user to sign it. * @param args */ public static void main(String[] args) { final JFrame frame = new JFrame("Sign data"); Container pane = frame.getContentPane(); frame.setSize(380, 380); final JFileChooser fc = new JFileChooser(); fc.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { printSHA1(generateSHA1(fc.getSelectedFile())); } }); fc.showOpenDialog(frame); JButton browse = new JButton("Browse"); browse.setPreferredSize(new Dimension(80, 10)); browse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fc.showOpenDialog(frame); } }); pane.add(browse, BorderLayout.WEST); pane.add(new JLabel("Phone number"), BorderLayout.PAGE_START); final JTextField number = new JTextField("+35847001001"); number.setPreferredSize(new Dimension(230, 10)); pane.add(number, BorderLayout.CENTER); JButton send = new JButton("Send"); send.setPreferredSize(new Dimension(70, 10)); pane.add(send, BorderLayout.EAST); responseBox.setPreferredSize(new Dimension(200, 300)); send.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { estamblishConnection(number.getText(), fc.getSelectedFile()); } }); pane.add(responseBox, BorderLayout.PAGE_END); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /** * * @param selectedFile * @return */ public static byte[] generateSHA1(final File selectedFile) { byte[] output = null; try { InputStream is = new FileInputStream(selectedFile); byte[] buffer = new byte[1024]; MessageDigest md = MessageDigest.getInstance("SHA1"); int numRead; do { numRead = is.read(buffer); if (numRead > 0) { md.update(buffer, 0, numRead); } } while (numRead != -1); output = md.digest(); } catch (NoSuchAlgorithmException e) { log.info("error finding algorithm", e); } catch (FileNotFoundException e) { log.info("error finding file", e); } catch (IOException e) { log.info("i/o error", e); } return output; } /** * Prints SHA1 to the <code>responseBox</code>. * @param buf */ public static void printSHA1(byte[] buf) { Formatter formatter = new Formatter(); for (byte b : buf) formatter.format("%02x", b); // Cuts first 8 characters of a hash because first 8 characters should be cut from a receiver. String sha1 = formatter.toString().substring(8).toUpperCase(); String shaTmp = new String(); for (int i = 0; i < sha1.length()/4; i++){ shaTmp += " " + sha1.substring(i*4, i*4+4); } responseBox.setText("SHA1: " + shaTmp + "\n\n" + responseBox.getText()); } }
Replaced browse button with cancel in SignData sample
samples-src/fi/laverca/samples/SignData.java
Replaced browse button with cancel in SignData sample
<ide><path>amples-src/fi/laverca/samples/SignData.java <ide> public class SignData { <ide> <ide> private static final Log log = LogFactory.getLog(SignData.class); <del> <add> private static FiComRequest req; <ide> private static JTextArea responseBox = new JTextArea(); <ide> <ide> /** <ide> <ide> try { <ide> log.info("calling signData"); <del> fiComClient.signData(apTransId, <add> req = <add> fiComClient.signData(apTransId, <ide> output, <ide> phoneNumber, <ide> noSpamService, <ide> }); <ide> fc.showOpenDialog(frame); <ide> <del> JButton browse = new JButton("Browse"); <add> /*JButton browse = new JButton("Browse"); <ide> browse.setPreferredSize(new Dimension(80, 10)); <ide> browse.addActionListener(new ActionListener() { <ide> public void actionPerformed(ActionEvent e) { <ide> fc.showOpenDialog(frame); <ide> } <ide> }); <del> pane.add(browse, BorderLayout.WEST); <add> pane.add(browse, BorderLayout.WEST);*/ <add> <add> JButton cancel = new JButton("Cancel"); <add> cancel.setPreferredSize(new Dimension(80, 10)); <add> cancel.addActionListener(new ActionListener() { <add> public void actionPerformed(ActionEvent e) { <add> req.cancel(); <add> responseBox.setText("Canceled\n" + responseBox.getText()); <add> } <add> }); <add> pane.add(cancel, BorderLayout.WEST); <ide> <ide> pane.add(new JLabel("Phone number"), BorderLayout.PAGE_START); <ide> final JTextField number = new JTextField("+35847001001");
Java
apache-2.0
06c269da8e6df801cce1d7194e7327d3ae8a8bbd
0
OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine
package org.ovirt.engine.core.bll; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyList; import static org.mockito.Matchers.anyListOf; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.ovirt.engine.core.bll.interfaces.BackendInternal; import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator; import org.ovirt.engine.core.bll.validator.storage.StorageDomainValidator; import org.ovirt.engine.core.common.action.AddVmFromSnapshotParameters; import org.ovirt.engine.core.common.action.AddVmParameters; import org.ovirt.engine.core.common.businessentities.ArchitectureType; import org.ovirt.engine.core.common.businessentities.DisplayType; import org.ovirt.engine.core.common.businessentities.GraphicsDevice; import org.ovirt.engine.core.common.businessentities.GraphicsType; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.StoragePoolStatus; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.DiskImageBase; import org.ovirt.engine.core.common.businessentities.storage.ImageStatus; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.interfaces.VDSBrokerFrontend; import org.ovirt.engine.core.common.osinfo.OsRepository; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.SimpleDependecyInjector; import org.ovirt.engine.core.common.utils.VmDeviceType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dao.DiskImageDao; import org.ovirt.engine.core.dao.SnapshotDao; import org.ovirt.engine.core.dao.StorageDomainDao; import org.ovirt.engine.core.dao.VdsGroupDao; import org.ovirt.engine.core.dao.VmDao; import org.ovirt.engine.core.dao.VmDeviceDao; import org.ovirt.engine.core.dao.VmTemplateDao; import org.ovirt.engine.core.utils.MockConfigRule; @SuppressWarnings("serial") public class AddVmCommandTest extends BaseCommandTest { private static final Guid STORAGE_DOMAIN_ID_1 = Guid.newGuid(); private static final Guid STORAGE_DOMAIN_ID_2 = Guid.newGuid(); protected static final int TOTAL_NUM_DOMAINS = 2; private static final int NUM_DISKS_STORAGE_DOMAIN_1 = 3; private static final int NUM_DISKS_STORAGE_DOMAIN_2 = 3; private static final int REQUIRED_DISK_SIZE_GB = 10; private static final int AVAILABLE_SPACE_GB = 11; private static final int USED_SPACE_GB = 4; private static final int MAX_PCI_SLOTS = 26; private static final Guid STORAGE_POOL_ID = Guid.newGuid(); private static final String CPU_ID = "0"; private VmTemplate vmTemplate; private VDSGroup vdsGroup; private StoragePool storagePool; protected StorageDomainValidator storageDomainValidator; private static final Map<String, String> migrationMap = new HashMap<>(); static { migrationMap.put("undefined", "true"); migrationMap.put("x86_64", "true"); migrationMap.put("ppc64", "false"); } @Rule public MockConfigRule mcr = new MockConfigRule(); @Rule public InjectorRule injectorRule = new InjectorRule(); @Mock StorageDomainDao sdDao; @Mock VmTemplateDao vmTemplateDao; @Mock VmDao vmDao; @Mock DiskImageDao diskImageDao; @Mock VdsGroupDao vdsGroupDao; @Mock BackendInternal backend; @Mock VDSBrokerFrontend vdsBrokerFrontend; @Mock SnapshotDao snapshotDao; @Mock CpuFlagsManagerHandler cpuFlagsManagerHandler; @Mock OsRepository osRepository; @Mock VmDeviceDao deviceDao; @Mock DbFacade dbFacade; @Before public void InitTest() { mockCpuFlagsManagerHandler(); mockOsRepository(); SimpleDependecyInjector.getInstance().bind(DbFacade.class, dbFacade); } @Test public void create10GBVmWith11GbAvailableAndA5GbBuffer() throws Exception { VM vm = createVm(); AddVmFromTemplateCommand<AddVmParameters> cmd = createVmFromTemplateCommand(vm); mockStorageDomainDaoGetForStoragePool(); mockVdsGroupDaoReturnVdsGroup(); mockVmTemplateDaoReturnVmTemplate(); mockDiskImageDaoGetSnapshotById(); mockVerifyAddVM(cmd); mockConfig(); mockMaxPciSlots(); mockOsRepository(); mockOsRepositoryGraphics(0, Version.v3_3, new Pair<>(GraphicsType.SPICE, DisplayType.qxl)); mockGraphicsDevices(vm.getId()); mockStorageDomainDaoGetAllStoragesForPool(AVAILABLE_SPACE_GB); mockUninterestingMethods(cmd); mockGetAllSnapshots(cmd); doReturn(createStoragePool()).when(cmd).getStoragePool(); CanDoActionTestUtils.runAndAssertCanDoActionFailure (cmd, EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN); } private void mockGraphicsDevices(Guid vmId) { VmDevice graphicsDevice = new GraphicsDevice(VmDeviceType.SPICE); graphicsDevice.setDeviceId(Guid.Empty); graphicsDevice.setVmId(vmId); when(deviceDao.getVmDeviceByVmIdAndType(vmId, VmDeviceGeneralType.GRAPHICS)).thenReturn(Arrays.asList(graphicsDevice)); doReturn(deviceDao).when(dbFacade).getVmDeviceDao(); } private void mockOsRepositoryGraphics(int osId, Version ver, Pair<GraphicsType, DisplayType> supportedGraphicsAndDisplay) { HashMap<Version, List<Pair<GraphicsType, DisplayType>>> value = new HashMap<>(); value.put(ver, Collections.singletonList(supportedGraphicsAndDisplay)); HashMap<Integer, Map<Version, List<Pair<GraphicsType, DisplayType>>>> g = new HashMap<>(); g.put(osId, value); when(osRepository.getGraphicsAndDisplays()).thenReturn(g); } protected void mockCpuFlagsManagerHandler() { injectorRule.bind(CpuFlagsManagerHandler.class, cpuFlagsManagerHandler); when(cpuFlagsManagerHandler.getCpuId(anyString(), any(Version.class))).thenReturn(CPU_ID); } protected void mockOsRepository() { SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository); VmHandler.init(); when(osRepository.isWindows(0)).thenReturn(true); when(osRepository.isCpuSupported(anyInt(), any(Version.class), anyString())).thenReturn(true); } @Test public void canAddVm() { ArrayList<String> reasons = new ArrayList<>(); final int domainSizeGB = 20; final int sizeRequired = 5; AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB, sizeRequired); cmd.postConstruct(); doReturn(true).when(cmd).validateCustomProperties(any(VmStatic.class), any(ArrayList.class)); doReturn(true).when(cmd).validateSpaceRequirements(); assertTrue("vm could not be added", cmd.canAddVm(reasons, Arrays.asList(createStorageDomain(domainSizeGB)))); } @Test public void canAddCloneVmFromSnapshotSnapshotDoesNotExist() { final int domainSizeGB = 15; final int sizeRequired = 4; final Guid sourceSnapshotId = Guid.newGuid(); AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd = setupCanAddVmFromSnapshotTests(domainSizeGB, sizeRequired, sourceSnapshotId); cmd.getVm().setName("vm1"); mockNonInterestingMethodsForCloneVmFromSnapshot(cmd); CanDoActionTestUtils.runAndAssertCanDoActionFailure (cmd, EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_DOES_NOT_EXIST); } @Test public void canAddCloneVmFromSnapshotNoConfiguration() { final int domainSizeGB = 15; final int sizeRequired = 4; final Guid sourceSnapshotId = Guid.newGuid(); AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd = setupCanAddVmFromSnapshotTests(domainSizeGB, sizeRequired, sourceSnapshotId); cmd.getVm().setName("vm1"); mockNonInterestingMethodsForCloneVmFromSnapshot(cmd); SnapshotsValidator sv = spy(new SnapshotsValidator()); doReturn(ValidationResult.VALID).when(sv).vmNotDuringSnapshot(any(Guid.class)); doReturn(sv).when(cmd).createSnapshotsValidator(); when(snapshotDao.get(sourceSnapshotId)).thenReturn(new Snapshot()); CanDoActionTestUtils.runAndAssertCanDoActionFailure (cmd, EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_HAS_NO_CONFIGURATION); } @Test public void canAddVmWithVirtioScsiControllerNotSupportedOs() { VM vm = createVm(); AddVmFromTemplateCommand<AddVmParameters> cmd = createVmFromTemplateCommand(vm); VDSGroup vdsGroup = createVdsGroup(); mockStorageDomainDaoGetForStoragePool(); mockVmTemplateDaoReturnVmTemplate(); mockDiskImageDaoGetSnapshotById(); mockVerifyAddVM(cmd); mockConfig(); mockMaxPciSlots(); mockStorageDomainDaoGetAllStoragesForPool(20); mockUninterestingMethods(cmd); mockDisplayTypes(vm.getOs(), vdsGroup.getCompatibilityVersion()); mockGraphicsDevices(vm.getId()); doReturn(true).when(cmd).checkCpuSockets(); doReturn(vdsGroup).when(cmd).getVdsGroup(); doReturn(createStoragePool()).when(cmd).getStoragePool(); cmd.getParameters().setVirtioScsiEnabled(true); when(osRepository.isSoundDeviceEnabled(any(Integer.class), any(Version.class))).thenReturn(true); when(osRepository.getArchitectureFromOS(any(Integer.class))).thenReturn(ArchitectureType.x86_64); when(osRepository.getDiskInterfaces(any(Integer.class), any(Version.class))).thenReturn( new ArrayList<>(Arrays.asList("VirtIO"))); mockGetAllSnapshots(cmd); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_OS_TYPE_DOES_NOT_SUPPORT_VIRTIO_SCSI); } @Test public void isVirtioScsiEnabledDefaultedToTrue() { AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(0, 0); doReturn(createVdsGroup()).when(cmd).getVdsGroup(); when(osRepository.getDiskInterfaces(any(Integer.class), any(Version.class))).thenReturn( new ArrayList<>(Arrays.asList("VirtIO_SCSI"))); assertTrue("isVirtioScsiEnabled hasn't been defaulted to true on cluster >= 3.3.", cmd.isVirtioScsiEnabled()); } @Test public void validateSpaceAndThreshold() { AddVmCommand<AddVmParameters> command = setupCanAddVmTests(0, 0); doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds(); doReturn(ValidationResult.VALID).when(storageDomainValidator).hasSpaceForNewDisks(anyList()); doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class)); assertTrue(command.validateSpaceRequirements()); verify(storageDomainValidator, times(TOTAL_NUM_DOMAINS)).hasSpaceForNewDisks(anyList()); verify(storageDomainValidator, never()).hasSpaceForClonedDisks(anyList()); } @Test public void validateSpaceNotEnough() throws Exception { AddVmCommand<AddVmParameters> command = setupCanAddVmTests(0, 0); doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds(); doReturn(new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN)). when(storageDomainValidator).hasSpaceForNewDisks(anyList()); doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class)); assertFalse(command.validateSpaceRequirements()); verify(storageDomainValidator).hasSpaceForNewDisks(anyList()); verify(storageDomainValidator, never()).hasSpaceForClonedDisks(anyList()); } @Test public void validateSpaceNotWithinThreshold() throws Exception { AddVmCommand<AddVmParameters> command = setupCanAddVmTests(0, 0); doReturn((new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN))). when(storageDomainValidator).isDomainWithinThresholds(); doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class)); assertFalse(command.validateSpaceRequirements()); } @Test public void testUnsupportedCpus() { // prepare a command to pass canDo action VM vm = createVm(); vm.setVmOs(OsRepository.DEFAULT_X86_OS); VDSGroup vdsGroup = createVdsGroup(); AddVmFromTemplateCommand<AddVmParameters> cmd = createVmFromTemplateCommand(vm); mockStorageDomainDaoGetForStoragePool(); mockVmTemplateDaoReturnVmTemplate(); mockDiskImageDaoGetSnapshotById(); mockVerifyAddVM(cmd); mockConfig(); mockMaxPciSlots(); mockStorageDomainDaoGetAllStoragesForPool(20); mockDisplayTypes(vm.getOs(), vdsGroup.getCompatibilityVersion()); mockUninterestingMethods(cmd); mockGetAllSnapshots(cmd); when(osRepository.getArchitectureFromOS(0)).thenReturn(ArchitectureType.x86_64); doReturn(createStoragePool()).when(cmd).getStoragePool(); // prepare the mock values HashMap<Pair<Integer, Version>, Set<String>> unsupported = new HashMap<>(); HashSet<String> value = new HashSet<>(); value.add(CPU_ID); unsupported.put(new Pair<>(vm.getVmOsId(), vdsGroup.getCompatibilityVersion()), value); when(osRepository.isCpuSupported(vm.getVmOsId(), vdsGroup.getCompatibilityVersion(), CPU_ID)).thenReturn(false); when(osRepository.getUnsupportedCpus()).thenReturn(unsupported); CanDoActionTestUtils.runAndAssertCanDoActionFailure( cmd, EngineMessage.CPU_TYPE_UNSUPPORTED_FOR_THE_GUEST_OS); } private void mockDisplayTypes(int osId, Version clusterVersion) { Map<Integer, Map<Version, List<Pair<GraphicsType, DisplayType>>>> displayTypeMap = new HashMap<>(); displayTypeMap.put(osId, new HashMap<Version, List<Pair<GraphicsType, DisplayType>>>()); displayTypeMap.get(osId).put(null, Arrays.asList(new Pair<>(GraphicsType.SPICE, DisplayType.qxl))); when(osRepository.getGraphicsAndDisplays()).thenReturn(displayTypeMap); } protected void mockNonInterestingMethodsForCloneVmFromSnapshot(AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd) { mockUninterestingMethods(cmd); doReturn(true).when(cmd).checkCpuSockets(); doReturn(null).when(cmd).getVmFromConfiguration(); } private void mockMaxPciSlots() { SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository); doReturn(MAX_PCI_SLOTS).when(osRepository).getMaxPciDevices(anyInt(), any(Version.class)); } protected AddVmFromTemplateCommand<AddVmParameters> createVmFromTemplateCommand(VM vm) { AddVmParameters param = new AddVmParameters(); param.setVm(vm); AddVmFromTemplateCommand<AddVmParameters> concrete = new AddVmFromTemplateCommand<AddVmParameters>(param) { @Override protected void initUser() { // Stub for testing } @Override protected void initTemplateDisks() { // Stub for testing } @Override protected void initStoragePoolId() { // Stub for testing } @Override public VmTemplate getVmTemplate() { return createVmTemplate(); } }; AddVmFromTemplateCommand<AddVmParameters> result = spy(concrete); doReturn(true).when(result).checkNumberOfMonitors(); doReturn(createVmTemplate()).when(result).getVmTemplate(); doReturn(true).when(result).validateCustomProperties(any(VmStatic.class), any(ArrayList.class)); mockDaos(result); mockBackend(result); initCommandMethods(result); result.postConstruct(); return result; } private AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> createVmFromSnapshotCommand(VM vm, Guid sourceSnapshotId) { AddVmFromSnapshotParameters param = new AddVmFromSnapshotParameters(); param.setVm(vm); param.setSourceSnapshotId(sourceSnapshotId); param.setStorageDomainId(Guid.newGuid()); AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd = new AddVmFromSnapshotCommand<AddVmFromSnapshotParameters>(param) { @Override protected void initUser() { // Stub for testing } @Override protected void initTemplateDisks() { // Stub for testing } @Override protected void initStoragePoolId() { // Stub for testing } @Override public VmTemplate getVmTemplate() { return createVmTemplate(); } }; cmd = spy(cmd); doReturn(vm).when(cmd).getVm(); mockDaos(cmd); doReturn(snapshotDao).when(cmd).getSnapshotDao(); mockBackend(cmd); return cmd; } protected AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> setupCanAddVmFromSnapshotTests(final int domainSizeGB, final int sizeRequired, Guid sourceSnapshotId) { VM vm = initializeMock(domainSizeGB, sizeRequired); initializeVmDaoMock(vm); AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd = createVmFromSnapshotCommand(vm, sourceSnapshotId); initCommandMethods(cmd); return cmd; } private void initializeVmDaoMock(VM vm) { when(vmDao.get(Matchers.<Guid>any(Guid.class))).thenReturn(vm); } private AddVmCommand<AddVmParameters> setupCanAddVmTests(final int domainSizeGB, final int sizeRequired) { VM vm = initializeMock(domainSizeGB, sizeRequired); AddVmCommand<AddVmParameters> cmd = createCommand(vm); initCommandMethods(cmd); doReturn(createVmTemplate()).when(cmd).getVmTemplate(); doReturn(createStoragePool()).when(cmd).getStoragePool(); return cmd; } private static <T extends AddVmParameters> void initCommandMethods(AddVmCommand<T> cmd) { doReturn(Guid.newGuid()).when(cmd).getStoragePoolId(); doReturn(true).when(cmd).canAddVm(anyListOf(String.class), anyString(), any(Guid.class), anyInt()); doReturn(STORAGE_POOL_ID).when(cmd).getStoragePoolId(); } private VM initializeMock(final int domainSizeGB, final int sizeRequired) { mockVmTemplateDaoReturnVmTemplate(); mockDiskImageDaoGetSnapshotById(); mockStorageDomainDaoGetForStoragePool(domainSizeGB); mockStorageDomainDaoGet(domainSizeGB); mockConfig(); VM vm = createVm(); return vm; } private void mockBackend(AddVmCommand<?> cmd) { when(backend.getResourceManager()).thenReturn(vdsBrokerFrontend); doReturn(backend).when(cmd).getBackend(); } private void mockDaos(AddVmCommand<?> cmd) { doReturn(vmDao).when(cmd).getVmDao(); doReturn(sdDao).when(cmd).getStorageDomainDao(); doReturn(vmTemplateDao).when(cmd).getVmTemplateDao(); doReturn(vdsGroupDao).when(cmd).getVdsGroupDao(); doReturn(deviceDao).when(cmd).getVmDeviceDao(); } private void mockStorageDomainDaoGetForStoragePool(int domainSpaceGB) { when(sdDao.getForStoragePool(Matchers.<Guid>any(Guid.class), Matchers.<Guid>any(Guid.class))).thenReturn(createStorageDomain(domainSpaceGB)); } private void mockStorageDomainDaoGet(final int domainSpaceGB) { doAnswer(new Answer<StorageDomain>() { @Override public StorageDomain answer(InvocationOnMock invocation) throws Throwable { StorageDomain result = createStorageDomain(domainSpaceGB); result.setId((Guid) invocation.getArguments()[0]); return result; } }).when(sdDao).get(any(Guid.class)); } private void mockStorageDomainDaoGetAllStoragesForPool(int domainSpaceGB) { when(sdDao.getAllForStoragePool(any(Guid.class))).thenReturn(Arrays.asList(createStorageDomain(domainSpaceGB))); } private void mockStorageDomainDaoGetForStoragePool() { mockStorageDomainDaoGetForStoragePool(AVAILABLE_SPACE_GB); } private void mockVmTemplateDaoReturnVmTemplate() { when(vmTemplateDao.get(Matchers.<Guid> any(Guid.class))).thenReturn(createVmTemplate()); } private void mockVdsGroupDaoReturnVdsGroup() { when(vdsGroupDao.get(Matchers.<Guid>any(Guid.class))).thenReturn(createVdsGroup()); } private VmTemplate createVmTemplate() { if (vmTemplate == null) { vmTemplate = new VmTemplate(); vmTemplate.setStoragePoolId(STORAGE_POOL_ID); DiskImage image = createDiskImageTemplate(); vmTemplate.getDiskTemplateMap().put(image.getImageId(), image); HashMap<Guid, DiskImage> diskImageMap = new HashMap<>(); DiskImage diskImage = createDiskImage(REQUIRED_DISK_SIZE_GB); diskImageMap.put(diskImage.getId(), diskImage); vmTemplate.setDiskImageMap(diskImageMap); } return vmTemplate; } private VDSGroup createVdsGroup() { if (vdsGroup == null) { vdsGroup = new VDSGroup(); vdsGroup.setVdsGroupId(Guid.newGuid()); vdsGroup.setCompatibilityVersion(Version.v3_3); vdsGroup.setCpuName("Intel Conroe Family"); vdsGroup.setArchitecture(ArchitectureType.x86_64); } return vdsGroup; } private StoragePool createStoragePool() { if (storagePool == null) { storagePool = new StoragePool(); storagePool.setId(STORAGE_POOL_ID); storagePool.setStatus(StoragePoolStatus.Up); } return storagePool; } private static DiskImage createDiskImageTemplate() { DiskImage i = new DiskImage(); i.setSizeInGigabytes(USED_SPACE_GB + AVAILABLE_SPACE_GB); i.setActualSizeInBytes(REQUIRED_DISK_SIZE_GB * 1024L * 1024L * 1024L); i.setImageId(Guid.newGuid()); i.setStorageIds(new ArrayList<>(Arrays.asList(STORAGE_DOMAIN_ID_1))); return i; } private void mockDiskImageDaoGetSnapshotById() { when(diskImageDao.getSnapshotById(Matchers.<Guid> any(Guid.class))).thenReturn(createDiskImage(REQUIRED_DISK_SIZE_GB)); } private static DiskImage createDiskImage(int size) { DiskImage diskImage = new DiskImage(); diskImage.setSizeInGigabytes(size); diskImage.setActualSize(size); diskImage.setId(Guid.newGuid()); diskImage.setImageId(Guid.newGuid()); diskImage.setStorageIds(new ArrayList<>(Arrays.asList(STORAGE_DOMAIN_ID_1))); return diskImage; } protected StorageDomain createStorageDomain(int availableSpace) { StorageDomain sd = new StorageDomain(); sd.setStorageDomainType(StorageDomainType.Master); sd.setStatus(StorageDomainStatus.Active); sd.setAvailableDiskSize(availableSpace); sd.setUsedDiskSize(USED_SPACE_GB); sd.setId(STORAGE_DOMAIN_ID_1); return sd; } private static void mockVerifyAddVM(AddVmCommand<?> cmd) { doReturn(true).when(cmd).verifyAddVM(anyListOf(String.class), anyInt()); } private void mockConfig() { mcr.mockConfigValue(ConfigValues.PredefinedVMProperties, Version.v3_0, ""); mcr.mockConfigValue(ConfigValues.UserDefinedVMProperties, Version.v3_0, ""); mcr.mockConfigValue(ConfigValues.InitStorageSparseSizeInGB, 1); mcr.mockConfigValue(ConfigValues.VirtIoScsiEnabled, Version.v3_3, true); mcr.mockConfigValue(ConfigValues.ValidNumOfMonitors, Arrays.asList("1,2,4".split(","))); mcr.mockConfigValue(ConfigValues.IsMigrationSupported, Version.v3_3, migrationMap); mcr.mockConfigValue(ConfigValues.MaxIoThreadsPerVm, 127); } protected static VM createVm() { VM vm = new VM(); VmDynamic dynamic = new VmDynamic(); VmStatic stat = new VmStatic(); stat.setVmtGuid(Guid.newGuid()); stat.setName("testVm"); stat.setPriority(1); vm.setStaticData(stat); vm.setDynamicData(dynamic); vm.setSingleQxlPci(false); return vm; } private AddVmCommand<AddVmParameters> createCommand(VM vm) { AddVmParameters param = new AddVmParameters(vm); AddVmCommand<AddVmParameters> cmd = new AddVmCommand<AddVmParameters>(param) { @Override protected void initUser() { // Stub for testing } @Override protected void initTemplateDisks() { // Stub for testing } @Override protected void initStoragePoolId() { // stub for testing } @Override public VmTemplate getVmTemplate() { return createVmTemplate(); } }; cmd = spy(cmd); mockDaos(cmd); mockBackend(cmd); doReturn(new VDSGroup()).when(cmd).getVdsGroup(); generateStorageToDisksMap(cmd); initDestSDs(cmd); storageDomainValidator = mock(StorageDomainValidator.class); doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds(); doReturn(storageDomainValidator).when(cmd).createStorageDomainValidator(any(StorageDomain.class)); return cmd; } protected void generateStorageToDisksMap(AddVmCommand<? extends AddVmParameters> command) { command.storageToDisksMap = new HashMap<>(); command.storageToDisksMap.put(STORAGE_DOMAIN_ID_1, generateDisksList(NUM_DISKS_STORAGE_DOMAIN_1)); command.storageToDisksMap.put(STORAGE_DOMAIN_ID_2, generateDisksList(NUM_DISKS_STORAGE_DOMAIN_2)); } private static List<DiskImage> generateDisksList(int size) { List<DiskImage> disksList = new ArrayList<>(); for (int i = 0; i < size; ++i) { DiskImage diskImage = createDiskImage(REQUIRED_DISK_SIZE_GB); disksList.add(diskImage); } return disksList; } protected void initDestSDs(AddVmCommand<? extends AddVmParameters> command) { StorageDomain sd1 = new StorageDomain(); StorageDomain sd2 = new StorageDomain(); sd1.setId(STORAGE_DOMAIN_ID_1); sd2.setId(STORAGE_DOMAIN_ID_2); command.destStorages.put(STORAGE_DOMAIN_ID_1, sd1); command.destStorages.put(STORAGE_DOMAIN_ID_2, sd2); } protected List<DiskImage> createDiskSnapshot(Guid diskId, int numOfImages) { List<DiskImage> disksList = new ArrayList<>(); for (int i = 0; i < numOfImages; ++i) { DiskImage diskImage = new DiskImage(); diskImage.setActive(false); diskImage.setId(diskId); diskImage.setImageId(Guid.newGuid()); diskImage.setParentId(Guid.newGuid()); diskImage.setImageStatus(ImageStatus.OK); disksList.add(diskImage); } return disksList; } private void mockGetAllSnapshots(AddVmFromTemplateCommand<AddVmParameters> command) { doAnswer(new Answer<List<DiskImage>>() { @Override public List<DiskImage> answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); DiskImage arg = (DiskImage) args[0]; List<DiskImage> list = createDiskSnapshot(arg.getId(), 3); return list; } }).when(command).getAllImageSnapshots(any(DiskImage.class)); } private <T extends AddVmParameters> void mockUninterestingMethods(AddVmCommand<T> spy) { doReturn(true).when(spy).isVmNameValidLength(Matchers.<VM> any(VM.class)); doReturn(false).when(spy).isVmWithSameNameExists(anyString(), any(Guid.class)); doReturn(STORAGE_POOL_ID).when(spy).getStoragePoolId(); doReturn(createVmTemplate()).when(spy).getVmTemplate(); doReturn(createVdsGroup()).when(spy).getVdsGroup(); doReturn(true).when(spy).areParametersLegal(anyListOf(String.class)); doReturn(Collections.<VmNetworkInterface> emptyList()).when(spy).getVmInterfaces(); doReturn(Collections.<DiskImageBase> emptyList()).when(spy).getVmDisks(); doReturn(false).when(spy).isVirtioScsiControllerAttached(any(Guid.class)); doReturn(true).when(osRepository).isSoundDeviceEnabled(any(Integer.class), any(Version.class)); spy.setVmTemplateId(Guid.newGuid()); } @Test public void testBeanValidations() { assertTrue(createCommand(initializeMock(1, 1)).validateInputs()); } @Test public void testPatternBasedNameFails() { AddVmCommand<AddVmParameters> cmd = createCommand(initializeMock(1, 1)); cmd.getParameters().getVm().setName("aa-??bb"); assertFalse("Pattern-based name should not be supported for VM", cmd.validateInputs()); } @Test public void refuseBalloonOnPPC() { AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest(); cmd.getParameters().setBalloonEnabled(true); when(osRepository.isBalloonEnabled(cmd.getParameters().getVm().getVmOsId(), cmd.getVdsGroup().getCompatibilityVersion())).thenReturn(false); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, EngineMessage.BALLOON_REQUESTED_ON_NOT_SUPPORTED_ARCH); } @Test public void refuseSoundDeviceOnPPC() { AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest(); cmd.getParameters().setSoundDeviceEnabled(true); when(osRepository.isSoundDeviceEnabled(cmd.getParameters().getVm().getVmOsId(), cmd.getVdsGroup().getCompatibilityVersion())).thenReturn(false); CanDoActionTestUtils.runAndAssertCanDoActionFailure (cmd, EngineMessage.SOUND_DEVICE_REQUESTED_ON_NOT_SUPPORTED_ARCH); } private AddVmCommand<AddVmParameters> setupCanAddPpcTest() { final int domainSizeGB = 20; final int sizeRequired = 5; AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB, sizeRequired); doReturn(true).when(cmd).validateSpaceRequirements(); doReturn(true).when(cmd).buildAndCheckDestStorageDomains(); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); VDSGroup cluster = new VDSGroup(); cluster.setArchitecture(ArchitectureType.ppc64); cluster.setCompatibilityVersion(Version.getLast()); doReturn(cluster).when(cmd).getVdsGroup(); return cmd; } @Test public void testStoragePoolDoesntExist() { final int domainSizeGB = 20; final int sizeRequired = 5; AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB, sizeRequired); doReturn(null).when(cmd).getStoragePool(); CanDoActionTestUtils.runAndAssertCanDoActionFailure (cmd, EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST); } }
backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/AddVmCommandTest.java
package org.ovirt.engine.core.bll; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyList; import static org.mockito.Matchers.anyListOf; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.ovirt.engine.core.bll.interfaces.BackendInternal; import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator; import org.ovirt.engine.core.bll.validator.storage.StorageDomainValidator; import org.ovirt.engine.core.common.action.AddVmFromSnapshotParameters; import org.ovirt.engine.core.common.action.AddVmParameters; import org.ovirt.engine.core.common.businessentities.ArchitectureType; import org.ovirt.engine.core.common.businessentities.DisplayType; import org.ovirt.engine.core.common.businessentities.GraphicsDevice; import org.ovirt.engine.core.common.businessentities.GraphicsType; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.StoragePoolStatus; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmDevice; import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.DiskImageBase; import org.ovirt.engine.core.common.businessentities.storage.ImageStatus; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.interfaces.VDSBrokerFrontend; import org.ovirt.engine.core.common.osinfo.OsRepository; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.utils.SimpleDependecyInjector; import org.ovirt.engine.core.common.utils.VmDeviceType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dao.DiskImageDao; import org.ovirt.engine.core.dao.SnapshotDao; import org.ovirt.engine.core.dao.StorageDomainDao; import org.ovirt.engine.core.dao.VdsGroupDao; import org.ovirt.engine.core.dao.VmDao; import org.ovirt.engine.core.dao.VmDeviceDao; import org.ovirt.engine.core.dao.VmTemplateDao; import org.ovirt.engine.core.utils.MockConfigRule; @SuppressWarnings("serial") public class AddVmCommandTest extends BaseCommandTest { private static final Guid STORAGE_DOMAIN_ID_1 = Guid.newGuid(); private static final Guid STORAGE_DOMAIN_ID_2 = Guid.newGuid(); protected static final int TOTAL_NUM_DOMAINS = 2; private static final int NUM_DISKS_STORAGE_DOMAIN_1 = 3; private static final int NUM_DISKS_STORAGE_DOMAIN_2 = 3; private static final int REQUIRED_DISK_SIZE_GB = 10; private static final int AVAILABLE_SPACE_GB = 11; private static final int USED_SPACE_GB = 4; private static final int MAX_PCI_SLOTS = 26; private static final Guid STORAGE_POOL_ID = Guid.newGuid(); private static final String CPU_ID = "0"; private VmTemplate vmTemplate; private VDSGroup vdsGroup; private StoragePool storagePool; protected StorageDomainValidator storageDomainValidator; private static final Map<String, String> migrationMap = new HashMap<>(); static { migrationMap.put("undefined", "true"); migrationMap.put("x86_64", "true"); migrationMap.put("ppc64", "false"); } @Rule public MockConfigRule mcr = new MockConfigRule(); @Rule public InjectorRule injectorRule = new InjectorRule(); @Mock StorageDomainDao sdDao; @Mock VmTemplateDao vmTemplateDao; @Mock VmDao vmDao; @Mock DiskImageDao diskImageDao; @Mock VdsGroupDao vdsGroupDao; @Mock BackendInternal backend; @Mock VDSBrokerFrontend vdsBrokerFrontend; @Mock SnapshotDao snapshotDao; @Mock CpuFlagsManagerHandler cpuFlagsManagerHandler; @Mock OsRepository osRepository; @Mock VmDeviceDao deviceDao; @Mock DbFacade dbFacade; @Before public void InitTest() { mockCpuFlagsManagerHandler(); mockOsRepository(); SimpleDependecyInjector.getInstance().bind(DbFacade.class, dbFacade); } @Test public void create10GBVmWith11GbAvailableAndA5GbBuffer() throws Exception { VM vm = createVm(); AddVmFromTemplateCommand<AddVmParameters> cmd = createVmFromTemplateCommand(vm); mockStorageDomainDaoGetForStoragePool(); mockVdsGroupDaoReturnVdsGroup(); mockVmTemplateDaoReturnVmTemplate(); mockDiskImageDaoGetSnapshotById(); mockVerifyAddVM(cmd); mockConfig(); mockMaxPciSlots(); mockOsRepository(); mockOsRepositoryGraphics(0, Version.v3_3, new Pair<>(GraphicsType.SPICE, DisplayType.qxl)); mockGraphicsDevices(vm.getId()); mockStorageDomainDaoGetAllStoragesForPool(AVAILABLE_SPACE_GB); mockUninterestingMethods(cmd); mockGetAllSnapshots(cmd); doReturn(createStoragePool()).when(cmd).getStoragePool(); assertFalse("If the disk is too big, canDoAction should fail", cmd.canDoAction()); assertTrue("canDoAction failed for the wrong reason", cmd.getReturnValue() .getCanDoActionMessages() .contains(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN.toString())); } private void mockGraphicsDevices(Guid vmId) { VmDevice graphicsDevice = new GraphicsDevice(VmDeviceType.SPICE); graphicsDevice.setDeviceId(Guid.Empty); graphicsDevice.setVmId(vmId); when(deviceDao.getVmDeviceByVmIdAndType(vmId, VmDeviceGeneralType.GRAPHICS)).thenReturn(Arrays.asList(graphicsDevice)); doReturn(deviceDao).when(dbFacade).getVmDeviceDao(); } private void mockOsRepositoryGraphics(int osId, Version ver, Pair<GraphicsType, DisplayType> supportedGraphicsAndDisplay) { HashMap<Version, List<Pair<GraphicsType, DisplayType>>> value = new HashMap<>(); value.put(ver, Collections.singletonList(supportedGraphicsAndDisplay)); HashMap<Integer, Map<Version, List<Pair<GraphicsType, DisplayType>>>> g = new HashMap<>(); g.put(osId, value); when(osRepository.getGraphicsAndDisplays()).thenReturn(g); } protected void mockCpuFlagsManagerHandler() { injectorRule.bind(CpuFlagsManagerHandler.class, cpuFlagsManagerHandler); when(cpuFlagsManagerHandler.getCpuId(anyString(), any(Version.class))).thenReturn(CPU_ID); } protected void mockOsRepository() { SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository); VmHandler.init(); when(osRepository.isWindows(0)).thenReturn(true); when(osRepository.isCpuSupported(anyInt(), any(Version.class), anyString())).thenReturn(true); } @Test public void canAddVm() { ArrayList<String> reasons = new ArrayList<>(); final int domainSizeGB = 20; final int sizeRequired = 5; AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB, sizeRequired); cmd.postConstruct(); doReturn(true).when(cmd).validateCustomProperties(any(VmStatic.class), any(ArrayList.class)); doReturn(true).when(cmd).validateSpaceRequirements(); assertTrue("vm could not be added", cmd.canAddVm(reasons, Arrays.asList(createStorageDomain(domainSizeGB)))); } @Test public void canAddCloneVmFromSnapshotSnapshotDoesNotExist() { final int domainSizeGB = 15; final int sizeRequired = 4; final Guid sourceSnapshotId = Guid.newGuid(); AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd = setupCanAddVmFromSnapshotTests(domainSizeGB, sizeRequired, sourceSnapshotId); cmd.getVm().setName("vm1"); mockNonInterestingMethodsForCloneVmFromSnapshot(cmd); assertFalse("Clone vm should have failed due to non existing snapshot id", cmd.canDoAction()); ArrayList<String> reasons = cmd.getReturnValue().getCanDoActionMessages(); assertTrue("Clone vm should have failed due to non existing snapshot id", reasons.contains(EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_DOES_NOT_EXIST.toString())); } @Test public void canAddCloneVmFromSnapshotNoConfiguration() { final int domainSizeGB = 15; final int sizeRequired = 4; final Guid sourceSnapshotId = Guid.newGuid(); AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd = setupCanAddVmFromSnapshotTests(domainSizeGB, sizeRequired, sourceSnapshotId); cmd.getVm().setName("vm1"); mockNonInterestingMethodsForCloneVmFromSnapshot(cmd); SnapshotsValidator sv = spy(new SnapshotsValidator()); doReturn(ValidationResult.VALID).when(sv).vmNotDuringSnapshot(any(Guid.class)); doReturn(sv).when(cmd).createSnapshotsValidator(); when(snapshotDao.get(sourceSnapshotId)).thenReturn(new Snapshot()); assertFalse("Clone vm should have failed due to non existing vm configuration", cmd.canDoAction()); ArrayList<String> reasons = cmd.getReturnValue().getCanDoActionMessages(); assertTrue("Clone vm should have failed due to no configuration id", reasons.contains(EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_HAS_NO_CONFIGURATION.toString())); } @Test public void canAddVmWithVirtioScsiControllerNotSupportedOs() { VM vm = createVm(); AddVmFromTemplateCommand<AddVmParameters> cmd = createVmFromTemplateCommand(vm); VDSGroup vdsGroup = createVdsGroup(); mockStorageDomainDaoGetForStoragePool(); mockVmTemplateDaoReturnVmTemplate(); mockDiskImageDaoGetSnapshotById(); mockVerifyAddVM(cmd); mockConfig(); mockMaxPciSlots(); mockStorageDomainDaoGetAllStoragesForPool(20); mockUninterestingMethods(cmd); mockDisplayTypes(vm.getOs(), vdsGroup.getCompatibilityVersion()); mockGraphicsDevices(vm.getId()); doReturn(true).when(cmd).checkCpuSockets(); doReturn(vdsGroup).when(cmd).getVdsGroup(); doReturn(createStoragePool()).when(cmd).getStoragePool(); cmd.getParameters().setVirtioScsiEnabled(true); when(osRepository.isSoundDeviceEnabled(any(Integer.class), any(Version.class))).thenReturn(true); when(osRepository.getArchitectureFromOS(any(Integer.class))).thenReturn(ArchitectureType.x86_64); when(osRepository.getDiskInterfaces(any(Integer.class), any(Version.class))).thenReturn( new ArrayList<>(Arrays.asList("VirtIO"))); mockGetAllSnapshots(cmd); CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_OS_TYPE_DOES_NOT_SUPPORT_VIRTIO_SCSI); } @Test public void isVirtioScsiEnabledDefaultedToTrue() { AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(0, 0); doReturn(createVdsGroup()).when(cmd).getVdsGroup(); when(osRepository.getDiskInterfaces(any(Integer.class), any(Version.class))).thenReturn( new ArrayList<>(Arrays.asList("VirtIO_SCSI"))); assertTrue("isVirtioScsiEnabled hasn't been defaulted to true on cluster >= 3.3.", cmd.isVirtioScsiEnabled()); } @Test public void validateSpaceAndThreshold() { AddVmCommand<AddVmParameters> command = setupCanAddVmTests(0, 0); doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds(); doReturn(ValidationResult.VALID).when(storageDomainValidator).hasSpaceForNewDisks(anyList()); doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class)); assertTrue(command.validateSpaceRequirements()); verify(storageDomainValidator, times(TOTAL_NUM_DOMAINS)).hasSpaceForNewDisks(anyList()); verify(storageDomainValidator, never()).hasSpaceForClonedDisks(anyList()); } @Test public void validateSpaceNotEnough() throws Exception { AddVmCommand<AddVmParameters> command = setupCanAddVmTests(0, 0); doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds(); doReturn(new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN)). when(storageDomainValidator).hasSpaceForNewDisks(anyList()); doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class)); assertFalse(command.validateSpaceRequirements()); verify(storageDomainValidator).hasSpaceForNewDisks(anyList()); verify(storageDomainValidator, never()).hasSpaceForClonedDisks(anyList()); } @Test public void validateSpaceNotWithinThreshold() throws Exception { AddVmCommand<AddVmParameters> command = setupCanAddVmTests(0, 0); doReturn((new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN))). when(storageDomainValidator).isDomainWithinThresholds(); doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class)); assertFalse(command.validateSpaceRequirements()); } @Test public void testUnsupportedCpus() { // prepare a command to pass canDo action VM vm = createVm(); vm.setVmOs(OsRepository.DEFAULT_X86_OS); VDSGroup vdsGroup = createVdsGroup(); AddVmFromTemplateCommand<AddVmParameters> cmd = createVmFromTemplateCommand(vm); mockStorageDomainDaoGetForStoragePool(); mockVmTemplateDaoReturnVmTemplate(); mockDiskImageDaoGetSnapshotById(); mockVerifyAddVM(cmd); mockConfig(); mockMaxPciSlots(); mockStorageDomainDaoGetAllStoragesForPool(20); mockDisplayTypes(vm.getOs(), vdsGroup.getCompatibilityVersion()); mockUninterestingMethods(cmd); mockGetAllSnapshots(cmd); when(osRepository.getArchitectureFromOS(0)).thenReturn(ArchitectureType.x86_64); doReturn(createStoragePool()).when(cmd).getStoragePool(); // prepare the mock values HashMap<Pair<Integer, Version>, Set<String>> unsupported = new HashMap<>(); HashSet<String> value = new HashSet<>(); value.add(CPU_ID); unsupported.put(new Pair<>(vm.getVmOsId(), vdsGroup.getCompatibilityVersion()), value); when(osRepository.isCpuSupported(vm.getVmOsId(), vdsGroup.getCompatibilityVersion(), CPU_ID)).thenReturn(false); when(osRepository.getUnsupportedCpus()).thenReturn(unsupported); CanDoActionTestUtils.runAndAssertCanDoActionFailure( cmd, EngineMessage.CPU_TYPE_UNSUPPORTED_FOR_THE_GUEST_OS); } private void mockDisplayTypes(int osId, Version clusterVersion) { Map<Integer, Map<Version, List<Pair<GraphicsType, DisplayType>>>> displayTypeMap = new HashMap<>(); displayTypeMap.put(osId, new HashMap<Version, List<Pair<GraphicsType, DisplayType>>>()); displayTypeMap.get(osId).put(null, Arrays.asList(new Pair<>(GraphicsType.SPICE, DisplayType.qxl))); when(osRepository.getGraphicsAndDisplays()).thenReturn(displayTypeMap); } protected void mockNonInterestingMethodsForCloneVmFromSnapshot(AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd) { mockUninterestingMethods(cmd); doReturn(true).when(cmd).checkCpuSockets(); doReturn(null).when(cmd).getVmFromConfiguration(); } private void mockMaxPciSlots() { SimpleDependecyInjector.getInstance().bind(OsRepository.class, osRepository); doReturn(MAX_PCI_SLOTS).when(osRepository).getMaxPciDevices(anyInt(), any(Version.class)); } protected AddVmFromTemplateCommand<AddVmParameters> createVmFromTemplateCommand(VM vm) { AddVmParameters param = new AddVmParameters(); param.setVm(vm); AddVmFromTemplateCommand<AddVmParameters> concrete = new AddVmFromTemplateCommand<AddVmParameters>(param) { @Override protected void initUser() { // Stub for testing } @Override protected void initTemplateDisks() { // Stub for testing } @Override protected void initStoragePoolId() { // Stub for testing } @Override public VmTemplate getVmTemplate() { return createVmTemplate(); } }; AddVmFromTemplateCommand<AddVmParameters> result = spy(concrete); doReturn(true).when(result).checkNumberOfMonitors(); doReturn(createVmTemplate()).when(result).getVmTemplate(); doReturn(true).when(result).validateCustomProperties(any(VmStatic.class), any(ArrayList.class)); mockDaos(result); mockBackend(result); initCommandMethods(result); result.postConstruct(); return result; } private AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> createVmFromSnapshotCommand(VM vm, Guid sourceSnapshotId) { AddVmFromSnapshotParameters param = new AddVmFromSnapshotParameters(); param.setVm(vm); param.setSourceSnapshotId(sourceSnapshotId); param.setStorageDomainId(Guid.newGuid()); AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd = new AddVmFromSnapshotCommand<AddVmFromSnapshotParameters>(param) { @Override protected void initUser() { // Stub for testing } @Override protected void initTemplateDisks() { // Stub for testing } @Override protected void initStoragePoolId() { // Stub for testing } @Override public VmTemplate getVmTemplate() { return createVmTemplate(); } }; cmd = spy(cmd); doReturn(vm).when(cmd).getVm(); mockDaos(cmd); doReturn(snapshotDao).when(cmd).getSnapshotDao(); mockBackend(cmd); return cmd; } protected AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> setupCanAddVmFromSnapshotTests(final int domainSizeGB, final int sizeRequired, Guid sourceSnapshotId) { VM vm = initializeMock(domainSizeGB, sizeRequired); initializeVmDaoMock(vm); AddVmFromSnapshotCommand<AddVmFromSnapshotParameters> cmd = createVmFromSnapshotCommand(vm, sourceSnapshotId); initCommandMethods(cmd); return cmd; } private void initializeVmDaoMock(VM vm) { when(vmDao.get(Matchers.<Guid>any(Guid.class))).thenReturn(vm); } private AddVmCommand<AddVmParameters> setupCanAddVmTests(final int domainSizeGB, final int sizeRequired) { VM vm = initializeMock(domainSizeGB, sizeRequired); AddVmCommand<AddVmParameters> cmd = createCommand(vm); initCommandMethods(cmd); doReturn(createVmTemplate()).when(cmd).getVmTemplate(); doReturn(createStoragePool()).when(cmd).getStoragePool(); return cmd; } private static <T extends AddVmParameters> void initCommandMethods(AddVmCommand<T> cmd) { doReturn(Guid.newGuid()).when(cmd).getStoragePoolId(); doReturn(true).when(cmd).canAddVm(anyListOf(String.class), anyString(), any(Guid.class), anyInt()); doReturn(STORAGE_POOL_ID).when(cmd).getStoragePoolId(); } private VM initializeMock(final int domainSizeGB, final int sizeRequired) { mockVmTemplateDaoReturnVmTemplate(); mockDiskImageDaoGetSnapshotById(); mockStorageDomainDaoGetForStoragePool(domainSizeGB); mockStorageDomainDaoGet(domainSizeGB); mockConfig(); VM vm = createVm(); return vm; } private void mockBackend(AddVmCommand<?> cmd) { when(backend.getResourceManager()).thenReturn(vdsBrokerFrontend); doReturn(backend).when(cmd).getBackend(); } private void mockDaos(AddVmCommand<?> cmd) { doReturn(vmDao).when(cmd).getVmDao(); doReturn(sdDao).when(cmd).getStorageDomainDao(); doReturn(vmTemplateDao).when(cmd).getVmTemplateDao(); doReturn(vdsGroupDao).when(cmd).getVdsGroupDao(); doReturn(deviceDao).when(cmd).getVmDeviceDao(); } private void mockStorageDomainDaoGetForStoragePool(int domainSpaceGB) { when(sdDao.getForStoragePool(Matchers.<Guid>any(Guid.class), Matchers.<Guid>any(Guid.class))).thenReturn(createStorageDomain(domainSpaceGB)); } private void mockStorageDomainDaoGet(final int domainSpaceGB) { doAnswer(new Answer<StorageDomain>() { @Override public StorageDomain answer(InvocationOnMock invocation) throws Throwable { StorageDomain result = createStorageDomain(domainSpaceGB); result.setId((Guid) invocation.getArguments()[0]); return result; } }).when(sdDao).get(any(Guid.class)); } private void mockStorageDomainDaoGetAllStoragesForPool(int domainSpaceGB) { when(sdDao.getAllForStoragePool(any(Guid.class))).thenReturn(Arrays.asList(createStorageDomain(domainSpaceGB))); } private void mockStorageDomainDaoGetForStoragePool() { mockStorageDomainDaoGetForStoragePool(AVAILABLE_SPACE_GB); } private void mockVmTemplateDaoReturnVmTemplate() { when(vmTemplateDao.get(Matchers.<Guid> any(Guid.class))).thenReturn(createVmTemplate()); } private void mockVdsGroupDaoReturnVdsGroup() { when(vdsGroupDao.get(Matchers.<Guid>any(Guid.class))).thenReturn(createVdsGroup()); } private VmTemplate createVmTemplate() { if (vmTemplate == null) { vmTemplate = new VmTemplate(); vmTemplate.setStoragePoolId(STORAGE_POOL_ID); DiskImage image = createDiskImageTemplate(); vmTemplate.getDiskTemplateMap().put(image.getImageId(), image); HashMap<Guid, DiskImage> diskImageMap = new HashMap<>(); DiskImage diskImage = createDiskImage(REQUIRED_DISK_SIZE_GB); diskImageMap.put(diskImage.getId(), diskImage); vmTemplate.setDiskImageMap(diskImageMap); } return vmTemplate; } private VDSGroup createVdsGroup() { if (vdsGroup == null) { vdsGroup = new VDSGroup(); vdsGroup.setVdsGroupId(Guid.newGuid()); vdsGroup.setCompatibilityVersion(Version.v3_3); vdsGroup.setCpuName("Intel Conroe Family"); vdsGroup.setArchitecture(ArchitectureType.x86_64); } return vdsGroup; } private StoragePool createStoragePool() { if (storagePool == null) { storagePool = new StoragePool(); storagePool.setId(STORAGE_POOL_ID); storagePool.setStatus(StoragePoolStatus.Up); } return storagePool; } private static DiskImage createDiskImageTemplate() { DiskImage i = new DiskImage(); i.setSizeInGigabytes(USED_SPACE_GB + AVAILABLE_SPACE_GB); i.setActualSizeInBytes(REQUIRED_DISK_SIZE_GB * 1024L * 1024L * 1024L); i.setImageId(Guid.newGuid()); i.setStorageIds(new ArrayList<>(Arrays.asList(STORAGE_DOMAIN_ID_1))); return i; } private void mockDiskImageDaoGetSnapshotById() { when(diskImageDao.getSnapshotById(Matchers.<Guid> any(Guid.class))).thenReturn(createDiskImage(REQUIRED_DISK_SIZE_GB)); } private static DiskImage createDiskImage(int size) { DiskImage diskImage = new DiskImage(); diskImage.setSizeInGigabytes(size); diskImage.setActualSize(size); diskImage.setId(Guid.newGuid()); diskImage.setImageId(Guid.newGuid()); diskImage.setStorageIds(new ArrayList<>(Arrays.asList(STORAGE_DOMAIN_ID_1))); return diskImage; } protected StorageDomain createStorageDomain(int availableSpace) { StorageDomain sd = new StorageDomain(); sd.setStorageDomainType(StorageDomainType.Master); sd.setStatus(StorageDomainStatus.Active); sd.setAvailableDiskSize(availableSpace); sd.setUsedDiskSize(USED_SPACE_GB); sd.setId(STORAGE_DOMAIN_ID_1); return sd; } private static void mockVerifyAddVM(AddVmCommand<?> cmd) { doReturn(true).when(cmd).verifyAddVM(anyListOf(String.class), anyInt()); } private void mockConfig() { mcr.mockConfigValue(ConfigValues.PredefinedVMProperties, Version.v3_0, ""); mcr.mockConfigValue(ConfigValues.UserDefinedVMProperties, Version.v3_0, ""); mcr.mockConfigValue(ConfigValues.InitStorageSparseSizeInGB, 1); mcr.mockConfigValue(ConfigValues.VirtIoScsiEnabled, Version.v3_3, true); mcr.mockConfigValue(ConfigValues.ValidNumOfMonitors, Arrays.asList("1,2,4".split(","))); mcr.mockConfigValue(ConfigValues.IsMigrationSupported, Version.v3_3, migrationMap); mcr.mockConfigValue(ConfigValues.MaxIoThreadsPerVm, 127); } protected static VM createVm() { VM vm = new VM(); VmDynamic dynamic = new VmDynamic(); VmStatic stat = new VmStatic(); stat.setVmtGuid(Guid.newGuid()); stat.setName("testVm"); stat.setPriority(1); vm.setStaticData(stat); vm.setDynamicData(dynamic); vm.setSingleQxlPci(false); return vm; } private AddVmCommand<AddVmParameters> createCommand(VM vm) { AddVmParameters param = new AddVmParameters(vm); AddVmCommand<AddVmParameters> cmd = new AddVmCommand<AddVmParameters>(param) { @Override protected void initUser() { // Stub for testing } @Override protected void initTemplateDisks() { // Stub for testing } @Override protected void initStoragePoolId() { // stub for testing } @Override public VmTemplate getVmTemplate() { return createVmTemplate(); } }; cmd = spy(cmd); mockDaos(cmd); mockBackend(cmd); doReturn(new VDSGroup()).when(cmd).getVdsGroup(); generateStorageToDisksMap(cmd); initDestSDs(cmd); storageDomainValidator = mock(StorageDomainValidator.class); doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds(); doReturn(storageDomainValidator).when(cmd).createStorageDomainValidator(any(StorageDomain.class)); return cmd; } protected void generateStorageToDisksMap(AddVmCommand<? extends AddVmParameters> command) { command.storageToDisksMap = new HashMap<>(); command.storageToDisksMap.put(STORAGE_DOMAIN_ID_1, generateDisksList(NUM_DISKS_STORAGE_DOMAIN_1)); command.storageToDisksMap.put(STORAGE_DOMAIN_ID_2, generateDisksList(NUM_DISKS_STORAGE_DOMAIN_2)); } private static List<DiskImage> generateDisksList(int size) { List<DiskImage> disksList = new ArrayList<>(); for (int i = 0; i < size; ++i) { DiskImage diskImage = createDiskImage(REQUIRED_DISK_SIZE_GB); disksList.add(diskImage); } return disksList; } protected void initDestSDs(AddVmCommand<? extends AddVmParameters> command) { StorageDomain sd1 = new StorageDomain(); StorageDomain sd2 = new StorageDomain(); sd1.setId(STORAGE_DOMAIN_ID_1); sd2.setId(STORAGE_DOMAIN_ID_2); command.destStorages.put(STORAGE_DOMAIN_ID_1, sd1); command.destStorages.put(STORAGE_DOMAIN_ID_2, sd2); } protected List<DiskImage> createDiskSnapshot(Guid diskId, int numOfImages) { List<DiskImage> disksList = new ArrayList<>(); for (int i = 0; i < numOfImages; ++i) { DiskImage diskImage = new DiskImage(); diskImage.setActive(false); diskImage.setId(diskId); diskImage.setImageId(Guid.newGuid()); diskImage.setParentId(Guid.newGuid()); diskImage.setImageStatus(ImageStatus.OK); disksList.add(diskImage); } return disksList; } private void mockGetAllSnapshots(AddVmFromTemplateCommand<AddVmParameters> command) { doAnswer(new Answer<List<DiskImage>>() { @Override public List<DiskImage> answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); DiskImage arg = (DiskImage) args[0]; List<DiskImage> list = createDiskSnapshot(arg.getId(), 3); return list; } }).when(command).getAllImageSnapshots(any(DiskImage.class)); } private <T extends AddVmParameters> void mockUninterestingMethods(AddVmCommand<T> spy) { doReturn(true).when(spy).isVmNameValidLength(Matchers.<VM> any(VM.class)); doReturn(false).when(spy).isVmWithSameNameExists(anyString(), any(Guid.class)); doReturn(STORAGE_POOL_ID).when(spy).getStoragePoolId(); doReturn(createVmTemplate()).when(spy).getVmTemplate(); doReturn(createVdsGroup()).when(spy).getVdsGroup(); doReturn(true).when(spy).areParametersLegal(anyListOf(String.class)); doReturn(Collections.<VmNetworkInterface> emptyList()).when(spy).getVmInterfaces(); doReturn(Collections.<DiskImageBase> emptyList()).when(spy).getVmDisks(); doReturn(false).when(spy).isVirtioScsiControllerAttached(any(Guid.class)); doReturn(true).when(osRepository).isSoundDeviceEnabled(any(Integer.class), any(Version.class)); spy.setVmTemplateId(Guid.newGuid()); } @Test public void testBeanValidations() { assertTrue(createCommand(initializeMock(1, 1)).validateInputs()); } @Test public void testPatternBasedNameFails() { AddVmCommand<AddVmParameters> cmd = createCommand(initializeMock(1, 1)); cmd.getParameters().getVm().setName("aa-??bb"); assertFalse("Pattern-based name should not be supported for VM", cmd.validateInputs()); } @Test public void refuseBalloonOnPPC() { AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest(); cmd.getParameters().setBalloonEnabled(true); when(osRepository.isBalloonEnabled(cmd.getParameters().getVm().getVmOsId(), cmd.getVdsGroup().getCompatibilityVersion())).thenReturn(false); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue() .getCanDoActionMessages() .contains(EngineMessage.BALLOON_REQUESTED_ON_NOT_SUPPORTED_ARCH.toString())); } @Test public void refuseSoundDeviceOnPPC() { AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest(); cmd.getParameters().setSoundDeviceEnabled(true); when(osRepository.isSoundDeviceEnabled(cmd.getParameters().getVm().getVmOsId(), cmd.getVdsGroup().getCompatibilityVersion())).thenReturn(false); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue() .getCanDoActionMessages() .contains(EngineMessage.SOUND_DEVICE_REQUESTED_ON_NOT_SUPPORTED_ARCH.toString())); } private AddVmCommand<AddVmParameters> setupCanAddPpcTest() { final int domainSizeGB = 20; final int sizeRequired = 5; AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB, sizeRequired); doReturn(true).when(cmd).validateSpaceRequirements(); doReturn(true).when(cmd).buildAndCheckDestStorageDomains(); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); VDSGroup cluster = new VDSGroup(); cluster.setArchitecture(ArchitectureType.ppc64); cluster.setCompatibilityVersion(Version.getLast()); doReturn(cluster).when(cmd).getVdsGroup(); return cmd; } @Test public void testStoragePoolDoesntExist() { final int domainSizeGB = 20; final int sizeRequired = 5; AddVmCommand<AddVmParameters> cmd = setupCanAddVmTests(domainSizeGB, sizeRequired); doReturn(null).when(cmd).getStoragePool(); assertFalse(cmd.canDoAction()); assertTrue(cmd.getReturnValue() .getCanDoActionMessages() .contains(EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST.toString())); } }
core: AddVmCommandTest asserts Use the pre-existing CanDoActionTestUtils wherever possible instead of re-implementing its functionality in different places. Change-Id: I4906008f67576bd3b52c16e347f2d6b6b7189281 Signed-off-by: Allon Mureinik <[email protected]>
backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/AddVmCommandTest.java
core: AddVmCommandTest asserts
<ide><path>ackend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/AddVmCommandTest.java <ide> mockUninterestingMethods(cmd); <ide> mockGetAllSnapshots(cmd); <ide> doReturn(createStoragePool()).when(cmd).getStoragePool(); <del> assertFalse("If the disk is too big, canDoAction should fail", cmd.canDoAction()); <del> assertTrue("canDoAction failed for the wrong reason", <del> cmd.getReturnValue() <del> .getCanDoActionMessages() <del> .contains(EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN.toString())); <add> <add> CanDoActionTestUtils.runAndAssertCanDoActionFailure <add> (cmd, EngineMessage.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_STORAGE_DOMAIN); <ide> } <ide> <ide> private void mockGraphicsDevices(Guid vmId) { <ide> setupCanAddVmFromSnapshotTests(domainSizeGB, sizeRequired, sourceSnapshotId); <ide> cmd.getVm().setName("vm1"); <ide> mockNonInterestingMethodsForCloneVmFromSnapshot(cmd); <del> assertFalse("Clone vm should have failed due to non existing snapshot id", cmd.canDoAction()); <del> ArrayList<String> reasons = cmd.getReturnValue().getCanDoActionMessages(); <del> assertTrue("Clone vm should have failed due to non existing snapshot id", <del> reasons.contains(EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_DOES_NOT_EXIST.toString())); <add> CanDoActionTestUtils.runAndAssertCanDoActionFailure <add> (cmd, EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_DOES_NOT_EXIST); <ide> } <ide> <ide> @Test <ide> doReturn(ValidationResult.VALID).when(sv).vmNotDuringSnapshot(any(Guid.class)); <ide> doReturn(sv).when(cmd).createSnapshotsValidator(); <ide> when(snapshotDao.get(sourceSnapshotId)).thenReturn(new Snapshot()); <del> assertFalse("Clone vm should have failed due to non existing vm configuration", cmd.canDoAction()); <del> ArrayList<String> reasons = cmd.getReturnValue().getCanDoActionMessages(); <del> assertTrue("Clone vm should have failed due to no configuration id", <del> reasons.contains(EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_HAS_NO_CONFIGURATION.toString())); <del> <add> CanDoActionTestUtils.runAndAssertCanDoActionFailure <add> (cmd, EngineMessage.ACTION_TYPE_FAILED_VM_SNAPSHOT_HAS_NO_CONFIGURATION); <ide> } <ide> <ide> @Test <ide> cmd.getParameters().setBalloonEnabled(true); <ide> when(osRepository.isBalloonEnabled(cmd.getParameters().getVm().getVmOsId(), cmd.getVdsGroup().getCompatibilityVersion())).thenReturn(false); <ide> <del> assertFalse(cmd.canDoAction()); <del> assertTrue(cmd.getReturnValue() <del> .getCanDoActionMessages() <del> .contains(EngineMessage.BALLOON_REQUESTED_ON_NOT_SUPPORTED_ARCH.toString())); <add> CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd, EngineMessage.BALLOON_REQUESTED_ON_NOT_SUPPORTED_ARCH); <ide> } <ide> <ide> @Test <ide> cmd.getParameters().setSoundDeviceEnabled(true); <ide> when(osRepository.isSoundDeviceEnabled(cmd.getParameters().getVm().getVmOsId(), cmd.getVdsGroup().getCompatibilityVersion())).thenReturn(false); <ide> <del> assertFalse(cmd.canDoAction()); <del> assertTrue(cmd.getReturnValue() <del> .getCanDoActionMessages() <del> .contains(EngineMessage.SOUND_DEVICE_REQUESTED_ON_NOT_SUPPORTED_ARCH.toString())); <add> CanDoActionTestUtils.runAndAssertCanDoActionFailure <add> (cmd, EngineMessage.SOUND_DEVICE_REQUESTED_ON_NOT_SUPPORTED_ARCH); <ide> } <ide> <ide> private AddVmCommand<AddVmParameters> setupCanAddPpcTest() { <ide> <ide> doReturn(null).when(cmd).getStoragePool(); <ide> <del> assertFalse(cmd.canDoAction()); <del> assertTrue(cmd.getReturnValue() <del> .getCanDoActionMessages() <del> .contains(EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST.toString())); <add> CanDoActionTestUtils.runAndAssertCanDoActionFailure <add> (cmd, EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST); <ide> } <ide> }
JavaScript
mit
b3e3b61211909cacffb8bd37e467e7c4b5c2b093
0
TWExchangeSolutions/es-components,TWExchangeSolutions/es-components
import React, { useState, useEffect, useRef, Children } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Button from './Button'; import LinkButton from './LinkButton'; import useUniqueId from '../../util/useUniqueId'; import RootCloseWrapper from '../../util/RootCloseWrapper'; const Caret = styled.span` border-left: 4px solid transparent; border-right: 4px solid transparent; border-top: 4px dashed; display: inline-block; height: 0; margin-left: 5px; vertical-align: middle; width: 0; `; const ButtonPanel = styled.div` background-color: ${props => props.theme.colors.white}; border: 1px solid ${props => props.theme.colors.gray3}; display: ${props => (props.isOpen ? 'block' : 'none')}; margin-top: 3px; position: relative; z-index: 999; @media (min-width: ${props => props.theme.screenSize.tablet}) { position: absolute; } `; const ButtonPanelChildrenContainer = styled.div` display: flex; flex-direction: column; `; const StyledButtonLink = styled(LinkButton)` color: black; margin-bottom: 0px; text-align: left; text-decoration: none; padding: 10px 20px; &:active, &:focus, &:hover { background-color: ${props => props.theme.colors.primary}; color: white; } `; const TAB_KEY_CODE = 9; const UP_ARROW_CODE = 38; const DOWN_ARROW_CODE = 40; function getFocusables(node) { const focusableElements = node.querySelectorAll('button'); const firstFocusable = focusableElements[0]; const lastFocusable = focusableElements[focusableElements.length - 1]; return { focusableElements, firstFocusable, lastFocusable }; } function isCurrentlyActive(node) { const rootNode = node.getRootNode(); return rootNode.activeElement === node; } function focusTrap(node) { const { firstFocusable, lastFocusable } = getFocusables(node); function handleTabFocus(event) { if (event.key === 'Tab' || event.keyCode === TAB_KEY_CODE) { if (event.shiftKey) { if (isCurrentlyActive(firstFocusable)) { lastFocusable.focus(); event.preventDefault(); } } else if (isCurrentlyActive(lastFocusable)) { firstFocusable.focus(); event.preventDefault(); } } } node.addEventListener('keydown', handleTabFocus); return function removeKeydownListener() { node.removeEventListener('keydown', handleTabFocus); }; } function arrowMovement(node) { const { focusableElements, firstFocusable, lastFocusable } = getFocusables( node ); const focusables = [...focusableElements]; const rootNode = node.getRootNode(); function handleArrowMovementKeys(event) { if (event.keyCode === UP_ARROW_CODE) { if (isCurrentlyActive(firstFocusable)) { lastFocusable.focus(); event.preventDefault(); } else { const index = focusables.indexOf(rootNode.activeElement); focusables[index - 1].focus(); event.preventDefault(); } } if (event.keyCode === DOWN_ARROW_CODE) { if (isCurrentlyActive(lastFocusable)) { firstFocusable.focus(); event.preventDefault(); } else { const index = focusables.indexOf(rootNode.activeElement); focusableElements[index + 1].focus(); event.preventDefault(); } } } node.addEventListener('keydown', handleArrowMovementKeys); return function removeArrowMovementListener() { node.removeEventListener('keydown', handleArrowMovementKeys); }; } function DropdownButton(props) { const [buttonValue, setButtonValue] = useState(props.buttonValue); const [isOpen, setIsOpen] = useState(false); const initialRender = useRef(true); const buttonDropdown = useRef(); const triggerButton = useRef(); const panelId = useUniqueId(props.id); useEffect(() => { const removeFocusTrapListener = focusTrap(buttonDropdown.current); const removeArrowMovementListener = arrowMovement(buttonDropdown.current); return function removeListeners() { removeFocusTrapListener(); removeArrowMovementListener(); }; }, [isOpen]); useEffect(() => { if (!initialRender.current) { triggerButton.current.focus(); } initialRender.current = false; }, [isOpen]); const toggleDropdown = () => setIsOpen(!isOpen); function closeDropdown() { if (isOpen) { setIsOpen(false); } } function handleDropdownItemClick(buttonProps) { const { shouldCloseOnButtonClick, shouldUpdateButtonValue } = props; return event => { if (shouldUpdateButtonValue) { setButtonValue(buttonProps.children); } if (shouldCloseOnButtonClick) { closeDropdown(); } buttonProps.onClick(event, buttonProps.name); }; } const { rootClose, children, manualButtonValue, styleType, inline, ...otherProps } = props; return ( <RootCloseWrapper onRootClose={closeDropdown} disabled={!rootClose} css={` display: ${inline ? 'inline-flex' : 'block'}; flex-direction: column; position: relative; `} > <div ref={buttonDropdown} role="combobox" aria-controls={panelId} aria-expanded={isOpen} aria-haspopup="listbox" > <Button {...otherProps} onClick={toggleDropdown} aria-haspopup="true" aria-pressed={isOpen} ref={triggerButton} styleType={styleType} > {manualButtonValue || buttonValue} <Caret /> </Button> <div css="position: relative;"> <ButtonPanel isOpen={isOpen} id={panelId}> <ButtonPanelChildrenContainer> {Children.map(children, child => { const onClickHandler = handleDropdownItemClick(child.props); const newProps = { onClick: onClickHandler, role: 'option' }; return React.cloneElement(child, newProps); })} </ButtonPanelChildrenContainer> </ButtonPanel> </div> </div> </RootCloseWrapper> ); } DropdownButton.Button = StyledButtonLink; DropdownButton.propTypes = { /** Content shown in the button */ buttonValue: PropTypes.any, /** * Defines what value should be displayed on the button. * Overrides the stored state value, and renders shouldUpdateButtonValue * useless */ manualButtonValue: PropTypes.node, children: PropTypes.any.isRequired, /** * Defines if the buttons value should update to the last pressed, * childs value. */ shouldUpdateButtonValue: PropTypes.bool, /** Defines if the dropdown should close when any child button is clicked */ shouldCloseOnButtonClick: PropTypes.bool, /** * Defines whether the dropdown will close when any other element on the page is clicked. * Uses RootCloseWrapper from React-Overlay */ rootClose: PropTypes.bool, /** Select the color style of the button, types come from theme */ styleType: PropTypes.string, /** Display the dropdown button inline */ inline: PropTypes.bool, id: PropTypes.string }; DropdownButton.defaultProps = { buttonValue: undefined, manualButtonValue: undefined, shouldUpdateButtonValue: false, shouldCloseOnButtonClick: false, styleType: 'default', rootClose: false, inline: false, id: undefined }; export default DropdownButton;
packages/es-components/src/components/controls/buttons/DropdownButton.js
import React, { useState, useEffect, useRef, Children } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Button from './Button'; import LinkButton from './LinkButton'; import useUniqueId from '../../util/useUniqueId'; import RootCloseWrapper from '../../util/RootCloseWrapper'; const Caret = styled.span` border-left: 4px solid transparent; border-right: 4px solid transparent; border-top: 4px dashed; display: inline-block; height: 0; margin-left: 5px; vertical-align: middle; width: 0; `; const ButtonPanel = styled.div` background-color: ${props => props.theme.colors.white}; border: 1px solid ${props => props.theme.colors.gray3}; display: ${props => (props.isOpen ? 'block' : 'none')}; margin-top: 3px; position: relative; z-index: 999; @media (min-width: ${props => props.theme.screenSize.tablet}) { position: absolute; } `; const ButtonPanelChildrenContainer = styled.div` display: flex; flex-direction: column; `; const StyledButtonLink = styled(LinkButton)` color: black; margin-bottom: 0px; text-align: left; text-decoration: none; padding: 10px 20px; &:active, &:focus, &:hover { background-color: ${props => props.theme.colors.primary}; color: white; } `; const TAB_KEY_CODE = 9; const UP_ARROW_CODE = 38; const DOWN_ARROW_CODE = 40; function getFocusables(node) { const focusableElements = node.querySelectorAll('button'); const firstFocusable = focusableElements[0]; const lastFocusable = focusableElements[focusableElements.length - 1]; return { focusableElements, firstFocusable, lastFocusable }; } function isCurrentlyActive(node) { return document.activeElement === node; } function focusTrap(node) { const { firstFocusable, lastFocusable } = getFocusables(node); function handleTabFocus(event) { if (event.key === 'Tab' || event.keyCode === TAB_KEY_CODE) { if (event.shiftKey) { if (isCurrentlyActive(firstFocusable)) { lastFocusable.focus(); event.preventDefault(); } } else if (isCurrentlyActive(lastFocusable)) { firstFocusable.focus(); event.preventDefault(); } } } node.addEventListener('keydown', handleTabFocus); return function removeKeydownListener() { node.removeEventListener('keydown', handleTabFocus); }; } function arrowMovement(node) { const { focusableElements, firstFocusable, lastFocusable } = getFocusables( node ); const focusables = [...focusableElements]; function handleArrowMovementKeys(event) { if (event.keyCode === UP_ARROW_CODE) { if (isCurrentlyActive(firstFocusable)) { lastFocusable.focus(); event.preventDefault(); } else { const index = focusables.indexOf(document.activeElement); focusables[index - 1].focus(); event.preventDefault(); } } if (event.keyCode === DOWN_ARROW_CODE) { if (isCurrentlyActive(lastFocusable)) { firstFocusable.focus(); event.preventDefault(); } else { const index = focusables.indexOf(document.activeElement); focusableElements[index + 1].focus(); event.preventDefault(); } } } node.addEventListener('keydown', handleArrowMovementKeys); return function removeArrowMovementListener() { node.removeEventListener('keydown', handleArrowMovementKeys); }; } function DropdownButton(props) { const [buttonValue, setButtonValue] = useState(props.buttonValue); const [isOpen, setIsOpen] = useState(false); const initialRender = useRef(true); const buttonDropdown = useRef(); const triggerButton = useRef(); const panelId = useUniqueId(props.id); useEffect(() => { const removeFocusTrapListener = focusTrap(buttonDropdown.current); const removeArrowMovementListener = arrowMovement(buttonDropdown.current); return function removeListeners() { removeFocusTrapListener(); removeArrowMovementListener(); }; }, [isOpen]); useEffect(() => { if (!initialRender.current) { triggerButton.current.focus(); } initialRender.current = false; }, [isOpen]); const toggleDropdown = () => setIsOpen(!isOpen); function closeDropdown() { if (isOpen) { setIsOpen(false); } } function handleDropdownItemClick(buttonProps) { const { shouldCloseOnButtonClick, shouldUpdateButtonValue } = props; return event => { if (shouldUpdateButtonValue) { setButtonValue(buttonProps.children); } if (shouldCloseOnButtonClick) { closeDropdown(); } buttonProps.onClick(event, buttonProps.name); }; } const { rootClose, children, manualButtonValue, styleType, inline, ...otherProps } = props; return ( <RootCloseWrapper onRootClose={closeDropdown} disabled={!rootClose} css={` display: ${inline ? 'inline-flex' : 'block'}; flex-direction: column; position: relative; `} > <div ref={buttonDropdown} role="combobox" aria-controls={panelId} aria-expanded={isOpen} aria-haspopup="listbox" > <Button {...otherProps} onClick={toggleDropdown} aria-haspopup="true" aria-pressed={isOpen} ref={triggerButton} styleType={styleType} > {manualButtonValue || buttonValue} <Caret /> </Button> <div css="position: relative;"> <ButtonPanel isOpen={isOpen} id={panelId}> <ButtonPanelChildrenContainer> {Children.map(children, child => { const onClickHandler = handleDropdownItemClick(child.props); const newProps = { onClick: onClickHandler, role: 'option' }; return React.cloneElement(child, newProps); })} </ButtonPanelChildrenContainer> </ButtonPanel> </div> </div> </RootCloseWrapper> ); } DropdownButton.Button = StyledButtonLink; DropdownButton.propTypes = { /** Content shown in the button */ buttonValue: PropTypes.any, /** * Defines what value should be displayed on the button. * Overrides the stored state value, and renders shouldUpdateButtonValue * useless */ manualButtonValue: PropTypes.node, children: PropTypes.any.isRequired, /** * Defines if the buttons value should update to the last pressed, * childs value. */ shouldUpdateButtonValue: PropTypes.bool, /** Defines if the dropdown should close when any child button is clicked */ shouldCloseOnButtonClick: PropTypes.bool, /** * Defines whether the dropdown will close when any other element on the page is clicked. * Uses RootCloseWrapper from React-Overlay */ rootClose: PropTypes.bool, /** Select the color style of the button, types come from theme */ styleType: PropTypes.string, /** Display the dropdown button inline */ inline: PropTypes.bool, id: PropTypes.string }; DropdownButton.defaultProps = { buttonValue: undefined, manualButtonValue: undefined, shouldUpdateButtonValue: false, shouldCloseOnButtonClick: false, styleType: 'default', rootClose: false, inline: false, id: undefined }; export default DropdownButton;
Update: using getRootNode in DropdownButton
packages/es-components/src/components/controls/buttons/DropdownButton.js
Update: using getRootNode in DropdownButton
<ide><path>ackages/es-components/src/components/controls/buttons/DropdownButton.js <ide> } <ide> <ide> function isCurrentlyActive(node) { <del> return document.activeElement === node; <add> const rootNode = node.getRootNode(); <add> return rootNode.activeElement === node; <ide> } <ide> <ide> function focusTrap(node) { <ide> node <ide> ); <ide> const focusables = [...focusableElements]; <add> const rootNode = node.getRootNode(); <ide> <ide> function handleArrowMovementKeys(event) { <ide> if (event.keyCode === UP_ARROW_CODE) { <ide> lastFocusable.focus(); <ide> event.preventDefault(); <ide> } else { <del> const index = focusables.indexOf(document.activeElement); <add> const index = focusables.indexOf(rootNode.activeElement); <ide> focusables[index - 1].focus(); <ide> event.preventDefault(); <ide> } <ide> firstFocusable.focus(); <ide> event.preventDefault(); <ide> } else { <del> const index = focusables.indexOf(document.activeElement); <add> const index = focusables.indexOf(rootNode.activeElement); <ide> focusableElements[index + 1].focus(); <ide> event.preventDefault(); <ide> }
Java
apache-2.0
52962baf39ab1cab8a0122113c9d380d85d6fdd1
0
ptkool/presto,prestodb/presto,twitter-forks/presto,ptkool/presto,zzhao0/presto,stewartpark/presto,stewartpark/presto,prestodb/presto,arhimondr/presto,zzhao0/presto,facebook/presto,twitter-forks/presto,zzhao0/presto,facebook/presto,shixuan-fan/presto,EvilMcJerkface/presto,EvilMcJerkface/presto,ptkool/presto,shixuan-fan/presto,shixuan-fan/presto,facebook/presto,mvp/presto,EvilMcJerkface/presto,nezihyigitbasi/presto,mvp/presto,nezihyigitbasi/presto,arhimondr/presto,nezihyigitbasi/presto,prestodb/presto,zzhao0/presto,twitter-forks/presto,nezihyigitbasi/presto,mvp/presto,facebook/presto,stewartpark/presto,ptkool/presto,arhimondr/presto,nezihyigitbasi/presto,stewartpark/presto,prestodb/presto,twitter-forks/presto,shixuan-fan/presto,prestodb/presto,facebook/presto,arhimondr/presto,mvp/presto,EvilMcJerkface/presto,EvilMcJerkface/presto,mvp/presto,arhimondr/presto,shixuan-fan/presto,ptkool/presto,zzhao0/presto,twitter-forks/presto,prestodb/presto,stewartpark/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive.security; import com.facebook.presto.hive.HiveConnectorId; import com.facebook.presto.hive.HiveTransactionHandle; import com.facebook.presto.hive.metastore.Database; import com.facebook.presto.hive.metastore.HivePrivilegeInfo; import com.facebook.presto.hive.metastore.SemiTransactionalHiveMetastore; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.connector.ConnectorAccessControl; import com.facebook.presto.spi.connector.ConnectorTransactionHandle; import com.facebook.presto.spi.security.AccessDeniedException; import com.facebook.presto.spi.security.ConnectorIdentity; import com.facebook.presto.spi.security.PrestoPrincipal; import com.facebook.presto.spi.security.Privilege; import com.facebook.presto.spi.security.RoleGrant; import com.google.common.collect.ImmutableSet; import javax.inject.Inject; import java.util.Optional; import java.util.Set; import java.util.function.Function; import static com.facebook.presto.hive.metastore.Database.DEFAULT_DATABASE_NAME; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.DELETE; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.INSERT; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.OWNERSHIP; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.SELECT; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.toHivePrivilege; import static com.facebook.presto.hive.metastore.thrift.ThriftMetastoreUtil.listApplicableRoles; import static com.facebook.presto.hive.metastore.thrift.ThriftMetastoreUtil.listApplicableTablePrivileges; import static com.facebook.presto.spi.security.AccessDeniedException.denyAddColumn; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateRole; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateSchema; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateView; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateViewWithSelect; import static com.facebook.presto.spi.security.AccessDeniedException.denyDeleteTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropColumn; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropRole; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropSchema; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropView; import static com.facebook.presto.spi.security.AccessDeniedException.denyGrantRoles; import static com.facebook.presto.spi.security.AccessDeniedException.denyGrantTablePrivilege; import static com.facebook.presto.spi.security.AccessDeniedException.denyInsertTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyRenameColumn; import static com.facebook.presto.spi.security.AccessDeniedException.denyRenameSchema; import static com.facebook.presto.spi.security.AccessDeniedException.denyRenameTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyRevokeRoles; import static com.facebook.presto.spi.security.AccessDeniedException.denyRevokeTablePrivilege; import static com.facebook.presto.spi.security.AccessDeniedException.denySelectTable; import static com.facebook.presto.spi.security.AccessDeniedException.denySetCatalogSessionProperty; import static com.facebook.presto.spi.security.AccessDeniedException.denySetRole; import static com.facebook.presto.spi.security.AccessDeniedException.denyShowRoles; import static com.facebook.presto.spi.security.PrincipalType.ROLE; import static com.facebook.presto.spi.security.PrincipalType.USER; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toSet; public class SqlStandardAccessControl implements ConnectorAccessControl { public static final String ADMIN_ROLE_NAME = "admin"; private static final String INFORMATION_SCHEMA_NAME = "information_schema"; private static final SchemaTableName ROLES = new SchemaTableName(INFORMATION_SCHEMA_NAME, "roles"); private final String connectorId; private final Function<HiveTransactionHandle, SemiTransactionalHiveMetastore> metastoreProvider; @Inject public SqlStandardAccessControl( HiveConnectorId connectorId, Function<HiveTransactionHandle, SemiTransactionalHiveMetastore> metastoreProvider) { this.connectorId = requireNonNull(connectorId, "connectorId is null").toString(); this.metastoreProvider = requireNonNull(metastoreProvider, "metastoreProvider is null"); } @Override public void checkCanCreateSchema(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String schemaName) { if (!isAdmin(transaction, identity)) { denyCreateSchema(schemaName); } } @Override public void checkCanDropSchema(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String schemaName) { if (!isDatabaseOwner(transaction, identity, schemaName)) { denyDropSchema(schemaName); } } @Override public void checkCanRenameSchema(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String schemaName, String newSchemaName) { if (!isDatabaseOwner(transaction, identity, schemaName)) { denyRenameSchema(schemaName, newSchemaName); } } @Override public void checkCanShowSchemas(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity) { } @Override public Set<String> filterSchemas(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, Set<String> schemaNames) { return schemaNames; } @Override public void checkCanCreateTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!isDatabaseOwner(transaction, identity, tableName.getSchemaName())) { denyCreateTable(tableName.toString()); } } @Override public void checkCanDropTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!isTableOwner(transaction, identity, tableName)) { denyDropTable(tableName.toString()); } } @Override public void checkCanRenameTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, SchemaTableName newTableName) { if (!isTableOwner(transaction, identity, tableName)) { denyRenameTable(tableName.toString(), newTableName.toString()); } } @Override public void checkCanShowTablesMetadata(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String schemaName) { } @Override public Set<SchemaTableName> filterTables(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, Set<SchemaTableName> tableNames) { return tableNames; } @Override public void checkCanAddColumn(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!isTableOwner(transaction, identity, tableName)) { denyAddColumn(tableName.toString()); } } @Override public void checkCanDropColumn(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!isTableOwner(transaction, identity, tableName)) { denyDropColumn(tableName.toString()); } } @Override public void checkCanRenameColumn(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!isTableOwner(transaction, identity, tableName)) { denyRenameColumn(tableName.toString()); } } @Override public void checkCanSelectFromColumns(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, Set<String> columnNames) { // TODO: Implement column level access control if (!checkTablePermission(transaction, identity, tableName, SELECT)) { denySelectTable(tableName.toString()); } } @Override public void checkCanInsertIntoTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!checkTablePermission(transaction, identity, tableName, INSERT)) { denyInsertTable(tableName.toString()); } } @Override public void checkCanDeleteFromTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!checkTablePermission(transaction, identity, tableName, DELETE)) { denyDeleteTable(tableName.toString()); } } @Override public void checkCanCreateView(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName viewName) { if (!isDatabaseOwner(transaction, identity, viewName.getSchemaName())) { denyCreateView(viewName.toString()); } } @Override public void checkCanDropView(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName viewName) { if (!isTableOwner(transaction, identity, viewName)) { denyDropView(viewName.toString()); } } @Override public void checkCanCreateViewWithSelectFromColumns(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, Set<String> columnNames) { // TODO implement column level access control if (!checkTablePermission(transaction, identity, tableName, SELECT)) { denySelectTable(tableName.toString()); } if (!hasGrantOptionForPrivilege(transaction, identity, Privilege.SELECT, tableName)) { denyCreateViewWithSelect(tableName.toString(), identity); } } @Override public void checkCanSetCatalogSessionProperty(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String propertyName) { if (!isAdmin(transaction, identity)) { denySetCatalogSessionProperty(connectorId, propertyName); } } @Override public void checkCanGrantTablePrivilege(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Privilege privilege, SchemaTableName tableName, PrestoPrincipal grantee, boolean withGrantOption) { if (isTableOwner(transaction, identity, tableName)) { return; } if (!hasGrantOptionForPrivilege(transaction, identity, privilege, tableName)) { denyGrantTablePrivilege(privilege.name(), tableName.toString()); } } @Override public void checkCanRevokeTablePrivilege(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Privilege privilege, SchemaTableName tableName, PrestoPrincipal revokee, boolean grantOptionFor) { if (isTableOwner(transaction, identity, tableName)) { return; } if (!hasGrantOptionForPrivilege(transaction, identity, privilege, tableName)) { denyRevokeTablePrivilege(privilege.name(), tableName.toString()); } } @Override public void checkCanCreateRole(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String role, Optional<PrestoPrincipal> grantor) { // currently specifying grantor is supported by metastore, but it is not supported by Hive itself if (grantor.isPresent()) { throw new AccessDeniedException("Hive Connector does not support WITH ADMIN statement"); } if (!isAdmin(transactionHandle, identity)) { denyCreateRole(role); } } @Override public void checkCanDropRole(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String role) { if (!isAdmin(transactionHandle, identity)) { denyDropRole(role); } } @Override public void checkCanGrantRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, Set<String> roles, Set<PrestoPrincipal> grantees, boolean withAdminOption, Optional<PrestoPrincipal> grantor, String catalogName) { // currently specifying grantor is supported by metastore, but it is not supported by Hive itself if (grantor.isPresent()) { throw new AccessDeniedException("Hive Connector does not support GRANTED BY statement"); } if (!hasAdminOptionForRoles(transactionHandle, identity, roles)) { denyGrantRoles(roles, grantees); } } @Override public void checkCanRevokeRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, Set<String> roles, Set<PrestoPrincipal> grantees, boolean adminOptionFor, Optional<PrestoPrincipal> grantor, String catalogName) { // currently specifying grantor is supported by metastore, but it is not supported by Hive itself if (grantor.isPresent()) { throw new AccessDeniedException("Hive Connector does not support GRANTED BY statement"); } if (!hasAdminOptionForRoles(transactionHandle, identity, roles)) { denyRevokeRoles(roles, grantees); } } @Override public void checkCanSetRole(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String role, String catalogName) { SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); if (!listApplicableRoles(metastore, new PrestoPrincipal(USER, identity.getUser())).contains(role)) { denySetRole(role); } } @Override public void checkCanShowRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String catalogName) { if (!isAdmin(transactionHandle, identity)) { denyShowRoles(catalogName); } } @Override public void checkCanShowCurrentRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String catalogName) { } @Override public void checkCanShowRoleGrants(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String catalogName) { } private boolean isAdmin(ConnectorTransactionHandle transaction, ConnectorIdentity identity) { SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); return listApplicableRoles(metastore, new PrestoPrincipal(USER, identity.getUser())).contains(ADMIN_ROLE_NAME); } private boolean isDatabaseOwner(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String databaseName) { // all users are "owners" of the default database if (DEFAULT_DATABASE_NAME.equalsIgnoreCase(databaseName)) { return true; } if (isAdmin(transaction, identity)) { return true; } SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); Optional<Database> databaseMetadata = metastore.getDatabase(databaseName); if (!databaseMetadata.isPresent()) { return false; } Database database = databaseMetadata.get(); // a database can be owned by a user or role if (database.getOwnerType() == USER && identity.getUser().equals(database.getOwnerName())) { return true; } if (database.getOwnerType() == ROLE && listApplicableRoles(metastore, new PrestoPrincipal(USER, identity.getUser())).contains(database.getOwnerName())) { return true; } return false; } private boolean isTableOwner(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { return checkTablePermission(transaction, identity, tableName, OWNERSHIP); } private boolean checkTablePermission(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, HivePrivilege... requiredPrivileges) { if (isAdmin(transaction, identity)) { return true; } if (tableName.equals(ROLES)) { return false; } if (INFORMATION_SCHEMA_NAME.equals(tableName.getSchemaName())) { return true; } SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); Set<HivePrivilege> privilegeSet = listApplicableTablePrivileges( metastore, tableName.getSchemaName(), tableName.getTableName(), new PrestoPrincipal(USER, identity.getUser())) .stream() .map(HivePrivilegeInfo::getHivePrivilege) .collect(toSet()); return privilegeSet.containsAll(ImmutableSet.copyOf(requiredPrivileges)); } private boolean hasGrantOptionForPrivilege(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Privilege privilege, SchemaTableName tableName) { if (isAdmin(transaction, identity)) { return true; } SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); return listApplicableTablePrivileges( metastore, tableName.getSchemaName(), tableName.getTableName(), new PrestoPrincipal(USER, identity.getUser())) .contains(new HivePrivilegeInfo(toHivePrivilege(privilege), true)); } private boolean hasAdminOptionForRoles(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Set<String> roles) { if (isAdmin(transaction, identity)) { return true; } SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); Set<RoleGrant> grants = listApplicableRoles(new PrestoPrincipal(USER, identity.getUser()), metastore::listRoleGrants); Set<String> rolesWithGrantOption = grants.stream() .filter(RoleGrant::isGrantable) .map(RoleGrant::getRoleName) .collect(toSet()); return rolesWithGrantOption.containsAll(roles); } }
presto-hive/src/main/java/com/facebook/presto/hive/security/SqlStandardAccessControl.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive.security; import com.facebook.presto.hive.HiveConnectorId; import com.facebook.presto.hive.HiveTransactionHandle; import com.facebook.presto.hive.metastore.Database; import com.facebook.presto.hive.metastore.HivePrivilegeInfo; import com.facebook.presto.hive.metastore.SemiTransactionalHiveMetastore; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.connector.ConnectorAccessControl; import com.facebook.presto.spi.connector.ConnectorTransactionHandle; import com.facebook.presto.spi.security.AccessDeniedException; import com.facebook.presto.spi.security.ConnectorIdentity; import com.facebook.presto.spi.security.PrestoPrincipal; import com.facebook.presto.spi.security.Privilege; import com.facebook.presto.spi.security.RoleGrant; import com.google.common.collect.ImmutableSet; import javax.inject.Inject; import java.util.Optional; import java.util.Set; import java.util.function.Function; import static com.facebook.presto.hive.metastore.Database.DEFAULT_DATABASE_NAME; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.DELETE; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.INSERT; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.OWNERSHIP; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.SELECT; import static com.facebook.presto.hive.metastore.HivePrivilegeInfo.toHivePrivilege; import static com.facebook.presto.hive.metastore.thrift.ThriftMetastoreUtil.listApplicableRoles; import static com.facebook.presto.hive.metastore.thrift.ThriftMetastoreUtil.listApplicableTablePrivileges; import static com.facebook.presto.spi.security.AccessDeniedException.denyAddColumn; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateRole; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateSchema; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateView; import static com.facebook.presto.spi.security.AccessDeniedException.denyCreateViewWithSelect; import static com.facebook.presto.spi.security.AccessDeniedException.denyDeleteTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropColumn; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropRole; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropSchema; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyDropView; import static com.facebook.presto.spi.security.AccessDeniedException.denyGrantRoles; import static com.facebook.presto.spi.security.AccessDeniedException.denyGrantTablePrivilege; import static com.facebook.presto.spi.security.AccessDeniedException.denyInsertTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyRenameColumn; import static com.facebook.presto.spi.security.AccessDeniedException.denyRenameSchema; import static com.facebook.presto.spi.security.AccessDeniedException.denyRenameTable; import static com.facebook.presto.spi.security.AccessDeniedException.denyRevokeRoles; import static com.facebook.presto.spi.security.AccessDeniedException.denyRevokeTablePrivilege; import static com.facebook.presto.spi.security.AccessDeniedException.denySelectTable; import static com.facebook.presto.spi.security.AccessDeniedException.denySetCatalogSessionProperty; import static com.facebook.presto.spi.security.AccessDeniedException.denySetRole; import static com.facebook.presto.spi.security.AccessDeniedException.denyShowRoles; import static com.facebook.presto.spi.security.PrincipalType.ROLE; import static com.facebook.presto.spi.security.PrincipalType.USER; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toSet; public class SqlStandardAccessControl implements ConnectorAccessControl { public static final String ADMIN_ROLE_NAME = "admin"; private static final String INFORMATION_SCHEMA_NAME = "information_schema"; private static final SchemaTableName ROLES = new SchemaTableName(INFORMATION_SCHEMA_NAME, "roles"); private final String connectorId; private final Function<HiveTransactionHandle, SemiTransactionalHiveMetastore> metastoreProvider; @Inject public SqlStandardAccessControl( HiveConnectorId connectorId, Function<HiveTransactionHandle, SemiTransactionalHiveMetastore> metastoreProvider) { this.connectorId = requireNonNull(connectorId, "connectorId is null").toString(); this.metastoreProvider = requireNonNull(metastoreProvider, "metastoreProvider is null"); } @Override public void checkCanCreateSchema(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String schemaName) { if (!isAdmin(transaction, identity)) { denyCreateSchema(schemaName); } } @Override public void checkCanDropSchema(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String schemaName) { if (!isDatabaseOwner(transaction, identity, schemaName)) { denyDropSchema(schemaName); } } @Override public void checkCanRenameSchema(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String schemaName, String newSchemaName) { if (!isDatabaseOwner(transaction, identity, schemaName)) { denyRenameSchema(schemaName, newSchemaName); } } @Override public void checkCanShowSchemas(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity) { } @Override public Set<String> filterSchemas(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, Set<String> schemaNames) { return schemaNames; } @Override public void checkCanCreateTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!isDatabaseOwner(transaction, identity, tableName.getSchemaName())) { denyCreateTable(tableName.toString()); } } @Override public void checkCanDropTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { denyDropTable(tableName.toString()); } } @Override public void checkCanRenameTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, SchemaTableName newTableName) { if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { denyRenameTable(tableName.toString(), newTableName.toString()); } } @Override public void checkCanShowTablesMetadata(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String schemaName) { } @Override public Set<SchemaTableName> filterTables(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, Set<SchemaTableName> tableNames) { return tableNames; } @Override public void checkCanAddColumn(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { denyAddColumn(tableName.toString()); } } @Override public void checkCanDropColumn(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { denyDropColumn(tableName.toString()); } } @Override public void checkCanRenameColumn(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { denyRenameColumn(tableName.toString()); } } @Override public void checkCanSelectFromColumns(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, Set<String> columnNames) { // TODO: Implement column level access control if (!checkTablePermission(transaction, identity, tableName, SELECT)) { denySelectTable(tableName.toString()); } } @Override public void checkCanInsertIntoTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!checkTablePermission(transaction, identity, tableName, INSERT)) { denyInsertTable(tableName.toString()); } } @Override public void checkCanDeleteFromTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) { if (!checkTablePermission(transaction, identity, tableName, DELETE)) { denyDeleteTable(tableName.toString()); } } @Override public void checkCanCreateView(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName viewName) { if (!isDatabaseOwner(transaction, identity, viewName.getSchemaName())) { denyCreateView(viewName.toString()); } } @Override public void checkCanDropView(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName viewName) { if (!checkTablePermission(transaction, identity, viewName, OWNERSHIP)) { denyDropView(viewName.toString()); } } @Override public void checkCanCreateViewWithSelectFromColumns(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, Set<String> columnNames) { // TODO implement column level access control if (!checkTablePermission(transaction, identity, tableName, SELECT)) { denySelectTable(tableName.toString()); } if (!hasGrantOptionForPrivilege(transaction, identity, Privilege.SELECT, tableName)) { denyCreateViewWithSelect(tableName.toString(), identity); } } @Override public void checkCanSetCatalogSessionProperty(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String propertyName) { if (!isAdmin(transaction, identity)) { denySetCatalogSessionProperty(connectorId, propertyName); } } @Override public void checkCanGrantTablePrivilege(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Privilege privilege, SchemaTableName tableName, PrestoPrincipal grantee, boolean withGrantOption) { if (checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { return; } if (!hasGrantOptionForPrivilege(transaction, identity, privilege, tableName)) { denyGrantTablePrivilege(privilege.name(), tableName.toString()); } } @Override public void checkCanRevokeTablePrivilege(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Privilege privilege, SchemaTableName tableName, PrestoPrincipal revokee, boolean grantOptionFor) { if (checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { return; } if (!hasGrantOptionForPrivilege(transaction, identity, privilege, tableName)) { denyRevokeTablePrivilege(privilege.name(), tableName.toString()); } } @Override public void checkCanCreateRole(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String role, Optional<PrestoPrincipal> grantor) { // currently specifying grantor is supported by metastore, but it is not supported by Hive itself if (grantor.isPresent()) { throw new AccessDeniedException("Hive Connector does not support WITH ADMIN statement"); } if (!isAdmin(transactionHandle, identity)) { denyCreateRole(role); } } @Override public void checkCanDropRole(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String role) { if (!isAdmin(transactionHandle, identity)) { denyDropRole(role); } } @Override public void checkCanGrantRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, Set<String> roles, Set<PrestoPrincipal> grantees, boolean withAdminOption, Optional<PrestoPrincipal> grantor, String catalogName) { // currently specifying grantor is supported by metastore, but it is not supported by Hive itself if (grantor.isPresent()) { throw new AccessDeniedException("Hive Connector does not support GRANTED BY statement"); } if (!hasAdminOptionForRoles(transactionHandle, identity, roles)) { denyGrantRoles(roles, grantees); } } @Override public void checkCanRevokeRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, Set<String> roles, Set<PrestoPrincipal> grantees, boolean adminOptionFor, Optional<PrestoPrincipal> grantor, String catalogName) { // currently specifying grantor is supported by metastore, but it is not supported by Hive itself if (grantor.isPresent()) { throw new AccessDeniedException("Hive Connector does not support GRANTED BY statement"); } if (!hasAdminOptionForRoles(transactionHandle, identity, roles)) { denyRevokeRoles(roles, grantees); } } @Override public void checkCanSetRole(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String role, String catalogName) { SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); if (!listApplicableRoles(metastore, new PrestoPrincipal(USER, identity.getUser())).contains(role)) { denySetRole(role); } } @Override public void checkCanShowRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String catalogName) { if (!isAdmin(transactionHandle, identity)) { denyShowRoles(catalogName); } } @Override public void checkCanShowCurrentRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String catalogName) { } @Override public void checkCanShowRoleGrants(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, String catalogName) { } private boolean isAdmin(ConnectorTransactionHandle transaction, ConnectorIdentity identity) { SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); return listApplicableRoles(metastore, new PrestoPrincipal(USER, identity.getUser())).contains(ADMIN_ROLE_NAME); } private boolean isDatabaseOwner(ConnectorTransactionHandle transaction, ConnectorIdentity identity, String databaseName) { // all users are "owners" of the default database if (DEFAULT_DATABASE_NAME.equalsIgnoreCase(databaseName)) { return true; } if (isAdmin(transaction, identity)) { return true; } SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); Optional<Database> databaseMetadata = metastore.getDatabase(databaseName); if (!databaseMetadata.isPresent()) { return false; } Database database = databaseMetadata.get(); // a database can be owned by a user or role if (database.getOwnerType() == USER && identity.getUser().equals(database.getOwnerName())) { return true; } if (database.getOwnerType() == ROLE && listApplicableRoles(metastore, new PrestoPrincipal(USER, identity.getUser())).contains(database.getOwnerName())) { return true; } return false; } private boolean checkTablePermission(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, HivePrivilege... requiredPrivileges) { if (isAdmin(transaction, identity)) { return true; } if (tableName.equals(ROLES)) { return false; } if (INFORMATION_SCHEMA_NAME.equals(tableName.getSchemaName())) { return true; } SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); Set<HivePrivilege> privilegeSet = listApplicableTablePrivileges( metastore, tableName.getSchemaName(), tableName.getTableName(), new PrestoPrincipal(USER, identity.getUser())) .stream() .map(HivePrivilegeInfo::getHivePrivilege) .collect(toSet()); return privilegeSet.containsAll(ImmutableSet.copyOf(requiredPrivileges)); } private boolean hasGrantOptionForPrivilege(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Privilege privilege, SchemaTableName tableName) { if (isAdmin(transaction, identity)) { return true; } SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); return listApplicableTablePrivileges( metastore, tableName.getSchemaName(), tableName.getTableName(), new PrestoPrincipal(USER, identity.getUser())) .contains(new HivePrivilegeInfo(toHivePrivilege(privilege), true)); } private boolean hasAdminOptionForRoles(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Set<String> roles) { if (isAdmin(transaction, identity)) { return true; } SemiTransactionalHiveMetastore metastore = metastoreProvider.apply(((HiveTransactionHandle) transaction)); Set<RoleGrant> grants = listApplicableRoles(new PrestoPrincipal(USER, identity.getUser()), metastore::listRoleGrants); Set<String> rolesWithGrantOption = grants.stream() .filter(RoleGrant::isGrantable) .map(RoleGrant::getRoleName) .collect(toSet()); return rolesWithGrantOption.containsAll(roles); } }
Introduce isTableOwner method for readability
presto-hive/src/main/java/com/facebook/presto/hive/security/SqlStandardAccessControl.java
Introduce isTableOwner method for readability
<ide><path>resto-hive/src/main/java/com/facebook/presto/hive/security/SqlStandardAccessControl.java <ide> @Override <ide> public void checkCanDropTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) <ide> { <del> if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { <add> if (!isTableOwner(transaction, identity, tableName)) { <ide> denyDropTable(tableName.toString()); <ide> } <ide> } <ide> @Override <ide> public void checkCanRenameTable(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, SchemaTableName newTableName) <ide> { <del> if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { <add> if (!isTableOwner(transaction, identity, tableName)) { <ide> denyRenameTable(tableName.toString(), newTableName.toString()); <ide> } <ide> } <ide> @Override <ide> public void checkCanAddColumn(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) <ide> { <del> if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { <add> if (!isTableOwner(transaction, identity, tableName)) { <ide> denyAddColumn(tableName.toString()); <ide> } <ide> } <ide> @Override <ide> public void checkCanDropColumn(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) <ide> { <del> if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { <add> if (!isTableOwner(transaction, identity, tableName)) { <ide> denyDropColumn(tableName.toString()); <ide> } <ide> } <ide> @Override <ide> public void checkCanRenameColumn(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) <ide> { <del> if (!checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { <add> if (!isTableOwner(transaction, identity, tableName)) { <ide> denyRenameColumn(tableName.toString()); <ide> } <ide> } <ide> @Override <ide> public void checkCanDropView(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName viewName) <ide> { <del> if (!checkTablePermission(transaction, identity, viewName, OWNERSHIP)) { <add> if (!isTableOwner(transaction, identity, viewName)) { <ide> denyDropView(viewName.toString()); <ide> } <ide> } <ide> @Override <ide> public void checkCanGrantTablePrivilege(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Privilege privilege, SchemaTableName tableName, PrestoPrincipal grantee, boolean withGrantOption) <ide> { <del> if (checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { <add> if (isTableOwner(transaction, identity, tableName)) { <ide> return; <ide> } <ide> <ide> @Override <ide> public void checkCanRevokeTablePrivilege(ConnectorTransactionHandle transaction, ConnectorIdentity identity, Privilege privilege, SchemaTableName tableName, PrestoPrincipal revokee, boolean grantOptionFor) <ide> { <del> if (checkTablePermission(transaction, identity, tableName, OWNERSHIP)) { <add> if (isTableOwner(transaction, identity, tableName)) { <ide> return; <ide> } <ide> <ide> return true; <ide> } <ide> return false; <add> } <add> <add> private boolean isTableOwner(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName) <add> { <add> return checkTablePermission(transaction, identity, tableName, OWNERSHIP); <ide> } <ide> <ide> private boolean checkTablePermission(ConnectorTransactionHandle transaction, ConnectorIdentity identity, SchemaTableName tableName, HivePrivilege... requiredPrivileges)
JavaScript
mit
d27d39555aedc16fc55e4ce4c2e8be21fd183de8
0
ghaiklor/generator-sails-rest-api,konstantinzolotarev/generator-trails,italoag/generator-sails-rest-api,tnunes/generator-trails,eithewliter5518/generator-sails-rest-api,mhipo1364/generator-sails-rest-api,italoag/generator-sails-rest-api,jaumard/generator-trails,IncoCode/generator-sails-rest-api,synergycns/generator-sails-rest-api,ghaiklor/generator-sails-rest-api
/** * Passport configuration file where you should configure all your strategies * @description :: Configuration file where you configure your passport authentication */ var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, JwtStrategy = require('passport-jwt').Strategy, FacebookTokenStrategy = require('passport-facebook-token').Strategy, TwitterTokenStrategy = require('passport-twitter-token').Strategy, YahooTokenStrategy = require('passport-yahoo-token').Strategy, GooglePlusTokenStrategy = require('passport-google-plus-token').Strategy; // TODO: make this more stable and properly parse profile data /** * Triggers when user authenticates via local strategy * @param {String} email Email from body field in request * @param {String} password Password from body field in request * @param {Function} next Callback * @private */ function _onLocalStrategyAuth(email, password, next) { User .findOne({email: email}) .exec(function (error, user) { if (error) return next(error, false, {}); if (!user) return next(null, false, { code: 'E_USER_NOT_FOUND', message: email + ' is not found' }); if (!CipherService.create('bcrypt', user.password).compareSync(password)) return next(null, false, { code: 'E_WRONG_PASSWORD', message: 'Password is wrong' }); return next(null, user, {}); }); } /** * Triggers when user authenticates via JWT strategy * @param {Object} payload Decoded payload from JWT * @param {Function} next Callback * @private */ function _onJwtStrategyAuth(payload, next) { User .findOne({id: payload.id}) .exec(function (error, user) { if (error) return next(error, false, {}); if (!user) return next(null, false, { code: 'E_USER_NOT_FOUND', message: 'User with that JWT not found' }); return next(null, user, {}); }); } /** * Triggers when user authenticates via one of social strategies * @param {String} strategyName What strategy was used? * @param {Object} req Request object * @param {String} accessToken Access token from social network * @param {String} refreshToken Refresh token from social network * @param {Object} profile Social profile * @param {Function} next Callback * @private */ function _onSocialStrategyAuth(strategyName, req, accessToken, refreshToken, profile, next) { if (!req.user) { User .findOrCreate({'facebook.id': profile.id}, { username: profile.username || profile.displayName || '', email: (profile.emails && profile.emails[0].value) || '', firstName: (profile.name && profile.name.givenName) || '', lastName: (profile.name && profile.name.familyName) || '', photo: (profile.photos && profile.photos[0].value) || '', facebook: profile._json }) .exec(function (error, user) { if (error) return next(error, false, {}); if (!user) return next(null, false, { code: 'E_AUTH_FAILED', message: [strategyName.charAt(0).toUpperCase(), strategyName.slice(1), ' auth failed'].join('') }); return next(null, user, {}); }); } else { req.user[strategyName] = profile._json; req.user.save(next); } } passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, _onLocalStrategyAuth)); passport.use(new JwtStrategy({ secretOrKey: "<%= answers['application:jwt-secret'] %>", tokenBodyField: 'jwt-token', tokenHeader: 'JWT' }, _onJwtStrategyAuth)); passport.use(new FacebookTokenStrategy({ clientID: "<%= answers['application:passport-facebook-client-id'] || '-' %>", clientSecret: "<%= answers['application:passport-facebook-client-secret'] || '-' %>", passReqToCallback: true }, _onSocialStrategyAuth.bind(this, 'facebook'))); passport.use(new TwitterTokenStrategy({ consumerKey: "<%= answers['application:passport-twitter-client-id'] || '-' %>", consumerSecret: "<%= answers['application:passport-twitter-client-secret'] || '-' %>", passReqToCallback: true }, _onSocialStrategyAuth.bind(this, 'twitter'))); passport.use(new YahooTokenStrategy({ clientID: "<%= answers['application:passport-yahoo-client-id'] || '-' %>", clientSecret: "<%= answers['application:passport-yahoo-client-secret'] || '-' %>", passReqToCallback: true }, _onSocialStrategyAuth.bind(this, 'yahoo'))); passport.use(new GooglePlusTokenStrategy({ clientID: "<%= answers['application:passport-google-client-id'] || '-' %>", clientSecret: "<%= answers['application:passport-google-client-secret'] || '-' %>", passReqToCallback: true }, _onSocialStrategyAuth.bind(this, 'google')));
generators/app/templates/config/passport.js
/** * Passport configuration file where you should configure all your strategies * @description :: Configuration file where you configure your passport authentication */ var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, JwtStrategy = require('passport-jwt').Strategy, FacebookTokenStrategy = require('passport-facebook-token').Strategy, TwitterTokenStrategy = require('passport-twitter-token').Strategy, YahooTokenStrategy = require('passport-yahoo-token').Strategy, GooglePlusTokenStrategy = require('passport-google-plus-token').Strategy; // TODO: make this more stable and properly parse profile data /** * Triggers when user authenticates via local strategy * @param {String} username Username from body field in request * @param {String} password Password from body field in request * @param {Function} next Callback * @private */ function _onLocalStrategyAuth(username, password, next) { User .findOne({or: [{username: username}, {email: username}]}) .exec(function (error, user) { if (error) return next(error, false, {}); if (!user) return next(null, false, { code: 'E_USER_NOT_FOUND', message: username + ' is not found' }); if (!CipherService.create('bcrypt', user.password).compareSync(password)) return next(null, false, { code: 'E_WRONG_PASSWORD', message: 'Password is wrong' }); return next(null, user, {}); }); } /** * Triggers when user authenticates via JWT strategy * @param {Object} payload Decoded payload from JWT * @param {Function} next Callback * @private */ function _onJwtStrategyAuth(payload, next) { User .findOne({id: payload.id}) .exec(function (error, user) { if (error) return next(error, false, {}); if (!user) return next(null, false, { code: 'E_USER_NOT_FOUND', message: 'User with that JWT not found' }); return next(null, user, {}); }); } /** * Triggers when user authenticates via one of social strategies * @param {String} strategyName What strategy was used? * @param {Object} req Request object * @param {String} accessToken Access token from social network * @param {String} refreshToken Refresh token from social network * @param {Object} profile Social profile * @param {Function} next Callback * @private */ function _onSocialStrategyAuth(strategyName, req, accessToken, refreshToken, profile, next) { if (!req.user) { User .findOrCreate({'facebook.id': profile.id}, { username: profile.username || profile.displayName || '', email: (profile.emails && profile.emails[0].value) || '', firstName: (profile.name && profile.name.givenName) || '', lastName: (profile.name && profile.name.familyName) || '', photo: (profile.photos && profile.photos[0].value) || '', facebook: profile._json }) .exec(function (error, user) { if (error) return next(error, false, {}); if (!user) return next(null, false, { code: 'E_AUTH_FAILED', message: [strategyName.charAt(0).toUpperCase(), strategyName.slice(1), ' auth failed'].join('') }); return next(null, user, {}); }); } else { req.user[strategyName] = profile._json; req.user.save(next); } } passport.use(new LocalStrategy({ usernameField: 'username', passwordField: 'password' }, _onLocalStrategyAuth)); passport.use(new JwtStrategy({ secretOrKey: "<%= answers['application:jwt-secret'] %>", tokenBodyField: 'jwt-token', tokenHeader: 'JWT' }, _onJwtStrategyAuth)); passport.use(new FacebookTokenStrategy({ clientID: "<%= answers['application:passport-facebook-client-id'] || '-' %>", clientSecret: "<%= answers['application:passport-facebook-client-secret'] || '-' %>", passReqToCallback: true }, _onSocialStrategyAuth.bind(this, 'facebook'))); passport.use(new TwitterTokenStrategy({ consumerKey: "<%= answers['application:passport-twitter-client-id'] || '-' %>", consumerSecret: "<%= answers['application:passport-twitter-client-secret'] || '-' %>", passReqToCallback: true }, _onSocialStrategyAuth.bind(this, 'twitter'))); passport.use(new YahooTokenStrategy({ clientID: "<%= answers['application:passport-yahoo-client-id'] || '-' %>", clientSecret: "<%= answers['application:passport-yahoo-client-secret'] || '-' %>", passReqToCallback: true }, _onSocialStrategyAuth.bind(this, 'yahoo'))); passport.use(new GooglePlusTokenStrategy({ clientID: "<%= answers['application:passport-google-client-id'] || '-' %>", clientSecret: "<%= answers['application:passport-google-client-secret'] || '-' %>", passReqToCallback: true }, _onSocialStrategyAuth.bind(this, 'google')));
Remove sign in via username
generators/app/templates/config/passport.js
Remove sign in via username
<ide><path>enerators/app/templates/config/passport.js <ide> <ide> /** <ide> * Triggers when user authenticates via local strategy <del> * @param {String} username Username from body field in request <add> * @param {String} email Email from body field in request <ide> * @param {String} password Password from body field in request <ide> * @param {Function} next Callback <ide> * @private <ide> */ <del>function _onLocalStrategyAuth(username, password, next) { <add>function _onLocalStrategyAuth(email, password, next) { <ide> User <del> .findOne({or: [{username: username}, {email: username}]}) <add> .findOne({email: email}) <ide> .exec(function (error, user) { <ide> if (error) return next(error, false, {}); <ide> <ide> if (!user) return next(null, false, { <ide> code: 'E_USER_NOT_FOUND', <del> message: username + ' is not found' <add> message: email + ' is not found' <ide> }); <ide> <ide> if (!CipherService.create('bcrypt', user.password).compareSync(password)) return next(null, false, { <ide> } <ide> <ide> passport.use(new LocalStrategy({ <del> usernameField: 'username', <add> usernameField: 'email', <ide> passwordField: 'password' <ide> }, _onLocalStrategyAuth)); <ide>
JavaScript
mit
62f9143bc5fa49f3441a462014c9bde976d3691c
0
TylerOBrien/LudusJS
/* * LudusJS * https://github.com/TylerOBrien/LudusJS * * Copyright (c) 2012 Tyler O'Brien * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ var Ludus = {}; (function($) { "use strict"; /* * AJAXRequest Object * Is used in the Ludus.AJAX() function. * */ function AJAXRequest(args) { this.async = $.exists(args.async, true); this.charset = $.exists(args.charset, "utf-8"); this.contentType = $.exists(args.contentType, "application/x-www-form-urlencoded"); this.data = $.exists(args.data, {}); this.http = new XMLHttpRequest(); this.http.request = this; this.method = $.exists(args.method, "GET"); this.onError = args.onError; this.onConnect = args.onConnect; this.onNotFound = args.onNotFound; this.onProcess = args.onProcess; this.onRecvRequest = args.onRecvRequest; this.onSuccess = args.onSuccess; this.queryString = $.encodeQueryString(this.data); this.url = $.exists(args.url, "/"); this.urlToOpen = (this.method === "POST") ? this.url : (this.url + "?" + this.queryString); } /* * AJAXRequestHandler() returns Nothing * Input: Nothing * This is the handler function for http.onreadystatechange. * Is called in the Ludus.AJAX() function. * */ function AJAXRequestHandler() { switch (this.readyState) { case 1: /* CONNECT */ $.call(this.request.onConnect); break; case 2: /* REQUEST RECEIVED */ this.timeBegin = new Date().getTime(); $.call(this.request.onRecvRequest); break; case 3: /* PROCESSING */ $.call(this.request.onProcess); break; case 4: /* COMPLETE */ if (typeof this.request.timeout !== Cache.undefined) { clearTimeout(this.request.timeout); } this.timeEnd = new Date().getTime(); this.timeDifference = (this.timeEnd - this.timeBegin); switch (this.status) { case 200: $.call(this.request.onSuccess, this.responseText, this.timeDifference); break; case 404: $.call(this.request.onNotFound, this.responseText, this.timeDifference); default: $.call(this.request.onError, [this.responseText,this.status], this.timeDifference); break; } break; } } /* * Cache of commonly used values. * */ var Cache = { array: "array", contentType: "contentType", cookieGetRegex: "=([^;]+);?", /* Passed as an argument to RegExp's constructor. */ func: "function", number: "number", object: "object", on: "on", string: "string", timeout: "timeout", undefined: "undefined", uint32max: 4294967296 }, /* * Cache used for implementing the $.Type() function. * Based on jQuery's code for doing the same thing. * */ ClassTypes = {}; (function(ctypes) { var buffer = "Array Boolean Date Function Number Object RegExp String".split(" "); for (var i=buffer.length; i--;) { ctypes["[object " + buffer[i] + "]"] = buffer[i].toLowerCase(); } }(ClassTypes)); /* * Comparison() returns Boolean * Input: Array, Function * Called by the "is" functions, such as "isArray" and "isObject". * Is used when comparing an array of values. * */ var Comparison = function(values, predicate) { var result = $.isArray(values); for (var len=values.length; result && len--;) { result = predicate(values[len]); } return result; }, /* * Array of Function. * Each function in this array will be called when the DOM is ready. * */ DOMReadyCallbacks = [], /* * All event based functions will go here. * Right now that is only the DOM loading events. * Might add some more here in the future. * */ Events = { /* * onDOMContentLoaded() returns Nothing * Input: Nothing * Called by one of two possible event listeners. * For modern browsers this will be the document's "DOMContentLoaded" event. * */ onDOMContentLoaded: function() { if (State.hasAddEventListener) { document.removeEventListener("DOMContentLoaded", Events.onDOMContentLoaded, false); Events.onReady(); } else if (State.hasAttachEvent && document.readyState === "complete" && document.body !== null) { document.detachEvent("onreadystatechange", Events.onDOMContentLoaded); Events.onReady(); } }, /* * onReady() returns Nothing * Input: Nothing * Called when the DOM is considered ready. * Typically, on modern browsers, this is called by Events.onDOMContentLoaded(). * Legacy browsers may call this from the window.onload event. * */ onReady: function() { if (State.isReady === false && State.isBusy === false) { State.isBusy = true; for (var i=0, len=DOMReadyCallbacks.length; i < len; i++) { DOMReadyCallbacks[i](); } State.isReady = true; State.isBusy = false; } } }, /* * Functions for adding/removing events are here. * */ EventManager = { /* * ProcessEventListener() returns Nothing * Input: Boolean, Array|String, Array|String, Function, Boolean * This function is called by the Ludus.AddEvent and Ludus.RemoveEvent functions. * If the "element" or "event" objects are arrays then they will be processed recursively. * */ ProcessEventListener: function(isAddingEvent, element, event, callback, useCapture) { /* If a string is given then assume it's a DOM element. */ if ($.isString(element)) { element = $.element(element); } /* If an array has been given then pass each element to this function recursivly. */ if ($.isDOMElementArray(element) || $.isArray(element)) { /* Use "i<len" instead of "len--" to ensure the events are processed in order. */ for (var i=0, len=element.length; i < len; i++) { EventManager.ProcessEventListener(isAddingEvent, element[i], event, callback, useCapture); } } else { /* The event object might be an array. */ if ($.isArray(event)) { for (var i=0, len=event.length; i < len; i++) { EventManager.ToggleEventListener(isAddingEvent, element, event[i], callback, useCapture); } } else { EventManager.ToggleEventListener(isAddingEvent, element, event, callback, useCapture); } } }, /* * ToggleEventListener() returns Nothing * Input: Boolean, DOMElement, String, Function, Boolean * Is called by EventManager.ProcessEventListener(). * Depending on the value of "isAddingEvent" will either add or remove the passed event. * */ ToggleEventListener: function(isAddingEvent, element, event, callback, useCapture) { /* First: ensure the required objects are defined. */ if (typeof element !== Cache.undefined && element !== null) { /* Second: determine which event type to use: "addEventListener" or "attachEvent". */ if (typeof element.addEventListener !== Cache.undefined) { if (typeof useCapture === Cache.undefined) { useCapture = false; } /* Determine if the event is being added or removed. */ if (isAddingEvent) { element.addEventListener(event, callback, useCapture); } else { element.removeEventListener(event, callback, useCapture); } } else { /* Determine if the event is being added or removed. */ if (isAddingEvent) { element.attachEvent(Cache.on+event, callback); } else { element.detachEvent(Cache.on+event, callback); } } } } }, /* * */ ObjectShortcut = function(source) { switch (source) { case $.cookie: return $.cookie.getAll(); case $.get: return QueryString; default: return source; } }, /* * Cache of commonly used regular expressions * */ RegularExpressions = { cookie: /[ ]?([^=]+)=([^;]+)[; ]?/g, floatingPoint: /[0-9]+([.][0-9]+)?/g, notNumber: /[^0-9.\-+]+/g, /* Used to match anything NOT a number. That is 0-9 and decimal points. */ number: /([0-9]{1,3}([,][0-9]{3})?)+([.][0-9]+)?/g, /* Used to match any number. Includes commas because some string-numbers use them. */ queryString: /[?&]?([^&=]+)=?([^&]+)?/g, sprintfVariable: /%[b|d|f|h|H|o|s|u|x|X]/g }, /* * SendAJAXRequest() returns Nothing * Input: AJAXInternal.Request, Object * A "safe" version of XMLHttpRequest.send(). * Is compatible with both ActiveX-based AJAX and otherwise. * */ SendAJAXRequest = function(request, args) { if (typeof args === Cache.undefined || args === null) { if (request.isActiveX) { request.http.send(); } else { request.http.send(null); } } else if ("method" in args && "queryString" in args && args.method === "post") { request.http.send(args.queryString); } else { SendAJAXRequest(request, null); } }, /* * Made a seperate block for this because I might add additional functions in the future. * For now it is just the Process() one. * */ TextProcessor = { /* * Process() returns String * Input: String, String * Is called by Ludus.Sprintf(). * Replaced sprintf variables with the appropriate value; converting it * to a string if necessary. * */ Process: function(type, value) { switch (type){ case "%b": return $.toInt(value).toString(2); case "%d": return $.toInt(value).toString(); case "%f": return parseFloat(value).toString(); case "%h": return $.toInt(value).toString(16); case "%H": return $.toInt(value).toString(16).toUpperCase(); case "%o": return $.toInt(value).toString(8); case "%u": return $.toUnsignedInt(value).toString(); case "%x": return "0x" + $.toInt(value).toString(16); case "%X": return "0x" + $.toInt(value).toString(16).toUpperCase(); default: return value; } } }, /* * Various states will be stored here. * Is essentially a cache of boolean values. * */ State = { hasAddEventListener: (typeof document.addEventListener !== Cache.undefined), hasAttachEvent: (typeof document.attachEvent !== Cache.undefined), isReady: false, isBusy: false }; /* * * Public * * */ /* * addEvent() returns Nothing * Input: Array|String, Array|String, Function, Boolean * Adds the processed event. * If this event already exists then this function won't actually do anything. * */ $.addEvent = function(element, event, callback, useCapture) { EventManager.ProcessEventListener(true, element, event, callback, useCapture); }; /* * ajax() returns Nothing * */ $.ajax = function(args) { var request = new AJAXRequest(args); /* * Prepare the AJAX request. * */ request.http.open(request.method, request.urlToOpen, request.async); request.http.setRequestHeader(Cache.contentType, request.contentType+"; charset="+request.charset); request.http.onreadystatechange = AJAXRequestHandler; /* * Add a new timeout if one is given. * The time is assumed to be milliseconds. * */ if ($.isNumeric(args[Cache.timeout])) { request.timeout = setTimeout(function() { request.http.abort(); $.call(request.onTimeout); }, args[Cache.timeout]); } /* * Pass the object twice because the request object will also contain the GET/POST * variables being sent through HTTP (which is what the second parameter holds). */ SendAJAXRequest(request, request); }; /* * all() returns Boolean * Input: Array|Object, Function * Returns true if every call to the predicate also returns true. * Returns false otherwise, or if empty data is given. * */ $.all = function(data, predicate) { var result; $.each(data, function(itr) { return predicate ? result = predicate(itr.value) : itr.value; }); return result ? true : false; }; /* * arraysEqual() returns Boolean * Input: Array, Array * Returns true if the two passed arrays are identical. * False otherwise. * */ $.arraysEqual = function(first, second) { var result = $.isArray([first,second],true) && first.length === second.length; if (result) { for (var len=first.length; result && len--;) { result = $.equals(first[len], second[len]); } } return result; }; /* * call() returns Mixed * Input: Mixed, Mixed, Mixed * */ $.call = function(callback, first, second) { if ($.type(callback) === Cache.func) { if (typeof second !== Cache.undefined) { return callback(first, second); } else if (typeof first !== Cache.undefined) { return callback(first); } else { return callback(); } } }; /* * cookie management is in here. * Will update this description in the future, maybe. * */ $.cookie = { /* * exists() returns Boolean * Input: String * Returns true if the passed cookie name has been defined. * False otherwise. * */ exists: function(name) { return $.hasProperty($.cookie.getAll(), name); }, /* * get() returns String|undefined * Input: String * Returns the value of the passed cookie name. * Will return undefined if the cookie has not been defined. * */ get: function(name) { var result = new RegExp(name + Cache.cookieGetRegex, "g").exec(document.cookie); if (result !== null) { return result[1]; } }, /* * getAll() returns Object * Input: Nothing * Returns an object containing all of the cookie definitions. * */ getAll: function() { var currentCookie = document.cookie; var regex = RegularExpressions.cookie; var buffer = regex.exec(currentCookie); var result = {}; while (buffer !== null) { result[buffer[1]] = buffer[2]; buffer = regex.exec(currentCookie); } return result; }, /* * set() returns Nothing * Input: String, Mixed, Number, String, String, Boolean * */ set: function(name, value, milliseconds, path, domain, secure) { var date = new Date; var expiration = new Date(milliseconds); date.setTime(date.getTime() + expiration.getTime()); document.cookie = [ encodeURIComponent(name)+"="+encodeURIComponent(value), "; expires="+date.toUTCString(), path ? "; path=" + path : "", domain ? "; domain=" + domain : "", secure ? "; secure" : "" ].join(""); } }; /* * each() returns Nothing * Input: Mixed, Function, Boolean * Iterates through the passed haystack. * Will pass an iterator to the callback. * */ $.each = function(haystack, callback, ignoreReturnValues) { haystack = ObjectShortcut(haystack); /* * By default the each() function will halt if a callback returns false. * This boolean will disable that. * */ ignoreReturnValues = $.exists(ignoreReturnValues, null, true); /* * DOMObjectArrays aren't actually arrays, so the $.IsArray function returns false. * So also check for them. * */ if ($.isArray(haystack) || $.isDOMElementArray(haystack)) { var valueBuffer; for (var i=0, end=haystack.length; i < end; i++) { valueBuffer = haystack[i]; if (callback.call(valueBuffer, {"index":i,"value":valueBuffer}) === false && !ignoreReturnValues) { break; } } } else { var valueBuffer; for (var index in haystack) { valueBuffer = haystack[index]; if (callback.call(valueBuffer, {"index":index,"value":valueBuffer}) === false && !ignoreReturnValues) { break; } } } }; /* * element() returns Object * Input: String, String|DOMElement * */ $.element = function(elementStr, context) { /* Ensure context is defined. */ if (typeof context === Cache.undefined) { context = document; } else if ($.isString(context)) { context = $.element(context); } /* Second condition is necessary for IE6-8. */ if ($.isDOMElement(context) || context === document) { /* * Match the HTMLCollection object. * */ var result; switch (elementStr.charAt(0)) { case "#": result=context.getElementById(elementStr.substring(1)); break; case ".": result=context.getElementsByClassName(elementStr.substring(1)); break; case ":": result=context.getElementsByName(elementStr.substring(1)); break; default: result=context.getElementsByTagName(elementStr); break; } /* The getElements functions return arrays (sort of) * If any are empty then return NULL instead. * * */ if (result !== null && $.hasProperty(result, Cache.length) && result.length === 0) { return null; } else { return result; } } }; /* * decodeQueryString() returns Object * Input: String * Converts a passed query string in this format: * id=42&name=John%20Doe&type=user * Into an object containing the defined variables. * * Any variables not given a value, like so: * foo&bar&baz * Will be NULL valued in the object. * */ $.decodeQueryString = function(string) { var regex = RegularExpressions.queryString; var buffer = regex.exec(string); var result = {}; while (buffer) { result[decodeURIComponent(buffer[1])] = $.Exists(buffer[2], null, true) ? decodeURIComponent(buffer[2]) : ""; buffer = regex.exec(string); } return result; }; /* * encodeQueryString() returns String * Input: Object * Encodes a passed Object into a query string. * For example, this: * {name:"John Doe", id:42} * Will become: * name=John%20Doe&id=42 * */ $.encodeQueryString = function(source) { var result = ""; for (var index in source) { result += (encodeURIComponent(index) + "=" + encodeURIComponent(source[index]) + "&"); } return result.substring(0, result.length-1); }; /* * equals() returns Boolean * Input: Object, Object, Boolean * Compares the two passed objects and returns true if they are considered equal. * Returns false otherwise. * */ $.equals = function(first, second) { first = ObjectShortcut(first); second = ObjectShortcut(second); if ($.isArray([first,second],true)) { return $.arraysEqual(first, second); } else if ($.isObject([first,second],true)) { var firstArray=$.objectToArray(first), secondArray=$.objectToArray(second); return $.equals(firstArray[0],secondArray[0]) && $.equals(firstArray[1],secondArray[1]); } else { return first === second; } }; /* * erase() returns Nothing * Input: Array|Object, Object * Removes all instances of needle from the passed haystack. * */ $.erase = function(haystack, needle) { var indices = []; $.each(haystack, function(itr){ if ($.isArray(haystack) && $.equals(itr.value, needle)) { indices.push(itr.index); } else if ($.isObject(haystack) && $.equals(itr.index, needle)) { indices.push(itr.index); } }); if (indices.length) { if ($.isArray(haystack)) { for (var i=indices.length; i--;) { haystack.splice(indices[i], 1); } } else { delete haystack[indices[0]]; } } }; /* * exists() returns Mixed * Input: Mixed, Mixed, Boolean * Used for determining if the passed object is defined. * * If the object is defined then it will be returned. * Otherwise the override object will be returned. * * If "doReturnBoolean" is true then true/false is returned in place of object/override. * */ $.exists = function(source, override, doReturnBoolean) { source = ObjectShortcut(source); if (typeof source !== Cache.undefined) { if (doReturnBoolean) { return true; } else { return source; } } else { if (doReturnBoolean) { return false; } else { return override; } } }; /* * format() returns String * Input: String, Mixed * */ $.format = function(source) { if (arguments.length > 1) { /* * The values may be in the arguments array, * or may be an array passed as the second argument. * */ var indexOffset = 1; var values = arguments; if ($.isArray(arguments[1])) { indexOffset = 0; values = arguments[1]; } var variables = source.match(RegularExpressions.sprintfVariable); var end = (variables) ? variables.length : 0; /* Replace each format variable with the appropriate values. */ for (var i = 0; i < end; i++) { source = source.replace( variables[i], TextProcessor.Process(variables[i], values[i+indexOffset].toString()) ); } } return source; }; /* * This section contains query string related methods. * It is also a sort of "magic object". It can be passed to functions * to perform operations on the query string. * * Example: * var hasId = $.HasProperty($.GET, "id"); * var matches = $.Equals($.GET, {"id":"42", "name":"John Doe"}); * */ $.get = { /* * exists() returns Boolean * Input: Array|String * Returns true if the passed GET variable has been defined. * Does not require a value to have been assigned to the GET variables. * */ exists: function(name) { if ($.type(name) === Cache.array) { var result = name.length; for (var len=result; result && len--;) { result = (typeof QueryString[name[len]] !== Cache.undefined); } return result; } else { return typeof QueryString[name] !== Cache.undefined; } }, /* * get() returns String|undefined * Input: String * Returns the value of the passed query string variable. * Will return undefined if it has not been defined. * */ get: function(source) { if ($.type(source) === Cache.array) { var result = {}; for (var len=source.length; len--;) { result[source[len]] = QueryString[source[len]]; } return result; } else { return QueryString[source]; } }, /* * getAll() returns Object * Input: Nothing * Returns a copy of the query string object. * */ getAll: function() { var result = {}; for (var index in QueryString) { result[index] = QueryString[index]; } return result; } }; /* * generateArray() returns Array * Input: Number, Mixed, Boolean * Generates an array based on the passed parameters. * If the third argument is a boolean "true" then second argument is * treated as a callback. * Can be used to quickly create an array of N size by not assigning * the "value" argument a value: * var arr = $.GenerateArray(10); * The array can also be manipulated as it grows: * var arr = $.GenerateArray(10, function(src,i){ if (i>0) { src[i-1] = Math.pow(src.length,2); return 0; } }, true); * console.log(arr); // [1, 4, 9, 16, 25, 36, 49, 64, 81, 0] * */ $.generateArray = function(amount, value, isCallback) { var result = []; for (var i = 0; i < amount; i++) { result[i] = isCallback ? value(result,i) : value; } return result; }; /* * hasProperty() returns Boolean * Input: String, String, Boolean * Returns true if the object has the passed property defined. * For example, checking for "foo" on this object: * {"hello":"world", "id":42, "foo":null} * Will return true because it is defined. * Its value is irrelevent. * */ $.hasProperty = function(source, property, doIterateSource) { source = ObjectShortcut(source); if (typeof doIterateSource !== Cache.undefined && doIterateSource) { var result = $.isArray(source); for (var len=source.length; result && len--;) { result = source[len].hasOwnProperty(property); } return result; } else { return source.hasOwnProperty(property); } }; /* * hasValue() returns Boolean * Input: Array|Object, Mixed * Returns true if the passed container has the passed source defined. * For example, the following will return true for the value "bar": * {"id":42, "foo":"bar", "hello":"world"}; * [1, 2, "foo", 3, 4, 5]; * However, only the second will return true for "foo". * Indices in objects are not searched. * */ $.hasValue = function(source, value) { source = ObjectShortcut(source); var result = false; $.each(source, function(itr){ return !(result = $.equals(value,itr.value)); }); return result; }; /* * indexOf() returns Number|String|null * Input: Array|Object, Object * Returns the index of the passed value if found in the container. * Will return NULL if the value is not found. * */ $.indexOf = function(haystack, needle) { var result = null; $.each(haystack, function(itr){ if ($.equals(itr.value, needle)) { result = itr.index; return false; } }); return result; } /* * isArray() returns Boolean * Input: Array, Boolean * */ $.isArray = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isArray); } else { return ($.type(source) === Cache.array); } }; /* * isDOMElement() returns Boolean * Input: Object, Boolean * */ $.isDOMElement = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isDOMElement); } else { return typeof source !== Cache.undefined && source !== null && typeof source.ELEMENT_NODE !== Cache.undefined; } }; /* * isDOMElementArray() returns Boolean * Input: Object, Boolean * */ $.isDOMElementArray = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isDOMElementArray); } else { return typeof source !== Cache.undefined && source !== null && typeof source.item !== Cache.undefined; } }; /* * isEmptyArray() returns Boolean * Input: Array, Boolean * Returns true if the passed array is empty. * False otherwise. * */ $.isEmptyArray = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isEmptyArray); } else { return $.isArray(source) && !source.length; } }; /* * isEmptyObject() returns Boolean * Input: Object|Array, Boolean * Returns true if the passed object contains no indices, or is undefined. * Will only return false if the object contains no indices, even if defined. * */ $.isEmptyObject = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isEmptyObject); } else { if (typeof source !== Cache.undefined) { for (var index in source) { return false; } } return true; } }; /* * isFunction() returns Boolean * Input: Array|Object, Boolean * */ $.isFunction = function(source, doIteratSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isFunction); } else { return typeof source === Cache.func; } }; /* * isNumeric() returns Boolean * Input: Array|Mixed, Array * */ $.isNumeric = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isNumeric); } else { return !isNaN(parseFloat(source)) && isFinite(source); } }; /* * isObject() returns Boolean * Input: Object|Array, Boolean * */ $.isObject = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isObject); } else { return ($.type(source) === Cache.object); } }; /* * isString() returns Boolean * Input: Array|String, Boolean * */ $.isString = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isString); } else { return ($.type(source) === Cache.string); } }; /* * lambda() returns Function * Input: Mixed * Returns a function that will do nothing but return the passed value. * Based on the MooTools function of the same name. * */ $.lambda = function(value) { return (function(){return value;}); }; /* * objectToArray() returns Array * Input: Object * Converts the passed object into an array. * The first element will be the object's indices. * The second element will be the object's values. * * For example: * {foo:"bar", id:42, name:"John Doe"} * Will become: * [ ["foo", "id", "name"], ["bar", 42, "John Doe"] ] * * */ $.objectToArray = function(source) { source = ObjectShortcut(source); var result = [[],[]]; for (var index in source) { result[0].push(index); result[1].push(source[index]); } return result; }; /* * random() returns Number * Input: Number, Number, Number * */ $.random = function(min, max, decimalPlaces) { if (typeof max === Cache.undefined) { max = min; min = 0; } return $.round((Math.random() * (max-min)) + min, decimalPlaces); }; /* * ready() returns Nothing * Input: Function * Adds the passed function to the list of callbacks that * are called when the DOM is ready. * */ $.ready = function(callback) { if ($.type(callback) === Cache.func) { if (State.isReady === false && State.isBusy === false) { DOMReadyCallbacks.push(callback); } else { callback(); } } }; /* * removeEvent() returns Nothing * Input: Array|String, Array|String, Function, Boolean * Removed the processed event. * If this event does not exist then this function won't actually do anything. * */ $.removeEvent = function(element, event, callback, useCapture) { EventManager.ProcessEventListener(false, element, event, callback, useCapture); }; /* * round returns Number * Input: Number, Number * */ $.round = function(num, decimalPlaces) { decimalPlaces = Math.pow(10, decimalPlaces ? decimalPlaces : 0); return Math.round(num*decimalPlaces) / decimalPlaces; }; /* * toInt() returns Number|NaN * Input: Mixed, Number * Converts the passed object to an integer. * Objects that cannot be converted will be returned as NaN. * */ $.toInt = function(source, base) { if ($.type(source) !== Cache.number) { var result = source.match(RegularExpressions.number); if (result !== null && result.length === 1) { return parseInt(source.replace(RegularExpressions.notNumber, Cache.emptyString), $.exists(base,10)); } else { return NaN; } } else { return parseInt(source, $.exists(base,10)); } }; /* * toUnsignedInt() returns Number|NaN * Input: Mixed, Number, Number * Converts the passed object to an unsigned integer. * Objects that cannot be converted will be returned as NaN. * */ $.toUnsignedInt = function(source, base, max) { if (source = $.toInt(source, base)) { return (source > 0) ? source : ($.exists(max,Cache.uint32max) - Math.abs(source)); } else { return source; } }; /* * type() returns String * Input: Mixed * Returns the type of the passed object. * Based on jQuery's code for doing the same thing. * */ $.type = function(source) { return source === null ? "null" : (ClassTypes[Object.prototype.toString.call(source)] || "object"); }; /* * * Query Strings * * */ var QueryString = $.decodeQueryString(document.location.search); /* * * Event Listeners * * */ if (State.hasAddEventListener) { document.addEventListener("DOMContentLoaded", Events.onDOMContentLoaded, false); window.addEventListener("load", Events.onReady, false); } else if (State.hasAttachEvent) { document.attachEvent("onreadystatechange", Events.onDOMContentLoaded); window.attachEvent("onload", Events.onReady, false); } else { window.onload = Events.onReady; } }(Ludus));
src/ludus.js
/* * LudusJS * https://github.com/TylerOBrien/LudusJS * * Copyright (c) 2012 Tyler O'Brien * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ var Ludus = {}; (function($) { "use strict"; /* * AJAXRequest Object * Is used in the Ludus.AJAX() function. * */ function AJAXRequest(args) { this.async = $.exists(args.async, true); this.charset = $.exists(args.charset, "utf-8"); this.contentType = $.exists(args.contentType, "application/x-www-form-urlencoded"); this.data = $.exists(args.data, {}); this.http = new XMLHttpRequest(); this.http.request = this; this.method = $.exists(args.method, "GET"); this.onError = args.onError; this.onConnect = args.onConnect; this.onNotFound = args.onNotFound; this.onProcess = args.onProcess; this.onRecvRequest = args.onRecvRequest; this.onSuccess = args.onSuccess; this.queryString = $.encodeQueryString(this.data); this.url = $.exists(args.url, "/"); this.urlToOpen = (this.method === "POST") ? this.url : (this.url + "?" + this.queryString); } /* * AJAXRequestHandler() returns Nothing * Input: Nothing * This is the handler function for http.onreadystatechange. * Is called in the Ludus.AJAX() function. * */ function AJAXRequestHandler() { switch (this.readyState) { case 1: /* CONNECT */ $.call(this.request.onConnect); break; case 2: /* REQUEST RECEIVED */ this.timeBegin = new Date().getTime(); $.call(this.request.onRecvRequest); break; case 3: /* PROCESSING */ $.call(this.request.onProcess); break; case 4: /* COMPLETE */ if (typeof this.request.timeout !== Cache.undefined) { clearTimeout(this.request.timeout); } this.timeEnd = new Date().getTime(); this.timeDifference = (this.timeEnd - this.timeBegin); switch (this.status) { case 200: $.call(this.request.onSuccess, this.responseText, this.timeDifference); break; case 404: $.call(this.request.onNotFound, this.responseText, this.timeDifference); default: $.call(this.request.onError, [this.responseText,this.status], this.timeDifference); break; } break; } } /* * Cache of commonly used values. * */ var Cache = { array: "array", contentType: "contentType", cookieGetRegex: "=([^;]+);?", /* Passed as an argument to RegExp's constructor. */ func: "function", number: "number", object: "object", on: "on", string: "string", timeout: "timeout", undefined: "undefined", uint32max: 4294967296 }, /* * Cache used for implementing the $.Type() function. * Based on jQuery's code for doing the same thing. * */ ClassTypes = {}; (function(ctypes) { var buffer = "Array Boolean Date Function Number Object RegExp String".split(" "); for (var i=buffer.length; i--;) { ctypes["[object " + buffer[i] + "]"] = buffer[i].toLowerCase(); } }(ClassTypes)); /* * Comparison() returns Boolean * Input: Array, Function * Called by the "is" functions, such as "isArray" and "isObject". * Is used when comparing an array of values. * */ var Comparison = function(values, predicate) { var result = $.isArray(values); for (var len=values.length; result && len--;) { result = predicate(values[len]); } return result; }, /* * Array of Function. * Each function in this array will be called when the DOM is ready. * */ DOMReadyCallbacks = [], /* * All event based functions will go here. * Right now that is only the DOM loading events. * Might add some more here in the future. * */ Events = { /* * onDOMContentLoaded() returns Nothing * Input: Nothing * Called by one of two possible event listeners. * For modern browsers this will be the document's "DOMContentLoaded" event. * */ onDOMContentLoaded: function() { if (State.hasAddEventListener) { document.removeEventListener("DOMContentLoaded", Events.onDOMContentLoaded, false); Events.onReady(); } else if (State.hasAttachEvent && document.readyState === "complete" && document.body !== null) { document.detachEvent("onreadystatechange", Events.onDOMContentLoaded); Events.onReady(); } }, /* * onReady() returns Nothing * Input: Nothing * Called when the DOM is considered ready. * Typically, on modern browsers, this is called by Events.onDOMContentLoaded(). * Legacy browsers may call this from the window.onload event. * */ onReady: function() { if (State.isReady === false && State.isBusy === false) { State.isBusy = true; for (var i=0, len=DOMReadyCallbacks.length; i < len; i++) { DOMReadyCallbacks[i](); } State.isReady = true; State.isBusy = false; } } }, /* * Functions for adding/removing events are here. * */ EventManager = { /* * ProcessEventListener() returns Nothing * Input: Boolean, Array|String, Array|String, Function, Boolean * This function is called by the Ludus.AddEvent and Ludus.RemoveEvent functions. * If the "element" or "event" objects are arrays then they will be processed recursively. * */ ProcessEventListener: function(isAddingEvent, element, event, callback, useCapture) { /* If a string is given then assume it's a DOM element. */ if ($.isString(element)) { element = $.element(element); } /* If an array has been given then pass each element to this function recursivly. */ if ($.isDOMElementArray(element) || $.isArray(element)) { /* Use "i<len" instead of "len--" to ensure the events are processed in order. */ for (var i=0, len=element.length; i < len; i++) { EventManager.ProcessEventListener(isAddingEvent, element[i], event, callback, useCapture); } } else { /* The event object might be an array. */ if ($.isArray(event)) { for (var i=0, len=event.length; i < len; i++) { EventManager.ToggleEventListener(isAddingEvent, element, event[i], callback, useCapture); } } else { EventManager.ToggleEventListener(isAddingEvent, element, event, callback, useCapture); } } }, /* * ToggleEventListener() returns Nothing * Input: Boolean, DOMElement, String, Function, Boolean * Is called by EventManager.ProcessEventListener(). * Depending on the value of "isAddingEvent" will either add or remove the passed event. * */ ToggleEventListener: function(isAddingEvent, element, event, callback, useCapture) { /* First: ensure the required objects are defined. */ if (typeof element !== Cache.undefined && element !== null) { /* Second: determine which event type to use: "addEventListener" or "attachEvent". */ if (typeof element.addEventListener !== Cache.undefined) { if (typeof useCapture === Cache.undefined) { useCapture = false; } /* Determine if the event is being added or removed. */ if (isAddingEvent) { element.addEventListener(event, callback, useCapture); } else { element.removeEventListener(event, callback, useCapture); } } else { /* Determine if the event is being added or removed. */ if (isAddingEvent) { element.attachEvent(Cache.on+event, callback); } else { element.detachEvent(Cache.on+event, callback); } } } } }, /* * */ ObjectShortcut = function(source) { switch (source) { case $.cookie: return $.cookie.getAll(); case $.get: return QueryString; default: return source; } }, /* * Cache of commonly used regular expressions * */ RegularExpressions = { cookie: /[ ]?([^=]+)=([^;]+)[; ]?/g, floatingPoint: /[0-9]+([.][0-9]+)?/g, notNumber: /[^0-9.\-+]+/g, /* Used to match anything NOT a number. That is 0-9 and decimal points. */ number: /([0-9]{1,3}([,][0-9]{3})?)+([.][0-9]+)?/g, /* Used to match any number. Includes commas because some string-numbers use them. */ queryString: /[?&]?([^&=]+)=?([^&]+)?/g, sprintfVariable: /%[b|d|f|h|H|o|s|u|x|X]/g }, /* * SendAJAXRequest() returns Nothing * Input: AJAXInternal.Request, Object * A "safe" version of XMLHttpRequest.send(). * Is compatible with both ActiveX-based AJAX and otherwise. * */ SendAJAXRequest = function(request, args) { if (typeof args === Cache.undefined || args === null) { if (request.isActiveX) { request.http.send(); } else { request.http.send(null); } } else if ("method" in args && "queryString" in args && args.method === "post") { request.http.send(args.queryString); } else { SendAJAXRequest(request, null); } }, /* * Made a seperate block for this because I might add additional functions in the future. * For now it is just the Process() one. * */ TextProcessor = { /* * Process() returns String * Input: String, String * Is called by Ludus.Sprintf(). * Replaced sprintf variables with the appropriate value; converting it * to a string if necessary. * */ Process: function(type, value) { switch (type){ case "%b": return $.toInt(value).toString(2); case "%d": return $.toInt(value).toString(); case "%f": return parseFloat(value).toString(); case "%h": return $.toInt(value).toString(16); case "%H": return $.toInt(value).toString(16).toUpperCase(); case "%o": return $.toInt(value).toString(8); case "%u": return $.toUnsignedInt(value).toString(); case "%x": return "0x" + $.toInt(value).toString(16); case "%X": return "0x" + $.toInt(value).toString(16).toUpperCase(); default: return value; } } }, /* * Various states will be stored here. * Is essentially a cache of boolean values. * */ State = { hasAddEventListener: (typeof document.addEventListener !== Cache.undefined), hasAttachEvent: (typeof document.attachEvent !== Cache.undefined), isReady: false, isBusy: false }; /* * * Public * * */ /* * addEvent() returns Nothing * Input: Array|String, Array|String, Function, Boolean * Adds the processed event. * If this event already exists then this function won't actually do anything. * */ $.addEvent = function(element, event, callback, useCapture) { EventManager.ProcessEventListener(true, element, event, callback, useCapture); }; /* * ajax() returns Nothing * */ $.ajax = function(args) { var request = new AJAXRequest(args); /* * Prepare the AJAX request. * */ request.http.open(request.method, request.urlToOpen, request.async); request.http.setRequestHeader(Cache.contentType, request.contentType+"; charset="+request.charset); request.http.onreadystatechange = AJAXRequestHandler; /* * Add a new timeout if one is given. * The time is assumed to be milliseconds. * */ if ($.isNumeric(args[Cache.timeout])) { request.timeout = setTimeout(function() { request.http.abort(); $.call(request.onTimeout); }, args[Cache.timeout]); } /* * Pass the object twice because the request object will also contain the GET/POST * variables being sent through HTTP (which is what the second parameter holds). */ SendAJAXRequest(request, request); }; /* * arraysEqual() returns Boolean * Input: Array, Array * Returns true if the two passed arrays are identical. * False otherwise. * */ $.arraysEqual = function(first, second) { var result = $.isArray([first,second],true) && first.length === second.length; if (result) { for (var len=first.length; result && len--;) { result = $.equals(first[len], second[len]); } } return result; }; /* * call() returns Mixed * Input: Mixed, Mixed, Mixed * */ $.call = function(callback, first, second) { if ($.type(callback) === Cache.func) { if (typeof second !== Cache.undefined) { return callback(first, second); } else if (typeof first !== Cache.undefined) { return callback(first); } else { return callback(); } } }; /* * cookie management is in here. * Will update this description in the future, maybe. * */ $.cookie = { /* * exists() returns Boolean * Input: String * Returns true if the passed cookie name has been defined. * False otherwise. * */ exists: function(name) { return $.hasProperty($.cookie.getAll(), name); }, /* * get() returns String|undefined * Input: String * Returns the value of the passed cookie name. * Will return undefined if the cookie has not been defined. * */ get: function(name) { var result = new RegExp(name + Cache.cookieGetRegex, "g").exec(document.cookie); if (result !== null) { return result[1]; } }, /* * getAll() returns Object * Input: Nothing * Returns an object containing all of the cookie definitions. * */ getAll: function() { var currentCookie = document.cookie; var regex = RegularExpressions.cookie; var buffer = regex.exec(currentCookie); var result = {}; while (buffer !== null) { result[buffer[1]] = buffer[2]; buffer = regex.exec(currentCookie); } return result; }, /* * set() returns Nothing * Input: String, Mixed, Number, String, String, Boolean * */ set: function(name, value, milliseconds, path, domain, secure) { var date = new Date; var expiration = new Date(milliseconds); date.setTime(date.getTime() + expiration.getTime()); document.cookie = [ encodeURIComponent(name)+"="+encodeURIComponent(value), "; expires="+date.toUTCString(), path ? "; path=" + path : "", domain ? "; domain=" + domain : "", secure ? "; secure" : "" ].join(""); } }; /* * each() returns Nothing * Input: Mixed, Function, Boolean * Iterates through the passed haystack. * Will pass an iterator to the callback. * */ $.each = function(haystack, callback, ignoreReturnValues) { haystack = ObjectShortcut(haystack); /* * By default the each() function will halt if a callback returns false. * This boolean will disable that. * */ ignoreReturnValues = $.exists(ignoreReturnValues, null, true); /* * DOMObjectArrays aren't actually arrays, so the $.IsArray function returns false. * So also check for them. * */ if ($.isArray(haystack) || $.isDOMElementArray(haystack)) { var valueBuffer; for (var i=0, end=haystack.length; i < end; i++) { valueBuffer = haystack[i]; if (callback.call(valueBuffer, {"index":i,"value":valueBuffer}) === false && !ignoreReturnValues) { break; } } } else { var valueBuffer; for (var index in haystack) { valueBuffer = haystack[index]; if (callback.call(valueBuffer, {"index":index,"value":valueBuffer}) === false && !ignoreReturnValues) { break; } } } }; /* * element() returns Object * Input: String, String|DOMElement * */ $.element = function(elementStr, context) { /* Ensure context is defined. */ if (typeof context === Cache.undefined) { context = document; } else if ($.isString(context)) { context = $.element(context); } /* Second condition is necessary for IE6-8. */ if ($.isDOMElement(context) || context === document) { /* * Match the HTMLCollection object. * */ var result; switch (elementStr.charAt(0)) { case "#": result=context.getElementById(elementStr.substring(1)); break; case ".": result=context.getElementsByClassName(elementStr.substring(1)); break; case ":": result=context.getElementsByName(elementStr.substring(1)); break; default: result=context.getElementsByTagName(elementStr); break; } /* The getElements functions return arrays (sort of) * If any are empty then return NULL instead. * * */ if (result !== null && $.hasProperty(result, Cache.length) && result.length === 0) { return null; } else { return result; } } }; /* * decodeQueryString() returns Object * Input: String * Converts a passed query string in this format: * id=42&name=John%20Doe&type=user * Into an object containing the defined variables. * * Any variables not given a value, like so: * foo&bar&baz * Will be NULL valued in the object. * */ $.decodeQueryString = function(string) { var regex = RegularExpressions.queryString; var buffer = regex.exec(string); var result = {}; while (buffer) { result[decodeURIComponent(buffer[1])] = $.Exists(buffer[2], null, true) ? decodeURIComponent(buffer[2]) : ""; buffer = regex.exec(string); } return result; }; /* * encodeQueryString() returns String * Input: Object * Encodes a passed Object into a query string. * For example, this: * {name:"John Doe", id:42} * Will become: * name=John%20Doe&id=42 * */ $.encodeQueryString = function(source) { var result = ""; for (var index in source) { result += (encodeURIComponent(index) + "=" + encodeURIComponent(source[index]) + "&"); } return result.substring(0, result.length-1); }; /* * equals() returns Boolean * Input: Object, Object, Boolean * Compares the two passed objects and returns true if they are considered equal. * Returns false otherwise. * */ $.equals = function(first, second) { first = ObjectShortcut(first); second = ObjectShortcut(second); if ($.isArray([first,second],true)) { return $.arraysEqual(first, second); } else if ($.isObject([first,second],true)) { var firstArray=$.objectToArray(first), secondArray=$.objectToArray(second); return $.equals(firstArray[0],secondArray[0]) && $.equals(firstArray[1],secondArray[1]); } else { return first === second; } }; /* * erase() returns Nothing * Input: Array|Object, Object * Removes all instances of needle from the passed haystack. * */ $.erase = function(haystack, needle) { var indices = []; $.each(haystack, function(itr){ if ($.isArray(haystack) && $.equals(itr.value, needle)) { indices.push(itr.index); } else if ($.isObject(haystack) && $.equals(itr.index, needle)) { indices.push(itr.index); } }); if (indices.length) { if ($.isArray(haystack)) { for (var i=indices.length; i--;) { haystack.splice(indices[i], 1); } } else { delete haystack[indices[0]]; } } }; /* * exists() returns Mixed * Input: Mixed, Mixed, Boolean * Used for determining if the passed object is defined. * * If the object is defined then it will be returned. * Otherwise the override object will be returned. * * If "doReturnBoolean" is true then true/false is returned in place of object/override. * */ $.exists = function(source, override, doReturnBoolean) { source = ObjectShortcut(source); if (typeof source !== Cache.undefined) { if (doReturnBoolean) { return true; } else { return source; } } else { if (doReturnBoolean) { return false; } else { return override; } } }; /* * format() returns String * Input: String, Mixed * */ $.format = function(source) { if (arguments.length > 1) { /* * The values may be in the arguments array, * or may be an array passed as the second argument. * */ var indexOffset = 1; var values = arguments; if ($.isArray(arguments[1])) { indexOffset = 0; values = arguments[1]; } var variables = source.match(RegularExpressions.sprintfVariable); var end = (variables) ? variables.length : 0; /* Replace each format variable with the appropriate values. */ for (var i = 0; i < end; i++) { source = source.replace( variables[i], TextProcessor.Process(variables[i], values[i+indexOffset].toString()) ); } } return source; }; /* * This section contains query string related methods. * It is also a sort of "magic object". It can be passed to functions * to perform operations on the query string. * * Example: * var hasId = $.HasProperty($.GET, "id"); * var matches = $.Equals($.GET, {"id":"42", "name":"John Doe"}); * */ $.get = { /* * exists() returns Boolean * Input: Array|String * Returns true if the passed GET variable has been defined. * Does not require a value to have been assigned to the GET variables. * */ exists: function(name) { if ($.type(name) === Cache.array) { var result = name.length; for (var len=result; result && len--;) { result = (typeof QueryString[name[len]] !== Cache.undefined); } return result; } else { return typeof QueryString[name] !== Cache.undefined; } }, /* * get() returns String|undefined * Input: String * Returns the value of the passed query string variable. * Will return undefined if it has not been defined. * */ get: function(source) { if ($.type(source) === Cache.array) { var result = {}; for (var len=source.length; len--;) { result[source[len]] = QueryString[source[len]]; } return result; } else { return QueryString[source]; } }, /* * getAll() returns Object * Input: Nothing * Returns a copy of the query string object. * */ getAll: function() { var result = {}; for (var index in QueryString) { result[index] = QueryString[index]; } return result; } }; /* * generateArray() returns Array * Input: Number, Mixed, Boolean * Generates an array based on the passed parameters. * If the third argument is a boolean "true" then second argument is * treated as a callback. * Can be used to quickly create an array of N size by not assigning * the "value" argument a value: * var arr = $.GenerateArray(10); * The array can also be manipulated as it grows: * var arr = $.GenerateArray(10, function(src,i){ if (i>0) { src[i-1] = Math.pow(src.length,2); return 0; } }, true); * console.log(arr); // [1, 4, 9, 16, 25, 36, 49, 64, 81, 0] * */ $.generateArray = function(amount, value, isCallback) { var result = []; for (var i = 0; i < amount; i++) { result[i] = isCallback ? value(result,i) : value; } return result; }; /* * hasProperty() returns Boolean * Input: String, String, Boolean * Returns true if the object has the passed property defined. * For example, checking for "foo" on this object: * {"hello":"world", "id":42, "foo":null} * Will return true because it is defined. * Its value is irrelevent. * */ $.hasProperty = function(source, property, doIterateSource) { source = ObjectShortcut(source); if (typeof doIterateSource !== Cache.undefined && doIterateSource) { var result = $.isArray(source); for (var len=source.length; result && len--;) { result = source[len].hasOwnProperty(property); } return result; } else { return source.hasOwnProperty(property); } }; /* * hasValue() returns Boolean * Input: Array|Object, Mixed * Returns true if the passed container has the passed source defined. * For example, the following will return true for the value "bar": * {"id":42, "foo":"bar", "hello":"world"}; * [1, 2, "foo", 3, 4, 5]; * However, only the second will return true for "foo". * Indices in objects are not searched. * */ $.hasValue = function(source, value) { source = ObjectShortcut(source); var result = false; $.each(source, function(itr){ return !(result = $.equals(value,itr.value)); }); return result; }; /* * indexOf() returns Number|String|null * Input: Array|Object, Object * Returns the index of the passed value if found in the container. * Will return NULL if the value is not found. * */ $.indexOf = function(haystack, needle) { var result = null; $.each(haystack, function(itr){ if ($.equals(itr.value, needle)) { result = itr.index; return false; } }); return result; } /* * isArray() returns Boolean * Input: Array, Boolean * */ $.isArray = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isArray); } else { return ($.type(source) === Cache.array); } }; /* * isDOMElement() returns Boolean * Input: Object, Boolean * */ $.isDOMElement = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isDOMElement); } else { return typeof source !== Cache.undefined && source !== null && typeof source.ELEMENT_NODE !== Cache.undefined; } }; /* * isDOMElementArray() returns Boolean * Input: Object, Boolean * */ $.isDOMElementArray = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isDOMElementArray); } else { return typeof source !== Cache.undefined && source !== null && typeof source.item !== Cache.undefined; } }; /* * isEmptyArray() returns Boolean * Input: Array, Boolean * Returns true if the passed array is empty. * False otherwise. * */ $.isEmptyArray = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isEmptyArray); } else { return $.isArray(source) && !source.length; } }; /* * isEmptyObject() returns Boolean * Input: Object|Array, Boolean * Returns true if the passed object contains no indices, or is undefined. * Will only return false if the object contains no indices, even if defined. * */ $.isEmptyObject = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isEmptyObject); } else { if (typeof source !== Cache.undefined) { for (var index in source) { return false; } } return true; } }; /* * isFunction() returns Boolean * Input: Array|Object, Boolean * */ $.isFunction = function(source, doIteratSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isFunction); } else { return typeof source === Cache.func; } }; /* * isNumeric() returns Boolean * Input: Array|Mixed, Array * */ $.isNumeric = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isNumeric); } else { return !isNaN(parseFloat(source)) && isFinite(source); } }; /* * isObject() returns Boolean * Input: Object|Array, Boolean * */ $.isObject = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isObject); } else { return ($.type(source) === Cache.object); } }; /* * isString() returns Boolean * Input: Array|String, Boolean * */ $.isString = function(source, doIterateSource) { if (typeof doIterateSource !== Cache.undefined && doIterateSource) { return Comparison(source, $.isString); } else { return ($.type(source) === Cache.string); } }; /* * lambda() returns Function * Input: Mixed * Returns a function that will do nothing but return the passed value. * Based on the MooTools function of the same name. * */ $.lambda = function(value) { return (function(){return value;}); }; /* * objectToArray() returns Array * Input: Object * Converts the passed object into an array. * The first element will be the object's indices. * The second element will be the object's values. * * For example: * {foo:"bar", id:42, name:"John Doe"} * Will become: * [ ["foo", "id", "name"], ["bar", 42, "John Doe"] ] * * */ $.objectToArray = function(source) { source = ObjectShortcut(source); var result = [[],[]]; for (var index in source) { result[0].push(index); result[1].push(source[index]); } return result; }; /* * random() returns Number * Input: Number, Number, Number * */ $.random = function(min, max, decimalPlaces) { if (typeof max === Cache.undefined) { max = min; min = 0; } return $.round((Math.random() * (max-min)) + min, decimalPlaces); }; /* * ready() returns Nothing * Input: Function * Adds the passed function to the list of callbacks that * are called when the DOM is ready. * */ $.ready = function(callback) { if ($.type(callback) === Cache.func) { if (State.isReady === false && State.isBusy === false) { DOMReadyCallbacks.push(callback); } else { callback(); } } }; /* * removeEvent() returns Nothing * Input: Array|String, Array|String, Function, Boolean * Removed the processed event. * If this event does not exist then this function won't actually do anything. * */ $.removeEvent = function(element, event, callback, useCapture) { EventManager.ProcessEventListener(false, element, event, callback, useCapture); }; /* * round returns Number * Input: Number, Number * */ $.round = function(num, decimalPlaces) { decimalPlaces = Math.pow(10, decimalPlaces ? decimalPlaces : 0); return Math.round(num*decimalPlaces) / decimalPlaces; }; /* * toInt() returns Number|NaN * Input: Mixed, Number * Converts the passed object to an integer. * Objects that cannot be converted will be returned as NaN. * */ $.toInt = function(source, base) { if ($.type(source) !== Cache.number) { var result = source.match(RegularExpressions.number); if (result !== null && result.length === 1) { return parseInt(source.replace(RegularExpressions.notNumber, Cache.emptyString), $.exists(base,10)); } else { return NaN; } } else { return parseInt(source, $.exists(base,10)); } }; /* * toUnsignedInt() returns Number|NaN * Input: Mixed, Number, Number * Converts the passed object to an unsigned integer. * Objects that cannot be converted will be returned as NaN. * */ $.toUnsignedInt = function(source, base, max) { if (source = $.toInt(source, base)) { return (source > 0) ? source : ($.exists(max,Cache.uint32max) - Math.abs(source)); } else { return source; } }; /* * type() returns String * Input: Mixed * Returns the type of the passed object. * Based on jQuery's code for doing the same thing. * */ $.type = function(source) { return source === null ? "null" : (ClassTypes[Object.prototype.toString.call(source)] || "object"); }; /* * * Query Strings * * */ var QueryString = $.decodeQueryString(document.location.search); /* * * Event Listeners * * */ if (State.hasAddEventListener) { document.addEventListener("DOMContentLoaded", Events.onDOMContentLoaded, false); window.addEventListener("load", Events.onReady, false); } else if (State.hasAttachEvent) { document.attachEvent("onreadystatechange", Events.onDOMContentLoaded); window.attachEvent("onload", Events.onReady, false); } else { window.onload = Events.onReady; } }(Ludus));
Added new function "Ludus.all()" Was originally named "compare". Changes: - Now if no predicate is given the data in each element themselves will be used for the true/false check
src/ludus.js
Added new function "Ludus.all()"
<ide><path>rc/ludus.js <ide> */ <ide> SendAJAXRequest(request, request); <ide> }; <add> <add> /* <add> * all() returns Boolean <add> * Input: Array|Object, Function <add> * Returns true if every call to the predicate also returns true. <add> * Returns false otherwise, or if empty data is given. <add> * */ <add> $.all = function(data, predicate) { <add> var result; <add> <add> $.each(data, function(itr) { <add> return predicate ? result = predicate(itr.value) : itr.value; <add> }); <add> <add> return result ? true : false; <add> }; <ide> <ide> /* <ide> * arraysEqual() returns Boolean
JavaScript
mit
919074aae49459af5042ba4ba3a3833a2d600139
0
ansal/jaagademovote
// Routes for JaagaDemoVote app // global backbone app var JaagaDemoVote = JaagaDemoVote || {}; (function(){ 'use strict'; // shortcut var J = JaagaDemoVote; // app containersb // html rendered by backbone views are put into this container var $container = $('#appContainer'); // spinner template var spinnerHTML = $('#spinnerTemplate').html(); J.AppRouter = Backbone.Router.extend({ routes: { // admin only urls 'app/admin/users': 'adminUsers', 'app/admin/users/add': 'adminUsersAdd', 'app/admin/users/view/:id': 'adminUser', // urls for all users 'app/dashboard': 'dashboard', 'app/deliverables/add': 'userAddDeliverable', 'app/user/deliverable/view/:id': 'userEditDeliverable', 'app/user/family/view/:id': 'memberView', 'app/user/family/deliverable/view/:id': 'memberDeliverableView' }, adminUsers: function() { $container.html(spinnerHTML); if(J.Collections.AllowedUsers.length !== 0) { J.AppState.currentView = new J.Views.AdminUsersView; $container.html( J.AppState.currentView.render().$el ); } else { J.Collections.AllowedUsers.fetch({ success: function() { J.AppState.currentView = new J.Views.AdminUsersView; $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } }, adminUser: function(id) { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } var user = J.Collections.AllowedUsers.get(id); // check whether we get a model or not // if not, it might be because collection has not been fetched yet if(!user) { J.Collections.AllowedUsers.fetch({ success: function() { var user = J.Collections.AllowedUsers.get(id); J.AppState.currentView = new J.Views.AdminUserView( {model: user} ); $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } else { J.AppState.currentView = new J.Views.AdminUserView( {model: user} ); $container.html( J.AppState.currentView.render().$el ); } }, adminUsersAdd: function() { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } J.AppState.currentView = new J.Views.AdminUserAddView; $container.html( J.AppState.currentView.render().$el ); }, dashboard: function() { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } // Fetch all collections before loading // This is an antipattern as described in Backbone FAQ // But for the time being Models are not bootstrapped by // the backend. if(J.Collections.Deliverables.length !== 0) { J.AppState.currentView = new J.Views.UserDashboardView; $container.html( J.AppState.currentView.render().$el ); } else { J.Collections.Deliverables.fetch({ success: function() { // Since dashboard also shows family members, // we have to show them too J.Collections.Family.fetch({ success: function() { J.AppState.currentView = new J.Views.UserDashboardView; $container.html( J.AppState.currentView.render().$el ); }, error: function() { alert('Failed to load data. Please see log for details'); console.log(err); } }); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } }, userAddDeliverable: function() { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } J.AppState.currentView = new J.Views.UserAddDeliverableView; $container.html( J.AppState.currentView.render().$el ); }, userEditDeliverable: function(id) { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } var deliverable = J.Collections.Deliverables.get(id); // check whether we get a model or not // if not, it might be because collection has not been fetched yet if(!deliverable) { J.Collections.Deliverables.fetch({ success: function() { var deliverable = J.Collections.Deliverables.get(id); J.AppState.currentView = new J.Views.UserEditDeliverableView( {model: deliverable} ); $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } else { J.AppState.currentView = new J.Views.UserEditDeliverableView( {model: deliverable} ); $container.html( J.AppState.currentView.render().$el ); } }, memberView: function(id) { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } var member = J.Collections.Family.get(id); // check whether we get a model or not // if not, it might be because collection has not been fetched yet if(!member) { J.Collections.Family.fetch({ success: function() { var member = J.Collections.Family.get(id); J.AppState.currentView = new J.Views.MemberView( {model: member} ); $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } else { J.AppState.currentView = new J.Views.MemberView( {model: member} ); $container.html( J.AppState.currentView.render().$el ); } }, memberDeliverableView: function(id) { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } var deliverable = J.Collections.Deliverables.get(id); // check whether we get a model or not // if not, it might be because collection has not been fetched yet if(!deliverable) { J.Collections.Deliverables.fetch({ success: function() { var deliverable = J.Collections.Deliverables.get(id); J.AppState.currentView = new J.Views.MemberDeliverableView( {model: deliverable} ); $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } else { J.AppState.currentView = new J.Views.MemberDeliverableView( {model: deliverable} ); $container.html( J.AppState.currentView.render().$el ); } } }); })();
public/js/routes.js
// Routes for JaagaDemoVote app // global backbone app var JaagaDemoVote = JaagaDemoVote || {}; (function(){ 'use strict'; // shortcut var J = JaagaDemoVote; // app containersb // html rendered by backbone views are put into this container var $container = $('#appContainer'); // spinner template var spinnerHTML = $('#spinnerTemplate').html(); J.AppRouter = Backbone.Router.extend({ routes: { // admin only urls 'app/admin/users': 'adminUsers', 'app/admin/users/add': 'adminUsersAdd', 'app/admin/users/view/:id': 'adminUser', // urls for all users 'app/dashboard': 'dashboard', 'app/deliverables/add': 'userAddDeliverable', 'app/user/deliverable/view/:id': 'userEditDeliverable', 'app/user/family/view/:id': 'memberView', 'app/user/family/deliverable/view/:id': 'memberDeliverableView' }, adminUsers: function() { $container.html(spinnerHTML); J.Collections.AllowedUsers.fetch({ success: function() { J.AppState.currentView = new J.Views.AdminUsersView; $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); }, adminUser: function(id) { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } var user = J.Collections.AllowedUsers.get(id); // check whether we get a model or not // if not, it might be because collection has not been fetched yet if(!user) { J.Collections.AllowedUsers.fetch({ success: function() { var user = J.Collections.AllowedUsers.get(id); J.AppState.currentView = new J.Views.AdminUserView( {model: user} ); $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } else { J.AppState.currentView = new J.Views.AdminUserView( {model: user} ); $container.html( J.AppState.currentView.render().$el ); } }, adminUsersAdd: function() { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } J.AppState.currentView = new J.Views.AdminUserAddView; $container.html( J.AppState.currentView.render().$el ); }, dashboard: function() { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } // Fetch all collections before loading // This is an antipattern as described in Backbone FAQ // But for the time being Models are not bootstrapped by // the backend. J.Collections.Deliverables.fetch({ success: function() { // Since dashboard also shows family members, // we have to show them too J.Collections.Family.fetch({ success: function() { J.AppState.currentView = new J.Views.UserDashboardView; $container.html( J.AppState.currentView.render().$el ); }, error: function() { alert('Failed to load data. Please see log for details'); console.log(err); } }); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); }, userAddDeliverable: function() { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } J.AppState.currentView = new J.Views.UserAddDeliverableView; $container.html( J.AppState.currentView.render().$el ); }, userEditDeliverable: function(id) { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } var deliverable = J.Collections.Deliverables.get(id); // check whether we get a model or not // if not, it might be because collection has not been fetched yet if(!deliverable) { J.Collections.Deliverables.fetch({ success: function() { var deliverable = J.Collections.Deliverables.get(id); J.AppState.currentView = new J.Views.UserEditDeliverableView( {model: deliverable} ); $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } else { J.AppState.currentView = new J.Views.UserEditDeliverableView( {model: deliverable} ); $container.html( J.AppState.currentView.render().$el ); } }, memberView: function(id) { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } var member = J.Collections.Family.get(id); // check whether we get a model or not // if not, it might be because collection has not been fetched yet if(!member) { J.Collections.Family.fetch({ success: function() { var member = J.Collections.Family.get(id); J.AppState.currentView = new J.Views.MemberView( {model: member} ); $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } else { J.AppState.currentView = new J.Views.MemberView( {model: member} ); $container.html( J.AppState.currentView.render().$el ); } }, memberDeliverableView: function(id) { $container.html(spinnerHTML); if(J.AppState.currentView) { J.AppState.currentView.remove(); } var deliverable = J.Collections.Deliverables.get(id); // check whether we get a model or not // if not, it might be because collection has not been fetched yet if(!deliverable) { J.Collections.Deliverables.fetch({ success: function() { var deliverable = J.Collections.Deliverables.get(id); J.AppState.currentView = new J.Views.MemberDeliverableView( {model: deliverable} ); $container.html( J.AppState.currentView.render().$el ); }, error: function(err) { alert('Failed to load data. Please see log for details'); console.log(err); } }); } else { J.AppState.currentView = new J.Views.MemberDeliverableView( {model: deliverable} ); $container.html( J.AppState.currentView.render().$el ); } } }); })();
dashboard and user management now only fetches collection if not already loaded
public/js/routes.js
dashboard and user management now only fetches collection if not already loaded
<ide><path>ublic/js/routes.js <ide> <ide> adminUsers: function() { <ide> $container.html(spinnerHTML); <del> J.Collections.AllowedUsers.fetch({ <add> if(J.Collections.AllowedUsers.length !== 0) { <add> J.AppState.currentView = new J.Views.AdminUsersView; <add> $container.html( J.AppState.currentView.render().$el ); <add> } else { <add> J.Collections.AllowedUsers.fetch({ <ide> success: function() { <ide> J.AppState.currentView = new J.Views.AdminUsersView; <ide> $container.html( J.AppState.currentView.render().$el ); <ide> alert('Failed to load data. Please see log for details'); <ide> console.log(err); <ide> } <del> }); <add> }); <add> } <ide> }, <ide> <ide> adminUser: function(id) { <ide> // This is an antipattern as described in Backbone FAQ <ide> // But for the time being Models are not bootstrapped by <ide> // the backend. <del> J.Collections.Deliverables.fetch({ <del> success: function() { <del> // Since dashboard also shows family members, <del> // we have to show them too <del> J.Collections.Family.fetch({ <del> success: function() { <del> J.AppState.currentView = new J.Views.UserDashboardView; <del> $container.html( J.AppState.currentView.render().$el ); <del> }, <del> error: function() { <del> alert('Failed to load data. Please see log for details'); <del> console.log(err); <del> } <del> }); <del> }, <del> error: function(err) { <del> alert('Failed to load data. Please see log for details'); <del> console.log(err); <del> } <del> }); <add> if(J.Collections.Deliverables.length !== 0) { <add> J.AppState.currentView = new J.Views.UserDashboardView; <add> $container.html( J.AppState.currentView.render().$el ); <add> } else { <add> J.Collections.Deliverables.fetch({ <add> success: function() { <add> // Since dashboard also shows family members, <add> // we have to show them too <add> J.Collections.Family.fetch({ <add> success: function() { <add> J.AppState.currentView = new J.Views.UserDashboardView; <add> $container.html( J.AppState.currentView.render().$el ); <add> }, <add> error: function() { <add> alert('Failed to load data. Please see log for details'); <add> console.log(err); <add> } <add> }); <add> }, <add> error: function(err) { <add> alert('Failed to load data. Please see log for details'); <add> console.log(err); <add> } <add> }); <add> } <ide> }, <ide> <ide> userAddDeliverable: function() {
Java
apache-2.0
347f6dcafad795da44c49f193aa9b0850d3037c4
0
roele/sling,ieb/sling,Nimco/sling,anchela/sling,dulvac/sling,tteofili/sling,headwirecom/sling,mcdan/sling,cleliameneghin/sling,JEBailey/sling,JEBailey/sling,awadheshv/sling,gutsy/sling,awadheshv/sling,cleliameneghin/sling,tteofili/sling,headwirecom/sling,Sivaramvt/sling,plutext/sling,JEBailey/sling,mikibrv/sling,tmaret/sling,SylvesterAbreu/sling,tyge68/sling,SylvesterAbreu/sling,mmanski/sling,Sivaramvt/sling,cleliameneghin/sling,Sivaramvt/sling,tteofili/sling,Nimco/sling,tyge68/sling,sdmcraft/sling,klcodanr/sling,ieb/sling,klcodanr/sling,anchela/sling,roele/sling,dulvac/sling,codders/k2-sling-fork,trekawek/sling,JEBailey/sling,trekawek/sling,ist-dresden/sling,vladbailescu/sling,nleite/sling,labertasch/sling,cleliameneghin/sling,awadheshv/sling,sdmcraft/sling,tyge68/sling,nleite/sling,mmanski/sling,sdmcraft/sling,tteofili/sling,mikibrv/sling,ist-dresden/sling,dulvac/sling,klcodanr/sling,SylvesterAbreu/sling,anchela/sling,plutext/sling,JEBailey/sling,tyge68/sling,mmanski/sling,ist-dresden/sling,mmanski/sling,awadheshv/sling,mcdan/sling,tyge68/sling,Sivaramvt/sling,dulvac/sling,mikibrv/sling,wimsymons/sling,gutsy/sling,SylvesterAbreu/sling,codders/k2-sling-fork,wimsymons/sling,tmaret/sling,headwirecom/sling,gutsy/sling,ieb/sling,tmaret/sling,nleite/sling,gutsy/sling,ffromm/sling,vladbailescu/sling,roele/sling,codders/k2-sling-fork,ieb/sling,mikibrv/sling,SylvesterAbreu/sling,wimsymons/sling,headwirecom/sling,trekawek/sling,tyge68/sling,gutsy/sling,anchela/sling,ffromm/sling,roele/sling,mmanski/sling,mcdan/sling,vladbailescu/sling,wimsymons/sling,Nimco/sling,plutext/sling,trekawek/sling,ffromm/sling,nleite/sling,plutext/sling,sdmcraft/sling,wimsymons/sling,gutsy/sling,headwirecom/sling,plutext/sling,awadheshv/sling,Sivaramvt/sling,ffromm/sling,mcdan/sling,mikibrv/sling,ist-dresden/sling,cleliameneghin/sling,vladbailescu/sling,ffromm/sling,mcdan/sling,ieb/sling,nleite/sling,ffromm/sling,klcodanr/sling,labertasch/sling,anchela/sling,Nimco/sling,tmaret/sling,mmanski/sling,labertasch/sling,sdmcraft/sling,trekawek/sling,dulvac/sling,Nimco/sling,plutext/sling,SylvesterAbreu/sling,nleite/sling,ieb/sling,klcodanr/sling,sdmcraft/sling,Sivaramvt/sling,klcodanr/sling,labertasch/sling,mikibrv/sling,wimsymons/sling,mcdan/sling,trekawek/sling,dulvac/sling,ist-dresden/sling,labertasch/sling,roele/sling,Nimco/sling,vladbailescu/sling,tteofili/sling,tmaret/sling,awadheshv/sling,tteofili/sling
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.microsling.scripting; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import javax.jcr.Item; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Property; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.servlet.ServletException; import org.apache.sling.api.SlingException; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.scripting.SlingScript; import org.apache.sling.api.scripting.SlingScriptEngine; import org.apache.sling.api.scripting.SlingScriptResolver; import org.apache.sling.microsling.scripting.engines.rhino.RhinoJavasSriptEngine; import org.apache.sling.microsling.scripting.engines.velocity.VelocityTemplatesScriptEngine; import org.apache.sling.microsling.scripting.helpers.ScriptFilenameBuilder; import org.apache.sling.microsling.scripting.helpers.ScriptHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Find scripts in the repository, based on the current Resource type. The * script filename is built using the current HTTP request method name, followed * by the extension of the current request and the desired script extension. For * example, a "js" script for a GET request on a Resource of type some/type with * request extension "html" should be stored as * * <pre> * /sling/scripts/some/type/get.html.js * </pre> * * in the repository. */ public class MicroslingScriptResolver implements SlingScriptResolver { private static final Logger log = LoggerFactory.getLogger(MicroslingScriptResolver.class); public static final String SCRIPT_BASE_PATH = "/sling/scripts"; /** * jcr:encoding */ public static final String JCR_ENCODING = "jcr:encoding"; private final ScriptFilenameBuilder scriptFilenameBuilder = new ScriptFilenameBuilder(); private Map<String, SlingScriptEngine> scriptEngines; public MicroslingScriptResolver() throws SlingException { scriptEngines = new HashMap<String, SlingScriptEngine>(); addScriptEngine(new RhinoJavasSriptEngine()); addScriptEngine(new VelocityTemplatesScriptEngine()); } /** * @param req * @param scriptExtension * @return <code>true</code> if a MicroslingScript and a ScriptEngine to * evaluate it could be found. Otherwise <code>false</code> is * returned. * @throws ServletException * @throws IOException */ public static void evaluateScript(final SlingScript script, final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws ServletException, IOException { try { // the script helper ScriptHelper helper = new ScriptHelper(req, resp); // prepare the properties for the script Map<String, Object> props = new HashMap<String, Object>(); props.put(SlingScriptEngine.SLING, helper); props.put(SlingScriptEngine.RESOURCE, helper.getRequest().getResource()); props.put(SlingScriptEngine.REQUEST, helper.getRequest()); props.put(SlingScriptEngine.RESPONSE, helper.getResponse()); props.put(SlingScriptEngine.OUT, helper.getResponse().getWriter()); props.put(SlingScriptEngine.LOG, LoggerFactory.getLogger(script.getScriptPath())); resp.setContentType(req.getResponseContentType() + "; charset=UTF-8"); // evaluate the script now using the ScriptEngine script.getScriptEngine().eval(script, props); // ensure data is flushed to the underlying writer in case // anything has been written helper.getResponse().getWriter().flush(); } catch (IOException ioe) { throw ioe; } catch (ServletException se) { throw se; } catch (Exception e) { throw new SlingException("Cannot get MicroslingScript: " + e.getMessage(), e); } } public SlingScript findScript(String path) throws SlingException { // TODO Auto-generated method stub return null; } /** * Try to find a script Node that can process the given request, based on * the rules defined above. * * @return null if not found. */ public SlingScript resolveScript(final SlingHttpServletRequest request) throws SlingException { try { return resolveScriptInternal(request); } catch (RepositoryException re) { throw new SlingException("Cannot resolve script for request", re); } } public SlingScript resolveScriptInternal( final SlingHttpServletRequest request) throws RepositoryException { final Resource r = request.getResource(); // ensure repository access if (!(r.getRawData() instanceof Item)) { return null; } final Session s = ((Item) r.getRawData()).getSession(); MicroslingScript result = null; if (r == null) { return null; } String scriptFilename = scriptFilenameBuilder.buildScriptFilename( request.getMethod(), request.getRequestPathInfo().getSelectorString(), request.getResponseContentType(), "*"); String scriptPath = SCRIPT_BASE_PATH + "/" + r.getResourceType(); // SLING-72: if the scriptfilename contains a relative path, move that // to the scriptPath and make the scriptFilename a direct child pattern int lastSlash = scriptFilename.lastIndexOf('/'); if (lastSlash >= 0) { scriptPath += "/" + scriptFilename.substring(0, lastSlash); scriptFilename = scriptFilename.substring(lastSlash + 1); } // this is the location of the trailing asterisk final int scriptExtensionOffset = scriptFilename.length() - 1; if (log.isDebugEnabled()) { log.debug("Looking for script with filename=" + scriptFilename + " under " + scriptPath); } if (s.itemExists(scriptPath)) { // get the item and ensure it is a node final Item i = s.getItem(scriptPath); if (i.isNode()) { Node parent = (Node) i; NodeIterator scriptNodeIterator = parent.getNodes(scriptFilename); while (scriptNodeIterator.hasNext()) { Node scriptNode = scriptNodeIterator.nextNode(); // SLING-72: Require the node to be an nt:file if (scriptNode.isNodeType("nt:file")) { String scriptName = scriptNode.getName(); String scriptExt = scriptName.substring(scriptExtensionOffset); SlingScriptEngine scriptEngine = scriptEngines.get(scriptExt); if (scriptEngine != null) { MicroslingScript script = new MicroslingScript(); script.setNode(scriptNode); script.setScriptPath(scriptNode.getPath()); script.setScriptEngine(scriptEngine); result = script; break; } } } } } if (result != null) { log.info("Found nt:file script node " + result.getScriptPath() + " for Resource=" + r); } else { log.debug("nt:file script node not found at path=" + scriptPath + " for Resource=" + r); } return result; } protected String filterStringForFilename(String inputString) { final StringBuffer sb = new StringBuffer(); final String str = inputString.toLowerCase(); for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (Character.isLetterOrDigit(c)) { sb.append(c); } else { sb.append("_"); } } return sb.toString(); } private void addScriptEngine(SlingScriptEngine scriptEngine) { String[] extensions = scriptEngine.getExtensions(); for (String extension : extensions) { scriptEngines.put(extension, scriptEngine); } } private static class MicroslingScript implements SlingScript { private Node node; private String scriptPath; private SlingScriptEngine scriptEngine; /** * @return the node */ Node getNode() { return node; } /** * @param node the node to set */ void setNode(Node node) { this.node = node; } /** * @return the scriptPath */ public String getScriptPath() { return scriptPath; } /** * @param scriptPath the scriptPath to set */ void setScriptPath(String scriptPath) { this.scriptPath = scriptPath; } /** * @return the scriptEngine */ public SlingScriptEngine getScriptEngine() { return scriptEngine; } /** * @param scriptEngine the scriptEngine to set */ void setScriptEngine(SlingScriptEngine scriptEngine) { this.scriptEngine = scriptEngine; } /** * @return The script stored in the node as a Reader */ public Reader getScriptReader() throws IOException { Property property; Value value; try { // SLING-72: Cannot use primary items due to WebDAV creating // nt:unstructured as jcr:content node. So we just assume // nt:file and try to use the well-known data path property = getNode().getProperty("jcr:content/jcr:data"); value = null; if (property.getDefinition().isMultiple()) { // for a multi-valued property, we take the first non-null // value (null values are possible in multi-valued // properties) // TODO: verify this claim ... Value[] values = property.getValues(); for (Value candidateValue : values) { if (candidateValue != null) { value = candidateValue; break; } } // incase we could not find a non-null value, we bail out if (value == null) { throw new IOException("Cannot access " + getScriptPath()); } } else { // for single-valued properties, we just take this value value = property.getValue(); } } catch (RepositoryException re) { throw (IOException) new IOException("Cannot get script " + getScriptPath()).initCause(re); } // Now know how to get the input stream, we still have to decide // on the encoding of the stream's data. Primarily we assume it is // UTF-8, which is a default in many places in JCR. Secondarily // we try to get a jcr:encoding property besides the data property // to provide a possible encoding String encoding = "UTF-8"; try { Node parent = property.getParent(); if (parent.hasNode(JCR_ENCODING)) { encoding = parent.getProperty(JCR_ENCODING).getString(); } } catch (RepositoryException re) { // don't care if we fail for any reason here, just assume // default } // access the value as a stream and return a buffered reader // converting the stream data using UTF-8 encoding, which is // the default encoding used try { InputStream input = value.getStream(); return new BufferedReader( new InputStreamReader(input, encoding)); } catch (RepositoryException re) { throw (IOException) new IOException("Cannot get script " + getScriptPath()).initCause(re); } } } }
microsling/microsling-core/src/main/java/org/apache/sling/microsling/scripting/MicroslingScriptResolver.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.microsling.scripting; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; import javax.jcr.Item; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Property; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.servlet.ServletException; import org.apache.sling.api.SlingException; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.scripting.SlingScript; import org.apache.sling.api.scripting.SlingScriptEngine; import org.apache.sling.api.scripting.SlingScriptResolver; import org.apache.sling.microsling.scripting.engines.rhino.RhinoJavasSriptEngine; import org.apache.sling.microsling.scripting.engines.velocity.VelocityTemplatesScriptEngine; import org.apache.sling.microsling.scripting.helpers.ScriptFilenameBuilder; import org.apache.sling.microsling.scripting.helpers.ScriptHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Find scripts in the repository, based on the current Resource type. The * script filename is built using the current HTTP request method name, followed * by the extension of the current request and the desired script extension. For * example, a "js" script for a GET request on a Resource of type some/type with * request extension "html" should be stored as * * <pre> * /sling/scripts/some/type/get.html.js * </pre> * * in the repository. */ public class MicroslingScriptResolver implements SlingScriptResolver { private static final Logger log = LoggerFactory.getLogger(MicroslingScriptResolver.class); public static final String SCRIPT_BASE_PATH = "/sling/scripts"; /** * jcr:encoding */ public static final String JCR_ENCODING = "jcr:encoding"; private final ScriptFilenameBuilder scriptFilenameBuilder = new ScriptFilenameBuilder(); private Map<String, SlingScriptEngine> scriptEngines; public MicroslingScriptResolver() throws SlingException { scriptEngines = new HashMap<String, SlingScriptEngine>(); addScriptEngine(new RhinoJavasSriptEngine()); addScriptEngine(new VelocityTemplatesScriptEngine()); } /** * @param req * @param scriptExtension * @return <code>true</code> if a MicroslingScript and a ScriptEngine to * evaluate it could be found. Otherwise <code>false</code> is * returned. * @throws ServletException * @throws IOException */ public static void evaluateScript(final SlingScript script, final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws ServletException, IOException { try { // the script helper ScriptHelper helper = new ScriptHelper(req, resp); // prepare the properties for the script Map<String, Object> props = new HashMap<String, Object>(); props.put(SlingScriptEngine.SLING, helper); props.put(SlingScriptEngine.REQUEST, helper.getRequest()); props.put(SlingScriptEngine.RESPONSE, helper.getResponse()); props.put(SlingScriptEngine.OUT, helper.getResponse().getWriter()); props.put(SlingScriptEngine.LOG, LoggerFactory.getLogger(script.getScriptPath())); resp.setContentType(req.getResponseContentType() + "; charset=UTF-8"); // evaluate the script now using the ScriptEngine script.getScriptEngine().eval(script, props); // ensure data is flushed to the underlying writer in case // anything has been written helper.getResponse().getWriter().flush(); } catch (IOException ioe) { throw ioe; } catch (ServletException se) { throw se; } catch (Exception e) { throw new SlingException("Cannot get MicroslingScript: " + e.getMessage(), e); } } public SlingScript findScript(String path) throws SlingException { // TODO Auto-generated method stub return null; } /** * Try to find a script Node that can process the given request, based on * the rules defined above. * * @return null if not found. */ public SlingScript resolveScript(final SlingHttpServletRequest request) throws SlingException { try { return resolveScriptInternal(request); } catch (RepositoryException re) { throw new SlingException("Cannot resolve script for request", re); } } public SlingScript resolveScriptInternal( final SlingHttpServletRequest request) throws RepositoryException { final Resource r = request.getResource(); // ensure repository access if (!(r.getRawData() instanceof Item)) { return null; } final Session s = ((Item) r.getRawData()).getSession(); MicroslingScript result = null; if (r == null) { return null; } String scriptFilename = scriptFilenameBuilder.buildScriptFilename( request.getMethod(), request.getRequestPathInfo().getSelectorString(), request.getResponseContentType(), "*"); String scriptPath = SCRIPT_BASE_PATH + "/" + r.getResourceType(); // SLING-72: if the scriptfilename contains a relative path, move that // to the scriptPath and make the scriptFilename a direct child pattern int lastSlash = scriptFilename.lastIndexOf('/'); if (lastSlash >= 0) { scriptPath += "/" + scriptFilename.substring(0, lastSlash); scriptFilename = scriptFilename.substring(lastSlash + 1); } // this is the location of the trailing asterisk final int scriptExtensionOffset = scriptFilename.length() - 1; if (log.isDebugEnabled()) { log.debug("Looking for script with filename=" + scriptFilename + " under " + scriptPath); } if (s.itemExists(scriptPath)) { // get the item and ensure it is a node final Item i = s.getItem(scriptPath); if (i.isNode()) { Node parent = (Node) i; NodeIterator scriptNodeIterator = parent.getNodes(scriptFilename); while (scriptNodeIterator.hasNext()) { Node scriptNode = scriptNodeIterator.nextNode(); // SLING-72: Require the node to be an nt:file if (scriptNode.isNodeType("nt:file")) { String scriptName = scriptNode.getName(); String scriptExt = scriptName.substring(scriptExtensionOffset); SlingScriptEngine scriptEngine = scriptEngines.get(scriptExt); if (scriptEngine != null) { MicroslingScript script = new MicroslingScript(); script.setNode(scriptNode); script.setScriptPath(scriptNode.getPath()); script.setScriptEngine(scriptEngine); result = script; break; } } } } } if (result != null) { log.info("Found nt:file script node " + result.getScriptPath() + " for Resource=" + r); } else { log.debug("nt:file script node not found at path=" + scriptPath + " for Resource=" + r); } return result; } protected String filterStringForFilename(String inputString) { final StringBuffer sb = new StringBuffer(); final String str = inputString.toLowerCase(); for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (Character.isLetterOrDigit(c)) { sb.append(c); } else { sb.append("_"); } } return sb.toString(); } private void addScriptEngine(SlingScriptEngine scriptEngine) { String[] extensions = scriptEngine.getExtensions(); for (String extension : extensions) { scriptEngines.put(extension, scriptEngine); } } private static class MicroslingScript implements SlingScript { private Node node; private String scriptPath; private SlingScriptEngine scriptEngine; /** * @return the node */ Node getNode() { return node; } /** * @param node the node to set */ void setNode(Node node) { this.node = node; } /** * @return the scriptPath */ public String getScriptPath() { return scriptPath; } /** * @param scriptPath the scriptPath to set */ void setScriptPath(String scriptPath) { this.scriptPath = scriptPath; } /** * @return the scriptEngine */ public SlingScriptEngine getScriptEngine() { return scriptEngine; } /** * @param scriptEngine the scriptEngine to set */ void setScriptEngine(SlingScriptEngine scriptEngine) { this.scriptEngine = scriptEngine; } /** * @return The script stored in the node as a Reader */ public Reader getScriptReader() throws IOException { Property property; Value value; try { // SLING-72: Cannot use primary items due to WebDAV creating // nt:unstructured as jcr:content node. So we just assume // nt:file and try to use the well-known data path property = getNode().getProperty("jcr:content/jcr:data"); value = null; if (property.getDefinition().isMultiple()) { // for a multi-valued property, we take the first non-null // value (null values are possible in multi-valued // properties) // TODO: verify this claim ... Value[] values = property.getValues(); for (Value candidateValue : values) { if (candidateValue != null) { value = candidateValue; break; } } // incase we could not find a non-null value, we bail out if (value == null) { throw new IOException("Cannot access " + getScriptPath()); } } else { // for single-valued properties, we just take this value value = property.getValue(); } } catch (RepositoryException re) { throw (IOException) new IOException("Cannot get script " + getScriptPath()).initCause(re); } // Now know how to get the input stream, we still have to decide // on the encoding of the stream's data. Primarily we assume it is // UTF-8, which is a default in many places in JCR. Secondarily // we try to get a jcr:encoding property besides the data property // to provide a possible encoding String encoding = "UTF-8"; try { Node parent = property.getParent(); if (parent.hasNode(JCR_ENCODING)) { encoding = parent.getProperty(JCR_ENCODING).getString(); } } catch (RepositoryException re) { // don't care if we fail for any reason here, just assume // default } // access the value as a stream and return a buffered reader // converting the stream data using UTF-8 encoding, which is // the default encoding used try { InputStream input = value.getStream(); return new BufferedReader( new InputStreamReader(input, encoding)); } catch (RepositoryException re) { throw (IOException) new IOException("Cannot get script " + getScriptPath()).initCause(re); } } } }
SLING-88 Add global variable "resource" for the scripts git-svn-id: c3eb811ccca381e673aa62a65336ec26649ed58c@591049 13f79535-47bb-0310-9956-ffa450edef68
microsling/microsling-core/src/main/java/org/apache/sling/microsling/scripting/MicroslingScriptResolver.java
SLING-88 Add global variable "resource" for the scripts
<ide><path>icrosling/microsling-core/src/main/java/org/apache/sling/microsling/scripting/MicroslingScriptResolver.java <ide> // prepare the properties for the script <ide> Map<String, Object> props = new HashMap<String, Object>(); <ide> props.put(SlingScriptEngine.SLING, helper); <add> props.put(SlingScriptEngine.RESOURCE, helper.getRequest().getResource()); <ide> props.put(SlingScriptEngine.REQUEST, helper.getRequest()); <ide> props.put(SlingScriptEngine.RESPONSE, helper.getResponse()); <ide> props.put(SlingScriptEngine.OUT, helper.getResponse().getWriter());
Java
apache-2.0
18dda98b1e3162ba2ea54ee476258bd0741d50a3
0
soluvas/karaf,soluvas/karaf,soluvas/karaf
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.karaf.diagnostic.common; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Dictionary; import java.util.Enumeration; import org.apache.karaf.diagnostic.core.DumpDestination; import org.apache.karaf.diagnostic.core.DumpProvider; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; /** * Dump provider which copies log files from data/log directory to * destination. */ public class LogDumpProvider implements DumpProvider { private BundleContext bundleContext; public void setBundleContext(BundleContext bundleContext) { this.bundleContext = bundleContext; } /** * Attach log entries from directory. */ public void createDump(DumpDestination destination) throws Exception { // get the ConfigAdmin service ServiceReference ref = bundleContext.getServiceReference(ConfigurationAdmin.class.getName()); if (ref == null) { return; } // get the PAX Logging configuration ConfigurationAdmin configurationAdmin = (ConfigurationAdmin) bundleContext.getService(ref); try { Configuration configuration = configurationAdmin.getConfiguration("org.ops4j.pax.logging"); // get the ".file" Pax Logging properties Dictionary dictionary = configuration.getProperties(); for (Enumeration e = dictionary.keys(); e.hasMoreElements(); ) { String property = (String) e.nextElement(); if (property.endsWith(".file")) { // it's a file appender, get the file location String location = (String) dictionary.get(property); File file = new File(location); if (file.exists()) { FileInputStream inputStream = new FileInputStream(file); OutputStream outputStream = destination.add("log/" + file.getName()); copy(inputStream, outputStream); } } } } catch (Exception e) { throw e; } finally { bundleContext.ungetService(ref); } } /** * Rewrites data from input stream to output stream. This code is very common * but we would avoid additional dependencies in diagnostic stuff. * * @param inputStream Source stream. * @param outputStream Destination stream. * @throws IOException When IO operation fails. */ private void copy(InputStream inputStream, OutputStream outputStream) throws IOException { byte[] buffer = new byte[4096]; int n = 0; while (-1 != (n = inputStream.read(buffer))) { outputStream.write(buffer, 0, n); } } }
diagnostic/common/src/main/java/org/apache/karaf/diagnostic/common/LogDumpProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.karaf.diagnostic.common; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Dictionary; import java.util.Enumeration; import org.apache.karaf.diagnostic.core.DumpDestination; import org.apache.karaf.diagnostic.core.DumpProvider; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; /** * Dump provider which copies log files from data/log directory to * destination. */ public class LogDumpProvider implements DumpProvider { private BundleContext bundleContext; public void setBundleContext(BundleContext bundleContext) { this.bundleContext = bundleContext; } /** * Attach log entries from directory. */ public void createDump(DumpDestination destination) throws Exception { // get the ConfigAdmin service ServiceReference ref = bundleContext.getServiceReference(ConfigurationAdmin.class.getName()); if (ref == null) { return; } // get the PAX Logging configuration ConfigurationAdmin configurationAdmin = (ConfigurationAdmin) bundleContext.getService(ref); Configuration configuration = configurationAdmin.getConfiguration("org.ops4j.pax.logging"); // get the ".file" Pax Logging properties Dictionary dictionary = configuration.getProperties(); for (Enumeration e = dictionary.keys(); e.hasMoreElements();) { String property = (String) e.nextElement(); if (property.endsWith(".file")) { // it's a file appender, get the file location String location = (String) dictionary.get(property); File file = new File(location); if (file.exists()) { FileInputStream inputStream = new FileInputStream(file); OutputStream outputStream = destination.add("log/" + file.getName()); copy(inputStream, outputStream); } } } } /** * Rewrites data from input stream to output stream. This code is very common * but we would avoid additional dependencies in diagnostic stuff. * * @param inputStream Source stream. * @param outputStream Destination stream. * @throws IOException When IO operation fails. */ private void copy(InputStream inputStream, OutputStream outputStream) throws IOException { byte[] buffer = new byte[4096]; int n = 0; while (-1 != (n = inputStream.read(buffer))) { outputStream.write(buffer, 0, n); } } }
[KARAF-951] LogDumpProvider ungets the ConfigAdmin service ref git-svn-id: 71d8a689455c5fbb0f077bc40adcfc391e14cb9d@1188594 13f79535-47bb-0310-9956-ffa450edef68
diagnostic/common/src/main/java/org/apache/karaf/diagnostic/common/LogDumpProvider.java
[KARAF-951] LogDumpProvider ungets the ConfigAdmin service ref
<ide><path>iagnostic/common/src/main/java/org/apache/karaf/diagnostic/common/LogDumpProvider.java <ide> <ide> // get the PAX Logging configuration <ide> ConfigurationAdmin configurationAdmin = (ConfigurationAdmin) bundleContext.getService(ref); <del> Configuration configuration = configurationAdmin.getConfiguration("org.ops4j.pax.logging"); <add> try { <add> Configuration configuration = configurationAdmin.getConfiguration("org.ops4j.pax.logging"); <ide> <del> // get the ".file" Pax Logging properties <del> Dictionary dictionary = configuration.getProperties(); <del> for (Enumeration e = dictionary.keys(); e.hasMoreElements();) { <del> String property = (String) e.nextElement(); <del> if (property.endsWith(".file")) { <del> // it's a file appender, get the file location <del> String location = (String) dictionary.get(property); <del> File file = new File(location); <del> if (file.exists()) { <del> FileInputStream inputStream = new FileInputStream(file); <del> OutputStream outputStream = destination.add("log/" + file.getName()); <del> copy(inputStream, outputStream); <add> // get the ".file" Pax Logging properties <add> Dictionary dictionary = configuration.getProperties(); <add> for (Enumeration e = dictionary.keys(); e.hasMoreElements(); ) { <add> String property = (String) e.nextElement(); <add> if (property.endsWith(".file")) { <add> // it's a file appender, get the file location <add> String location = (String) dictionary.get(property); <add> File file = new File(location); <add> if (file.exists()) { <add> FileInputStream inputStream = new FileInputStream(file); <add> OutputStream outputStream = destination.add("log/" + file.getName()); <add> copy(inputStream, outputStream); <add> } <ide> } <ide> } <add> } catch (Exception e) { <add> throw e; <add> } finally { <add> bundleContext.ungetService(ref); <ide> } <ide> } <ide> <ide> /** <ide> * Rewrites data from input stream to output stream. This code is very common <ide> * but we would avoid additional dependencies in diagnostic stuff. <del> * <del> * @param inputStream Source stream. <add> * <add> * @param inputStream Source stream. <ide> * @param outputStream Destination stream. <ide> * @throws IOException When IO operation fails. <ide> */ <del> private void copy(InputStream inputStream, OutputStream outputStream) throws IOException { <add> private void copy(InputStream inputStream, OutputStream outputStream) throws IOException { <ide> byte[] buffer = new byte[4096]; <ide> int n = 0; <ide> while (-1 != (n = inputStream.read(buffer))) { <ide> outputStream.write(buffer, 0, n); <ide> } <del> } <add> } <ide> <ide> }
JavaScript
mit
bc7e2cf5324cf22c69b5864b37b23cdfe96e54d0
0
alairjt/modular-pkg-1,alairjt/modular-pkg-1,alairjt/modular-home,charlie77/angularAMD,charlie77/angularAMD,aSimpleMan/angularAMD,the-unsoul/AngularAMD_TEST,the-unsoul/AngularAMD_TEST,marcoslin/angularAMD,paulodrade/angularAMD,marcoslin/angularAMD,alairjt/modular-home,freedomdebug/angularAMD,kannaiahchinni/angularAMD,paulodrade/angularAMD,kannaiahchinni/angularAMD,aSimpleMan/angularAMD,freedomdebug/angularAMD
/*jslint node: true, vars: true, nomen: true */ /*globals define, angular */ define(['angular'], function () { var ngAMD = {}, orig_angular, alternate_queue = [], app_injector, app_cached_providers = {}; /** * Return route for given controller and set the resolver to instantiate defined controller. * controller_path is needed to allow requirejs to find the code for controller. If the path * to controller is defined in require.config, it can then be omitted. * * @param: {string} templateURL: Path to the html template * @param: {string} controller: Name of the controller to use * @param: {string} controller_path: Path to the controller to be loaded that requirejs will understand. * If not provided, will attempt to load using @controller */ ngAMD.route = function (templateURL, controller, controller_path) { var req_dep = controller_path || controller; return { templateUrl: templateURL, controller: controller, resolve: { load: ['$q', '$rootScope', function ($q, $rootScope) { var defer = $q.defer(); require([req_dep], function () { defer.resolve(); $rootScope.$apply(); }); return defer.promise; }] } }; }; /** * Recreate the modules created by alternate angular in ng-app using cached $provider. * As AMD loader does not guarantee the order of dependency in a require([...],...) * clause, user must make sure that dependecies are clearly setup in shim in order * for this to work. * * HACK ALERT: * This method relay on inner working of angular.module code, and access _invokeQueue * and _runBlock private variable. Must test carefully with each release of angular. */ ngAMD.processQueue = function () { // Process alternate queue in FIFO fashion while (alternate_queue.length) { var item = alternate_queue.shift(), invokeQueue = item.module._invokeQueue, y; // Setup the providers define in the module for (y = 0; y < invokeQueue.length; y += 1) { var q = invokeQueue[y], provider = q[0], method = q[1], args = q[2]; if (app_cached_providers.hasOwnProperty(provider)) { var cachedProvider = app_cached_providers[provider]; //console.log("'" + item.name + "': applying " + provider + "." + method + " for args: ", args); cachedProvider[method].apply(null, args); } } // Execute the run block of the module if (item.module._runBlocks) { angular.forEach(item.module._runBlocks, function processRunBlock(block) { var injector = app_cached_providers.$injector; //console.log("'" + item.name + "': executing run block: ", run_block); injector.invoke(block); }); } // How to remove the module??? orig_angular.module(item.name, [], orig_angular.noop); } }; /** * Return cached app injector */ ngAMD.getCachedProvider = function (provider_name) { // Hack used for unit testing that orig_angular has been captured if (provider_name === "__orig_angular") { return orig_angular; } else { return app_cached_providers[provider_name]; } }; /** * Create inject function that uses cached $injector. * Designed primarly to be used during unit testing. */ ngAMD.inject = function () { return app_injector.invoke.apply(null, arguments); }; /** * Create an alternate angular so that subsequent call to angular.module will queue up * the module created for later processing via the .processQueue method. * * This delaying processing is needed as angular does not recognize any newly created * module after angular.bootstrap has ran. The only way to add new objects to angular * post bootstrap is using cached provider. * * Once the modules has been queued, processQueue would then use each module's _invokeQueue * and _runBlock to recreate object using cached $provider. In essence, creating a dumplite * object into the current ng-app. As result, if there are subsequent call to retrieve the * module post processQueue, it would retrieve a module that is not integrated into the ng-app. * * Therefore, any subsequent angular.module call to retrieve the module created with alternate * angular will return undefined. * */ ngAMD.getAlternateAngular = function () { var alternateAngular = {}, alternateModules = {}; orig_angular.extend(alternateAngular, orig_angular); // Custom version of angular.module used as cache alternateAngular.module = function (name, requires) { if (typeof requires === "undefined") { // Return undefined if module was created using the alternateAngular if (alternateModules.hasOwnProperty(name)) { return undefined; } else { return orig_angular.module(name); } } else { //console.log("alternateAngular.module START for '" + name + "': ", arguments); var orig_mod = orig_angular.module.apply(null, arguments), item = { name: name, module: orig_mod}; alternate_queue.push(item); alternateModules[name] = orig_mod; return orig_mod; } }; return alternateAngular; }; /** * Initialization of angularAMD. The objective is to cache the $provider and $injector from the app * to be used later. */ return function (app) { // Store the original angular orig_angular = angular; // Cache provider needed app.config( ['$controllerProvider', '$compileProvider', '$filterProvider', '$animateProvider', '$provide', function (controllerProvider, compileProvider, filterProvider, animateProvider, provide) { // Cache Providers app_cached_providers = { $controllerProvider: controllerProvider, $directive: compileProvider, $filter: filterProvider, $animateProvider: animateProvider, $provide: provide }; // Create a app.register object app.register = { controller: controllerProvider.register, directive: compileProvider.directive, filter: filterProvider.register, factory: provide.factory, service: provide.service, constant: provide.constant, value: provide.value, animation: animateProvider.register }; }] ); // Get the injector for the app app.run(['$injector', function ($injector) { // $injector must be obtained in .run instead of .config app_injector = $injector; app_cached_providers.$injector = app_injector; }]); // Create a property to store ngAMD on app app.ngAMD = ngAMD; // Return the angularAMD object return ngAMD; }; });
src/angularAMD.js
/*jslint node: true, vars: true, nomen: true */ /*globals define, angular */ define(['angular'], function () { var ngAMD = {}, orig_angular, alternate_queue = [], app_injector, app_cached_providers = {}; /** * Return route for given controller and set the resolver to instantiate defined controller. * controller_path is needed to allow requirejs to find the code for controller. If the path * to controller is defined in require.config, it can then be omitted. * * @param: {string} templateURL: Path to the html template * @param: {string} controller: Name of the controller to use * @param: {string} controller_path: Path to the controller to be loaded that requirejs will understand. * If not provided, will attempt to load using @controller */ ngAMD.route = function (templateURL, controller, controller_path) { var req_dep = controller_path || controller; return { templateUrl: templateURL, controller: controller, resolve: { load: ['$q', '$rootScope', function ($q, $rootScope) { var defer = $q.defer(); require([req_dep], function () { defer.resolve(); $rootScope.$apply(); }); return defer.promise; }] } }; }; /** * Recreate the modules created by alternate angular in ng-app using cached $provider. * As AMD loader does not guarantee the order of dependency in a require([...],...) * clause, user must make sure that dependecies are clearly setup in shim in order * for this to work. * * HACK ALERT: * This method relay on inner working of angular.module code, and access _invokeQueue * and _runBlock private variable. Must test carefully with each release of angular. */ ngAMD.processQueue = function () { // Process alternate queue in FIFO fashion while (alternate_queue.length) { var item = alternate_queue.shift(), invokeQueue = item.module._invokeQueue, y; // Setup the providers define in the module for (y = 0; y < invokeQueue.length; y += 1) { var q = invokeQueue[y], provider = q[0], method = q[1], args = q[2]; if (app_cached_providers.hasOwnProperty(provider)) { var cachedProvider = app_cached_providers[provider]; //console.log("'" + item.name + "': applying " + provider + "." + method + " for args: ", args); cachedProvider[method].apply(null, args); } } // Execute the run block of the module if (item.module._runBlocks) { angular.forEach(item.module._runBlocks, function processRunBlock(block) { var injector = app_cached_providers.$injector; //console.log("'" + item.name + "': executing run block: ", run_block); injector.invoke(block); }); } // How to remove the module??? orig_angular.module(item.name, [], orig_angular.noop); } }; /** * Return cached app injector */ ngAMD.getCachedProvider = function (provider_name) { // Hack used for unit testing that orig_angular has been captured if (provider_name === "__orig_angular") { return orig_angular; } else { return app_cached_providers[provider_name]; } }; /** * Create inject function that uses cached $injector. * Designed primarly to be used during unit testing. */ ngAMD.inject = function () { return app_injector.invoke.apply(null, arguments); }; /** * Create an alternate angular so that subsequent call to angular.module will queue up * the module created for later processing via the .processQueue method. * * This delaying processing is needed as angular does not recognize any newly created * module after angular.bootstrap has ran. The only way to add new objects to angular * post bootstrap is using cached provider. * * Once the modules has been queued, processQueue would then use each module's _invokeQueue * and _runBlock to recreate object using cached $provider. In essence, creating a dumplite * object into the current ng-app. As result, if there are subsequent call to retrieve the * module post processQueue, it would retrieve a module that is not integrated into the ng-app. * * Therefore, any subsequent angular.module call to retrieve the module created with alternate * angular will return undefined. * */ ngAMD.getAlternateAngular = function () { var alternateAngular = {}, alternateModules = {}; orig_angular.extend(alternateAngular, orig_angular); // Custom version of angular.module used as cache alternateAngular.module = function (name, requires) { if (typeof requires === "undefined") { // Return undefined if module was created using the alternateAngular if (alternateModules.hasOwnProperty(name)) { return undefined; } else { return orig_angular.module(name); } } else { //console.log("alternateAngular.module START for '" + name + "': ", arguments); var orig_mod = orig_angular.module.apply(null, arguments), item = { name: name, module: orig_mod}; alternate_queue.push(item); alternateModules[name] = orig_mod; return orig_mod; } }; return alternateAngular; }; /** * Initialization of angularAMD. The objective is to cache the $provider and $injector from the app * to be used later. */ return function (app) { // Store the original angular orig_angular = angular; // Cache provider needed app.config( ['$controllerProvider', '$compileProvider', '$filterProvider', '$animateProvider', '$provide', function (controllerProvider, compileProvider, filterProvider, animateProvider, provide) { // Cache Providers app_cached_providers = { $controllerProvider: controllerProvider, $directive: compileProvider, $filter: filterProvider, $animateProvider: animateProvider, $provide: provide }; // Create a app.register object app.register = { controller: controllerProvider.register, directive: compileProvider.directive, filter: filterProvider.register, factory: provide.factory, service: provide.service, constant: provide.constant, value: provide.value, animation: animateProvider.register }; }] ); // Get the injector for the app app.run(function ($injector) { // $injector must be obtained in .run instead of .config app_injector = $injector; app_cached_providers.$injector = app_injector; }); // Create a property to store ngAMD on app app.ngAMD = ngAMD; // Return the angularAMD object return ngAMD; }; });
Fixed the missing array syntax for dependency injection on app.config.
src/angularAMD.js
Fixed the missing array syntax for dependency injection on app.config.
<ide><path>rc/angularAMD.js <ide> ); <ide> <ide> // Get the injector for the app <del> app.run(function ($injector) { <add> app.run(['$injector', function ($injector) { <ide> // $injector must be obtained in .run instead of .config <ide> app_injector = $injector; <ide> app_cached_providers.$injector = app_injector; <del> }); <add> }]); <ide> <ide> // Create a property to store ngAMD on app <ide> app.ngAMD = ngAMD;
Java
apache-2.0
d321c00712d6f8e60f80256964a4c28b0f12f93f
0
naver/android-pull-to-refresh,Ranjan101/android-pull-to-refresh,handstudio/android-pull-to-refresh,LinKingR/android-pull-to-refresh,wskplho/android-pull-to-refresh,androidjhent/naver.v2,Ranjan101/android-pull-to-refresh,wskplho/android-pull-to-refresh,androidjhent/naver,toker/android-pull-to-refresh
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * Copyright 2013 Naver Business Platform Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.handmark.pulltorefresh.library; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ProgressBar; import com.handmark.pulltorefresh.configuration.xml.PullToRefreshXmlConfiguration; import com.handmark.pulltorefresh.library.internal.LoadingLayout; import com.handmark.pulltorefresh.library.internal.Utils; import com.handmark.pulltorefresh.library.internal.ViewCompat; public abstract class PullToRefreshBase<T extends View> extends LinearLayout implements IPullToRefresh<T> { // =========================================================== // Constants // =========================================================== static final boolean DEBUG = false; static final boolean USE_HW_LAYERS = false; static final String LOG_TAG = "PullToRefresh"; public static final float DEFAULT_FRICTION = 2.0f; public static final int DEFAULT_SMOOTH_SCROLL_DURATION_MS = 200; public static final int DEFAULT_SMOOTH_SCROLL_LONG_DURATION_MS = 325; static final int DEMO_SCROLL_INTERVAL = 225; static final String STATE_STATE = "ptr_state"; static final String STATE_MODE = "ptr_mode"; static final String STATE_CURRENT_MODE = "ptr_current_mode"; static final String STATE_SCROLLING_REFRESHING_ENABLED = "ptr_disable_scrolling"; static final String STATE_SHOW_REFRESHING_VIEW = "ptr_show_refreshing_view"; static final String STATE_SUPER = "ptr_super"; static final int REFRESHABLEVIEW_REFRESHING_BAR_VIEW_WHILE_REFRESHING_DURATION = 100; static final int REFRESHABLE_VIEW_HIDE_WHILE_REFRESHING_DURATION = 500; static final int GOOGLE_STYLE_VIEW_APPEAREANCE_DURATION = 200; static final int LAYER_TYPE_HARDWARE = 2; static final int LAYER_TYPE_NONE = 0; // =========================================================== // Fields // =========================================================== private int mTouchSlop; private float mLastMotionX, mLastMotionY; private float mInitialMotionX, mInitialMotionY; // needed properties while scrolling private float mFriction; private int mSmoothScrollDurationMs = 200; private int mSmoothScrollLongDurationMs = 325; private boolean mIsBeingDragged = false; private State mState = State.RESET; private Mode mMode = Mode.getDefault(); private Mode mCurrentMode; T mRefreshableView; private FrameLayout mRefreshableViewWrapper; private boolean mShowViewWhileRefreshing = true; private boolean mScrollingWhileRefreshingEnabled = false; private boolean mFilterTouchEvents = true; private boolean mOverScrollEnabled = true; private boolean mLayoutVisibilityChangesEnabled = true; private Interpolator mScrollAnimationInterpolator; private Class<? extends LoadingLayout> mLoadingLayoutClazz = null; private LoadingLayout mHeaderLayout; private LoadingLayout mFooterLayout; private LoadingLayout mViewOnTopLoadingLayout; /** * Top DecorView for containing google style-ptr */ private FrameLayout mTopActionbarLayout; private boolean mWindowAttached = false; private ProgressBar mRefreshableViewProgressBar; private OnRefreshListener<T> mOnRefreshListener; private OnRefreshListener2<T> mOnRefreshListener2; private OnPullEventListener<T> mOnPullEventListener; private SmoothScrollRunnable mCurrentSmoothScrollRunnable; private int mStatusBarHeight; /** * Current actionbar size */ private int mActionBarHeight; /** * Flag whether {@link #onRefreshing(boolean)} has been called */ private boolean mRefreshing; /** * Flag whether Google style view layout appearance animation will be shown */ private boolean mShowGoogleStyleViewAnimationEnabled = true; /** * Duration of Google style view layout appearance animation */ private int mShowGoogleStyleViewAnimationDuration = GOOGLE_STYLE_VIEW_APPEAREANCE_DURATION; /** * Flag whether {@code mRefreshaleView} will be hidden while refreshing */ private boolean mRefeshableViewHideWhileRefreshingEnabled = true; /** * {@code mRefreshableView}'s fade-out Duration */ private int mRefeshableViewHideWhileRefreshingDuration = REFRESHABLE_VIEW_HIDE_WHILE_REFRESHING_DURATION; /** * Flag whether some {@code ProgressBar} will be shown while refreshing */ private boolean mRefeshableViewRefreshingBarViewWhileRefreshingEnabled = true; /** * {@code mRefreshableViewRefreshingBar}'s fade-in Duration */ private int mRefeshableViewRefreshingBarViewWhileRefreshingDuration = REFRESHABLEVIEW_REFRESHING_BAR_VIEW_WHILE_REFRESHING_DURATION; // =========================================================== // Constructors // =========================================================== public PullToRefreshBase(Context context) { super(context); init(context, null); } public PullToRefreshBase(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public PullToRefreshBase(Context context, Mode mode) { super(context); mMode = mode; init(context, null); } public PullToRefreshBase(Context context, Mode mode, Class<? extends LoadingLayout> loadingLayoutClazz) { super(context); mMode = mode; mLoadingLayoutClazz = loadingLayoutClazz; init(context, null); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (DEBUG) { Log.d(LOG_TAG, "addView: " + child.getClass().getSimpleName()); } final T refreshableView = getRefreshableView(); if (refreshableView instanceof ViewGroup) { ((ViewGroup) refreshableView).addView(child, index, params); } else { throw new UnsupportedOperationException("Refreshable View is not a ViewGroup so can't addView"); } } @Deprecated @Override public final boolean demo() { if (mMode.showHeaderLoadingLayout() && isReadyForPullStart()) { smoothScrollToAndBack(-getHeaderSize() * 2); return true; } else if (mMode.showFooterLoadingLayout() && isReadyForPullEnd()) { smoothScrollToAndBack(getFooterSize() * 2); return true; } return false; } @Override public final Mode getCurrentMode() { return mCurrentMode; } @Override public final boolean getFilterTouchEvents() { return mFilterTouchEvents; } @Override public final ILoadingLayout getLoadingLayoutProxy() { return getLoadingLayoutProxy(true, true); } @Override public final ILoadingLayout getLoadingLayoutProxy(boolean includeStart, boolean includeEnd) { return createLoadingLayoutProxy(includeStart, includeEnd); } @Override public final Mode getMode() { return mMode; } @Override public final T getRefreshableView() { return mRefreshableView; } @Override public final boolean getShowViewWhileRefreshing() { return mShowViewWhileRefreshing; } @Override public final State getState() { return mState; } /** * @deprecated See {@link #isScrollingWhileRefreshingEnabled()}. */ public final boolean isDisableScrollingWhileRefreshing() { return !isScrollingWhileRefreshingEnabled(); } @Override public final boolean isPullToRefreshEnabled() { return mMode.permitsPullToRefresh(); } @Override public final boolean isPullToRefreshOverScrollEnabled() { return VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD && mOverScrollEnabled && OverscrollHelper.isAndroidOverScrollEnabled(mRefreshableView); } @Override public final boolean isRefreshing() { return mState == State.REFRESHING || mState == State.MANUAL_REFRESHING; } @Override public final boolean isScrollingWhileRefreshingEnabled() { return mScrollingWhileRefreshingEnabled; } @Override public final boolean onInterceptTouchEvent(MotionEvent event) { if (!isPullToRefreshEnabled()) { return false; } final int action = event.getAction(); if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { mIsBeingDragged = false; return false; } if (action != MotionEvent.ACTION_DOWN && mIsBeingDragged) { return true; } switch (action) { case MotionEvent.ACTION_MOVE: { // If we're refreshing, and the flag is set. Eat all MOVE events if (!mScrollingWhileRefreshingEnabled && isRefreshing()) { return true; } if (isReadyForPull()) { final float y = event.getY(), x = event.getX(); final float diff, oppositeDiff, absDiff; // We need to use the correct values, based on scroll // direction switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: diff = x - mLastMotionX; oppositeDiff = y - mLastMotionY; break; case VERTICAL: default: diff = y - mLastMotionY; oppositeDiff = x - mLastMotionX; break; } absDiff = Math.abs(diff); if (absDiff > mTouchSlop && (!mFilterTouchEvents || absDiff > Math.abs(oppositeDiff))) { if ((mMode.showHeaderLoadingLayout() || mMode.showGoogleStyle()) && diff >= 1f && isReadyForPullStart()) { mLastMotionY = y; mLastMotionX = x; mIsBeingDragged = true; if (mMode == Mode.BOTH) { mCurrentMode = Mode.PULL_FROM_START; } } else if (mMode.showFooterLoadingLayout() && diff <= -1f && isReadyForPullEnd()) { mLastMotionY = y; mLastMotionX = x; mIsBeingDragged = true; if (mMode == Mode.BOTH) { mCurrentMode = Mode.PULL_FROM_END; } } } } break; } case MotionEvent.ACTION_DOWN: { if (isReadyForPull()) { mLastMotionY = mInitialMotionY = event.getY(); mLastMotionX = mInitialMotionX = event.getX(); mIsBeingDragged = false; } break; } } return mIsBeingDragged; } @Override public final void onRefreshComplete() { if (isRefreshing()) { setState(State.RESET); } } @Override public final boolean onTouchEvent(MotionEvent event) { if (!isPullToRefreshEnabled()) { return false; } // If we're refreshing, and the flag is set. Eat the event if (!mScrollingWhileRefreshingEnabled && isRefreshing()) { return true; } if (event.getAction() == MotionEvent.ACTION_DOWN && event.getEdgeFlags() != 0) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_MOVE: { if (mIsBeingDragged) { mLastMotionY = event.getY(); mLastMotionX = event.getX(); pullEvent(); return true; } break; } case MotionEvent.ACTION_DOWN: { if (isReadyForPull()) { mLastMotionY = mInitialMotionY = event.getY(); mLastMotionX = mInitialMotionX = event.getX(); return true; } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { if (mIsBeingDragged) { mIsBeingDragged = false; if (mState == State.RELEASE_TO_REFRESH && (null != mOnRefreshListener || null != mOnRefreshListener2)) { setState(State.REFRESHING, true); return true; } // If we're already refreshing, just scroll back to the top if (isRefreshing()) { smoothScrollTo(0); return true; } // If we haven't returned by here, then we're not in a state // to pull, so just reset setState(State.RESET); return true; } break; } } return false; } /** * Set new friction * @param friction New friction value. Must be float. The default value is {@value #DEFAULT_FRICTION}. */ public final void setFriction(float friction) { this.mFriction = friction; } /** * Set new smooth scroll duration * @param smoothScrollDurationMs Milliseconds. The default value is {@value #DEFAULT_SMOOTH_SCROLL_DURATION_MS}. */ public final void setSmoothScrollDuration(int smoothScrollDurationMs) { this.mSmoothScrollDurationMs = smoothScrollDurationMs; } /** * Set new smooth scroll <b>longer</b> duration. <br /> This duration is only used by calling {@link #smoothScrollToLonger(int)}. * @param smoothScrollLongDurationMs Milliseconds. The default value is {@value #DEFAULT_SMOOTH_SCROLL_LONG_DURATION_MS}. */ public final void setSmoothScrollLongDuration(int smoothScrollLongDurationMs) { this.mSmoothScrollLongDurationMs = smoothScrollLongDurationMs; } /** * */ public final void setScrollingWhileRefreshingEnabled(boolean allowScrollingWhileRefreshing) { mScrollingWhileRefreshingEnabled = allowScrollingWhileRefreshing; } /** * @deprecated See {@link #setScrollingWhileRefreshingEnabled(boolean)} */ public void setDisableScrollingWhileRefreshing(boolean disableScrollingWhileRefreshing) { setScrollingWhileRefreshingEnabled(!disableScrollingWhileRefreshing); } @Override public final void setFilterTouchEvents(boolean filterEvents) { mFilterTouchEvents = filterEvents; } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setLastUpdatedLabel(CharSequence label) { getLoadingLayoutProxy().setLastUpdatedLabel(label); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setLoadingDrawable(Drawable drawable) { getLoadingLayoutProxy().setLoadingDrawable(drawable); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy(boolean, boolean)}. */ public void setLoadingDrawable(Drawable drawable, Mode mode) { getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setLoadingDrawable( drawable); } @Override public void setLongClickable(boolean longClickable) { getRefreshableView().setLongClickable(longClickable); } @Override public final void setMode(Mode mode) { if (mode != mMode) { if (DEBUG) { Log.d(LOG_TAG, "Setting mode to: " + mode); } mMode = mode; updateUIForMode(); updateUIForGoogleStyleMode(); } } public void setOnPullEventListener(OnPullEventListener<T> listener) { mOnPullEventListener = listener; } @Override public final void setOnRefreshListener(OnRefreshListener<T> listener) { mOnRefreshListener = listener; mOnRefreshListener2 = null; } @Override public final void setOnRefreshListener(OnRefreshListener2<T> listener) { mOnRefreshListener2 = listener; mOnRefreshListener = null; } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setPullLabel(CharSequence pullLabel) { getLoadingLayoutProxy().setPullLabel(pullLabel); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy(boolean, boolean)}. */ public void setPullLabel(CharSequence pullLabel, Mode mode) { getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setPullLabel(pullLabel); } /** * @param enable Whether Pull-To-Refresh should be used * @deprecated This simple calls setMode with an appropriate mode based on * the passed value. */ public final void setPullToRefreshEnabled(boolean enable) { setMode(enable ? Mode.getDefault() : Mode.DISABLED); } @Override public final void setPullToRefreshOverScrollEnabled(boolean enabled) { mOverScrollEnabled = enabled; } @Override public final void setRefreshing() { setRefreshing(true); } @Override public final void setRefreshing(boolean doScroll) { if (!isRefreshing()) { setState(State.MANUAL_REFRESHING, doScroll); } } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setRefreshingLabel(CharSequence refreshingLabel) { getLoadingLayoutProxy().setRefreshingLabel(refreshingLabel); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy(boolean, boolean)}. */ public void setRefreshingLabel(CharSequence refreshingLabel, Mode mode) { getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setRefreshingLabel( refreshingLabel); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setReleaseLabel(CharSequence releaseLabel) { setReleaseLabel(releaseLabel, Mode.BOTH); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy(boolean, boolean)}. */ public void setReleaseLabel(CharSequence releaseLabel, Mode mode) { getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setReleaseLabel( releaseLabel); } public void setScrollAnimationInterpolator(Interpolator interpolator) { mScrollAnimationInterpolator = interpolator; } @Override public final void setShowViewWhileRefreshing(boolean showView) { mShowViewWhileRefreshing = showView; } /** * @return Either {@link Orientation#VERTICAL} or * {@link Orientation#HORIZONTAL} depending on the scroll direction. */ public abstract Orientation getPullToRefreshScrollDirection(); /** * <p> * Wrap {@link #getPullToRefreshScrollDirection()} method <br /> * Other methods Use this method instead of {@link #getPullToRefreshScrollDirection()} method, because an orientation must be VERTICAL when mode is google style * </p> * @return Oreintation.VERTICAL if mMode.showGoogleStyle() is true,<br />Return value of {@link #getPullToRefreshScrollDirection()} method if else */ public final Orientation getFilteredPullToRefreshScrollDirection() { Orientation orientation = getPullToRefreshScrollDirection(); if (mMode.showGoogleStyle() ) { orientation = Orientation.VERTICAL; } return orientation; } final void setState(State state, final boolean... params) { mState = state; if (DEBUG) { Log.d(LOG_TAG, "State: " + mState.name()); } switch (mState) { case RESET: onReset(); break; case PULL_TO_REFRESH: onPullToRefresh(); break; case RELEASE_TO_REFRESH: onReleaseToRefresh(); break; case REFRESHING: case MANUAL_REFRESHING: onRefreshing(params[0]); break; case OVERSCROLLING: // NO-OP break; } // Call OnPullEventListener if (null != mOnPullEventListener) { mOnPullEventListener.onPullEvent(this, mState, mCurrentMode); } } /** * Used internally for adding view. Need because we override addView to * pass-through to the Refreshable View */ protected final void addViewInternal(View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); } /** * Used internally for adding view. Need because we override addView to * pass-through to the Refreshable View */ protected final void addViewInternal(View child, ViewGroup.LayoutParams params) { super.addView(child, -1, params); } /** * Create a new loading layout instance by using the class token {@link #mLoadingLayoutClazz} * @param context * @param mode * @param attrs * @return Loading layout instance which was created by using the class token {@link #mLoadingLayoutClazz} */ protected LoadingLayout createLoadingLayout(Context context, Mode mode, TypedArray attrs) { return LoadingLayoutFactory.createLoadingLayout(mLoadingLayoutClazz, context, mode, getFilteredPullToRefreshScrollDirection(), attrs); } /** * Used internally for {@link #getLoadingLayoutProxy(boolean, boolean)}. * Allows derivative classes to include any extra LoadingLayouts. */ protected LoadingLayoutProxy createLoadingLayoutProxy(final boolean includeStart, final boolean includeEnd) { LoadingLayoutProxy proxy = new LoadingLayoutProxy(); if (includeStart && mMode.showHeaderLoadingLayout()) { proxy.addLayout(mHeaderLayout); } if (includeEnd && mMode.showFooterLoadingLayout()) { proxy.addLayout(mFooterLayout); } return proxy; } /** * This is implemented by derived classes to return the created View. If you * need to use a custom View (such as a custom ListView), override this * method and return an instance of your custom class. * <p/> * Be sure to set the ID of the view in this method, especially if you're * using a ListActivity or ListFragment. * * @param context Context to create view with * @param attrs AttributeSet from wrapped class. Means that anything you * include in the XML layout declaration will be routed to the * created View * @return New instance of the Refreshable View */ protected abstract T createRefreshableView(Context context, AttributeSet attrs); protected final void disableLoadingLayoutVisibilityChanges() { mLayoutVisibilityChangesEnabled = false; } protected final LoadingLayout getFooterLayout() { return mFooterLayout; } protected final int getFooterSize() { return mFooterLayout.getContentSize(); } protected final LoadingLayout getHeaderLayout() { return mHeaderLayout; } protected final int getHeaderSize() { return mHeaderLayout.getContentSize(); } protected final int getGoogleStyleViewSize() { return mViewOnTopLoadingLayout.getContentSize(); } protected int getPullToRefreshScrollDuration() { return mSmoothScrollDurationMs; } protected int getPullToRefreshScrollDurationLonger() { return mSmoothScrollLongDurationMs; } protected FrameLayout getRefreshableViewWrapper() { return mRefreshableViewWrapper; } /** * Allows Derivative classes to handle the XML Attrs without creating a * TypedArray themsevles * * @param a - TypedArray of PullToRefresh Attributes */ protected void handleStyledAttributes(TypedArray a) { } /** * Implemented by derived class to return whether the View is in a state * where the user can Pull to Refresh by scrolling from the end. * * @return true if the View is currently in the correct state (for example, * bottom of a ListView) */ protected abstract boolean isReadyForPullEnd(); /** * Implemented by derived class to return whether the View is in a state * where the user can Pull to Refresh by scrolling from the start. * * @return true if the View is currently the correct state (for example, top * of a ListView) */ protected abstract boolean isReadyForPullStart(); /** * Called by {@link #onRestoreInstanceState(Parcelable)} so that derivative * classes can handle their saved instance state. * * @param savedInstanceState - Bundle which contains saved instance state. */ protected void onPtrRestoreInstanceState(Bundle savedInstanceState) { } /** * Called by {@link #onSaveInstanceState()} so that derivative classes can * save their instance state. * * @param saveState - Bundle to be updated with saved state. */ protected void onPtrSaveInstanceState(Bundle saveState) { } /** * Called when the UI has been to be updated to be in the * {@link State#PULL_TO_REFRESH} state. */ protected void onPullToRefresh() { switch (mCurrentMode) { case PULL_FROM_END: mFooterLayout.pullToRefresh(); break; case GOOGLE_STYLE: showViewTopLayout(); mViewOnTopLoadingLayout.pullToRefresh(); break; case PULL_FROM_START: mHeaderLayout.pullToRefresh(); break; default: // NO-OP break; } } /** * Called when the UI has been to be updated to be in the * {@link State#REFRESHING} or {@link State#MANUAL_REFRESHING} state. * * @param doScroll - Whether the UI should scroll for this event. */ protected void onRefreshing(final boolean doScroll) { // Set the flag as below for fade-in animation of mRefreshableView when releasing mRefreshing = true; if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.refreshing(); } if (mMode.showFooterLoadingLayout()) { mFooterLayout.refreshing(); } if (mMode.showGoogleStyle()) { // Fade-out mRefreshableView if ( mRefeshableViewHideWhileRefreshingEnabled == true ) { AlphaAnimator.fadeout(mRefreshableView, mRefeshableViewHideWhileRefreshingDuration); } // Fade-in refreshing bar on center if (mRefeshableViewRefreshingBarViewWhileRefreshingEnabled == true ) { mRefreshableViewProgressBar.setVisibility(View.VISIBLE); AlphaAnimator.fadein(mRefreshableViewProgressBar, mRefeshableViewRefreshingBarViewWhileRefreshingDuration); } mViewOnTopLoadingLayout.refreshing(); } if (doScroll) { if (mShowViewWhileRefreshing) { // Call Refresh Listener when the Scroll has finished OnSmoothScrollFinishedListener listener = new OnSmoothScrollFinishedListener() { @Override public void onSmoothScrollFinished() { callRefreshListener(); } }; switch (mCurrentMode) { case MANUAL_REFRESH_ONLY: case PULL_FROM_END: smoothScrollTo(getFooterSize(), listener); break; default: case PULL_FROM_START: smoothScrollTo(-getHeaderSize(), listener); break; } } else { smoothScrollTo(0); } } else { // We're not scrolling, so just call Refresh Listener now callRefreshListener(); } } /** * Called when the UI has been to be updated to be in the * {@link State#RELEASE_TO_REFRESH} state. */ protected void onReleaseToRefresh() { switch (mCurrentMode) { case PULL_FROM_END: mFooterLayout.releaseToRefresh(); break; case GOOGLE_STYLE: mViewOnTopLoadingLayout.releaseToRefresh(); break; case PULL_FROM_START: mHeaderLayout.releaseToRefresh(); break; default: // NO-OP break; } } /** * Called when the UI has been to be updated to be in the * {@link State#RESET} state. */ protected void onReset() { mIsBeingDragged = false; mLayoutVisibilityChangesEnabled = true; // Always reset both layouts, just in case... mHeaderLayout.reset(); mFooterLayout.reset(); if (mMode.showGoogleStyle()) { mViewOnTopLoadingLayout.reset(); hideViewTopLayout(); // Fade-in mRefreshableView if ( mRefreshing == true && mRefeshableViewHideWhileRefreshingEnabled == true ) { mRefreshableView.clearAnimation(); AlphaAnimator.fadein(mRefreshableView, mRefeshableViewHideWhileRefreshingDuration); } // Fade-out refreshing bar on center if (mRefeshableViewRefreshingBarViewWhileRefreshingEnabled == true ) { AlphaAnimator.fadeout(mRefreshableViewProgressBar, mRefeshableViewRefreshingBarViewWhileRefreshingDuration, new AnimationListener(){ @Override public void onAnimationEnd(Animation animation) { mRefreshableViewProgressBar.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation animation) { // do nothing } @Override public void onAnimationStart(Animation animation) { // do nothing }}); } } mRefreshing = false; smoothScrollTo(0); } @Override protected final void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle) state; setMode(Mode.mapIntToValue(bundle.getInt(STATE_MODE, 0))); mCurrentMode = Mode.mapIntToValue(bundle.getInt(STATE_CURRENT_MODE, 0)); mScrollingWhileRefreshingEnabled = bundle.getBoolean(STATE_SCROLLING_REFRESHING_ENABLED, false); mShowViewWhileRefreshing = bundle.getBoolean(STATE_SHOW_REFRESHING_VIEW, true); // Let super Restore Itself super.onRestoreInstanceState(bundle.getParcelable(STATE_SUPER)); State viewState = State.mapIntToValue(bundle.getInt(STATE_STATE, 0)); if (viewState == State.REFRESHING || viewState == State.MANUAL_REFRESHING) { setState(viewState, true); } // Now let derivative classes restore their state onPtrRestoreInstanceState(bundle); return; } super.onRestoreInstanceState(state); } @Override protected final Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); // Let derivative classes get a chance to save state first, that way we // can make sure they don't overrite any of our values onPtrSaveInstanceState(bundle); bundle.putInt(STATE_STATE, mState.getIntValue()); bundle.putInt(STATE_MODE, mMode.getIntValue()); bundle.putInt(STATE_CURRENT_MODE, mCurrentMode.getIntValue()); bundle.putBoolean(STATE_SCROLLING_REFRESHING_ENABLED, mScrollingWhileRefreshingEnabled); bundle.putBoolean(STATE_SHOW_REFRESHING_VIEW, mShowViewWhileRefreshing); bundle.putParcelable(STATE_SUPER, super.onSaveInstanceState()); return bundle; } @Override protected final void onSizeChanged(int w, int h, int oldw, int oldh) { if (DEBUG) { Log.d(LOG_TAG, String.format("onSizeChanged. W: %d, H: %d", w, h)); } super.onSizeChanged(w, h, oldw, oldh); // We need to update the header/footer when our size changes refreshLoadingViewsSize(); // Update the Refreshable View layout refreshRefreshableViewSize(w, h); /** * As we're currently in a Layout Pass, we need to schedule another one * to layout any changes we've made here */ post(new Runnable() { @Override public void run() { requestLayout(); } }); } /** * Re-measure the Loading Views height, and adjust internal padding as * necessary */ protected final void refreshLoadingViewsSize() { final int maximumPullScroll = (int) (getMaximumPullScroll() * 1.2f); int pLeft = getPaddingLeft(); int pTop = getPaddingTop(); int pRight = getPaddingRight(); int pBottom = getPaddingBottom(); switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.setWidth(maximumPullScroll); pLeft = -maximumPullScroll; } else { pLeft = 0; } if (mMode.showFooterLoadingLayout()) { mFooterLayout.setWidth(maximumPullScroll); pRight = -maximumPullScroll; } else { pRight = 0; } break; case VERTICAL: if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.setHeight(maximumPullScroll); pTop = -maximumPullScroll; } else if (mMode.showGoogleStyle() && mWindowAttached == true ) { // WARNING : There is a magic number! mViewOnTopLoadingLayout.setHeight(96 * 2); pTop = 0; } else { pTop = 0; } if (mMode.showFooterLoadingLayout()) { mFooterLayout.setHeight(maximumPullScroll); pBottom = -maximumPullScroll; } else { pBottom = 0; } break; } if (DEBUG) { Log.d(LOG_TAG, String.format("Setting Padding. L: %d, T: %d, R: %d, B: %d", pLeft, pTop, pRight, pBottom)); } setPadding(pLeft, pTop, pRight, pBottom); } protected final void refreshRefreshableViewSize(int width, int height) { // We need to set the Height of the Refreshable View to the same as // this layout LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mRefreshableViewWrapper.getLayoutParams(); switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: if (lp.width != width) { lp.width = width; mRefreshableViewWrapper.requestLayout(); } break; case VERTICAL: if (lp.height != height) { lp.height = height; mRefreshableViewWrapper.requestLayout(); } break; } } /** * Helper method which just calls scrollTo() in the correct scrolling * direction. * * @param value - New Scroll value */ protected final void setHeaderScroll(int value) { if (DEBUG) { Log.d(LOG_TAG, "setHeaderScroll: " + value); } // Clamp value to with pull scroll range final int maximumPullScroll = getMaximumPullScroll(); value = Math.min(maximumPullScroll, Math.max(-maximumPullScroll, value)); if (mLayoutVisibilityChangesEnabled) { if (value < 0) { switch (mCurrentMode) { case GOOGLE_STYLE: mViewOnTopLoadingLayout.setVisibility(View.VISIBLE); break; default: case PULL_FROM_START: mHeaderLayout.setVisibility(View.VISIBLE); break; } } else if (value > 0) { mFooterLayout.setVisibility(View.VISIBLE); } else { mHeaderLayout.setVisibility(View.INVISIBLE); mFooterLayout.setVisibility(View.INVISIBLE); } } if (USE_HW_LAYERS) { /** * Use a Hardware Layer on the Refreshable View if we've scrolled at * all. We don't use them on the Header/Footer Views as they change * often, which would negate any HW layer performance boost. */ ViewCompat.setLayerType(mRefreshableViewWrapper, value != 0 ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE /* View.LAYER_TYPE_NONE */); } // skip ScrollTo(...) if (mMode.showGoogleStyle() ) { return; } switch (getFilteredPullToRefreshScrollDirection()) { case VERTICAL: scrollTo(0, value); break; case HORIZONTAL: scrollTo(value, 0); break; } } /** * Smooth Scroll to position using the duration of * {@link #mSmoothScrollDurationMs} ms. * * @param scrollValue - Position to scroll to */ protected final void smoothScrollTo(int scrollValue) { smoothScrollTo(scrollValue, getPullToRefreshScrollDuration()); } /** * Smooth Scroll to position using the the duration of * {@link #mSmoothScrollDurationMs} ms. * * @param scrollValue - Position to scroll to * @param listener - Listener for scroll */ protected final void smoothScrollTo(int scrollValue, OnSmoothScrollFinishedListener listener) { smoothScrollTo(scrollValue, getPullToRefreshScrollDuration(), 0, listener); } /** * Smooth Scroll to position using the longer the duration of * {@link #mSmoothScrollLongDurationMs} ms. * * @param scrollValue - Position to scroll to */ protected final void smoothScrollToLonger(int scrollValue) { smoothScrollTo(scrollValue, getPullToRefreshScrollDurationLonger()); } /** * Updates the View State when the mode has been set. This does not do any * checking that the mode is different to current state so always updates. */ protected void updateUIForMode() { // We need to use the correct LayoutParam values, based on scroll // direction final LinearLayout.LayoutParams lp = getLoadingLayoutLayoutParams(); // Remove Header, and then add Header Loading View again if needed if (this == mHeaderLayout.getParent()) { removeView(mHeaderLayout); } if (mMode.showHeaderLoadingLayout()) { addViewInternal(mHeaderLayout, 0, lp); } // Remove Footer, and then add Footer Loading View again if needed if (this == mFooterLayout.getParent()) { removeView(mFooterLayout); } if (mMode.showFooterLoadingLayout()) { addViewInternal(mFooterLayout, lp); } // Hide Loading Views refreshLoadingViewsSize(); // If we're not using Mode.BOTH, set mCurrentMode to mMode, otherwise // set it to pull down mCurrentMode = (mMode != Mode.BOTH) ? mMode : Mode.PULL_FROM_START; } protected void updateUIForGoogleStyleMode() { if ( mWindowAttached == false ) { return; } if ( mMode.showGoogleStyle() == false ) { return; } // We need to use the correct LayoutParam values, based on scroll // direction @SuppressWarnings("deprecation") final FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, mActionBarHeight); lp.gravity = Gravity.CENTER; // if ( mTopActionbarLayout == mViewOnTopLoadingLayout.getParent()) { mTopActionbarLayout.removeView(mViewOnTopLoadingLayout); } if (mMode.showGoogleStyle()) { Log.d(LOG_TAG, "mViewOnTopLayout has been added." + mViewOnTopLoadingLayout); mTopActionbarLayout.addView(mViewOnTopLoadingLayout, lp); mViewOnTopLoadingLayout.setVisibility(View.VISIBLE); } // Hide Loading Views refreshLoadingViewsSize(); // If we're not using Mode.BOTH, set mCurrentMode to mMode, otherwise // set it to pull down mCurrentMode = (mMode != Mode.BOTH) ? mMode : Mode.PULL_FROM_START; } private void addRefreshableView(Context context, T refreshableView) { mRefreshableViewWrapper = new FrameLayout(context); mRefreshableViewWrapper.addView(refreshableView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); addViewInternal(mRefreshableViewWrapper, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } private void callRefreshListener() { if (null != mOnRefreshListener) { mOnRefreshListener.onRefresh(this); } else if (null != mOnRefreshListener2) { if (mCurrentMode == Mode.PULL_FROM_START || mCurrentMode == Mode.GOOGLE_STYLE) { mOnRefreshListener2.onPullDownToRefresh(this); } else if (mCurrentMode == Mode.PULL_FROM_END) { mOnRefreshListener2.onPullUpToRefresh(this); } } } @SuppressWarnings("deprecation") private void init(Context context, AttributeSet attrs) { // PullToRefreshXmlConfiguration must be initialized. PullToRefreshXmlConfiguration.getInstance().init(context); /** * start initialization */ // Styleables from XML // Getting mMode is first, because It uses mMode in getFilteredPullToRefreshScrollDirection() TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh); if (a.hasValue(R.styleable.PullToRefresh_ptrMode)) { mMode = Mode.mapIntToValue(a.getInteger(R.styleable.PullToRefresh_ptrMode, 0)); } switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: setOrientation(LinearLayout.HORIZONTAL); break; case VERTICAL: default: setOrientation(LinearLayout.VERTICAL); break; } ViewConfiguration config = ViewConfiguration.get(context); mTouchSlop = config.getScaledTouchSlop(); // Default value of PTR View's gravity is center. So let the value be set center when the gravity is not set yet in XML. if (!Utils.existAttributeIntValue(attrs, "gravity")) { setGravity(Gravity.CENTER); } // Get a loading layout class token String loadingLayoutCode = null; if (a.hasValue(R.styleable.PullToRefresh_ptrAnimationStyle)) { loadingLayoutCode = a.getString(R.styleable.PullToRefresh_ptrAnimationStyle); } mLoadingLayoutClazz = LoadingLayoutFactory.createLoadingLayoutClazzByLayoutCode(loadingLayoutCode); // Refreshable View // By passing the attrs, we can add ListView/GridView params via XML mRefreshableView = createRefreshableView(context, attrs); addRefreshableView(context, mRefreshableView); // We need to create now layouts now mHeaderLayout = createLoadingLayout(context, Mode.PULL_FROM_START, a); mFooterLayout = createLoadingLayout(context, Mode.PULL_FROM_END, a); mViewOnTopLoadingLayout = createLoadingLayout(context, Mode.PULL_FROM_START, a); // Get animation options for Google style mode if (a.hasValue(R.styleable.PullToRefresh_ptrShowGoogleStyleViewAnimationEnabled)) { mShowGoogleStyleViewAnimationEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrShowGoogleStyleViewAnimationEnabled, true); } if (a.hasValue(R.styleable.PullToRefresh_ptrHideRefeshableViewWhileRefreshingEnabled)) { mRefeshableViewHideWhileRefreshingEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrHideRefeshableViewWhileRefreshingEnabled, true); } if (a.hasValue(R.styleable.PullToRefresh_ptrViewRefeshableViewProgressBarOnCenterWhileRefreshingEnabled)) { mRefeshableViewRefreshingBarViewWhileRefreshingEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrViewRefeshableViewProgressBarOnCenterWhileRefreshingEnabled, true); } if (a.hasValue(R.styleable.PullToRefresh_ptrShowGoogleStyleViewAnimationDuration)) { mShowGoogleStyleViewAnimationDuration = a.getInteger(R.styleable.PullToRefresh_ptrShowGoogleStyleViewAnimationDuration, GOOGLE_STYLE_VIEW_APPEAREANCE_DURATION); } if (a.hasValue(R.styleable.PullToRefresh_ptrHideRefeshableViewWhileRefreshingDuration)) { mRefeshableViewHideWhileRefreshingDuration = a.getInteger(R.styleable.PullToRefresh_ptrHideRefeshableViewWhileRefreshingDuration, REFRESHABLE_VIEW_HIDE_WHILE_REFRESHING_DURATION); } if (a.hasValue(R.styleable.PullToRefresh_ptrViewRefeshableViewProgressBarOnCenterWhileRefreshingDuration)) { mRefeshableViewRefreshingBarViewWhileRefreshingDuration = a.getInteger(R.styleable.PullToRefresh_ptrViewRefeshableViewProgressBarOnCenterWhileRefreshingDuration, REFRESHABLEVIEW_REFRESHING_BAR_VIEW_WHILE_REFRESHING_DURATION); } /** * Styleables from XML */ if (a.hasValue(R.styleable.PullToRefresh_ptrRefreshableViewBackground)) { Drawable background = a.getDrawable(R.styleable.PullToRefresh_ptrRefreshableViewBackground); if (null != background) { mRefreshableView.setBackgroundDrawable(background); } } else if (a.hasValue(R.styleable.PullToRefresh_ptrAdapterViewBackground)) { Utils.warnDeprecation("ptrAdapterViewBackground", "ptrRefreshableViewBackground"); Drawable background = a.getDrawable(R.styleable.PullToRefresh_ptrAdapterViewBackground); if (null != background) { mRefreshableView.setBackgroundDrawable(background); } } if (a.hasValue(R.styleable.PullToRefresh_ptrOverScroll)) { mOverScrollEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrOverScroll, true); } if (a.hasValue(R.styleable.PullToRefresh_ptrScrollingWhileRefreshingEnabled)) { mScrollingWhileRefreshingEnabled = a.getBoolean( R.styleable.PullToRefresh_ptrScrollingWhileRefreshingEnabled, false); } // set scroll properties from attributes float friction = a.getFloat(R.styleable.PullToRefresh_ptrFriction, DEFAULT_FRICTION); int smoothScrollDuration = a.getInt(R.styleable.PullToRefresh_ptrSmoothScrollDuration, DEFAULT_SMOOTH_SCROLL_DURATION_MS); int smoothScrollLongDuration = a.getInt(R.styleable.PullToRefresh_ptrSmoothScrollLongDuration, DEFAULT_SMOOTH_SCROLL_LONG_DURATION_MS); setFriction(friction); setSmoothScrollDuration(smoothScrollDuration); setSmoothScrollLongDuration(smoothScrollLongDuration); // Let the derivative classes have a go at handling attributes, then // recycle them... handleStyledAttributes(a); a.recycle(); // Get action bar height and status bar height initActionBarSize(context); initStatusBarSize(context); // Finally update the UI for the modes updateUIForMode(); // updateUIForGoogleStyleMode() method will be called when onAttachedToWindow() event has been fired. } /** * Show google view layout and google progress layout when pulling */ private void showViewTopLayout() { if (mMode.showGoogleStyle() == false ) { return; } // Initialize Translate and Alpha animation if ( mShowGoogleStyleViewAnimationEnabled == true ) { AnimationSet set = new AnimationSet(true /* share interpolator */); set.setDuration(mShowGoogleStyleViewAnimationDuration); set.setFillAfter(true); set.setAnimationListener(new AnimationListener(){ @Override public void onAnimationEnd(Animation anim) { } @Override public void onAnimationRepeat(Animation anim) { } @Override public void onAnimationStart(Animation anim) { mTopActionbarLayout.setVisibility(View.VISIBLE); }}); TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,Animation.ABSOLUTE, 0, Animation.ABSOLUTE, -mActionBarHeight, Animation.ABSOLUTE, mStatusBarHeight); AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f); set.addAnimation(transAnimation); set.addAnimation(alphaAnimation); // Start animation mTopActionbarLayout.startAnimation(set); } else { // Show Google style view layout without animation ((FrameLayout.LayoutParams) mTopActionbarLayout.getLayoutParams()).topMargin = mStatusBarHeight; mTopActionbarLayout.setVisibility(View.VISIBLE); } } /** * Hide google view layout and google progress layout when releasing */ private void hideViewTopLayout() { if (mMode.showGoogleStyle() == false ) { return; } if ( mShowGoogleStyleViewAnimationEnabled == true ) { // Initialize Translate and Alpha animation AnimationSet set = new AnimationSet(true /* share interpolator */); set.setDuration(mShowGoogleStyleViewAnimationDuration); set.setFillAfter(true); set.setAnimationListener(new AnimationListener(){ @Override public void onAnimationEnd(Animation anim) { mTopActionbarLayout.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation anim) { } @Override public void onAnimationStart(Animation anim) { }}); TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,Animation.ABSOLUTE, 0, Animation.ABSOLUTE, mTopActionbarLayout.getTop(), Animation.ABSOLUTE, -mStatusBarHeight); AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f); set.addAnimation(transAnimation); set.addAnimation(alphaAnimation); // Start animation mTopActionbarLayout.startAnimation(set); } else { // Hide Google style view layout without animation ((FrameLayout.LayoutParams) mTopActionbarLayout.getLayoutParams()).topMargin = -mActionBarHeight; mTopActionbarLayout.setVisibility(View.INVISIBLE); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mWindowAttached = true; initTopViewGroup(); updateUIForGoogleStyleMode(); } /** * Initialize {@code mTopActionbarLayout} and add that into Top DecorView(this is the root view), * and initialize needed components */ private void initTopViewGroup() { if ( mMode.showGoogleStyle() == false ) { return; } View view = this.getRootView(); ViewGroup topViewGroup = null; Context context = getContext(); if (view instanceof ViewGroup == false) { Log.w(LOG_TAG, "Current root view is not ViewGroup type. Google Style Pull To Refresh mode will be disabled."); topViewGroup = new ViewGroup(context) { @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // do nothing }}; } else { topViewGroup = (ViewGroup) view; } // Initialize Top Layout Layout FrameLayout layout = new FrameLayout(context); @SuppressWarnings("deprecation") int matchParent = ViewGroup.LayoutParams.FILL_PARENT; ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(matchParent, mActionBarHeight); topViewGroup.addView(layout, params); layout.setVisibility(View.INVISIBLE); // Initialize refreshing bar on center if (mMode.showGoogleStyle()) { mRefreshableViewProgressBar = generateCircleProgressBar(context); // WARNING : There is a magic number! FrameLayout.LayoutParams barParams = new FrameLayout.LayoutParams(200, 200); barParams.gravity = Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL; mRefreshableViewProgressBar.setVisibility(View.INVISIBLE); mRefreshableViewWrapper.addView(mRefreshableViewProgressBar, -1, barParams); } // Finally assign mTopActionbarLayout = layout; } /** * Get an actionBar's size and save into a field * @param context */ private void initActionBarSize(Context context) { mActionBarHeight = Utils.getActionBarSize(context); } /** * Get an StatusBar's size and save into a field * @param context */ private void initStatusBarSize(Context context) { mStatusBarHeight = Utils.getStatusBarSize(context); } /** * Generate Progress bar UI Component on center * @param context * @return Generated ProgressBar instance */ private ProgressBar generateCircleProgressBar(Context context) { ProgressBar circleProgressBar = new ProgressBar(context); circleProgressBar.setScrollBarStyle(android.R.attr.progressBarStyle); circleProgressBar.setIndeterminate(true); return circleProgressBar; } private boolean isReadyForPull() { switch (mMode) { case PULL_FROM_START: case GOOGLE_STYLE: return isReadyForPullStart(); case PULL_FROM_END: return isReadyForPullEnd(); case BOTH: return isReadyForPullEnd() || isReadyForPullStart(); default: return false; } } /** * Actions a Pull Event * * @return true if the Event has been handled, false if there has been no * change */ private void pullEvent() { final int newScrollValue; final int itemDimension; final float initialMotionValue, lastMotionValue; switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: initialMotionValue = mInitialMotionX; lastMotionValue = mLastMotionX; break; case VERTICAL: default: initialMotionValue = mInitialMotionY; lastMotionValue = mLastMotionY; break; } switch (mCurrentMode) { case PULL_FROM_END: newScrollValue = Math.round(Math.max(initialMotionValue - lastMotionValue, 0) / mFriction); itemDimension = getFooterSize(); break; case GOOGLE_STYLE: newScrollValue = Math.round(Math.min(initialMotionValue - lastMotionValue, 0) / mFriction); itemDimension = getGoogleStyleViewSize(); break; case PULL_FROM_START: default: newScrollValue = Math.round(Math.min(initialMotionValue - lastMotionValue, 0) / mFriction); itemDimension = getHeaderSize(); break; } setHeaderScroll(newScrollValue); if (newScrollValue != 0 && !isRefreshing()) { float scale = Math.abs(newScrollValue) / (float) itemDimension; switch (mCurrentMode) { case PULL_FROM_END: mFooterLayout.onPull(scale); break; case GOOGLE_STYLE: mViewOnTopLoadingLayout.onPull(scale); break; case PULL_FROM_START: default: mHeaderLayout.onPull(scale); break; } if (mState != State.PULL_TO_REFRESH && itemDimension >= Math.abs(newScrollValue)) { setState(State.PULL_TO_REFRESH); } else if (mState == State.PULL_TO_REFRESH && itemDimension < Math.abs(newScrollValue)) { setState(State.RELEASE_TO_REFRESH); } } } @SuppressWarnings("deprecation") private LinearLayout.LayoutParams getLoadingLayoutLayoutParams() { switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT); case VERTICAL: default: return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); } } private int getMaximumPullScroll() { switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: return Math.round(getWidth() / mFriction); case VERTICAL: default: return Math.round(getHeight() / mFriction); } } /** * Smooth Scroll to position using the specific duration * * @param scrollValue - Position to scroll to * @param duration - Duration of animation in milliseconds */ private final void smoothScrollTo(int scrollValue, long duration) { smoothScrollTo(scrollValue, duration, 0, null); } private final void smoothScrollTo(int newScrollValue, long duration, long delayMillis, OnSmoothScrollFinishedListener listener) { if (null != mCurrentSmoothScrollRunnable) { mCurrentSmoothScrollRunnable.stop(); } final int oldScrollValue; switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: oldScrollValue = getScrollX(); break; case VERTICAL: default: oldScrollValue = getScrollY(); break; } if (oldScrollValue != newScrollValue) { if (null == mScrollAnimationInterpolator) { // Default interpolator is a Decelerate Interpolator mScrollAnimationInterpolator = new DecelerateInterpolator(); } mCurrentSmoothScrollRunnable = new SmoothScrollRunnable(oldScrollValue, newScrollValue, duration, listener); if (delayMillis > 0) { postDelayed(mCurrentSmoothScrollRunnable, delayMillis); } else { post(mCurrentSmoothScrollRunnable); } } else if ( listener != null ) { // Call listener immediately listener.onSmoothScrollFinished(); } } private final void smoothScrollToAndBack(int y) { smoothScrollTo(y, mSmoothScrollDurationMs, 0, new OnSmoothScrollFinishedListener() { @Override public void onSmoothScrollFinished() { smoothScrollTo(0, mSmoothScrollDurationMs, DEMO_SCROLL_INTERVAL, null); } }); } public static enum Mode { /** * Disable all Pull-to-Refresh gesture and Refreshing handling */ DISABLED(0x0), /** * Only allow the user to Pull from the start of the Refreshable View to * refresh. The start is either the Top or Left, depending on the * scrolling direction. */ PULL_FROM_START(0x1), /** * Only allow the user to Pull from the end of the Refreshable View to * refresh. The start is either the Bottom or Right, depending on the * scrolling direction. */ PULL_FROM_END(0x2), /** * Allow the user to both Pull from the start, from the end to refresh. */ BOTH(0x3), /** * Disables Pull-to-Refresh gesture handling, but allows manually * setting the Refresh state via * {@link PullToRefreshBase#setRefreshing() setRefreshing()}. */ MANUAL_REFRESH_ONLY(0x4), /** * Google style pull-to-refresh mode * */ GOOGLE_STYLE(0x5); /** * @deprecated Use {@link #PULL_FROM_START} from now on. */ public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START; /** * @deprecated Use {@link #PULL_FROM_END} from now on. */ public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END; /** * Maps an int to a specific mode. This is needed when saving state, or * inflating the view from XML where the mode is given through a attr * int. * * @param modeInt - int to map a Mode to * @return Mode that modeInt maps to, or PULL_FROM_START by default. */ static Mode mapIntToValue(final int modeInt) { for (Mode value : Mode.values()) { if (modeInt == value.getIntValue()) { return value; } } // If not, return default return getDefault(); } static Mode getDefault() { return PULL_FROM_START; } private int mIntValue; // The modeInt values need to match those from attrs.xml Mode(int modeInt) { mIntValue = modeInt; } /** * @return true if the mode permits Pull-to-Refresh */ boolean permitsPullToRefresh() { return !(this == DISABLED || this == MANUAL_REFRESH_ONLY); } /** * @return true if this mode wants the Loading Layout Header to be shown */ public boolean showHeaderLoadingLayout() { return this == PULL_FROM_START || this == BOTH; } /** * @return true if this mode wants the Loading Layout Footer to be shown */ public boolean showFooterLoadingLayout() { return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY; } /** * @return true if this mode wants the Loading Layout to be shown like Google style pull-to-refresh */ public boolean showGoogleStyle() { return this == GOOGLE_STYLE; } int getIntValue() { return mIntValue; } } // =========================================================== // Inner, Anonymous Classes, and Enumerations // =========================================================== /** * Simple Listener that allows you to be notified when the user has scrolled * to the end of the AdapterView. See ( * {@link PullToRefreshAdapterViewBase#setOnLastItemVisibleListener}. * * @author Chris Banes */ public static interface OnLastItemVisibleListener { /** * Called when the user has scrolled to the end of the list */ public void onLastItemVisible(); } /** * Listener that allows you to be notified when the user has started or * finished a touch event. Useful when you want to append extra UI events * (such as sounds). See ( * {@link PullToRefreshAdapterViewBase#setOnPullEventListener}. * * @author Chris Banes */ public static interface OnPullEventListener<V extends View> { /** * Called when the internal state has been changed, usually by the user * pulling. * * @param refreshView - View which has had it's state change. * @param state - The new state of View. * @param direction - One of {@link Mode#PULL_FROM_START} or * {@link Mode#PULL_FROM_END} depending on which direction * the user is pulling. Only useful when <var>state</var> is * {@link State#PULL_TO_REFRESH} or * {@link State#RELEASE_TO_REFRESH}. */ public void onPullEvent(final PullToRefreshBase<V> refreshView, State state, Mode direction); } /** * Simple Listener to listen for any callbacks to Refresh. * * @author Chris Banes */ public static interface OnRefreshListener<V extends View> { /** * onRefresh will be called for both a Pull from start, and Pull from * end */ public void onRefresh(final PullToRefreshBase<V> refreshView); } /** * An advanced version of the Listener to listen for callbacks to Refresh. * This listener is different as it allows you to differentiate between Pull * Ups, and Pull Downs. * * @author Chris Banes */ public static interface OnRefreshListener2<V extends View> { // TODO These methods need renaming to START/END rather than DOWN/UP /** * onPullDownToRefresh will be called only when the user has Pulled from * the start, and released. */ public void onPullDownToRefresh(final PullToRefreshBase<V> refreshView); /** * onPullUpToRefresh will be called only when the user has Pulled from * the end, and released. */ public void onPullUpToRefresh(final PullToRefreshBase<V> refreshView); } public static enum Orientation { VERTICAL, HORIZONTAL; } public static enum State { /** * When the UI is in a state which means that user is not interacting * with the Pull-to-Refresh function. */ RESET(0x0), /** * When the UI is being pulled by the user, but has not been pulled far * enough so that it refreshes when released. */ PULL_TO_REFRESH(0x1), /** * When the UI is being pulled by the user, and <strong>has</strong> * been pulled far enough so that it will refresh when released. */ RELEASE_TO_REFRESH(0x2), /** * When the UI is currently refreshing, caused by a pull gesture. */ REFRESHING(0x8), /** * When the UI is currently refreshing, caused by a call to * {@link PullToRefreshBase#setRefreshing() setRefreshing()}. */ MANUAL_REFRESHING(0x9), /** * When the UI is currently overscrolling, caused by a fling on the * Refreshable View. */ OVERSCROLLING(0x10); /** * Maps an int to a specific state. This is needed when saving state. * * @param stateInt - int to map a State to * @return State that stateInt maps to */ static State mapIntToValue(final int stateInt) { for (State value : State.values()) { if (stateInt == value.getIntValue()) { return value; } } // If not, return default return RESET; } private int mIntValue; State(int intValue) { mIntValue = intValue; } int getIntValue() { return mIntValue; } } final class SmoothScrollRunnable implements Runnable { private final Interpolator mInterpolator; private final int mScrollToY; private final int mScrollFromY; private final long mDuration; private OnSmoothScrollFinishedListener mListener; private boolean mContinueRunning = true; private long mStartTime = -1; private int mCurrentY = -1; public SmoothScrollRunnable(int fromY, int toY, long duration, OnSmoothScrollFinishedListener listener) { mScrollFromY = fromY; mScrollToY = toY; mInterpolator = mScrollAnimationInterpolator; mDuration = duration; mListener = listener; } @Override public void run() { /** * Only set mStartTime if this is the first time we're starting, * else actually calculate the Y delta */ if (mStartTime == -1) { mStartTime = System.currentTimeMillis(); } else { /** * We do do all calculations in long to reduce software float * calculations. We use 1000 as it gives us good accuracy and * small rounding errors */ long normalizedTime = (1000 * (System.currentTimeMillis() - mStartTime)) / mDuration; normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0); final int deltaY = Math.round((mScrollFromY - mScrollToY) * mInterpolator.getInterpolation(normalizedTime / 1000f)); mCurrentY = mScrollFromY - deltaY; setHeaderScroll(mCurrentY); } // If we're not at the target Y, keep going... if (mContinueRunning && mScrollToY != mCurrentY) { ViewCompat.postOnAnimation(PullToRefreshBase.this, this); } else { if (null != mListener) { mListener.onSmoothScrollFinished(); } } } public void stop() { mContinueRunning = false; removeCallbacks(this); } } static interface OnSmoothScrollFinishedListener { void onSmoothScrollFinished(); } }
library/src/main/java/com/handmark/pulltorefresh/library/PullToRefreshBase.java
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * Copyright 2013 Naver Business Platform Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.handmark.pulltorefresh.library; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.TranslateAnimation; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ProgressBar; import com.handmark.pulltorefresh.configuration.xml.PullToRefreshXmlConfiguration; import com.handmark.pulltorefresh.library.internal.LoadingLayout; import com.handmark.pulltorefresh.library.internal.Utils; import com.handmark.pulltorefresh.library.internal.ViewCompat; public abstract class PullToRefreshBase<T extends View> extends LinearLayout implements IPullToRefresh<T> { // =========================================================== // Constants // =========================================================== static final boolean DEBUG = false; static final boolean USE_HW_LAYERS = false; static final String LOG_TAG = "PullToRefresh"; public static final float DEFAULT_FRICTION = 2.0f; public static final int DEFAULT_SMOOTH_SCROLL_DURATION_MS = 200; public static final int DEFAULT_SMOOTH_SCROLL_LONG_DURATION_MS = 325; static final int DEMO_SCROLL_INTERVAL = 225; static final String STATE_STATE = "ptr_state"; static final String STATE_MODE = "ptr_mode"; static final String STATE_CURRENT_MODE = "ptr_current_mode"; static final String STATE_SCROLLING_REFRESHING_ENABLED = "ptr_disable_scrolling"; static final String STATE_SHOW_REFRESHING_VIEW = "ptr_show_refreshing_view"; static final String STATE_SUPER = "ptr_super"; static final int REFRESHABLEVIEW_REFRESHING_BAR_VIEW_WHILE_REFRESHING_DURATION = 100; static final int REFRESHABLE_VIEW_HIDE_WHILE_REFRESHING_DURATION = 500; static final int GOOGLE_STYLE_VIEW_APPEAREANCE_DURATION = 200; static final int LAYER_TYPE_HARDWARE = 2; static final int LAYER_TYPE_NONE = 0; // =========================================================== // Fields // =========================================================== private int mTouchSlop; private float mLastMotionX, mLastMotionY; private float mInitialMotionX, mInitialMotionY; // needed properties while scrolling private float mFriction; private int mSmoothScrollDurationMs = 200; private int mSmoothScrollLongDurationMs = 325; private boolean mIsBeingDragged = false; private State mState = State.RESET; private Mode mMode = Mode.getDefault(); private Mode mCurrentMode; T mRefreshableView; private FrameLayout mRefreshableViewWrapper; private boolean mShowViewWhileRefreshing = true; private boolean mScrollingWhileRefreshingEnabled = false; private boolean mFilterTouchEvents = true; private boolean mOverScrollEnabled = true; private boolean mLayoutVisibilityChangesEnabled = true; private Interpolator mScrollAnimationInterpolator; private Class<? extends LoadingLayout> mLoadingLayoutClazz = null; private LoadingLayout mHeaderLayout; private LoadingLayout mFooterLayout; private LoadingLayout mViewOnTopLoadingLayout; /** * Top DecorView for containing google style-ptr */ private FrameLayout mTopActionbarLayout; private boolean mWindowAttached = false; private ProgressBar mRefreshableViewProgressBar; private OnRefreshListener<T> mOnRefreshListener; private OnRefreshListener2<T> mOnRefreshListener2; private OnPullEventListener<T> mOnPullEventListener; private SmoothScrollRunnable mCurrentSmoothScrollRunnable; private int mStatusBarHeight; /** * Current actionbar size */ private int mActionBarHeight; /** * Flag whether {@link #onRefreshing(boolean)} has been called */ private boolean mRefreshing; /** * Flag whether Google style view layout appearance animation will be shown */ private boolean mShowGoogleStyleViewAnimationEnabled = true; /** * Duration of Google style view layout appearance animation */ private int mShowGoogleStyleViewAnimationDuration = GOOGLE_STYLE_VIEW_APPEAREANCE_DURATION; /** * Flag whether {@code mRefreshaleView} will be hidden while refreshing */ private boolean mRefeshableViewHideWhileRefreshingEnabled = true; /** * {@code mRefreshableView}'s fade-out Duration */ private int mRefeshableViewHideWhileRefreshingDuration = REFRESHABLE_VIEW_HIDE_WHILE_REFRESHING_DURATION; /** * Flag whether some {@code ProgressBar} will be shown while refreshing */ private boolean mRefeshableViewRefreshingBarViewWhileRefreshingEnabled = true; /** * {@code mRefreshableViewRefreshingBar}'s fade-in Duration */ private int mRefeshableViewRefreshingBarViewWhileRefreshingDuration = REFRESHABLEVIEW_REFRESHING_BAR_VIEW_WHILE_REFRESHING_DURATION; // =========================================================== // Constructors // =========================================================== public PullToRefreshBase(Context context) { super(context); init(context, null); } public PullToRefreshBase(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public PullToRefreshBase(Context context, Mode mode) { super(context); mMode = mode; init(context, null); } public PullToRefreshBase(Context context, Mode mode, Class<? extends LoadingLayout> loadingLayoutClazz) { super(context); mMode = mode; mLoadingLayoutClazz = loadingLayoutClazz; init(context, null); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (DEBUG) { Log.d(LOG_TAG, "addView: " + child.getClass().getSimpleName()); } final T refreshableView = getRefreshableView(); if (refreshableView instanceof ViewGroup) { ((ViewGroup) refreshableView).addView(child, index, params); } else { throw new UnsupportedOperationException("Refreshable View is not a ViewGroup so can't addView"); } } @Deprecated @Override public final boolean demo() { if (mMode.showHeaderLoadingLayout() && isReadyForPullStart()) { smoothScrollToAndBack(-getHeaderSize() * 2); return true; } else if (mMode.showFooterLoadingLayout() && isReadyForPullEnd()) { smoothScrollToAndBack(getFooterSize() * 2); return true; } return false; } @Override public final Mode getCurrentMode() { return mCurrentMode; } @Override public final boolean getFilterTouchEvents() { return mFilterTouchEvents; } @Override public final ILoadingLayout getLoadingLayoutProxy() { return getLoadingLayoutProxy(true, true); } @Override public final ILoadingLayout getLoadingLayoutProxy(boolean includeStart, boolean includeEnd) { return createLoadingLayoutProxy(includeStart, includeEnd); } @Override public final Mode getMode() { return mMode; } @Override public final T getRefreshableView() { return mRefreshableView; } @Override public final boolean getShowViewWhileRefreshing() { return mShowViewWhileRefreshing; } @Override public final State getState() { return mState; } /** * @deprecated See {@link #isScrollingWhileRefreshingEnabled()}. */ public final boolean isDisableScrollingWhileRefreshing() { return !isScrollingWhileRefreshingEnabled(); } @Override public final boolean isPullToRefreshEnabled() { return mMode.permitsPullToRefresh(); } @Override public final boolean isPullToRefreshOverScrollEnabled() { return VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD && mOverScrollEnabled && OverscrollHelper.isAndroidOverScrollEnabled(mRefreshableView); } @Override public final boolean isRefreshing() { return mState == State.REFRESHING || mState == State.MANUAL_REFRESHING; } @Override public final boolean isScrollingWhileRefreshingEnabled() { return mScrollingWhileRefreshingEnabled; } @Override public final boolean onInterceptTouchEvent(MotionEvent event) { if (!isPullToRefreshEnabled()) { return false; } final int action = event.getAction(); if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { mIsBeingDragged = false; return false; } if (action != MotionEvent.ACTION_DOWN && mIsBeingDragged) { return true; } switch (action) { case MotionEvent.ACTION_MOVE: { // If we're refreshing, and the flag is set. Eat all MOVE events if (!mScrollingWhileRefreshingEnabled && isRefreshing()) { return true; } if (isReadyForPull()) { final float y = event.getY(), x = event.getX(); final float diff, oppositeDiff, absDiff; // We need to use the correct values, based on scroll // direction switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: diff = x - mLastMotionX; oppositeDiff = y - mLastMotionY; break; case VERTICAL: default: diff = y - mLastMotionY; oppositeDiff = x - mLastMotionX; break; } absDiff = Math.abs(diff); if (absDiff > mTouchSlop && (!mFilterTouchEvents || absDiff > Math.abs(oppositeDiff))) { if ((mMode.showHeaderLoadingLayout() || mMode.showGoogleStyle()) && diff >= 1f && isReadyForPullStart()) { mLastMotionY = y; mLastMotionX = x; mIsBeingDragged = true; if (mMode == Mode.BOTH) { mCurrentMode = Mode.PULL_FROM_START; } } else if (mMode.showFooterLoadingLayout() && diff <= -1f && isReadyForPullEnd()) { mLastMotionY = y; mLastMotionX = x; mIsBeingDragged = true; if (mMode == Mode.BOTH) { mCurrentMode = Mode.PULL_FROM_END; } } } } break; } case MotionEvent.ACTION_DOWN: { if (isReadyForPull()) { mLastMotionY = mInitialMotionY = event.getY(); mLastMotionX = mInitialMotionX = event.getX(); mIsBeingDragged = false; } break; } } return mIsBeingDragged; } @Override public final void onRefreshComplete() { if (isRefreshing()) { setState(State.RESET); } } @Override public final boolean onTouchEvent(MotionEvent event) { if (!isPullToRefreshEnabled()) { return false; } // If we're refreshing, and the flag is set. Eat the event if (!mScrollingWhileRefreshingEnabled && isRefreshing()) { return true; } if (event.getAction() == MotionEvent.ACTION_DOWN && event.getEdgeFlags() != 0) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_MOVE: { if (mIsBeingDragged) { mLastMotionY = event.getY(); mLastMotionX = event.getX(); pullEvent(); return true; } break; } case MotionEvent.ACTION_DOWN: { if (isReadyForPull()) { mLastMotionY = mInitialMotionY = event.getY(); mLastMotionX = mInitialMotionX = event.getX(); return true; } break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { if (mIsBeingDragged) { mIsBeingDragged = false; if (mState == State.RELEASE_TO_REFRESH && (null != mOnRefreshListener || null != mOnRefreshListener2)) { setState(State.REFRESHING, true); return true; } // If we're already refreshing, just scroll back to the top if (isRefreshing()) { smoothScrollTo(0); return true; } // If we haven't returned by here, then we're not in a state // to pull, so just reset setState(State.RESET); return true; } break; } } return false; } /** * Set new friction * @param friction New friction value. Must be float. The default value is {@value #DEFAULT_FRICTION}. */ public final void setFriction(float friction) { this.mFriction = friction; } /** * Set new smooth scroll duration * @param smoothScrollDurationMs Milliseconds. The default value is {@value #DEFAULT_SMOOTH_SCROLL_DURATION_MS}. */ public final void setSmoothScrollDuration(int smoothScrollDurationMs) { this.mSmoothScrollDurationMs = smoothScrollDurationMs; } /** * Set new smooth scroll <b>longer</b> duration. <br /> This duration is only used by calling {@link #smoothScrollToLonger(int)}. * @param smoothScrollLongDurationMs Milliseconds. The default value is {@value #DEFAULT_SMOOTH_SCROLL_LONG_DURATION_MS}. */ public final void setSmoothScrollLongDuration(int smoothScrollLongDurationMs) { this.mSmoothScrollLongDurationMs = smoothScrollLongDurationMs; } /** * */ public final void setScrollingWhileRefreshingEnabled(boolean allowScrollingWhileRefreshing) { mScrollingWhileRefreshingEnabled = allowScrollingWhileRefreshing; } /** * @deprecated See {@link #setScrollingWhileRefreshingEnabled(boolean)} */ public void setDisableScrollingWhileRefreshing(boolean disableScrollingWhileRefreshing) { setScrollingWhileRefreshingEnabled(!disableScrollingWhileRefreshing); } @Override public final void setFilterTouchEvents(boolean filterEvents) { mFilterTouchEvents = filterEvents; } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setLastUpdatedLabel(CharSequence label) { getLoadingLayoutProxy().setLastUpdatedLabel(label); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setLoadingDrawable(Drawable drawable) { getLoadingLayoutProxy().setLoadingDrawable(drawable); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy(boolean, boolean)}. */ public void setLoadingDrawable(Drawable drawable, Mode mode) { getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setLoadingDrawable( drawable); } @Override public void setLongClickable(boolean longClickable) { getRefreshableView().setLongClickable(longClickable); } @Override public final void setMode(Mode mode) { if (mode != mMode) { if (DEBUG) { Log.d(LOG_TAG, "Setting mode to: " + mode); } mMode = mode; updateUIForMode(); updateUIForGoogleStyleMode(); } } public void setOnPullEventListener(OnPullEventListener<T> listener) { mOnPullEventListener = listener; } @Override public final void setOnRefreshListener(OnRefreshListener<T> listener) { mOnRefreshListener = listener; mOnRefreshListener2 = null; } @Override public final void setOnRefreshListener(OnRefreshListener2<T> listener) { mOnRefreshListener2 = listener; mOnRefreshListener = null; } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setPullLabel(CharSequence pullLabel) { getLoadingLayoutProxy().setPullLabel(pullLabel); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy(boolean, boolean)}. */ public void setPullLabel(CharSequence pullLabel, Mode mode) { getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setPullLabel(pullLabel); } /** * @param enable Whether Pull-To-Refresh should be used * @deprecated This simple calls setMode with an appropriate mode based on * the passed value. */ public final void setPullToRefreshEnabled(boolean enable) { setMode(enable ? Mode.getDefault() : Mode.DISABLED); } @Override public final void setPullToRefreshOverScrollEnabled(boolean enabled) { mOverScrollEnabled = enabled; } @Override public final void setRefreshing() { setRefreshing(true); } @Override public final void setRefreshing(boolean doScroll) { if (!isRefreshing()) { setState(State.MANUAL_REFRESHING, doScroll); } } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setRefreshingLabel(CharSequence refreshingLabel) { getLoadingLayoutProxy().setRefreshingLabel(refreshingLabel); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy(boolean, boolean)}. */ public void setRefreshingLabel(CharSequence refreshingLabel, Mode mode) { getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setRefreshingLabel( refreshingLabel); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy()}. */ public void setReleaseLabel(CharSequence releaseLabel) { setReleaseLabel(releaseLabel, Mode.BOTH); } /** * @deprecated You should now call this method on the result of * {@link #getLoadingLayoutProxy(boolean, boolean)}. */ public void setReleaseLabel(CharSequence releaseLabel, Mode mode) { getLoadingLayoutProxy(mode.showHeaderLoadingLayout(), mode.showFooterLoadingLayout()).setReleaseLabel( releaseLabel); } public void setScrollAnimationInterpolator(Interpolator interpolator) { mScrollAnimationInterpolator = interpolator; } @Override public final void setShowViewWhileRefreshing(boolean showView) { mShowViewWhileRefreshing = showView; } /** * @return Either {@link Orientation#VERTICAL} or * {@link Orientation#HORIZONTAL} depending on the scroll direction. */ public abstract Orientation getPullToRefreshScrollDirection(); /** * <p> * Wrap {@link #getPullToRefreshScrollDirection()} method <br /> * Other methods Use this method instead of {@link #getPullToRefreshScrollDirection()} method, because an orientation must be VERTICAL when mode is google style * </p> * @return Oreintation.VERTICAL if mMode.showGoogleStyle() is true,<br />Return value of {@link #getPullToRefreshScrollDirection()} method if else */ public final Orientation getFilteredPullToRefreshScrollDirection() { Orientation orientation = getPullToRefreshScrollDirection(); if (mMode.showGoogleStyle() ) { orientation = Orientation.VERTICAL; } return orientation; } final void setState(State state, final boolean... params) { mState = state; if (DEBUG) { Log.d(LOG_TAG, "State: " + mState.name()); } switch (mState) { case RESET: onReset(); break; case PULL_TO_REFRESH: onPullToRefresh(); break; case RELEASE_TO_REFRESH: onReleaseToRefresh(); break; case REFRESHING: case MANUAL_REFRESHING: onRefreshing(params[0]); break; case OVERSCROLLING: // NO-OP break; } // Call OnPullEventListener if (null != mOnPullEventListener) { mOnPullEventListener.onPullEvent(this, mState, mCurrentMode); } } /** * Used internally for adding view. Need because we override addView to * pass-through to the Refreshable View */ protected final void addViewInternal(View child, int index, ViewGroup.LayoutParams params) { super.addView(child, index, params); } /** * Used internally for adding view. Need because we override addView to * pass-through to the Refreshable View */ protected final void addViewInternal(View child, ViewGroup.LayoutParams params) { super.addView(child, -1, params); } /** * Create a new loading layout instance by using the class token {@link #mLoadingLayoutClazz} * @param context * @param mode * @param attrs * @return Loading layout instance which was created by using the class token {@link #mLoadingLayoutClazz} */ protected LoadingLayout createLoadingLayout(Context context, Mode mode, TypedArray attrs) { return LoadingLayoutFactory.createLoadingLayout(mLoadingLayoutClazz, context, mode, getFilteredPullToRefreshScrollDirection(), attrs); } /** * Used internally for {@link #getLoadingLayoutProxy(boolean, boolean)}. * Allows derivative classes to include any extra LoadingLayouts. */ protected LoadingLayoutProxy createLoadingLayoutProxy(final boolean includeStart, final boolean includeEnd) { LoadingLayoutProxy proxy = new LoadingLayoutProxy(); if (includeStart && mMode.showHeaderLoadingLayout()) { proxy.addLayout(mHeaderLayout); } if (includeEnd && mMode.showFooterLoadingLayout()) { proxy.addLayout(mFooterLayout); } return proxy; } /** * This is implemented by derived classes to return the created View. If you * need to use a custom View (such as a custom ListView), override this * method and return an instance of your custom class. * <p/> * Be sure to set the ID of the view in this method, especially if you're * using a ListActivity or ListFragment. * * @param context Context to create view with * @param attrs AttributeSet from wrapped class. Means that anything you * include in the XML layout declaration will be routed to the * created View * @return New instance of the Refreshable View */ protected abstract T createRefreshableView(Context context, AttributeSet attrs); protected final void disableLoadingLayoutVisibilityChanges() { mLayoutVisibilityChangesEnabled = false; } protected final LoadingLayout getFooterLayout() { return mFooterLayout; } protected final int getFooterSize() { return mFooterLayout.getContentSize(); } protected final LoadingLayout getHeaderLayout() { return mHeaderLayout; } protected final int getHeaderSize() { return mHeaderLayout.getContentSize(); } protected final int getGoogleStyleViewSize() { return mViewOnTopLoadingLayout.getContentSize(); } protected int getPullToRefreshScrollDuration() { return mSmoothScrollDurationMs; } protected int getPullToRefreshScrollDurationLonger() { return mSmoothScrollLongDurationMs; } protected FrameLayout getRefreshableViewWrapper() { return mRefreshableViewWrapper; } /** * Allows Derivative classes to handle the XML Attrs without creating a * TypedArray themsevles * * @param a - TypedArray of PullToRefresh Attributes */ protected void handleStyledAttributes(TypedArray a) { } /** * Implemented by derived class to return whether the View is in a state * where the user can Pull to Refresh by scrolling from the end. * * @return true if the View is currently in the correct state (for example, * bottom of a ListView) */ protected abstract boolean isReadyForPullEnd(); /** * Implemented by derived class to return whether the View is in a state * where the user can Pull to Refresh by scrolling from the start. * * @return true if the View is currently the correct state (for example, top * of a ListView) */ protected abstract boolean isReadyForPullStart(); /** * Called by {@link #onRestoreInstanceState(Parcelable)} so that derivative * classes can handle their saved instance state. * * @param savedInstanceState - Bundle which contains saved instance state. */ protected void onPtrRestoreInstanceState(Bundle savedInstanceState) { } /** * Called by {@link #onSaveInstanceState()} so that derivative classes can * save their instance state. * * @param saveState - Bundle to be updated with saved state. */ protected void onPtrSaveInstanceState(Bundle saveState) { } /** * Called when the UI has been to be updated to be in the * {@link State#PULL_TO_REFRESH} state. */ protected void onPullToRefresh() { switch (mCurrentMode) { case PULL_FROM_END: mFooterLayout.pullToRefresh(); break; case GOOGLE_STYLE: showViewTopLayout(); mViewOnTopLoadingLayout.pullToRefresh(); break; case PULL_FROM_START: mHeaderLayout.pullToRefresh(); break; default: // NO-OP break; } } /** * Called when the UI has been to be updated to be in the * {@link State#REFRESHING} or {@link State#MANUAL_REFRESHING} state. * * @param doScroll - Whether the UI should scroll for this event. */ protected void onRefreshing(final boolean doScroll) { // Set the flag as below for fade-in animation of mRefreshableView when releasing mRefreshing = true; if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.refreshing(); } if (mMode.showFooterLoadingLayout()) { mFooterLayout.refreshing(); } if (mMode.showGoogleStyle()) { // Fade-out mRefreshableView AlphaAnimator.fadeout(mRefreshableView, 500); // Fade-in refreshing bar on center mRefreshableViewProgressBar.setVisibility(View.VISIBLE); AlphaAnimator.fadein(mRefreshableViewProgressBar, 200); mViewOnTopLoadingLayout.refreshing(); } if (doScroll) { if (mShowViewWhileRefreshing) { // Call Refresh Listener when the Scroll has finished OnSmoothScrollFinishedListener listener = new OnSmoothScrollFinishedListener() { @Override public void onSmoothScrollFinished() { callRefreshListener(); } }; switch (mCurrentMode) { case MANUAL_REFRESH_ONLY: case PULL_FROM_END: smoothScrollTo(getFooterSize(), listener); break; default: case PULL_FROM_START: smoothScrollTo(-getHeaderSize(), listener); break; } } else { smoothScrollTo(0); } } else { // We're not scrolling, so just call Refresh Listener now callRefreshListener(); } } /** * Called when the UI has been to be updated to be in the * {@link State#RELEASE_TO_REFRESH} state. */ protected void onReleaseToRefresh() { switch (mCurrentMode) { case PULL_FROM_END: mFooterLayout.releaseToRefresh(); break; case GOOGLE_STYLE: mViewOnTopLoadingLayout.releaseToRefresh(); break; case PULL_FROM_START: mHeaderLayout.releaseToRefresh(); break; default: // NO-OP break; } } /** * Called when the UI has been to be updated to be in the * {@link State#RESET} state. */ protected void onReset() { mIsBeingDragged = false; mLayoutVisibilityChangesEnabled = true; // Always reset both layouts, just in case... mHeaderLayout.reset(); mFooterLayout.reset(); if (mMode.showGoogleStyle()) { mViewOnTopLoadingLayout.reset(); hideViewTopLayout(); // Fade-in mRefreshableView if ( mRefreshing == true ) { mRefreshableView.clearAnimation(); AlphaAnimator.fadein(mRefreshableView, 500); } // Fade-out refreshing bar on center AlphaAnimator.fadeout(mRefreshableViewProgressBar, 200, new AnimationListener(){ @Override public void onAnimationEnd(Animation animation) { mRefreshableViewProgressBar.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation animation) { // do nothing } @Override public void onAnimationStart(Animation animation) { // do nothing }}); } mRefreshing = false; smoothScrollTo(0); } @Override protected final void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle) state; setMode(Mode.mapIntToValue(bundle.getInt(STATE_MODE, 0))); mCurrentMode = Mode.mapIntToValue(bundle.getInt(STATE_CURRENT_MODE, 0)); mScrollingWhileRefreshingEnabled = bundle.getBoolean(STATE_SCROLLING_REFRESHING_ENABLED, false); mShowViewWhileRefreshing = bundle.getBoolean(STATE_SHOW_REFRESHING_VIEW, true); // Let super Restore Itself super.onRestoreInstanceState(bundle.getParcelable(STATE_SUPER)); State viewState = State.mapIntToValue(bundle.getInt(STATE_STATE, 0)); if (viewState == State.REFRESHING || viewState == State.MANUAL_REFRESHING) { setState(viewState, true); } // Now let derivative classes restore their state onPtrRestoreInstanceState(bundle); return; } super.onRestoreInstanceState(state); } @Override protected final Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); // Let derivative classes get a chance to save state first, that way we // can make sure they don't overrite any of our values onPtrSaveInstanceState(bundle); bundle.putInt(STATE_STATE, mState.getIntValue()); bundle.putInt(STATE_MODE, mMode.getIntValue()); bundle.putInt(STATE_CURRENT_MODE, mCurrentMode.getIntValue()); bundle.putBoolean(STATE_SCROLLING_REFRESHING_ENABLED, mScrollingWhileRefreshingEnabled); bundle.putBoolean(STATE_SHOW_REFRESHING_VIEW, mShowViewWhileRefreshing); bundle.putParcelable(STATE_SUPER, super.onSaveInstanceState()); return bundle; } @Override protected final void onSizeChanged(int w, int h, int oldw, int oldh) { if (DEBUG) { Log.d(LOG_TAG, String.format("onSizeChanged. W: %d, H: %d", w, h)); } super.onSizeChanged(w, h, oldw, oldh); // We need to update the header/footer when our size changes refreshLoadingViewsSize(); // Update the Refreshable View layout refreshRefreshableViewSize(w, h); /** * As we're currently in a Layout Pass, we need to schedule another one * to layout any changes we've made here */ post(new Runnable() { @Override public void run() { requestLayout(); } }); } /** * Re-measure the Loading Views height, and adjust internal padding as * necessary */ protected final void refreshLoadingViewsSize() { final int maximumPullScroll = (int) (getMaximumPullScroll() * 1.2f); int pLeft = getPaddingLeft(); int pTop = getPaddingTop(); int pRight = getPaddingRight(); int pBottom = getPaddingBottom(); switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.setWidth(maximumPullScroll); pLeft = -maximumPullScroll; } else { pLeft = 0; } if (mMode.showFooterLoadingLayout()) { mFooterLayout.setWidth(maximumPullScroll); pRight = -maximumPullScroll; } else { pRight = 0; } break; case VERTICAL: if (mMode.showHeaderLoadingLayout()) { mHeaderLayout.setHeight(maximumPullScroll); pTop = -maximumPullScroll; } else if (mMode.showGoogleStyle() && mWindowAttached == true ) { // WARNING : There is a magic number! mViewOnTopLoadingLayout.setHeight(96 * 2); pTop = 0; } else { pTop = 0; } if (mMode.showFooterLoadingLayout()) { mFooterLayout.setHeight(maximumPullScroll); pBottom = -maximumPullScroll; } else { pBottom = 0; } break; } if (DEBUG) { Log.d(LOG_TAG, String.format("Setting Padding. L: %d, T: %d, R: %d, B: %d", pLeft, pTop, pRight, pBottom)); } setPadding(pLeft, pTop, pRight, pBottom); } protected final void refreshRefreshableViewSize(int width, int height) { // We need to set the Height of the Refreshable View to the same as // this layout LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mRefreshableViewWrapper.getLayoutParams(); switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: if (lp.width != width) { lp.width = width; mRefreshableViewWrapper.requestLayout(); } break; case VERTICAL: if (lp.height != height) { lp.height = height; mRefreshableViewWrapper.requestLayout(); } break; } } /** * Helper method which just calls scrollTo() in the correct scrolling * direction. * * @param value - New Scroll value */ protected final void setHeaderScroll(int value) { if (DEBUG) { Log.d(LOG_TAG, "setHeaderScroll: " + value); } // Clamp value to with pull scroll range final int maximumPullScroll = getMaximumPullScroll(); value = Math.min(maximumPullScroll, Math.max(-maximumPullScroll, value)); if (mLayoutVisibilityChangesEnabled) { if (value < 0) { switch (mCurrentMode) { case GOOGLE_STYLE: mViewOnTopLoadingLayout.setVisibility(View.VISIBLE); break; default: case PULL_FROM_START: mHeaderLayout.setVisibility(View.VISIBLE); break; } } else if (value > 0) { mFooterLayout.setVisibility(View.VISIBLE); } else { mHeaderLayout.setVisibility(View.INVISIBLE); mFooterLayout.setVisibility(View.INVISIBLE); } } if (USE_HW_LAYERS) { /** * Use a Hardware Layer on the Refreshable View if we've scrolled at * all. We don't use them on the Header/Footer Views as they change * often, which would negate any HW layer performance boost. */ ViewCompat.setLayerType(mRefreshableViewWrapper, value != 0 ? LAYER_TYPE_HARDWARE : LAYER_TYPE_NONE /* View.LAYER_TYPE_NONE */); } // skip ScrollTo(...) if (mMode.showGoogleStyle() ) { return; } switch (getFilteredPullToRefreshScrollDirection()) { case VERTICAL: scrollTo(0, value); break; case HORIZONTAL: scrollTo(value, 0); break; } } /** * Smooth Scroll to position using the duration of * {@link #mSmoothScrollDurationMs} ms. * * @param scrollValue - Position to scroll to */ protected final void smoothScrollTo(int scrollValue) { smoothScrollTo(scrollValue, getPullToRefreshScrollDuration()); } /** * Smooth Scroll to position using the the duration of * {@link #mSmoothScrollDurationMs} ms. * * @param scrollValue - Position to scroll to * @param listener - Listener for scroll */ protected final void smoothScrollTo(int scrollValue, OnSmoothScrollFinishedListener listener) { smoothScrollTo(scrollValue, getPullToRefreshScrollDuration(), 0, listener); } /** * Smooth Scroll to position using the longer the duration of * {@link #mSmoothScrollLongDurationMs} ms. * * @param scrollValue - Position to scroll to */ protected final void smoothScrollToLonger(int scrollValue) { smoothScrollTo(scrollValue, getPullToRefreshScrollDurationLonger()); } /** * Updates the View State when the mode has been set. This does not do any * checking that the mode is different to current state so always updates. */ protected void updateUIForMode() { // We need to use the correct LayoutParam values, based on scroll // direction final LinearLayout.LayoutParams lp = getLoadingLayoutLayoutParams(); // Remove Header, and then add Header Loading View again if needed if (this == mHeaderLayout.getParent()) { removeView(mHeaderLayout); } if (mMode.showHeaderLoadingLayout()) { addViewInternal(mHeaderLayout, 0, lp); } // Remove Footer, and then add Footer Loading View again if needed if (this == mFooterLayout.getParent()) { removeView(mFooterLayout); } if (mMode.showFooterLoadingLayout()) { addViewInternal(mFooterLayout, lp); } // Hide Loading Views refreshLoadingViewsSize(); // If we're not using Mode.BOTH, set mCurrentMode to mMode, otherwise // set it to pull down mCurrentMode = (mMode != Mode.BOTH) ? mMode : Mode.PULL_FROM_START; } protected void updateUIForGoogleStyleMode() { if ( mWindowAttached == false ) { return; } if ( mMode.showGoogleStyle() == false ) { return; } // We need to use the correct LayoutParam values, based on scroll // direction @SuppressWarnings("deprecation") final FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, mActionBarHeight); lp.gravity = Gravity.CENTER; // if ( mTopActionbarLayout == mViewOnTopLoadingLayout.getParent()) { mTopActionbarLayout.removeView(mViewOnTopLoadingLayout); } if (mMode.showGoogleStyle()) { Log.d(LOG_TAG, "mViewOnTopLayout has been added." + mViewOnTopLoadingLayout); mTopActionbarLayout.addView(mViewOnTopLoadingLayout, lp); mViewOnTopLoadingLayout.setVisibility(View.VISIBLE); } // Hide Loading Views refreshLoadingViewsSize(); // If we're not using Mode.BOTH, set mCurrentMode to mMode, otherwise // set it to pull down mCurrentMode = (mMode != Mode.BOTH) ? mMode : Mode.PULL_FROM_START; } private void addRefreshableView(Context context, T refreshableView) { mRefreshableViewWrapper = new FrameLayout(context); mRefreshableViewWrapper.addView(refreshableView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); addViewInternal(mRefreshableViewWrapper, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } private void callRefreshListener() { if (null != mOnRefreshListener) { mOnRefreshListener.onRefresh(this); } else if (null != mOnRefreshListener2) { if (mCurrentMode == Mode.PULL_FROM_START || mCurrentMode == Mode.GOOGLE_STYLE) { mOnRefreshListener2.onPullDownToRefresh(this); } else if (mCurrentMode == Mode.PULL_FROM_END) { mOnRefreshListener2.onPullUpToRefresh(this); } } } @SuppressWarnings("deprecation") private void init(Context context, AttributeSet attrs) { // PullToRefreshXmlConfiguration must be initialized. PullToRefreshXmlConfiguration.getInstance().init(context); /** * start initialization */ // Styleables from XML // Getting mMode is first, because It uses mMode in getFilteredPullToRefreshScrollDirection() TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh); if (a.hasValue(R.styleable.PullToRefresh_ptrMode)) { mMode = Mode.mapIntToValue(a.getInteger(R.styleable.PullToRefresh_ptrMode, 0)); } switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: setOrientation(LinearLayout.HORIZONTAL); break; case VERTICAL: default: setOrientation(LinearLayout.VERTICAL); break; } ViewConfiguration config = ViewConfiguration.get(context); mTouchSlop = config.getScaledTouchSlop(); // Default value of PTR View's gravity is center. So let the value be set center when the gravity is not set yet in XML. if (!Utils.existAttributeIntValue(attrs, "gravity")) { setGravity(Gravity.CENTER); } // Get a loading layout class token String loadingLayoutCode = null; if (a.hasValue(R.styleable.PullToRefresh_ptrAnimationStyle)) { loadingLayoutCode = a.getString(R.styleable.PullToRefresh_ptrAnimationStyle); } mLoadingLayoutClazz = LoadingLayoutFactory.createLoadingLayoutClazzByLayoutCode(loadingLayoutCode); // Refreshable View // By passing the attrs, we can add ListView/GridView params via XML mRefreshableView = createRefreshableView(context, attrs); addRefreshableView(context, mRefreshableView); // We need to create now layouts now mHeaderLayout = createLoadingLayout(context, Mode.PULL_FROM_START, a); mFooterLayout = createLoadingLayout(context, Mode.PULL_FROM_END, a); mViewOnTopLoadingLayout = createLoadingLayout(context, Mode.PULL_FROM_START, a); // Get animation options for Google style mode if (a.hasValue(R.styleable.PullToRefresh_ptrShowGoogleStyleViewAnimationEnabled)) { mShowGoogleStyleViewAnimationEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrShowGoogleStyleViewAnimationEnabled, true); } if (a.hasValue(R.styleable.PullToRefresh_ptrHideRefeshableViewWhileRefreshingEnabled)) { mRefeshableViewHideWhileRefreshingEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrHideRefeshableViewWhileRefreshingEnabled, true); } if (a.hasValue(R.styleable.PullToRefresh_ptrViewRefeshableViewProgressBarOnCenterWhileRefreshingEnabled)) { mRefeshableViewRefreshingBarViewWhileRefreshingEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrViewRefeshableViewProgressBarOnCenterWhileRefreshingEnabled, true); } if (a.hasValue(R.styleable.PullToRefresh_ptrShowGoogleStyleViewAnimationDuration)) { mShowGoogleStyleViewAnimationDuration = a.getInteger(R.styleable.PullToRefresh_ptrShowGoogleStyleViewAnimationDuration, GOOGLE_STYLE_VIEW_APPEAREANCE_DURATION); } if (a.hasValue(R.styleable.PullToRefresh_ptrHideRefeshableViewWhileRefreshingDuration)) { mRefeshableViewHideWhileRefreshingDuration = a.getInteger(R.styleable.PullToRefresh_ptrHideRefeshableViewWhileRefreshingDuration, REFRESHABLE_VIEW_HIDE_WHILE_REFRESHING_DURATION); } if (a.hasValue(R.styleable.PullToRefresh_ptrViewRefeshableViewProgressBarOnCenterWhileRefreshingDuration)) { mRefeshableViewRefreshingBarViewWhileRefreshingDuration = a.getInteger(R.styleable.PullToRefresh_ptrViewRefeshableViewProgressBarOnCenterWhileRefreshingDuration, REFRESHABLEVIEW_REFRESHING_BAR_VIEW_WHILE_REFRESHING_DURATION); } /** * Styleables from XML */ if (a.hasValue(R.styleable.PullToRefresh_ptrRefreshableViewBackground)) { Drawable background = a.getDrawable(R.styleable.PullToRefresh_ptrRefreshableViewBackground); if (null != background) { mRefreshableView.setBackgroundDrawable(background); } } else if (a.hasValue(R.styleable.PullToRefresh_ptrAdapterViewBackground)) { Utils.warnDeprecation("ptrAdapterViewBackground", "ptrRefreshableViewBackground"); Drawable background = a.getDrawable(R.styleable.PullToRefresh_ptrAdapterViewBackground); if (null != background) { mRefreshableView.setBackgroundDrawable(background); } } if (a.hasValue(R.styleable.PullToRefresh_ptrOverScroll)) { mOverScrollEnabled = a.getBoolean(R.styleable.PullToRefresh_ptrOverScroll, true); } if (a.hasValue(R.styleable.PullToRefresh_ptrScrollingWhileRefreshingEnabled)) { mScrollingWhileRefreshingEnabled = a.getBoolean( R.styleable.PullToRefresh_ptrScrollingWhileRefreshingEnabled, false); } // set scroll properties from attributes float friction = a.getFloat(R.styleable.PullToRefresh_ptrFriction, DEFAULT_FRICTION); int smoothScrollDuration = a.getInt(R.styleable.PullToRefresh_ptrSmoothScrollDuration, DEFAULT_SMOOTH_SCROLL_DURATION_MS); int smoothScrollLongDuration = a.getInt(R.styleable.PullToRefresh_ptrSmoothScrollLongDuration, DEFAULT_SMOOTH_SCROLL_LONG_DURATION_MS); setFriction(friction); setSmoothScrollDuration(smoothScrollDuration); setSmoothScrollLongDuration(smoothScrollLongDuration); // Let the derivative classes have a go at handling attributes, then // recycle them... handleStyledAttributes(a); a.recycle(); // Get action bar height and status bar height initActionBarSize(context); initStatusBarSize(context); // Finally update the UI for the modes updateUIForMode(); // updateUIForGoogleStyleMode() method will be called when onAttachedToWindow() event has been fired. } /** * Show google view layout and google progress layout when pulling */ private void showViewTopLayout() { if (mMode.showGoogleStyle() == false ) { return; } // Initialize Translate and Alpha animation AnimationSet set = new AnimationSet(true /* share interpolator */); set.setDuration(100); set.setFillAfter(true); set.setAnimationListener(new AnimationListener(){ @Override public void onAnimationEnd(Animation anim) { } @Override public void onAnimationRepeat(Animation anim) { } @Override public void onAnimationStart(Animation anim) { mTopActionbarLayout.setVisibility(View.VISIBLE); }}); TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,Animation.ABSOLUTE, 0, Animation.ABSOLUTE, -mActionBarHeight, Animation.ABSOLUTE, mStatusBarHeight); AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f); set.addAnimation(transAnimation); set.addAnimation(alphaAnimation); // Start animation mTopActionbarLayout.startAnimation(set); } /** * Hide google view layout and google progress layout when releasing */ private void hideViewTopLayout() { if (mMode.showGoogleStyle() == false ) { return; } // Initialize Translate and Alpha animation AnimationSet set = new AnimationSet(true /* share interpolator */); set.setDuration(100); set.setFillAfter(true); set.setAnimationListener(new AnimationListener(){ @Override public void onAnimationEnd(Animation anim) { mTopActionbarLayout.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation anim) { } @Override public void onAnimationStart(Animation anim) { }}); TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,Animation.ABSOLUTE, 0, Animation.ABSOLUTE, mTopActionbarLayout.getTop(), Animation.ABSOLUTE, -mStatusBarHeight); AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f); set.addAnimation(transAnimation); set.addAnimation(alphaAnimation); // Start animation mTopActionbarLayout.startAnimation(set); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mWindowAttached = true; initTopViewGroup(); updateUIForGoogleStyleMode(); } /** * Initialize {@code mTopActionbarLayout} and add that into Top DecorView(this is the root view), * and initialize needed components */ private void initTopViewGroup() { if ( mMode.showGoogleStyle() == false ) { return; } View view = this.getRootView(); ViewGroup topViewGroup = null; Context context = getContext(); if (view instanceof ViewGroup == false) { Log.w(LOG_TAG, "Current root view is not ViewGroup type. Google Style Pull To Refresh mode will be disabled."); topViewGroup = new ViewGroup(context) { @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // do nothing }}; } else { topViewGroup = (ViewGroup) view; } // Initialize Top Layout Layout FrameLayout layout = new FrameLayout(context); @SuppressWarnings("deprecation") int matchParent = ViewGroup.LayoutParams.FILL_PARENT; ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(matchParent, mActionBarHeight); topViewGroup.addView(layout, params); layout.setVisibility(View.INVISIBLE); // Initialize refreshing bar on center if (mMode.showGoogleStyle()) { mRefreshableViewProgressBar = generateCircleProgressBar(context); // WARNING : There is a magic number! FrameLayout.LayoutParams barParams = new FrameLayout.LayoutParams(200, 200); barParams.gravity = Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL; mRefreshableViewProgressBar.setVisibility(View.INVISIBLE); mRefreshableViewWrapper.addView(mRefreshableViewProgressBar, -1, barParams); } // Finally assign mTopActionbarLayout = layout; } /** * Get an actionBar's size and save into a field * @param context */ private void initActionBarSize(Context context) { mActionBarHeight = Utils.getActionBarSize(context); } /** * Get an StatusBar's size and save into a field * @param context */ private void initStatusBarSize(Context context) { mStatusBarHeight = Utils.getStatusBarSize(context); } /** * Generate Progress bar UI Component on center * @param context * @return Generated ProgressBar instance */ private ProgressBar generateCircleProgressBar(Context context) { ProgressBar circleProgressBar = new ProgressBar(context); circleProgressBar.setScrollBarStyle(android.R.attr.progressBarStyle); circleProgressBar.setIndeterminate(true); return circleProgressBar; } private boolean isReadyForPull() { switch (mMode) { case PULL_FROM_START: case GOOGLE_STYLE: return isReadyForPullStart(); case PULL_FROM_END: return isReadyForPullEnd(); case BOTH: return isReadyForPullEnd() || isReadyForPullStart(); default: return false; } } /** * Actions a Pull Event * * @return true if the Event has been handled, false if there has been no * change */ private void pullEvent() { final int newScrollValue; final int itemDimension; final float initialMotionValue, lastMotionValue; switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: initialMotionValue = mInitialMotionX; lastMotionValue = mLastMotionX; break; case VERTICAL: default: initialMotionValue = mInitialMotionY; lastMotionValue = mLastMotionY; break; } switch (mCurrentMode) { case PULL_FROM_END: newScrollValue = Math.round(Math.max(initialMotionValue - lastMotionValue, 0) / mFriction); itemDimension = getFooterSize(); break; case GOOGLE_STYLE: newScrollValue = Math.round(Math.min(initialMotionValue - lastMotionValue, 0) / mFriction); itemDimension = getGoogleStyleViewSize(); break; case PULL_FROM_START: default: newScrollValue = Math.round(Math.min(initialMotionValue - lastMotionValue, 0) / mFriction); itemDimension = getHeaderSize(); break; } setHeaderScroll(newScrollValue); if (newScrollValue != 0 && !isRefreshing()) { float scale = Math.abs(newScrollValue) / (float) itemDimension; switch (mCurrentMode) { case PULL_FROM_END: mFooterLayout.onPull(scale); break; case GOOGLE_STYLE: mViewOnTopLoadingLayout.onPull(scale); break; case PULL_FROM_START: default: mHeaderLayout.onPull(scale); break; } if (mState != State.PULL_TO_REFRESH && itemDimension >= Math.abs(newScrollValue)) { setState(State.PULL_TO_REFRESH); } else if (mState == State.PULL_TO_REFRESH && itemDimension < Math.abs(newScrollValue)) { setState(State.RELEASE_TO_REFRESH); } } } @SuppressWarnings("deprecation") private LinearLayout.LayoutParams getLoadingLayoutLayoutParams() { switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT); case VERTICAL: default: return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); } } private int getMaximumPullScroll() { switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: return Math.round(getWidth() / mFriction); case VERTICAL: default: return Math.round(getHeight() / mFriction); } } /** * Smooth Scroll to position using the specific duration * * @param scrollValue - Position to scroll to * @param duration - Duration of animation in milliseconds */ private final void smoothScrollTo(int scrollValue, long duration) { smoothScrollTo(scrollValue, duration, 0, null); } private final void smoothScrollTo(int newScrollValue, long duration, long delayMillis, OnSmoothScrollFinishedListener listener) { if (null != mCurrentSmoothScrollRunnable) { mCurrentSmoothScrollRunnable.stop(); } final int oldScrollValue; switch (getFilteredPullToRefreshScrollDirection()) { case HORIZONTAL: oldScrollValue = getScrollX(); break; case VERTICAL: default: oldScrollValue = getScrollY(); break; } if (oldScrollValue != newScrollValue) { if (null == mScrollAnimationInterpolator) { // Default interpolator is a Decelerate Interpolator mScrollAnimationInterpolator = new DecelerateInterpolator(); } mCurrentSmoothScrollRunnable = new SmoothScrollRunnable(oldScrollValue, newScrollValue, duration, listener); if (delayMillis > 0) { postDelayed(mCurrentSmoothScrollRunnable, delayMillis); } else { post(mCurrentSmoothScrollRunnable); } } else if ( listener != null ) { // Call listener immediately listener.onSmoothScrollFinished(); } } private final void smoothScrollToAndBack(int y) { smoothScrollTo(y, mSmoothScrollDurationMs, 0, new OnSmoothScrollFinishedListener() { @Override public void onSmoothScrollFinished() { smoothScrollTo(0, mSmoothScrollDurationMs, DEMO_SCROLL_INTERVAL, null); } }); } public static enum Mode { /** * Disable all Pull-to-Refresh gesture and Refreshing handling */ DISABLED(0x0), /** * Only allow the user to Pull from the start of the Refreshable View to * refresh. The start is either the Top or Left, depending on the * scrolling direction. */ PULL_FROM_START(0x1), /** * Only allow the user to Pull from the end of the Refreshable View to * refresh. The start is either the Bottom or Right, depending on the * scrolling direction. */ PULL_FROM_END(0x2), /** * Allow the user to both Pull from the start, from the end to refresh. */ BOTH(0x3), /** * Disables Pull-to-Refresh gesture handling, but allows manually * setting the Refresh state via * {@link PullToRefreshBase#setRefreshing() setRefreshing()}. */ MANUAL_REFRESH_ONLY(0x4), /** * Google style pull-to-refresh mode * */ GOOGLE_STYLE(0x5); /** * @deprecated Use {@link #PULL_FROM_START} from now on. */ public static Mode PULL_DOWN_TO_REFRESH = Mode.PULL_FROM_START; /** * @deprecated Use {@link #PULL_FROM_END} from now on. */ public static Mode PULL_UP_TO_REFRESH = Mode.PULL_FROM_END; /** * Maps an int to a specific mode. This is needed when saving state, or * inflating the view from XML where the mode is given through a attr * int. * * @param modeInt - int to map a Mode to * @return Mode that modeInt maps to, or PULL_FROM_START by default. */ static Mode mapIntToValue(final int modeInt) { for (Mode value : Mode.values()) { if (modeInt == value.getIntValue()) { return value; } } // If not, return default return getDefault(); } static Mode getDefault() { return PULL_FROM_START; } private int mIntValue; // The modeInt values need to match those from attrs.xml Mode(int modeInt) { mIntValue = modeInt; } /** * @return true if the mode permits Pull-to-Refresh */ boolean permitsPullToRefresh() { return !(this == DISABLED || this == MANUAL_REFRESH_ONLY); } /** * @return true if this mode wants the Loading Layout Header to be shown */ public boolean showHeaderLoadingLayout() { return this == PULL_FROM_START || this == BOTH; } /** * @return true if this mode wants the Loading Layout Footer to be shown */ public boolean showFooterLoadingLayout() { return this == PULL_FROM_END || this == BOTH || this == MANUAL_REFRESH_ONLY; } /** * @return true if this mode wants the Loading Layout to be shown like Google style pull-to-refresh */ public boolean showGoogleStyle() { return this == GOOGLE_STYLE; } int getIntValue() { return mIntValue; } } // =========================================================== // Inner, Anonymous Classes, and Enumerations // =========================================================== /** * Simple Listener that allows you to be notified when the user has scrolled * to the end of the AdapterView. See ( * {@link PullToRefreshAdapterViewBase#setOnLastItemVisibleListener}. * * @author Chris Banes */ public static interface OnLastItemVisibleListener { /** * Called when the user has scrolled to the end of the list */ public void onLastItemVisible(); } /** * Listener that allows you to be notified when the user has started or * finished a touch event. Useful when you want to append extra UI events * (such as sounds). See ( * {@link PullToRefreshAdapterViewBase#setOnPullEventListener}. * * @author Chris Banes */ public static interface OnPullEventListener<V extends View> { /** * Called when the internal state has been changed, usually by the user * pulling. * * @param refreshView - View which has had it's state change. * @param state - The new state of View. * @param direction - One of {@link Mode#PULL_FROM_START} or * {@link Mode#PULL_FROM_END} depending on which direction * the user is pulling. Only useful when <var>state</var> is * {@link State#PULL_TO_REFRESH} or * {@link State#RELEASE_TO_REFRESH}. */ public void onPullEvent(final PullToRefreshBase<V> refreshView, State state, Mode direction); } /** * Simple Listener to listen for any callbacks to Refresh. * * @author Chris Banes */ public static interface OnRefreshListener<V extends View> { /** * onRefresh will be called for both a Pull from start, and Pull from * end */ public void onRefresh(final PullToRefreshBase<V> refreshView); } /** * An advanced version of the Listener to listen for callbacks to Refresh. * This listener is different as it allows you to differentiate between Pull * Ups, and Pull Downs. * * @author Chris Banes */ public static interface OnRefreshListener2<V extends View> { // TODO These methods need renaming to START/END rather than DOWN/UP /** * onPullDownToRefresh will be called only when the user has Pulled from * the start, and released. */ public void onPullDownToRefresh(final PullToRefreshBase<V> refreshView); /** * onPullUpToRefresh will be called only when the user has Pulled from * the end, and released. */ public void onPullUpToRefresh(final PullToRefreshBase<V> refreshView); } public static enum Orientation { VERTICAL, HORIZONTAL; } public static enum State { /** * When the UI is in a state which means that user is not interacting * with the Pull-to-Refresh function. */ RESET(0x0), /** * When the UI is being pulled by the user, but has not been pulled far * enough so that it refreshes when released. */ PULL_TO_REFRESH(0x1), /** * When the UI is being pulled by the user, and <strong>has</strong> * been pulled far enough so that it will refresh when released. */ RELEASE_TO_REFRESH(0x2), /** * When the UI is currently refreshing, caused by a pull gesture. */ REFRESHING(0x8), /** * When the UI is currently refreshing, caused by a call to * {@link PullToRefreshBase#setRefreshing() setRefreshing()}. */ MANUAL_REFRESHING(0x9), /** * When the UI is currently overscrolling, caused by a fling on the * Refreshable View. */ OVERSCROLLING(0x10); /** * Maps an int to a specific state. This is needed when saving state. * * @param stateInt - int to map a State to * @return State that stateInt maps to */ static State mapIntToValue(final int stateInt) { for (State value : State.values()) { if (stateInt == value.getIntValue()) { return value; } } // If not, return default return RESET; } private int mIntValue; State(int intValue) { mIntValue = intValue; } int getIntValue() { return mIntValue; } } final class SmoothScrollRunnable implements Runnable { private final Interpolator mInterpolator; private final int mScrollToY; private final int mScrollFromY; private final long mDuration; private OnSmoothScrollFinishedListener mListener; private boolean mContinueRunning = true; private long mStartTime = -1; private int mCurrentY = -1; public SmoothScrollRunnable(int fromY, int toY, long duration, OnSmoothScrollFinishedListener listener) { mScrollFromY = fromY; mScrollToY = toY; mInterpolator = mScrollAnimationInterpolator; mDuration = duration; mListener = listener; } @Override public void run() { /** * Only set mStartTime if this is the first time we're starting, * else actually calculate the Y delta */ if (mStartTime == -1) { mStartTime = System.currentTimeMillis(); } else { /** * We do do all calculations in long to reduce software float * calculations. We use 1000 as it gives us good accuracy and * small rounding errors */ long normalizedTime = (1000 * (System.currentTimeMillis() - mStartTime)) / mDuration; normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0); final int deltaY = Math.round((mScrollFromY - mScrollToY) * mInterpolator.getInterpolation(normalizedTime / 1000f)); mCurrentY = mScrollFromY - deltaY; setHeaderScroll(mCurrentY); } // If we're not at the target Y, keep going... if (mContinueRunning && mScrollToY != mCurrentY) { ViewCompat.postOnAnimation(PullToRefreshBase.this, this); } else { if (null != mListener) { mListener.onSmoothScrollFinished(); } } } public void stop() { mContinueRunning = false; removeCallbacks(this); } } static interface OnSmoothScrollFinishedListener { void onSmoothScrollFinished(); } }
[issue-139] Apply animation options
library/src/main/java/com/handmark/pulltorefresh/library/PullToRefreshBase.java
[issue-139] Apply animation options
<ide><path>ibrary/src/main/java/com/handmark/pulltorefresh/library/PullToRefreshBase.java <ide> } <ide> if (mMode.showGoogleStyle()) { <ide> // Fade-out mRefreshableView <del> AlphaAnimator.fadeout(mRefreshableView, 500); <add> if ( mRefeshableViewHideWhileRefreshingEnabled == true ) { <add> AlphaAnimator.fadeout(mRefreshableView, mRefeshableViewHideWhileRefreshingDuration); <add> } <ide> // Fade-in refreshing bar on center <del> mRefreshableViewProgressBar.setVisibility(View.VISIBLE); <del> AlphaAnimator.fadein(mRefreshableViewProgressBar, 200); <del> <add> if (mRefeshableViewRefreshingBarViewWhileRefreshingEnabled == true ) { <add> mRefreshableViewProgressBar.setVisibility(View.VISIBLE); <add> AlphaAnimator.fadein(mRefreshableViewProgressBar, mRefeshableViewRefreshingBarViewWhileRefreshingDuration); <add> } <add> <ide> mViewOnTopLoadingLayout.refreshing(); <ide> } <ide> <ide> hideViewTopLayout(); <ide> <ide> // Fade-in mRefreshableView <del> if ( mRefreshing == true ) { <add> if ( mRefreshing == true && mRefeshableViewHideWhileRefreshingEnabled == true ) { <ide> mRefreshableView.clearAnimation(); <del> AlphaAnimator.fadein(mRefreshableView, 500); <add> AlphaAnimator.fadein(mRefreshableView, mRefeshableViewHideWhileRefreshingDuration); <ide> } <ide> // Fade-out refreshing bar on center <del> AlphaAnimator.fadeout(mRefreshableViewProgressBar, 200, new AnimationListener(){ <del> @Override <del> public void onAnimationEnd(Animation animation) { <del> mRefreshableViewProgressBar.setVisibility(View.INVISIBLE); <del> } <del> <del> @Override <del> public void onAnimationRepeat(Animation animation) { <del> // do nothing <del> } <del> <del> @Override <del> public void onAnimationStart(Animation animation) { <del> // do nothing <del> }}); <add> if (mRefeshableViewRefreshingBarViewWhileRefreshingEnabled == true ) { <add> AlphaAnimator.fadeout(mRefreshableViewProgressBar, mRefeshableViewRefreshingBarViewWhileRefreshingDuration, new AnimationListener(){ <add> @Override <add> public void onAnimationEnd(Animation animation) { <add> mRefreshableViewProgressBar.setVisibility(View.INVISIBLE); <add> } <add> <add> @Override <add> public void onAnimationRepeat(Animation animation) { <add> // do nothing <add> } <add> <add> @Override <add> public void onAnimationStart(Animation animation) { <add> // do nothing <add> }}); <add> } <ide> } <ide> <ide> mRefreshing = false; <ide> if (mMode.showGoogleStyle() == false ) { <ide> return; <ide> } <add> <ide> // Initialize Translate and Alpha animation <del> AnimationSet set = new AnimationSet(true /* share interpolator */); <del> set.setDuration(100); <del> set.setFillAfter(true); <del> set.setAnimationListener(new AnimationListener(){ <del> <del> @Override <del> public void onAnimationEnd(Animation anim) { <del> } <del> <del> @Override <del> public void onAnimationRepeat(Animation anim) { <del> } <del> <del> @Override <del> public void onAnimationStart(Animation anim) { <del> mTopActionbarLayout.setVisibility(View.VISIBLE); <del> }}); <del> <del> TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,Animation.ABSOLUTE, 0, Animation.ABSOLUTE, -mActionBarHeight, Animation.ABSOLUTE, mStatusBarHeight); <del> AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f); <del> set.addAnimation(transAnimation); <del> set.addAnimation(alphaAnimation); <del> // Start animation <del> mTopActionbarLayout.startAnimation(set); <add> if ( mShowGoogleStyleViewAnimationEnabled == true ) { <add> AnimationSet set = new AnimationSet(true /* share interpolator */); <add> set.setDuration(mShowGoogleStyleViewAnimationDuration); <add> set.setFillAfter(true); <add> set.setAnimationListener(new AnimationListener(){ <add> <add> @Override <add> public void onAnimationEnd(Animation anim) { <add> } <add> <add> @Override <add> public void onAnimationRepeat(Animation anim) { <add> } <add> <add> @Override <add> public void onAnimationStart(Animation anim) { <add> mTopActionbarLayout.setVisibility(View.VISIBLE); <add> }}); <add> <add> TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,Animation.ABSOLUTE, 0, Animation.ABSOLUTE, -mActionBarHeight, Animation.ABSOLUTE, mStatusBarHeight); <add> AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f); <add> set.addAnimation(transAnimation); <add> set.addAnimation(alphaAnimation); <add> // Start animation <add> mTopActionbarLayout.startAnimation(set); <add> } else { <add> // Show Google style view layout without animation <add> ((FrameLayout.LayoutParams) mTopActionbarLayout.getLayoutParams()).topMargin = mStatusBarHeight; <add> mTopActionbarLayout.setVisibility(View.VISIBLE); <add> } <add> <ide> } <ide> <ide> /** <ide> if (mMode.showGoogleStyle() == false ) { <ide> return; <ide> } <del> // Initialize Translate and Alpha animation <del> AnimationSet set = new AnimationSet(true /* share interpolator */); <del> set.setDuration(100); <del> set.setFillAfter(true); <del> set.setAnimationListener(new AnimationListener(){ <del> <del> @Override <del> public void onAnimationEnd(Animation anim) { <del> mTopActionbarLayout.setVisibility(View.INVISIBLE); <del> } <del> <del> @Override <del> public void onAnimationRepeat(Animation anim) { <del> } <del> <del> @Override <del> public void onAnimationStart(Animation anim) { <del> }}); <del> <del> TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,Animation.ABSOLUTE, 0, Animation.ABSOLUTE, mTopActionbarLayout.getTop(), Animation.ABSOLUTE, -mStatusBarHeight); <del> AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f); <del> set.addAnimation(transAnimation); <del> set.addAnimation(alphaAnimation); <del> // Start animation <del> mTopActionbarLayout.startAnimation(set); <add> <add> if ( mShowGoogleStyleViewAnimationEnabled == true ) { <add> // Initialize Translate and Alpha animation <add> AnimationSet set = new AnimationSet(true /* share interpolator */); <add> set.setDuration(mShowGoogleStyleViewAnimationDuration); <add> set.setFillAfter(true); <add> set.setAnimationListener(new AnimationListener(){ <add> <add> @Override <add> public void onAnimationEnd(Animation anim) { <add> mTopActionbarLayout.setVisibility(View.INVISIBLE); <add> } <add> <add> @Override <add> public void onAnimationRepeat(Animation anim) { <add> } <add> <add> @Override <add> public void onAnimationStart(Animation anim) { <add> }}); <add> <add> TranslateAnimation transAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,Animation.ABSOLUTE, 0, Animation.ABSOLUTE, mTopActionbarLayout.getTop(), Animation.ABSOLUTE, -mStatusBarHeight); <add> AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f); <add> set.addAnimation(transAnimation); <add> set.addAnimation(alphaAnimation); <add> // Start animation <add> mTopActionbarLayout.startAnimation(set); <add> } else { <add> // Hide Google style view layout without animation <add> ((FrameLayout.LayoutParams) mTopActionbarLayout.getLayoutParams()).topMargin = -mActionBarHeight; <add> mTopActionbarLayout.setVisibility(View.INVISIBLE); <add> } <add> <ide> } <ide> <ide> @Override
Java
epl-1.0
567f90f38f86180955e62572424c0b0a9a03b086
0
ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio
package org.csstudio.opibuilder.editparts; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import org.csstudio.opibuilder.OPIBuilderPlugin; import org.csstudio.opibuilder.model.AbstractPVWidgetModel; import org.csstudio.opibuilder.model.AbstractWidgetModel; import org.csstudio.opibuilder.model.IPVWidgetModel; import org.csstudio.opibuilder.properties.AbstractWidgetProperty; import org.csstudio.opibuilder.properties.IWidgetPropertyChangeHandler; import org.csstudio.opibuilder.properties.PVValueProperty; import org.csstudio.opibuilder.properties.StringProperty; import org.csstudio.opibuilder.util.AlarmRepresentationScheme; import org.csstudio.opibuilder.util.BOYPVFactory; import org.csstudio.opibuilder.util.ErrorHandlerUtil; import org.csstudio.opibuilder.util.OPIColor; import org.csstudio.opibuilder.util.OPITimer; import org.csstudio.opibuilder.visualparts.BorderFactory; import org.csstudio.opibuilder.visualparts.BorderStyle; import org.csstudio.simplepv.IPV; import org.csstudio.simplepv.IPVListener; import org.csstudio.simplepv.VTypeHelper; import org.csstudio.ui.util.CustomMediaFactory; import org.csstudio.ui.util.thread.UIBundlingThread; import org.eclipse.core.runtime.ListenerList; import org.eclipse.draw2d.AbstractBorder; import org.eclipse.draw2d.Border; import org.eclipse.draw2d.Cursors; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.gef.EditPart; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.RGB; import org.epics.vtype.AlarmSeverity; import org.epics.vtype.VType; public class PVWidgetEditpartDelegate implements IPVWidgetEditpart { // private interface AlarmSeverity extends ISeverity{ // public void copy(ISeverity severity); // } private final class WidgetPVListener extends IPVListener.Stub{ private String pvPropID; private boolean isControlPV; public WidgetPVListener(String pvPropID) { this.pvPropID = pvPropID; isControlPV = pvPropID.equals(controlPVPropId); } @Override public void connectionChanged(IPV pv) { if(!pv.isConnected()) lastWriteAccess = null; } @Override public void valueChanged(IPV pv) { final AbstractWidgetModel widgetModel = editpart.getWidgetModel(); //write access // if(isControlPV) // updateWritable(widgetModel, pv); if (pv.getValue() != null) { if (ignoreOldPVValue) { widgetModel.getPVMap() .get(widgetModel.getProperty(pvPropID)) .setPropertyValue_IgnoreOldValue(pv.getValue()); } else widgetModel.getPVMap() .get(widgetModel.getProperty(pvPropID)) .setPropertyValue(pv.getValue()); } } @Override public void writePermissionChanged(IPV pv) { if(isControlPV) updateWritable(editpart.getWidgetModel(), pvMap.get(pvPropID)); } } //invisible border for no_alarm state, this can prevent the widget from resizing //when alarm turn back to no_alarm state/ private static final AbstractBorder BORDER_NO_ALARM = new AbstractBorder() { public Insets getInsets(IFigure figure) { return new Insets(2); } public void paint(IFigure figure, Graphics graphics, Insets insets) { } }; private int updateSuppressTime = 1000; private String controlPVPropId = null; private String controlPVValuePropId = null; /** * In most cases, old pv value in the valueChange() method of {@link IWidgetPropertyChangeHandler} * is not useful. Ignore the old pv value will help to reduce memory usage. */ private boolean ignoreOldPVValue =true; private boolean isBackColorAlarmSensitive; private boolean isBorderAlarmSensitive; private boolean isForeColorAlarmSensitive; private AlarmSeverity alarmSeverity = AlarmSeverity.NONE; private Map<String, IPVListener> pvListenerMap = new HashMap<String, IPVListener>(); private Map<String, IPV> pvMap = new HashMap<String, IPV>(); private PropertyChangeListener[] pvValueListeners; private AbstractBaseEditPart editpart; private volatile AtomicBoolean lastWriteAccess; private Cursor savedCursor; private Color saveForeColor, saveBackColor; //the task which will be executed when the updateSuppressTimer due. protected Runnable timerTask; //The update from PV will be suppressed for a brief time when writing was performed protected OPITimer updateSuppressTimer; private IPVWidgetModel widgetModel; private boolean isAllValuesBuffered; private ListenerList setPVValueListeners; private ListenerList alarmSeverityListeners; /** * @param editpart the editpart to be delegated. * It must implemented {@link IPVWidgetEditpart} */ public PVWidgetEditpartDelegate(AbstractBaseEditPart editpart) { this.editpart = editpart; } public IPVWidgetModel getWidgetModel() { if(widgetModel == null) widgetModel = (IPVWidgetModel) editpart.getWidgetModel(); return widgetModel; } public void doActivate(){ saveFigureOKStatus(editpart.getFigure()); if(editpart.getExecutionMode() == ExecutionMode.RUN_MODE){ pvMap.clear(); final Map<StringProperty, PVValueProperty> pvPropertyMap = editpart.getWidgetModel().getPVMap(); for(final StringProperty sp : pvPropertyMap.keySet()){ if(sp.getPropertyValue() == null || ((String)sp.getPropertyValue()).trim().length() <=0) continue; try { IPV pv = BOYPVFactory.createPV((String) sp.getPropertyValue(), isAllValuesBuffered); pvMap.put(sp.getPropertyID(), pv); editpart.addToConnectionHandler((String) sp.getPropertyValue(), pv); WidgetPVListener pvListener = new WidgetPVListener(sp.getPropertyID()); pv.addListener(pvListener); pvListenerMap.put(sp.getPropertyID(), pvListener); } catch (Exception e) { OPIBuilderPlugin.getLogger().log(Level.WARNING, "Unable to connect to PV:" + (String)sp.getPropertyValue(), e); //$NON-NLS-1$ } } } } /**Start all PVs. * This should be called as the last step in editpart.activate(). */ public void startPVs() { //the pv should be started at the last minute for(String pvPropId : pvMap.keySet()){ IPV pv = pvMap.get(pvPropId); try { pv.start(); } catch (Exception e) { OPIBuilderPlugin.getLogger().log(Level.WARNING, "Unable to connect to PV:" + pv.getName(), e); //$NON-NLS-1$ } } } public void doDeActivate() { for(IPV pv : pvMap.values()) pv.stop(); for(String pvPropID : pvListenerMap.keySet()){ pvMap.get(pvPropID).removeListener(pvListenerMap.get(pvPropID)); } pvMap.clear(); pvListenerMap.clear(); } public IPV getControlPV(){ if(controlPVPropId != null) return pvMap.get(controlPVPropId); return null; } /**Get the PV corresponding to the <code>PV Name</code> property. * It is same as calling <code>getPV("pv_name")</code>. * @return the PV corresponding to the <code>PV Name</code> property. * null if PV Name is not configured for this widget. */ public IPV getPV(){ return pvMap.get(IPVWidgetModel.PROP_PVNAME); } /**Get the pv by PV property id. * @param pvPropId the PV property id. * @return the corresponding pv for the pvPropId. null if the pv doesn't exist. */ public IPV getPV(String pvPropId){ return pvMap.get(pvPropId); } /**Get value from one of the attached PVs. * @param pvPropId the property id of the PV. It is "pv_name" for the main PV. * @return the {@link IValue} of the PV. */ public VType getPVValue(String pvPropId){ final IPV pv = pvMap.get(pvPropId); if(pv != null){ return pv.getValue(); } return null; } /** * @return the time needed to suppress reading back from PV after writing. * No need to suppress if returned value <=0 */ public int getUpdateSuppressTime(){ return updateSuppressTime; } /**Set the time needed to suppress reading back from PV after writing. * No need to suppress if returned value <=0 * @param updateSuppressTime */ public void setUpdateSuppressTime(int updateSuppressTime) { this.updateSuppressTime = updateSuppressTime; } public void initFigure(IFigure figure){ //initialize frequent used variables isBorderAlarmSensitive = getWidgetModel().isBorderAlarmSensitve(); isBackColorAlarmSensitive = getWidgetModel().isBackColorAlarmSensitve(); isForeColorAlarmSensitive = getWidgetModel().isForeColorAlarmSensitve(); if(isBorderAlarmSensitive && editpart.getWidgetModel().getBorderStyle()== BorderStyle.NONE){ editpart.setFigureBorder(BORDER_NO_ALARM); } } /** * Initialize the updateSuppressTimer */ private synchronized void initUpdateSuppressTimer() { if(updateSuppressTimer == null) updateSuppressTimer = new OPITimer(); if(timerTask == null) timerTask = new Runnable() { public void run() { AbstractWidgetProperty pvValueProperty = editpart.getWidgetModel().getProperty(controlPVValuePropId); //recover update if(pvValueListeners != null){ for(PropertyChangeListener listener: pvValueListeners){ pvValueProperty.addPropertyChangeListener(listener); } } //forcefully set PV_Value property again pvValueProperty.setPropertyValue( pvValueProperty.getPropertyValue(), true); } }; } /**For PV Control widgets, mark this PV as control PV. * @param pvPropId the propId of the PV. */ public void markAsControlPV(String pvPropId, String pvValuePropId){ controlPVPropId = pvPropId; controlPVValuePropId = pvValuePropId; initUpdateSuppressTimer(); } public boolean isPVControlWidget(){ return controlPVPropId!=null; } public void registerBasePropertyChangeHandlers() { IWidgetPropertyChangeHandler borderHandler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { editpart.setFigureBorder(editpart.calculateBorder()); return true; } }; editpart.setPropertyChangeHandler(IPVWidgetModel.PROP_BORDER_ALARMSENSITIVE, borderHandler); // value IWidgetPropertyChangeHandler valueHandler = new IWidgetPropertyChangeHandler() { public boolean handleChange(final Object oldValue, final Object newValue, final IFigure figure) { // No valid value is given. Do nothing. if (newValue == null || !(newValue instanceof VType)) return false; AlarmSeverity newSeverity = VTypeHelper.getAlarmSeverity((VType) newValue); if(newSeverity == null) return false; if (newSeverity != alarmSeverity) { alarmSeverity = newSeverity; fireAlarmSeverityChanged(newSeverity, figure); } return true; } }; editpart.setPropertyChangeHandler(AbstractPVWidgetModel.PROP_PVVALUE, valueHandler); // Border Alarm Sensitive addAlarmSeverityListener(new AlarmSeverityListener() { @Override public boolean severityChanged(AlarmSeverity severity, IFigure figure) { if (!isBorderAlarmSensitive) return false; editpart.setFigureBorder(editpart.calculateBorder()); return true; } }); // BackColor Alarm Sensitive addAlarmSeverityListener(new AlarmSeverityListener() { @Override public boolean severityChanged(AlarmSeverity severity, IFigure figure) { if (!isBackColorAlarmSensitive) return false; figure.setBackgroundColor(calculateBackColor()); return true; } }); // ForeColor Alarm Sensitive addAlarmSeverityListener(new AlarmSeverityListener() { @Override public boolean severityChanged(AlarmSeverity severity, IFigure figure) { if (!isForeColorAlarmSensitive) return false; figure.setForegroundColor(calculateForeColor()); return true; } }); class PVNamePropertyChangeHandler implements IWidgetPropertyChangeHandler{ private String pvNamePropID; public PVNamePropertyChangeHandler(String pvNamePropID) { this.pvNamePropID = pvNamePropID; } public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { IPV oldPV = pvMap.get(pvNamePropID); editpart.removeFromConnectionHandler((String)oldValue); if(oldPV != null){ oldPV.stop(); oldPV.removeListener(pvListenerMap.get(pvNamePropID)); } pvMap.remove(pvNamePropID); String newPVName = ((String)newValue).trim(); if(newPVName.length() <= 0) return false; try { lastWriteAccess = null; IPV newPV = BOYPVFactory.createPV(newPVName, isAllValuesBuffered); WidgetPVListener pvListener = new WidgetPVListener(pvNamePropID); newPV.addListener(pvListener); pvMap.put(pvNamePropID, newPV); editpart.addToConnectionHandler(newPVName, newPV); pvListenerMap.put(pvNamePropID, pvListener); newPV.start(); } catch (Exception e) { OPIBuilderPlugin.getLogger().log(Level.WARNING, "Unable to connect to PV:" + //$NON-NLS-1$ newPVName, e); } return false; } } //PV name for(StringProperty pvNameProperty : editpart.getWidgetModel().getPVMap().keySet()){ if(editpart.getExecutionMode() == ExecutionMode.RUN_MODE) editpart.setPropertyChangeHandler(pvNameProperty.getPropertyID(), new PVNamePropertyChangeHandler(pvNameProperty.getPropertyID())); } if(editpart.getExecutionMode() == ExecutionMode.EDIT_MODE) editpart.getWidgetModel().getProperty(IPVWidgetModel.PROP_PVNAME).addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { //reselect the widget to update feedback. int selected = editpart.getSelected(); if(selected != EditPart.SELECTED_NONE){ editpart.setSelected(EditPart.SELECTED_NONE); editpart.setSelected(selected); } } }); IWidgetPropertyChangeHandler backColorHandler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { saveBackColor = ((OPIColor)newValue).getSWTColor(); return false; } }; editpart.setPropertyChangeHandler(AbstractWidgetModel.PROP_COLOR_BACKGROUND, backColorHandler); IWidgetPropertyChangeHandler foreColorHandler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { saveForeColor = ((OPIColor)newValue).getSWTColor(); return false; } }; editpart.setPropertyChangeHandler(AbstractWidgetModel.PROP_COLOR_FOREGROUND, foreColorHandler); IWidgetPropertyChangeHandler backColorAlarmSensitiveHandler = new IWidgetPropertyChangeHandler() { public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { isBackColorAlarmSensitive = (Boolean)newValue; figure.setBackgroundColor(calculateBackColor()); return true; } }; editpart.setPropertyChangeHandler(AbstractPVWidgetModel.PROP_BACKCOLOR_ALARMSENSITIVE, backColorAlarmSensitiveHandler); IWidgetPropertyChangeHandler foreColorAlarmSensitiveHandler = new IWidgetPropertyChangeHandler() { public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { isForeColorAlarmSensitive = (Boolean)newValue; figure.setForegroundColor(calculateForeColor()); return true; } }; editpart.setPropertyChangeHandler(AbstractPVWidgetModel.PROP_FORECOLOR_ALARMSENSITIVE, foreColorAlarmSensitiveHandler); } private void saveFigureOKStatus(IFigure figure) { saveForeColor = figure.getForegroundColor(); saveBackColor = figure.getBackgroundColor(); } /** * Start the updateSuppressTimer. All property change listeners of PV_Value property will * temporarily removed until timer is due. */ protected synchronized void startUpdateSuppressTimer(){ AbstractWidgetProperty pvValueProperty = editpart.getWidgetModel().getProperty(controlPVValuePropId); pvValueListeners = pvValueProperty.getAllPropertyChangeListeners(); pvValueProperty.removeAllPropertyChangeListeners(); updateSuppressTimer.start(timerTask, getUpdateSuppressTime()); } public Border calculateBorder(){ isBorderAlarmSensitive = getWidgetModel().isBorderAlarmSensitve(); if(!isBorderAlarmSensitive) return null; else { Border alarmBorder; switch (alarmSeverity) { case NONE: if(editpart.getWidgetModel().getBorderStyle()== BorderStyle.NONE) alarmBorder = BORDER_NO_ALARM; else alarmBorder = BorderFactory.createBorder( editpart.getWidgetModel().getBorderStyle(), editpart.getWidgetModel().getBorderWidth(), editpart.getWidgetModel().getBorderColor(), editpart.getWidgetModel().getName()); break; case MAJOR: alarmBorder = AlarmRepresentationScheme.getMajorBorder(editpart.getWidgetModel().getBorderStyle()); break; case MINOR: alarmBorder = AlarmRepresentationScheme.getMinorBorder(editpart.getWidgetModel().getBorderStyle()); break; case INVALID: case UNDEFINED: default: alarmBorder = AlarmRepresentationScheme.getInvalidBorder(editpart.getWidgetModel().getBorderStyle()); break; } return alarmBorder; } } public Color calculateBackColor() { return calculateAlarmColor(isBackColorAlarmSensitive, saveBackColor); } public Color calculateForeColor() { return calculateAlarmColor(isForeColorAlarmSensitive, saveForeColor); } public Color calculateAlarmColor(boolean isSensitive, Color saveColor) { if (!isSensitive) { return saveColor; } else { RGB alarmColor = AlarmRepresentationScheme.getAlarmColor(alarmSeverity); if (alarmColor != null) { // Alarm severity is either "Major", "Minor" or "Invalid. return CustomMediaFactory.getInstance().getColor(alarmColor); } else { // Alarm severity is "OK". return saveColor; } } } /**Set PV to given value. Should accept Double, Double[], Integer, String, maybe more. * @param pvPropId * @param value */ public void setPVValue(String pvPropId, Object value){ fireSetPVValue(pvPropId, value); final IPV pv = pvMap.get(pvPropId); if(pv != null){ try { if(pvPropId.equals(controlPVPropId) && controlPVValuePropId != null && getUpdateSuppressTime() >0){ //activate suppress timer synchronized (this) { if(updateSuppressTimer == null || timerTask == null) initUpdateSuppressTimer(); if(!updateSuppressTimer.isDue()) updateSuppressTimer.reset(); else startUpdateSuppressTimer(); } } pv.setValue(value); } catch (final Exception e) { UIBundlingThread.getInstance().addRunnable(new Runnable(){ public void run() { String message = "Failed to write PV:" + pv.getName(); ErrorHandlerUtil.handleError(message, e); } }); } } } public void setIgnoreOldPVValue(boolean ignoreOldValue) { this.ignoreOldPVValue = ignoreOldValue; } @Override public String[] getAllPVNames() { if(editpart.getWidgetModel().getPVMap().isEmpty()) return new String[]{""}; //$NON-NLS-1$ Set<String> result = new HashSet<String>(); for(StringProperty sp : editpart.getWidgetModel().getPVMap().keySet()){ if(sp.isVisibleInPropSheet() && !((String)sp.getPropertyValue()).trim().isEmpty()) result.add((String) sp.getPropertyValue()); } return result.toArray(new String[result.size()]); } @Override public String getPVName() { if(getPV() != null) return getPV().getName(); return getWidgetModel().getPVName(); } @Override public void addSetPVValueListener(ISetPVValueListener listener) { if(setPVValueListeners == null){ setPVValueListeners = new ListenerList(); } setPVValueListeners.add(listener); } protected void fireSetPVValue(String pvPropId, Object value){ if(setPVValueListeners == null) return; for(Object listener: setPVValueListeners.getListeners()){ ((ISetPVValueListener)listener).beforeSetPVValue(pvPropId, value); } } public boolean isAllValuesBuffered() { return isAllValuesBuffered; } public void setAllValuesBuffered(boolean isAllValuesBuffered) { this.isAllValuesBuffered = isAllValuesBuffered; } private void updateWritable(final AbstractWidgetModel widgetModel, IPV pv) { if(lastWriteAccess == null || lastWriteAccess.get() != pv.isWriteAllowed()){ if(lastWriteAccess == null) lastWriteAccess= new AtomicBoolean(); lastWriteAccess.set(pv.isWriteAllowed()); if(lastWriteAccess.get()){ UIBundlingThread.getInstance().addRunnable( editpart.getViewer().getControl().getDisplay(),new Runnable(){ public void run() { IFigure figure = editpart.getFigure(); if(figure.getCursor() == Cursors.NO) figure.setCursor(savedCursor); figure.setEnabled(widgetModel.isEnabled()); figure.repaint(); } }); }else{ UIBundlingThread.getInstance().addRunnable( editpart.getViewer().getControl().getDisplay(),new Runnable(){ public void run() { IFigure figure = editpart.getFigure(); if(figure.getCursor() != Cursors.NO) savedCursor = figure.getCursor(); figure.setEnabled(false); figure.setCursor(Cursors.NO); figure.repaint(); } }); } } } public void addAlarmSeverityListener(AlarmSeverityListener listener) { if(alarmSeverityListeners == null){ alarmSeverityListeners = new ListenerList(); } alarmSeverityListeners.add(listener); } private void fireAlarmSeverityChanged(AlarmSeverity severity, IFigure figure) { if(alarmSeverityListeners == null) return; for(Object listener: alarmSeverityListeners.getListeners()){ ((AlarmSeverityListener)listener).severityChanged(severity, figure); } } }
applications/plugins/org.csstudio.opibuilder/src/org/csstudio/opibuilder/editparts/PVWidgetEditpartDelegate.java
package org.csstudio.opibuilder.editparts; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import org.csstudio.opibuilder.OPIBuilderPlugin; import org.csstudio.opibuilder.model.AbstractPVWidgetModel; import org.csstudio.opibuilder.model.AbstractWidgetModel; import org.csstudio.opibuilder.model.IPVWidgetModel; import org.csstudio.opibuilder.properties.AbstractWidgetProperty; import org.csstudio.opibuilder.properties.IWidgetPropertyChangeHandler; import org.csstudio.opibuilder.properties.PVValueProperty; import org.csstudio.opibuilder.properties.StringProperty; import org.csstudio.opibuilder.util.AlarmRepresentationScheme; import org.csstudio.opibuilder.util.BOYPVFactory; import org.csstudio.opibuilder.util.ErrorHandlerUtil; import org.csstudio.opibuilder.util.OPITimer; import org.csstudio.opibuilder.visualparts.BorderFactory; import org.csstudio.opibuilder.visualparts.BorderStyle; import org.csstudio.simplepv.IPV; import org.csstudio.simplepv.IPVListener; import org.csstudio.simplepv.VTypeHelper; import org.csstudio.ui.util.CustomMediaFactory; import org.csstudio.ui.util.thread.UIBundlingThread; import org.eclipse.core.runtime.ListenerList; import org.eclipse.draw2d.AbstractBorder; import org.eclipse.draw2d.Border; import org.eclipse.draw2d.Cursors; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.gef.EditPart; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.RGB; import org.epics.vtype.AlarmSeverity; import org.epics.vtype.VType; public class PVWidgetEditpartDelegate implements IPVWidgetEditpart { // private interface AlarmSeverity extends ISeverity{ // public void copy(ISeverity severity); // } private final class WidgetPVListener extends IPVListener.Stub{ private String pvPropID; private boolean isControlPV; public WidgetPVListener(String pvPropID) { this.pvPropID = pvPropID; isControlPV = pvPropID.equals(controlPVPropId); } @Override public void connectionChanged(IPV pv) { if(!pv.isConnected()) lastWriteAccess = null; } @Override public void valueChanged(IPV pv) { final AbstractWidgetModel widgetModel = editpart.getWidgetModel(); //write access // if(isControlPV) // updateWritable(widgetModel, pv); if (pv.getValue() != null) { if (ignoreOldPVValue) { widgetModel.getPVMap() .get(widgetModel.getProperty(pvPropID)) .setPropertyValue_IgnoreOldValue(pv.getValue()); } else widgetModel.getPVMap() .get(widgetModel.getProperty(pvPropID)) .setPropertyValue(pv.getValue()); } } @Override public void writePermissionChanged(IPV pv) { if(isControlPV) updateWritable(editpart.getWidgetModel(), pvMap.get(pvPropID)); } } //invisible border for no_alarm state, this can prevent the widget from resizing //when alarm turn back to no_alarm state/ private static final AbstractBorder BORDER_NO_ALARM = new AbstractBorder() { public Insets getInsets(IFigure figure) { return new Insets(2); } public void paint(IFigure figure, Graphics graphics, Insets insets) { } }; private int updateSuppressTime = 1000; private String controlPVPropId = null; private String controlPVValuePropId = null; /** * In most cases, old pv value in the valueChange() method of {@link IWidgetPropertyChangeHandler} * is not useful. Ignore the old pv value will help to reduce memory usage. */ private boolean ignoreOldPVValue =true; private boolean isBackColorAlarmSensitive; private boolean isBorderAlarmSensitive; private boolean isForeColorAlarmSensitive; private AlarmSeverity alarmSeverity = AlarmSeverity.NONE; private Map<String, IPVListener> pvListenerMap = new HashMap<String, IPVListener>(); private Map<String, IPV> pvMap = new HashMap<String, IPV>(); private PropertyChangeListener[] pvValueListeners; private AbstractBaseEditPart editpart; private volatile AtomicBoolean lastWriteAccess; private Cursor savedCursor; private Color saveForeColor, saveBackColor; //the task which will be executed when the updateSuppressTimer due. protected Runnable timerTask; //The update from PV will be suppressed for a brief time when writing was performed protected OPITimer updateSuppressTimer; private IPVWidgetModel widgetModel; private boolean isAllValuesBuffered; private ListenerList setPVValueListeners; private ListenerList alarmSeverityListeners; /** * @param editpart the editpart to be delegated. * It must implemented {@link IPVWidgetEditpart} */ public PVWidgetEditpartDelegate(AbstractBaseEditPart editpart) { this.editpart = editpart; } public IPVWidgetModel getWidgetModel() { if(widgetModel == null) widgetModel = (IPVWidgetModel) editpart.getWidgetModel(); return widgetModel; } public void doActivate(){ if(editpart.getExecutionMode() == ExecutionMode.RUN_MODE){ pvMap.clear(); saveFigureOKStatus(editpart.getFigure()); final Map<StringProperty, PVValueProperty> pvPropertyMap = editpart.getWidgetModel().getPVMap(); for(final StringProperty sp : pvPropertyMap.keySet()){ if(sp.getPropertyValue() == null || ((String)sp.getPropertyValue()).trim().length() <=0) continue; try { IPV pv = BOYPVFactory.createPV((String) sp.getPropertyValue(), isAllValuesBuffered); pvMap.put(sp.getPropertyID(), pv); editpart.addToConnectionHandler((String) sp.getPropertyValue(), pv); WidgetPVListener pvListener = new WidgetPVListener(sp.getPropertyID()); pv.addListener(pvListener); pvListenerMap.put(sp.getPropertyID(), pvListener); } catch (Exception e) { OPIBuilderPlugin.getLogger().log(Level.WARNING, "Unable to connect to PV:" + (String)sp.getPropertyValue(), e); //$NON-NLS-1$ } } } } /**Start all PVs. * This should be called as the last step in editpart.activate(). */ public void startPVs() { //the pv should be started at the last minute for(String pvPropId : pvMap.keySet()){ IPV pv = pvMap.get(pvPropId); try { pv.start(); } catch (Exception e) { OPIBuilderPlugin.getLogger().log(Level.WARNING, "Unable to connect to PV:" + pv.getName(), e); //$NON-NLS-1$ } } } public void doDeActivate() { for(IPV pv : pvMap.values()) pv.stop(); for(String pvPropID : pvListenerMap.keySet()){ pvMap.get(pvPropID).removeListener(pvListenerMap.get(pvPropID)); } pvMap.clear(); pvListenerMap.clear(); } public IPV getControlPV(){ if(controlPVPropId != null) return pvMap.get(controlPVPropId); return null; } /**Get the PV corresponding to the <code>PV Name</code> property. * It is same as calling <code>getPV("pv_name")</code>. * @return the PV corresponding to the <code>PV Name</code> property. * null if PV Name is not configured for this widget. */ public IPV getPV(){ return pvMap.get(IPVWidgetModel.PROP_PVNAME); } /**Get the pv by PV property id. * @param pvPropId the PV property id. * @return the corresponding pv for the pvPropId. null if the pv doesn't exist. */ public IPV getPV(String pvPropId){ return pvMap.get(pvPropId); } /**Get value from one of the attached PVs. * @param pvPropId the property id of the PV. It is "pv_name" for the main PV. * @return the {@link IValue} of the PV. */ public VType getPVValue(String pvPropId){ final IPV pv = pvMap.get(pvPropId); if(pv != null){ return pv.getValue(); } return null; } /** * @return the time needed to suppress reading back from PV after writing. * No need to suppress if returned value <=0 */ public int getUpdateSuppressTime(){ return updateSuppressTime; } /**Set the time needed to suppress reading back from PV after writing. * No need to suppress if returned value <=0 * @param updateSuppressTime */ public void setUpdateSuppressTime(int updateSuppressTime) { this.updateSuppressTime = updateSuppressTime; } public void initFigure(IFigure figure){ //initialize frequent used variables isBorderAlarmSensitive = getWidgetModel().isBorderAlarmSensitve(); isBackColorAlarmSensitive = getWidgetModel().isBackColorAlarmSensitve(); isForeColorAlarmSensitive = getWidgetModel().isForeColorAlarmSensitve(); if(isBorderAlarmSensitive && editpart.getWidgetModel().getBorderStyle()== BorderStyle.NONE){ editpart.setFigureBorder(BORDER_NO_ALARM); } } /** * Initialize the updateSuppressTimer */ private synchronized void initUpdateSuppressTimer() { if(updateSuppressTimer == null) updateSuppressTimer = new OPITimer(); if(timerTask == null) timerTask = new Runnable() { public void run() { AbstractWidgetProperty pvValueProperty = editpart.getWidgetModel().getProperty(controlPVValuePropId); //recover update if(pvValueListeners != null){ for(PropertyChangeListener listener: pvValueListeners){ pvValueProperty.addPropertyChangeListener(listener); } } //forcefully set PV_Value property again pvValueProperty.setPropertyValue( pvValueProperty.getPropertyValue(), true); } }; } /**For PV Control widgets, mark this PV as control PV. * @param pvPropId the propId of the PV. */ public void markAsControlPV(String pvPropId, String pvValuePropId){ controlPVPropId = pvPropId; controlPVValuePropId = pvValuePropId; initUpdateSuppressTimer(); } public boolean isPVControlWidget(){ return controlPVPropId!=null; } public void registerBasePropertyChangeHandlers() { IWidgetPropertyChangeHandler borderHandler = new IWidgetPropertyChangeHandler(){ public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { editpart.setFigureBorder(editpart.calculateBorder()); return true; } }; editpart.setPropertyChangeHandler(IPVWidgetModel.PROP_BORDER_ALARMSENSITIVE, borderHandler); // value IWidgetPropertyChangeHandler valueHandler = new IWidgetPropertyChangeHandler() { public boolean handleChange(final Object oldValue, final Object newValue, final IFigure figure) { // No valid value is given. Do nothing. if (newValue == null || !(newValue instanceof VType)) return false; AlarmSeverity newSeverity = VTypeHelper.getAlarmSeverity((VType) newValue); if(newSeverity == null) return false; if (newSeverity != alarmSeverity) { alarmSeverity = newSeverity; fireAlarmSeverityChanged(newSeverity, figure); } return true; } }; editpart.setPropertyChangeHandler(AbstractPVWidgetModel.PROP_PVVALUE, valueHandler); // Border Alarm Sensitive addAlarmSeverityListener(new AlarmSeverityListener() { @Override public boolean severityChanged(AlarmSeverity severity, IFigure figure) { if (!isBorderAlarmSensitive) return false; editpart.setFigureBorder(editpart.calculateBorder()); return true; } }); // BackColor Alarm Sensitive addAlarmSeverityListener(new AlarmSeverityListener() { @Override public boolean severityChanged(AlarmSeverity severity, IFigure figure) { if (!isBackColorAlarmSensitive) return false; figure.setBackgroundColor(calculateBackColor()); return true; } }); // ForeColor Alarm Sensitive addAlarmSeverityListener(new AlarmSeverityListener() { @Override public boolean severityChanged(AlarmSeverity severity, IFigure figure) { if (!isForeColorAlarmSensitive) return false; figure.setForegroundColor(calculateForeColor()); return true; } }); class PVNamePropertyChangeHandler implements IWidgetPropertyChangeHandler{ private String pvNamePropID; public PVNamePropertyChangeHandler(String pvNamePropID) { this.pvNamePropID = pvNamePropID; } public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { IPV oldPV = pvMap.get(pvNamePropID); editpart.removeFromConnectionHandler((String)oldValue); if(oldPV != null){ oldPV.stop(); oldPV.removeListener(pvListenerMap.get(pvNamePropID)); } pvMap.remove(pvNamePropID); String newPVName = ((String)newValue).trim(); if(newPVName.length() <= 0) return false; try { lastWriteAccess = null; IPV newPV = BOYPVFactory.createPV(newPVName, isAllValuesBuffered); WidgetPVListener pvListener = new WidgetPVListener(pvNamePropID); newPV.addListener(pvListener); pvMap.put(pvNamePropID, newPV); editpart.addToConnectionHandler(newPVName, newPV); pvListenerMap.put(pvNamePropID, pvListener); newPV.start(); } catch (Exception e) { OPIBuilderPlugin.getLogger().log(Level.WARNING, "Unable to connect to PV:" + //$NON-NLS-1$ newPVName, e); } return false; } } //PV name for(StringProperty pvNameProperty : editpart.getWidgetModel().getPVMap().keySet()){ if(editpart.getExecutionMode() == ExecutionMode.RUN_MODE) editpart.setPropertyChangeHandler(pvNameProperty.getPropertyID(), new PVNamePropertyChangeHandler(pvNameProperty.getPropertyID())); } if(editpart.getExecutionMode() == ExecutionMode.EDIT_MODE) editpart.getWidgetModel().getProperty(IPVWidgetModel.PROP_PVNAME).addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { //reselect the widget to update feedback. int selected = editpart.getSelected(); if(selected != EditPart.SELECTED_NONE){ editpart.setSelected(EditPart.SELECTED_NONE); editpart.setSelected(selected); } } }); IWidgetPropertyChangeHandler backColorAlarmSensitiveHandler = new IWidgetPropertyChangeHandler() { public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { isBackColorAlarmSensitive = (Boolean)newValue; figure.setBackgroundColor(calculateBackColor()); return true; } }; editpart.setPropertyChangeHandler(AbstractPVWidgetModel.PROP_BACKCOLOR_ALARMSENSITIVE, backColorAlarmSensitiveHandler); IWidgetPropertyChangeHandler foreColorAlarmSensitiveHandler = new IWidgetPropertyChangeHandler() { public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { isForeColorAlarmSensitive = (Boolean)newValue; figure.setForegroundColor(calculateForeColor()); return true; } }; editpart.setPropertyChangeHandler(AbstractPVWidgetModel.PROP_FORECOLOR_ALARMSENSITIVE, foreColorAlarmSensitiveHandler); } private void saveFigureOKStatus(IFigure figure) { saveForeColor = figure.getForegroundColor(); saveBackColor = figure.getBackgroundColor(); } /** * Start the updateSuppressTimer. All property change listeners of PV_Value property will * temporarily removed until timer is due. */ protected synchronized void startUpdateSuppressTimer(){ AbstractWidgetProperty pvValueProperty = editpart.getWidgetModel().getProperty(controlPVValuePropId); pvValueListeners = pvValueProperty.getAllPropertyChangeListeners(); pvValueProperty.removeAllPropertyChangeListeners(); updateSuppressTimer.start(timerTask, getUpdateSuppressTime()); } public Border calculateBorder(){ isBorderAlarmSensitive = getWidgetModel().isBorderAlarmSensitve(); if(!isBorderAlarmSensitive) return null; else { Border alarmBorder; switch (alarmSeverity) { case NONE: if(editpart.getWidgetModel().getBorderStyle()== BorderStyle.NONE) alarmBorder = BORDER_NO_ALARM; else alarmBorder = BorderFactory.createBorder( editpart.getWidgetModel().getBorderStyle(), editpart.getWidgetModel().getBorderWidth(), editpart.getWidgetModel().getBorderColor(), editpart.getWidgetModel().getName()); break; case MAJOR: alarmBorder = AlarmRepresentationScheme.getMajorBorder(editpart.getWidgetModel().getBorderStyle()); break; case MINOR: alarmBorder = AlarmRepresentationScheme.getMinorBorder(editpart.getWidgetModel().getBorderStyle()); break; case INVALID: case UNDEFINED: default: alarmBorder = AlarmRepresentationScheme.getInvalidBorder(editpart.getWidgetModel().getBorderStyle()); break; } return alarmBorder; } } public Color calculateBackColor() { return calculateAlarmColor(isBackColorAlarmSensitive, saveBackColor); } public Color calculateForeColor() { return calculateAlarmColor(isForeColorAlarmSensitive, saveForeColor); } public Color calculateAlarmColor(boolean isSensitive, Color saveColor) { if (!isSensitive) { return saveColor; } else { RGB alarmColor = AlarmRepresentationScheme.getAlarmColor(alarmSeverity); if (alarmColor != null) { // Alarm severity is either "Major", "Minor" or "Invalid. return CustomMediaFactory.getInstance().getColor(alarmColor); } else { // Alarm severity is "OK". return saveColor; } } } /**Set PV to given value. Should accept Double, Double[], Integer, String, maybe more. * @param pvPropId * @param value */ public void setPVValue(String pvPropId, Object value){ fireSetPVValue(pvPropId, value); final IPV pv = pvMap.get(pvPropId); if(pv != null){ try { if(pvPropId.equals(controlPVPropId) && controlPVValuePropId != null && getUpdateSuppressTime() >0){ //activate suppress timer synchronized (this) { if(updateSuppressTimer == null || timerTask == null) initUpdateSuppressTimer(); if(!updateSuppressTimer.isDue()) updateSuppressTimer.reset(); else startUpdateSuppressTimer(); } } pv.setValue(value); } catch (final Exception e) { UIBundlingThread.getInstance().addRunnable(new Runnable(){ public void run() { String message = "Failed to write PV:" + pv.getName(); ErrorHandlerUtil.handleError(message, e); } }); } } } public void setIgnoreOldPVValue(boolean ignoreOldValue) { this.ignoreOldPVValue = ignoreOldValue; } @Override public String[] getAllPVNames() { if(editpart.getWidgetModel().getPVMap().isEmpty()) return new String[]{""}; //$NON-NLS-1$ Set<String> result = new HashSet<String>(); for(StringProperty sp : editpart.getWidgetModel().getPVMap().keySet()){ if(sp.isVisibleInPropSheet() && !((String)sp.getPropertyValue()).trim().isEmpty()) result.add((String) sp.getPropertyValue()); } return result.toArray(new String[result.size()]); } @Override public String getPVName() { if(getPV() != null) return getPV().getName(); return getWidgetModel().getPVName(); } @Override public void addSetPVValueListener(ISetPVValueListener listener) { if(setPVValueListeners == null){ setPVValueListeners = new ListenerList(); } setPVValueListeners.add(listener); } protected void fireSetPVValue(String pvPropId, Object value){ if(setPVValueListeners == null) return; for(Object listener: setPVValueListeners.getListeners()){ ((ISetPVValueListener)listener).beforeSetPVValue(pvPropId, value); } } public boolean isAllValuesBuffered() { return isAllValuesBuffered; } public void setAllValuesBuffered(boolean isAllValuesBuffered) { this.isAllValuesBuffered = isAllValuesBuffered; } private void updateWritable(final AbstractWidgetModel widgetModel, IPV pv) { if(lastWriteAccess == null || lastWriteAccess.get() != pv.isWriteAllowed()){ if(lastWriteAccess == null) lastWriteAccess= new AtomicBoolean(); lastWriteAccess.set(pv.isWriteAllowed()); if(lastWriteAccess.get()){ UIBundlingThread.getInstance().addRunnable( editpart.getViewer().getControl().getDisplay(),new Runnable(){ public void run() { IFigure figure = editpart.getFigure(); if(figure.getCursor() == Cursors.NO) figure.setCursor(savedCursor); figure.setEnabled(widgetModel.isEnabled()); figure.repaint(); } }); }else{ UIBundlingThread.getInstance().addRunnable( editpart.getViewer().getControl().getDisplay(),new Runnable(){ public void run() { IFigure figure = editpart.getFigure(); if(figure.getCursor() != Cursors.NO) savedCursor = figure.getCursor(); figure.setEnabled(false); figure.setCursor(Cursors.NO); figure.repaint(); } }); } } } public void addAlarmSeverityListener(AlarmSeverityListener listener) { if(alarmSeverityListeners == null){ alarmSeverityListeners = new ListenerList(); } alarmSeverityListeners.add(listener); } private void fireAlarmSeverityChanged(AlarmSeverity severity, IFigure figure) { if(alarmSeverityListeners == null) return; for(Object listener: alarmSeverityListeners.getListeners()){ ((AlarmSeverityListener)listener).severityChanged(severity, figure); } } }
Fix alarm colours so that background and foreground colours are saved when they are changed, and that the figureOKStatus is saved in edit mode as well as run mode so that checking alarm state doesn't lose your saved colours
applications/plugins/org.csstudio.opibuilder/src/org/csstudio/opibuilder/editparts/PVWidgetEditpartDelegate.java
Fix alarm colours so that background and foreground colours are saved when they are changed, and that the figureOKStatus is saved in edit mode as well as run mode so that checking alarm state doesn't lose your saved colours
<ide><path>pplications/plugins/org.csstudio.opibuilder/src/org/csstudio/opibuilder/editparts/PVWidgetEditpartDelegate.java <ide> import org.csstudio.opibuilder.util.AlarmRepresentationScheme; <ide> import org.csstudio.opibuilder.util.BOYPVFactory; <ide> import org.csstudio.opibuilder.util.ErrorHandlerUtil; <add>import org.csstudio.opibuilder.util.OPIColor; <ide> import org.csstudio.opibuilder.util.OPITimer; <ide> import org.csstudio.opibuilder.visualparts.BorderFactory; <ide> import org.csstudio.opibuilder.visualparts.BorderStyle; <ide> } <ide> <ide> public void doActivate(){ <add> saveFigureOKStatus(editpart.getFigure()); <ide> if(editpart.getExecutionMode() == ExecutionMode.RUN_MODE){ <ide> pvMap.clear(); <del> saveFigureOKStatus(editpart.getFigure()); <ide> final Map<StringProperty, PVValueProperty> pvPropertyMap = editpart.getWidgetModel().getPVMap(); <ide> <ide> for(final StringProperty sp : pvPropertyMap.keySet()){ <ide> } <ide> }); <ide> <add> IWidgetPropertyChangeHandler backColorHandler = new IWidgetPropertyChangeHandler(){ <add> public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { <add> saveBackColor = ((OPIColor)newValue).getSWTColor(); <add> return false; <add> } <add> }; <add> editpart.setPropertyChangeHandler(AbstractWidgetModel.PROP_COLOR_BACKGROUND, backColorHandler); <add> <add> IWidgetPropertyChangeHandler foreColorHandler = new IWidgetPropertyChangeHandler(){ <add> public boolean handleChange(Object oldValue, Object newValue, IFigure figure) { <add> saveForeColor = ((OPIColor)newValue).getSWTColor(); <add> return false; <add> } <add> }; <add> editpart.setPropertyChangeHandler(AbstractWidgetModel.PROP_COLOR_FOREGROUND, foreColorHandler); <ide> <ide> IWidgetPropertyChangeHandler backColorAlarmSensitiveHandler = new IWidgetPropertyChangeHandler() { <ide>
Java
bsd-3-clause
error: pathspec 'plugins/src/org/lockss/plugin/highwire/TriggeredHighWirePermissionCheckerFactory.java' did not match any file(s) known to git
736ab3af9fbd9bc7c998ef56ddbc2e7da9a8a262
1
edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon
/* * $Id: TriggeredHighWirePermissionCheckerFactory.java,v 1.1 2012-05-14 20:58:36 akanshab01 Exp $ */ /* Copyright (c) 2000-2006 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.highwire; import java.io.Reader; import java.util.*; import org.lockss.daemon.*; import org.lockss.plugin.*; public class TriggeredHighWirePermissionCheckerFactory implements PermissionCheckerFactory { public List createPermissionCheckers(ArchivalUnit au) { List list = new ArrayList(1); list.add(new TriggeredPermissionChecker(new HighWireLoginPageChecker(), au)); return list; } private class TriggeredPermissionChecker implements PermissionChecker { ArchivalUnit au; public TriggeredPermissionChecker(LoginPageChecker checker, ArchivalUnit au) { this.au = au; } public boolean checkPermission(Crawler.PermissionHelper pHelper, Reader inputReader, String url) { return true; } } }
plugins/src/org/lockss/plugin/highwire/TriggeredHighWirePermissionCheckerFactory.java
HighwirePermissionFactory for Triggered content. git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@17245 4f837ed2-42f5-46e7-a7a5-fa17313484d4
plugins/src/org/lockss/plugin/highwire/TriggeredHighWirePermissionCheckerFactory.java
HighwirePermissionFactory for Triggered content.
<ide><path>lugins/src/org/lockss/plugin/highwire/TriggeredHighWirePermissionCheckerFactory.java <add>/* <add> * $Id: TriggeredHighWirePermissionCheckerFactory.java,v 1.1 2012-05-14 20:58:36 akanshab01 Exp $ <add> */ <add> <add>/* <add> <add>Copyright (c) 2000-2006 Board of Trustees of Leland Stanford Jr. University, <add>all rights reserved. <add> <add>Permission is hereby granted, free of charge, to any person obtaining a copy <add>of this software and associated documentation files (the "Software"), to deal <add>in the Software without restriction, including without limitation the rights <add>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <add>copies of the Software, and to permit persons to whom the Software is <add>furnished to do so, subject to the following conditions: <add> <add>The above copyright notice and this permission notice shall be included in <add>all copies or substantial portions of the Software. <add> <add>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <add>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <add>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL <add>STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, <add>WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR <add>IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>Except as contained in this notice, the name of Stanford University shall not <add>be used in advertising or otherwise to promote the sale, use or other dealings <add>in this Software without prior written authorization from Stanford University. <add> <add>*/ <add> <add>package org.lockss.plugin.highwire; <add> <add>import java.io.Reader; <add>import java.util.*; <add>import org.lockss.daemon.*; <add>import org.lockss.plugin.*; <add> <add>public class TriggeredHighWirePermissionCheckerFactory implements <add> PermissionCheckerFactory { <add> <add> public List createPermissionCheckers(ArchivalUnit au) { <add> List list = new ArrayList(1); <add> list.add(new TriggeredPermissionChecker(new HighWireLoginPageChecker(), au)); <add> return list; <add> } <add> <add> private class TriggeredPermissionChecker implements PermissionChecker { <add> <add> ArchivalUnit au; <add> <add> public TriggeredPermissionChecker(LoginPageChecker checker, ArchivalUnit au) { <add> this.au = au; <add> } <add> <add> public boolean checkPermission(Crawler.PermissionHelper pHelper, <add> Reader inputReader, String url) { <add> return true; <add> } <add> } <add>}
Java
apache-2.0
3f335207a03c6ad280b2a027d6c1ba1608650e38
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij; import com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory; import com.intellij.idea.Bombed; import com.intellij.idea.RecordExecution; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.testFramework.TeamCityLogger; import com.intellij.testFramework.TestFrameworkUtil; import com.intellij.testFramework.TestLoggerFactory; import com.intellij.tests.ExternalClasspathClassLoader; import com.intellij.util.ArrayUtilRt; import com.intellij.util.ObjectUtils; import com.intellij.util.ReflectionUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.lang.UrlClassLoader; import gnu.trove.THashSet; import junit.framework.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.Parameterized; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import static com.intellij.TestCaseLoader.*; @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"}) public class TestAll implements Test { static { Logger.setFactory(TestLoggerFactory.class); } private static final String MAX_FAILURE_TEST_COUNT_FLAG = "idea.max.failure.test.count"; private static final int MAX_FAILURE_TEST_COUNT = Integer.parseInt(ObjectUtils.chooseNotNull( System.getProperty(MAX_FAILURE_TEST_COUNT_FLAG), "150" )); private static final Filter PERFORMANCE_ONLY = new Filter() { @Override public boolean shouldRun(Description description) { String className = description.getClassName(); String methodName = description.getMethodName(); return TestFrameworkUtil.isPerformanceTest(methodName, className); } @Override public String describe() { return "Performance Tests Only"; } }; private static final Filter NO_PERFORMANCE = new Filter() { @Override public boolean shouldRun(Description description) { return !PERFORMANCE_ONLY.shouldRun(description); } @Override public String describe() { return "All Except Performance"; } }; public static final Filter NOT_BOMBED = new Filter() { @Override public boolean shouldRun(Description description) { return !isBombed(description); } @Override public String describe() { return "Not @Bombed"; } private boolean isBombed(Description description) { Bombed bombed = description.getAnnotation(Bombed.class); return bombed != null && !TestFrameworkUtil.bombExplodes(bombed); } }; private final TestCaseLoader myTestCaseLoader; private int myRunTests = -1; private TestRecorder myTestRecorder; private static final List<Throwable> outClassLoadingProblems = new ArrayList<>(); private static JUnit4TestAdapterCache ourUnit4TestAdapterCache; public TestAll(String rootPackage) throws Throwable { this(rootPackage, getClassRoots()); } public TestAll(String rootPackage, List<? extends File> classesRoots) throws ClassNotFoundException { String classFilterName = "tests/testGroups.properties"; myTestCaseLoader = new TestCaseLoader(classFilterName); myTestCaseLoader.addFirstTest(Class.forName("_FirstInSuiteTest")); myTestCaseLoader.addLastTest(Class.forName("_LastInSuiteTest")); myTestCaseLoader.fillTestCases(rootPackage, classesRoots); outClassLoadingProblems.addAll(myTestCaseLoader.getClassLoadingErrors()); } public static List<Throwable> getLoadingClassProblems() { return outClassLoadingProblems; } public static List<File> getClassRoots() { String testRoots = System.getProperty("test.roots"); if (testRoots != null) { System.out.println("Collecting tests from roots specified by test.roots property: " + testRoots); return ContainerUtil.map(testRoots.split(";"), File::new); } List<File> roots = ExternalClasspathClassLoader.getRoots(); if (roots != null) { List<File> excludeRoots = ExternalClasspathClassLoader.getExcludeRoots(); if (excludeRoots != null) { System.out.println("Skipping tests from " + excludeRoots.size() + " roots"); roots = new ArrayList<>(roots); roots.removeAll(new THashSet<>(excludeRoots, FileUtil.FILE_HASHING_STRATEGY)); } System.out.println("Collecting tests from roots specified by classpath.file property: " + roots); return roots; } else { ClassLoader loader = TestAll.class.getClassLoader(); if (loader instanceof URLClassLoader) { return getClassRoots(((URLClassLoader)loader).getURLs()); } if (loader instanceof UrlClassLoader) { List<URL> urls = ((UrlClassLoader)loader).getBaseUrls(); return getClassRoots(urls.toArray(new URL[0])); } return ContainerUtil.map(System.getProperty("java.class.path").split(File.pathSeparator), File::new); } } private static List<File> getClassRoots(URL[] urls) { final List<File> classLoaderRoots = ContainerUtil.map(urls, url -> new File(VfsUtilCore.urlToPath(VfsUtilCore.convertFromUrl(url)))); System.out.println("Collecting tests from " + classLoaderRoots); return classLoaderRoots; } @Override public int countTestCases() { // counting test cases involves parallel directory scan now IdeaForkJoinWorkerThreadFactory.setupForkJoinCommonPool(true); int count = 0; for (Class<?> aClass : myTestCaseLoader.getClasses()) { Test test = getTest(aClass); if (test != null) count += test.countTestCases(); } return count; } private void addErrorMessage(TestResult testResult, String message) { String processedTestsMessage = myRunTests <= 0 ? "None of tests was run" : myRunTests + " tests processed"; try { testResult.startTest(this); testResult.addError(this, new Throwable(processedTestsMessage + " before: " + message)); testResult.endTest(this); } catch (Exception e) { e.printStackTrace(); } } @Override public void run(final TestResult testResult) { loadTestRecorder(); final TestListener testListener = loadDiscoveryListener(); if (testListener != null) { testResult.addListener(testListener); } List<Class<?>> classes = myTestCaseLoader.getClasses(); // to make it easier to reproduce order-dependent failures locally System.out.println("------"); System.out.println("Running tests:"); for (Class<?> aClass : classes) { System.out.println(aClass.getName()); } System.out.println("------"); int totalTests = classes.size(); for (Class<?> aClass : classes) { boolean recording = false; if (myTestRecorder != null && shouldRecord(aClass)) { myTestRecorder.beginRecording(aClass, aClass.getAnnotation(RecordExecution.class)); recording = true; } try { runNextTest(testResult, totalTests, aClass); } finally { if (recording) { myTestRecorder.endRecording(); } } if (testResult.shouldStop()) break; } if (testListener instanceof Closeable) { try { ((Closeable)testListener).close(); } catch (IOException e) { e.printStackTrace(); } } } private static TestListener loadDiscoveryListener() { // com.intellij.InternalTestDiscoveryListener final String discoveryListener = System.getProperty("test.discovery.listener"); if (discoveryListener != null) { try { return (TestListener)Class.forName(discoveryListener).newInstance(); } catch (Throwable e) { return null; } } return null; } private static boolean shouldRecord(@NotNull Class<?> aClass) { return aClass.getAnnotation(RecordExecution.class) != null; } private void loadTestRecorder() { String recorderClassName = System.getProperty("test.recorder.class"); if (recorderClassName != null) { try { Class<?> recorderClass = Class.forName(recorderClassName); myTestRecorder = (TestRecorder) recorderClass.newInstance(); } catch (Exception e) { System.out.println("Error loading test recorder class '" + recorderClassName + "': " + e); } } } private void runNextTest(final TestResult testResult, int totalTests, Class<?> testCaseClass) { myRunTests++; if (testResult.errorCount() + testResult.failureCount() > MAX_FAILURE_TEST_COUNT && MAX_FAILURE_TEST_COUNT >= 0) { addErrorMessage(testResult, "Too many errors. Executed: " + myRunTests + " of " + totalTests); testResult.stop(); return; } log("\nRunning " + testCaseClass.getName()); Test test = getTest(testCaseClass); if (test == null) return; try { test.run(testResult); } catch (Throwable t) { testResult.addError(test, t); } } @Nullable private Test getTest(@NotNull final Class<?> testCaseClass) { try { if ((testCaseClass.getModifiers() & Modifier.PUBLIC) == 0) { return null; } Bombed classBomb = testCaseClass.getAnnotation(Bombed.class); if (classBomb != null && TestFrameworkUtil.bombExplodes(classBomb)) { return new ExplodedBomb(testCaseClass.getName(), classBomb); } Method suiteMethod = safeFindMethod(testCaseClass, "suite"); if (suiteMethod != null && !isPerformanceTestsRun()) { return (Test)suiteMethod.invoke(null, ArrayUtilRt.EMPTY_OBJECT_ARRAY); } if (TestFrameworkUtil.isJUnit4TestClass(testCaseClass, false)) { boolean isPerformanceTest = isPerformanceTest(null, testCaseClass); boolean runEverything = isIncludingPerformanceTestsRun() || isPerformanceTest && isPerformanceTestsRun(); if (runEverything) return createJUnit4Adapter(testCaseClass); final RunWith runWithAnnotation = testCaseClass.getAnnotation(RunWith.class); if (runWithAnnotation != null && Parameterized.class.isAssignableFrom(runWithAnnotation.value())) { if (isPerformanceTestsRun() != isPerformanceTest) { // do not create JUnit4TestAdapter for @Parameterized tests to avoid @Parameters computation - just skip the test return null; } else { return createJUnit4Adapter(testCaseClass); } } JUnit4TestAdapter adapter = createJUnit4Adapter(testCaseClass); try { adapter.filter(NOT_BOMBED.intersect(isPerformanceTestsRun() ? PERFORMANCE_ONLY : NO_PERFORMANCE)); } catch (NoTestsRemainException ignored) { } return adapter; } final int[] testsCount = {0}; TestSuite suite = new TestSuite(testCaseClass) { @Override public void addTest(Test test) { if (!(test instanceof TestCase)) { doAddTest(test); } else { String name = ((TestCase)test).getName(); if ("warning".equals(name)) return; // Mute TestSuite's "no tests found" warning if (!isIncludingPerformanceTestsRun() && (isPerformanceTestsRun() ^ isPerformanceTest(name, testCaseClass))) { return; } Method method = findTestMethod((TestCase)test); Bombed methodBomb = method == null ? null : method.getAnnotation(Bombed.class); if (methodBomb == null) { doAddTest(test); } else if (TestFrameworkUtil.bombExplodes(methodBomb)) { doAddTest(new ExplodedBomb(method.getDeclaringClass().getName() + "." + method.getName(), methodBomb)); } } } private void doAddTest(Test test) { testsCount[0]++; super.addTest(test); } @Nullable private Method findTestMethod(final TestCase testCase) { return safeFindMethod(testCase.getClass(), testCase.getName()); } }; return testsCount[0] > 0 ? suite : null; } catch (Throwable t) { System.err.println("Failed to load test: " + testCaseClass.getName()); t.printStackTrace(System.err); return null; } } @NotNull protected JUnit4TestAdapter createJUnit4Adapter(@NotNull Class<?> testCaseClass) { return new JUnit4TestAdapter(testCaseClass, getJUnit4TestAdapterCache()); } private static JUnit4TestAdapterCache getJUnit4TestAdapterCache() { if (ourUnit4TestAdapterCache == null) { try { //noinspection SpellCheckingInspection ourUnit4TestAdapterCache = (JUnit4TestAdapterCache) Class.forName("org.apache.tools.ant.taskdefs.optional.junit.CustomJUnit4TestAdapterCache") .getMethod("getInstance") .invoke(null); } catch (Exception e) { System.out.println("Failed to create CustomJUnit4TestAdapterCache, the default JUnit4TestAdapterCache will be used" + " and ignored tests won't be properly reported: " + e.toString()); ourUnit4TestAdapterCache = JUnit4TestAdapterCache.getDefault(); } } return ourUnit4TestAdapterCache; } @Nullable private static Method safeFindMethod(Class<?> klass, String name) { return ReflectionUtil.getMethod(klass, name); } private static void log(String message) { TeamCityLogger.info(message); } @SuppressWarnings({"JUnitTestCaseWithNoTests", "JUnitTestClassNamingConvention", "JUnitTestCaseWithNonTrivialConstructors", "UnconstructableJUnitTestCase"}) private static class ExplodedBomb extends TestCase { private final Bombed myBombed; ExplodedBomb(@NotNull String testName, @NotNull Bombed bombed) { super(testName); myBombed = bombed; } @Override protected void runTest() throws Throwable { String description = myBombed.description().isEmpty() ? "" : " (" + myBombed.description() + ")"; fail("Bomb created by " + myBombed.user() + description + " now explodes!"); } } }
platform/testFramework/src/com/intellij/TestAll.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij; import com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory; import com.intellij.idea.Bombed; import com.intellij.idea.RecordExecution; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.testFramework.TeamCityLogger; import com.intellij.testFramework.TestFrameworkUtil; import com.intellij.testFramework.TestLoggerFactory; import com.intellij.tests.ExternalClasspathClassLoader; import com.intellij.util.ArrayUtilRt; import com.intellij.util.ObjectUtils; import com.intellij.util.ReflectionUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.lang.UrlClassLoader; import gnu.trove.THashSet; import junit.framework.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.Parameterized; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import static com.intellij.TestCaseLoader.*; @SuppressWarnings({"UseOfSystemOutOrSystemErr", "CallToPrintStackTrace"}) public class TestAll implements Test { static { Logger.setFactory(TestLoggerFactory.class); } private static final String MAX_FAILURE_TEST_COUNT_FLAG = "idea.max.failure.test.count"; private static final int MAX_FAILURE_TEST_COUNT = Integer.parseInt(ObjectUtils.chooseNotNull( System.getProperty(MAX_FAILURE_TEST_COUNT_FLAG), "150" )); private static final Filter PERFORMANCE_ONLY = new Filter() { @Override public boolean shouldRun(Description description) { String className = description.getClassName(); String methodName = description.getMethodName(); return TestFrameworkUtil.isPerformanceTest(methodName, className); } @Override public String describe() { return "Performance Tests Only"; } }; private static final Filter NO_PERFORMANCE = new Filter() { @Override public boolean shouldRun(Description description) { return !PERFORMANCE_ONLY.shouldRun(description); } @Override public String describe() { return "All Except Performance"; } }; public static final Filter NOT_BOMBED = new Filter() { @Override public boolean shouldRun(Description description) { return !isBombed(description); } @Override public String describe() { return "Not @Bombed"; } private boolean isBombed(Description description) { Bombed bombed = description.getAnnotation(Bombed.class); return bombed != null && !TestFrameworkUtil.bombExplodes(bombed); } }; private final TestCaseLoader myTestCaseLoader; private int myRunTests = -1; private TestRecorder myTestRecorder; private static final List<Throwable> outClassLoadingProblems = new ArrayList<>(); private static JUnit4TestAdapterCache ourUnit4TestAdapterCache; public TestAll(String rootPackage) throws Throwable { this(rootPackage, getClassRoots()); } public TestAll(String rootPackage, List<? extends File> classesRoots) throws ClassNotFoundException { String classFilterName = "tests/testGroups.properties"; myTestCaseLoader = new TestCaseLoader(classFilterName); myTestCaseLoader.addFirstTest(Class.forName("_FirstInSuiteTest")); myTestCaseLoader.addLastTest(Class.forName("_LastInSuiteTest")); myTestCaseLoader.fillTestCases(rootPackage, classesRoots); outClassLoadingProblems.addAll(myTestCaseLoader.getClassLoadingErrors()); } public static List<Throwable> getLoadingClassProblems() { return outClassLoadingProblems; } public static List<File> getClassRoots() { String testRoots = System.getProperty("test.roots"); if (testRoots != null) { System.out.println("Collecting tests from roots specified by test.roots property: " + testRoots); return ContainerUtil.map(testRoots.split(";"), File::new); } List<File> roots = ExternalClasspathClassLoader.getRoots(); if (roots != null) { List<File> excludeRoots = ExternalClasspathClassLoader.getExcludeRoots(); if (excludeRoots != null) { System.out.println("Skipping tests from " + excludeRoots.size() + " roots"); roots = new ArrayList<>(roots); roots.removeAll(new THashSet<>(excludeRoots, FileUtil.FILE_HASHING_STRATEGY)); } System.out.println("Collecting tests from roots specified by classpath.file property: " + roots); return roots; } else { ClassLoader loader = TestAll.class.getClassLoader(); if (loader instanceof URLClassLoader) { return getClassRoots(((URLClassLoader)loader).getURLs()); } if (loader instanceof UrlClassLoader) { List<URL> urls = ((UrlClassLoader)loader).getBaseUrls(); return getClassRoots(urls.toArray(new URL[0])); } return ContainerUtil.map(System.getProperty("java.class.path").split(File.pathSeparator), File::new); } } private static List<File> getClassRoots(URL[] urls) { final List<File> classLoaderRoots = ContainerUtil.map(urls, url -> new File(VfsUtilCore.urlToPath(VfsUtilCore.convertFromUrl(url)))); System.out.println("Collecting tests from " + classLoaderRoots); return classLoaderRoots; } @Override public int countTestCases() { // counting test cases involves parallel directory scan now IdeaForkJoinWorkerThreadFactory.setupForkJoinCommonPool(true); int count = 0; for (Class<?> aClass : myTestCaseLoader.getClasses()) { Test test = getTest(aClass); if (test != null) count += test.countTestCases(); } return count; } private void addErrorMessage(TestResult testResult, String message) { String processedTestsMessage = myRunTests <= 0 ? "None of tests was run" : myRunTests + " tests processed"; try { testResult.startTest(this); testResult.addError(this, new Throwable(processedTestsMessage + " before: " + message)); testResult.endTest(this); } catch (Exception e) { e.printStackTrace(); } } @Override public void run(final TestResult testResult) { loadTestRecorder(); final TestListener testListener = loadDiscoveryListener(); if (testListener != null) { testResult.addListener(testListener); } List<Class<?>> classes = myTestCaseLoader.getClasses(); // to make it easier to reproduce order-dependent failures locally System.out.println("------"); System.out.println("Running tests:"); for (Class<?> aClass : classes) { System.out.println(aClass.getName()); } System.out.println("------"); int totalTests = classes.size(); for (Class<?> aClass : classes) { boolean recording = false; if (myTestRecorder != null && shouldRecord(aClass)) { myTestRecorder.beginRecording(aClass, aClass.getAnnotation(RecordExecution.class)); recording = true; } try { runNextTest(testResult, totalTests, aClass); } finally { if (recording) { myTestRecorder.endRecording(); } } if (testResult.shouldStop()) break; } if (testListener instanceof Closeable) { try { ((Closeable)testListener).close(); } catch (IOException e) { e.printStackTrace(); } } } private static TestListener loadDiscoveryListener() { // com.intellij.InternalTestDiscoveryListener final String discoveryListener = System.getProperty("test.discovery.listener"); if (discoveryListener != null) { try { return (TestListener)Class.forName(discoveryListener).newInstance(); } catch (Throwable e) { return null; } } return null; } private static boolean shouldRecord(@NotNull Class<?> aClass) { return aClass.getAnnotation(RecordExecution.class) != null; } private void loadTestRecorder() { String recorderClassName = System.getProperty("test.recorder.class"); if (recorderClassName != null) { try { Class<?> recorderClass = Class.forName(recorderClassName); myTestRecorder = (TestRecorder) recorderClass.newInstance(); } catch (Exception e) { System.out.println("Error loading test recorder class '" + recorderClassName + "': " + e); } } } private void runNextTest(final TestResult testResult, int totalTests, Class<?> testCaseClass) { myRunTests++; if (testResult.errorCount() + testResult.failureCount() > MAX_FAILURE_TEST_COUNT && MAX_FAILURE_TEST_COUNT > 0) { addErrorMessage(testResult, "Too many errors. Executed: " + myRunTests + " of " + totalTests); testResult.stop(); return; } log("\nRunning " + testCaseClass.getName()); Test test = getTest(testCaseClass); if (test == null) return; try { test.run(testResult); } catch (Throwable t) { testResult.addError(test, t); } } @Nullable private Test getTest(@NotNull final Class<?> testCaseClass) { try { if ((testCaseClass.getModifiers() & Modifier.PUBLIC) == 0) { return null; } Bombed classBomb = testCaseClass.getAnnotation(Bombed.class); if (classBomb != null && TestFrameworkUtil.bombExplodes(classBomb)) { return new ExplodedBomb(testCaseClass.getName(), classBomb); } Method suiteMethod = safeFindMethod(testCaseClass, "suite"); if (suiteMethod != null && !isPerformanceTestsRun()) { return (Test)suiteMethod.invoke(null, ArrayUtilRt.EMPTY_OBJECT_ARRAY); } if (TestFrameworkUtil.isJUnit4TestClass(testCaseClass, false)) { boolean isPerformanceTest = isPerformanceTest(null, testCaseClass); boolean runEverything = isIncludingPerformanceTestsRun() || isPerformanceTest && isPerformanceTestsRun(); if (runEverything) return createJUnit4Adapter(testCaseClass); final RunWith runWithAnnotation = testCaseClass.getAnnotation(RunWith.class); if (runWithAnnotation != null && Parameterized.class.isAssignableFrom(runWithAnnotation.value())) { if (isPerformanceTestsRun() != isPerformanceTest) { // do not create JUnit4TestAdapter for @Parameterized tests to avoid @Parameters computation - just skip the test return null; } else { return createJUnit4Adapter(testCaseClass); } } JUnit4TestAdapter adapter = createJUnit4Adapter(testCaseClass); try { adapter.filter(NOT_BOMBED.intersect(isPerformanceTestsRun() ? PERFORMANCE_ONLY : NO_PERFORMANCE)); } catch (NoTestsRemainException ignored) { } return adapter; } final int[] testsCount = {0}; TestSuite suite = new TestSuite(testCaseClass) { @Override public void addTest(Test test) { if (!(test instanceof TestCase)) { doAddTest(test); } else { String name = ((TestCase)test).getName(); if ("warning".equals(name)) return; // Mute TestSuite's "no tests found" warning if (!isIncludingPerformanceTestsRun() && (isPerformanceTestsRun() ^ isPerformanceTest(name, testCaseClass))) { return; } Method method = findTestMethod((TestCase)test); Bombed methodBomb = method == null ? null : method.getAnnotation(Bombed.class); if (methodBomb == null) { doAddTest(test); } else if (TestFrameworkUtil.bombExplodes(methodBomb)) { doAddTest(new ExplodedBomb(method.getDeclaringClass().getName() + "." + method.getName(), methodBomb)); } } } private void doAddTest(Test test) { testsCount[0]++; super.addTest(test); } @Nullable private Method findTestMethod(final TestCase testCase) { return safeFindMethod(testCase.getClass(), testCase.getName()); } }; return testsCount[0] > 0 ? suite : null; } catch (Throwable t) { System.err.println("Failed to load test: " + testCaseClass.getName()); t.printStackTrace(System.err); return null; } } @NotNull protected JUnit4TestAdapter createJUnit4Adapter(@NotNull Class<?> testCaseClass) { return new JUnit4TestAdapter(testCaseClass, getJUnit4TestAdapterCache()); } private static JUnit4TestAdapterCache getJUnit4TestAdapterCache() { if (ourUnit4TestAdapterCache == null) { try { //noinspection SpellCheckingInspection ourUnit4TestAdapterCache = (JUnit4TestAdapterCache) Class.forName("org.apache.tools.ant.taskdefs.optional.junit.CustomJUnit4TestAdapterCache") .getMethod("getInstance") .invoke(null); } catch (Exception e) { System.out.println("Failed to create CustomJUnit4TestAdapterCache, the default JUnit4TestAdapterCache will be used" + " and ignored tests won't be properly reported: " + e.toString()); ourUnit4TestAdapterCache = JUnit4TestAdapterCache.getDefault(); } } return ourUnit4TestAdapterCache; } @Nullable private static Method safeFindMethod(Class<?> klass, String name) { return ReflectionUtil.getMethod(klass, name); } private static void log(String message) { TeamCityLogger.info(message); } @SuppressWarnings({"JUnitTestCaseWithNoTests", "JUnitTestClassNamingConvention", "JUnitTestCaseWithNonTrivialConstructors", "UnconstructableJUnitTestCase"}) private static class ExplodedBomb extends TestCase { private final Bombed myBombed; ExplodedBomb(@NotNull String testName, @NotNull Bombed bombed) { super(testName); myBombed = bombed; } @Override protected void runTest() throws Throwable { String description = myBombed.description().isEmpty() ? "" : " (" + myBombed.description() + ")"; fail("Bomb created by " + myBombed.user() + description + " now explodes!"); } } }
IDEA-CR-62086 0 is valid value for MAX_FAILURE_TEST_COUNT GitOrigin-RevId: 148d05528b18aeae8ef3e69edbe7519c7d6add6b
platform/testFramework/src/com/intellij/TestAll.java
IDEA-CR-62086 0 is valid value for MAX_FAILURE_TEST_COUNT
<ide><path>latform/testFramework/src/com/intellij/TestAll.java <ide> private void runNextTest(final TestResult testResult, int totalTests, Class<?> testCaseClass) { <ide> myRunTests++; <ide> <del> if (testResult.errorCount() + testResult.failureCount() > MAX_FAILURE_TEST_COUNT && MAX_FAILURE_TEST_COUNT > 0) { <add> if (testResult.errorCount() + testResult.failureCount() > MAX_FAILURE_TEST_COUNT && MAX_FAILURE_TEST_COUNT >= 0) { <ide> addErrorMessage(testResult, "Too many errors. Executed: " + myRunTests + " of " + totalTests); <ide> testResult.stop(); <ide> return;
Java
apache-2.0
765e903e184bc53706a1f3fed425c250ab2a11a0
0
mariosotil/couchbase-lite-java-core,mariosotil/couchbase-lite-java-core,gotmyjobs/couchbase-lite-java-core,Spotme/couchbase-lite-java-core,deleet/couchbase-lite-java-core,mariosotil/couchbase-lite-java-core,netsense-sas/couchbase-lite-java-core,couchbase/couchbase-lite-java-core,4u7/couchbase-lite-java-core
package com.couchbase.cblite.support; import android.util.Log; import com.couchbase.cblite.CBLDatabase; import org.apache.http.util.ByteArrayBuffer; import java.nio.charset.Charset; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class CBLMultipartReader { private static enum CBLMultipartReaderState { kUninitialized, kAtStart, kInPrologue, kInBody, kInHeaders, kAtEnd, kFailed } private static Charset utf8 = Charset.forName("UTF-8"); private static byte[] kCRLFCRLF = new String("\r\n\r\n").getBytes(utf8); private CBLMultipartReaderState state; private ByteArrayBuffer buffer; private String contentType; private byte[] boundary; private CBLMultipartReaderDelegate delegate; public Map<String, String> headers; public CBLMultipartReader(String contentType, CBLMultipartReaderDelegate delegate) { this.contentType = contentType; this.delegate = delegate; this.buffer = new ByteArrayBuffer(1024); this.state = CBLMultipartReaderState.kAtStart; parseContentType(); } public byte[] getBoundary() { return boundary; } public byte[] getBoundaryWithoutLeadingCRLF() { byte[] rawBoundary = getBoundary(); byte[] result = Arrays.copyOfRange(rawBoundary, 2, rawBoundary.length); return result; } public boolean finished() { return state == CBLMultipartReaderState.kAtEnd; } private byte[] eomBytes() { return new String("--").getBytes(Charset.forName("UTF-8")); } private boolean memcmp(byte[] array1, byte[] array2, int len) { boolean equals = true; for (int i=0; i<len; i++) { if (array1[i] != array2[i]) { equals = false; } } return equals; } public Range searchFor(byte[] pattern, int start) { KMPMatch searcher = new KMPMatch(); int matchIndex = searcher.indexOf(buffer, pattern, start); if (matchIndex != -1) { return new Range(matchIndex, pattern.length); } else { return new Range(matchIndex, 0); } } public void parseHeaders(String headersStr) { headers = new HashMap<String, String>(); if (headersStr != null && headersStr.length() > 0) { headersStr = headersStr.trim(); StringTokenizer tokenizer = new StringTokenizer(headersStr, "\r\n"); while (tokenizer.hasMoreTokens()) { String header = tokenizer.nextToken(); if (!header.contains(":")) { throw new IllegalArgumentException("Missing ':' in header line: " + header); } StringTokenizer headerTokenizer = new StringTokenizer(header, ":"); String key = headerTokenizer.nextToken().trim(); String value = headerTokenizer.nextToken().trim(); headers.put(key, value); } } } private void deleteUpThrough(int location) { // int start = location + 1; // start at the first byte after the location byte[] newBuffer = Arrays.copyOfRange(buffer.toByteArray(), location, buffer.length()); buffer.clear(); buffer.append(newBuffer, 0, newBuffer.length); } private void trimBuffer() { int bufLen = buffer.length(); int boundaryLen = getBoundary().length; if (bufLen > boundaryLen) { // Leave enough bytes in _buffer that we can find an incomplete boundary string byte[] dataToAppend = Arrays.copyOfRange(buffer.toByteArray(), 0, bufLen - boundaryLen); delegate.appendToPart(dataToAppend); deleteUpThrough(bufLen - boundaryLen); } } public void appendData(byte[] data) { if (buffer == null) { return; } if (data.length == 0) { return; } buffer.append(data, 0, data.length); CBLMultipartReaderState nextState; do { nextState = CBLMultipartReaderState.kUninitialized; int bufLen = buffer.length(); // Log.d(CBLDatabase.TAG, "appendData. bufLen: " + bufLen); switch (state) { case kAtStart: { // The entire message might start with a boundary without a leading CRLF. byte[] boundaryWithoutLeadingCRLF = getBoundaryWithoutLeadingCRLF(); if (bufLen >= boundaryWithoutLeadingCRLF.length) { // if (Arrays.equals(buffer.toByteArray(), boundaryWithoutLeadingCRLF)) { if (memcmp(buffer.toByteArray(), boundaryWithoutLeadingCRLF, boundaryWithoutLeadingCRLF.length)) { deleteUpThrough(boundaryWithoutLeadingCRLF.length); nextState = CBLMultipartReaderState.kInHeaders; } else { nextState = CBLMultipartReaderState.kInPrologue; } } break; } case kInPrologue: case kInBody: { // Look for the next part boundary in the data we just added and the ending bytes of // the previous data (in case the boundary string is split across calls) if (bufLen < boundary.length) { break; } int start = Math.max(0, bufLen - data.length - boundary.length); Range r = searchFor(boundary, start); if (r.getLength() > 0) { if (state == CBLMultipartReaderState.kInBody) { byte[] dataToAppend = Arrays.copyOfRange(buffer.toByteArray(), 0, r.getLocation()); delegate.appendToPart(dataToAppend); delegate.finishedPart(); } deleteUpThrough(r.getLocation() + r.getLength()); nextState = CBLMultipartReaderState.kInHeaders; } else { trimBuffer(); } break; } case kInHeaders: { // First check for the end-of-message string ("--" after separator): if (bufLen >= 2 && memcmp(buffer.toByteArray(), eomBytes(), 2)) { state = CBLMultipartReaderState.kAtEnd; close(); return; } // Otherwise look for two CRLFs that delimit the end of the headers: Range r = searchFor(kCRLFCRLF, 0); if (r.getLength() > 0) { byte[] headersBytes = Arrays.copyOf(buffer.toByteArray(), r.getLocation()); // byte[] headersBytes = Arrays.copyOfRange(buffer.toByteArray(), 0, r.getLocation()) <-- better? String headersString = new String(headersBytes, utf8); parseHeaders(headersString); deleteUpThrough(r.getLocation() + r.getLength()); delegate.startedPart(headers); nextState = CBLMultipartReaderState.kInBody; } break; } default: { throw new IllegalStateException("Unexpected data after end of MIME body"); } } if (nextState != CBLMultipartReaderState.kUninitialized) { state = nextState; } } while (nextState != CBLMultipartReaderState.kUninitialized && buffer.length() > 0); } private void close() { buffer = null; boundary = null; } private void parseContentType() { StringTokenizer tokenizer = new StringTokenizer(contentType, ";"); boolean first = true; while (tokenizer.hasMoreTokens()) { String param = tokenizer.nextToken().trim(); if (first == true) { if (!param.startsWith("multipart/")) { throw new IllegalArgumentException(contentType + " does not start with multipart/"); } first = false; } else { if (param.startsWith("boundary=")) { String tempBoundary = param.substring(9); if (tempBoundary.startsWith("\"")) { if (tempBoundary.length() < 2 || !tempBoundary.endsWith("\"")) { throw new IllegalArgumentException(contentType + " is not valid"); } tempBoundary = tempBoundary.substring(1, tempBoundary.length()-1); } if (tempBoundary.length() < 1) { throw new IllegalArgumentException(contentType + " has zero-length boundary"); } tempBoundary = String.format("\r\n--%s", tempBoundary); boundary = tempBoundary.getBytes(Charset.forName("UTF-8")); break; } } } } } /** * Knuth-Morris-Pratt Algorithm for Pattern Matching */ class KMPMatch { /** * Finds the first occurrence of the pattern in the text. */ public int indexOf(ByteArrayBuffer data, byte[] pattern, int dataOffset) { int[] failure = computeFailure(pattern); int j = 0; if (data.length() == 0) return -1; for (int i = dataOffset; i < data.length(); i++) { while (j > 0 && pattern[j] != data.byteAt(i)) { j = failure[j - 1]; } if (pattern[j] == data.byteAt(i)) { j++; } if (j == pattern.length) { return i - pattern.length + 1; } } return -1; } /** * Computes the failure function using a boot-strapping process, * where the pattern is matched against itself. */ private int[] computeFailure(byte[] pattern) { int[] failure = new int[pattern.length]; int j = 0; for (int i = 1; i < pattern.length; i++) { while (j > 0 && pattern[j] != pattern[i]) { j = failure[j - 1]; } if (pattern[j] == pattern[i]) { j++; } failure[i] = j; } return failure; } }
src/main/java/com/couchbase/cblite/support/CBLMultipartReader.java
package com.couchbase.cblite.support; import android.util.Log; import com.couchbase.cblite.CBLDatabase; import org.apache.http.util.ByteArrayBuffer; import java.nio.charset.Charset; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class CBLMultipartReader { private static enum CBLMultipartReaderState { kUninitialized, kAtStart, kInPrologue, kInBody, kInHeaders, kAtEnd, kFailed } private static Charset utf8 = Charset.forName("UTF-8"); private static byte[] kCRLFCRLF = new String("\r\n\r\n").getBytes(utf8); private CBLMultipartReaderState state; private ByteArrayBuffer buffer; private String contentType; private byte[] boundary; private CBLMultipartReaderDelegate delegate; public Map<String, String> headers; public CBLMultipartReader(String contentType, CBLMultipartReaderDelegate delegate) { this.contentType = contentType; this.delegate = delegate; this.buffer = new ByteArrayBuffer(1024); this.state = CBLMultipartReaderState.kAtStart; parseContentType(); } public byte[] getBoundary() { return boundary; } public byte[] getBoundaryWithoutLeadingCRLF() { byte[] rawBoundary = getBoundary(); byte[] result = Arrays.copyOfRange(rawBoundary, 2, rawBoundary.length); return result; } public boolean finished() { return state == CBLMultipartReaderState.kAtEnd; } private byte[] eomBytes() { return new String("--").getBytes(Charset.forName("UTF-8")); } private boolean memcmp(byte[] array1, byte[] array2, int len) { boolean equals = true; for (int i=0; i<len; i++) { if (array1[i] != array2[i]) { equals = false; } } return equals; } public Range searchFor(byte[] pattern, int start) { KMPMatch searcher = new KMPMatch(); int matchIndex = searcher.indexOf(buffer, pattern, start); if (matchIndex != -1) { return new Range(matchIndex, pattern.length); } else { return new Range(matchIndex, 0); } } public void parseHeaders(String headersStr) { headers = new HashMap<String, String>(); if (headersStr != null && headersStr.length() > 0) { headersStr = headersStr.trim(); StringTokenizer tokenizer = new StringTokenizer(headersStr, "\r\n"); while (tokenizer.hasMoreTokens()) { String header = tokenizer.nextToken(); if (!header.contains(":")) { throw new IllegalArgumentException("Missing ':' in header line: " + header); } StringTokenizer headerTokenizer = new StringTokenizer(header, ":"); String key = headerTokenizer.nextToken().trim(); String value = headerTokenizer.nextToken().trim(); headers.put(key, value); } } } private void deleteUpThrough(int location) { // int start = location + 1; // start at the first byte after the location byte[] newBuffer = Arrays.copyOfRange(buffer.toByteArray(), location, buffer.length()); buffer.clear(); buffer.append(newBuffer, 0, newBuffer.length); } public void appendData(byte[] data) { if (buffer == null) { return; } if (data.length == 0) { return; } buffer.append(data, 0, data.length); CBLMultipartReaderState nextState; do { nextState = CBLMultipartReaderState.kUninitialized; int bufLen = buffer.length(); // Log.d(CBLDatabase.TAG, "appendData. bufLen: " + bufLen); switch (state) { case kAtStart: { // The entire message might start with a boundary without a leading CRLF. byte[] boundaryWithoutLeadingCRLF = getBoundaryWithoutLeadingCRLF(); if (bufLen >= boundaryWithoutLeadingCRLF.length) { // if (Arrays.equals(buffer.toByteArray(), boundaryWithoutLeadingCRLF)) { if (memcmp(buffer.toByteArray(), boundaryWithoutLeadingCRLF, boundaryWithoutLeadingCRLF.length)) { deleteUpThrough(boundaryWithoutLeadingCRLF.length); nextState = CBLMultipartReaderState.kInHeaders; } else { nextState = CBLMultipartReaderState.kInPrologue; } } break; } case kInPrologue: case kInBody: { // Look for the next part boundary in the data we just added and the ending bytes of // the previous data (in case the boundary string is split across calls) if (bufLen < boundary.length) { break; } int start = Math.max(0, bufLen - data.length - boundary.length); Range r = searchFor(boundary, start); if (r.getLength() > 0) { if (state == CBLMultipartReaderState.kInBody) { byte[] dataToAppend = Arrays.copyOfRange(buffer.toByteArray(), 0, r.getLocation()); delegate.appendToPart(dataToAppend); delegate.finishedPart(); } deleteUpThrough(r.getLocation() + r.getLength()); nextState = CBLMultipartReaderState.kInHeaders; } break; } case kInHeaders: { // First check for the end-of-message string ("--" after separator): if (bufLen >= 2 && memcmp(buffer.toByteArray(), eomBytes(), 2 )) { state = CBLMultipartReaderState.kAtEnd; close(); return; } // Otherwise look for two CRLFs that delimit the end of the headers: Range r = searchFor(kCRLFCRLF, 0); if (r.getLength() > 0) { byte[] headersBytes = Arrays.copyOf(buffer.toByteArray(), r.getLocation()); // byte[] headersBytes = Arrays.copyOfRange(buffer.toByteArray(), 0, r.getLocation()) <-- better? String headersString = new String(headersBytes, utf8); parseHeaders(headersString); deleteUpThrough(r.getLocation() + r.getLength()); delegate.startedPart(headers); nextState = CBLMultipartReaderState.kInBody; } break; } default: { throw new IllegalStateException("Unexpected data after end of MIME body"); } } if (nextState != CBLMultipartReaderState.kUninitialized) { state = nextState; } } while (nextState != CBLMultipartReaderState.kUninitialized && buffer.length() > 0); } private void close() { buffer = null; boundary = null; } private void parseContentType() { StringTokenizer tokenizer = new StringTokenizer(contentType, ";"); boolean first = true; while (tokenizer.hasMoreTokens()) { String param = tokenizer.nextToken().trim(); if (first == true) { if (!param.startsWith("multipart/")) { throw new IllegalArgumentException(contentType + " does not start with multipart/"); } first = false; } else { if (param.startsWith("boundary=")) { String tempBoundary = param.substring(9); if (tempBoundary.startsWith("\"")) { if (tempBoundary.length() < 2 || !tempBoundary.endsWith("\"")) { throw new IllegalArgumentException(contentType + " is not valid"); } tempBoundary = tempBoundary.substring(1, tempBoundary.length()-1); } if (tempBoundary.length() < 1) { throw new IllegalArgumentException(contentType + " has zero-length boundary"); } tempBoundary = String.format("\r\n--%s", tempBoundary); boundary = tempBoundary.getBytes(Charset.forName("UTF-8")); break; } } } } } /** * Knuth-Morris-Pratt Algorithm for Pattern Matching */ class KMPMatch { /** * Finds the first occurrence of the pattern in the text. */ public int indexOf(ByteArrayBuffer data, byte[] pattern, int dataOffset) { int[] failure = computeFailure(pattern); int j = 0; if (data.length() == 0) return -1; for (int i = dataOffset; i < data.length(); i++) { while (j > 0 && pattern[j] != data.byteAt(i)) { j = failure[j - 1]; } if (pattern[j] == data.byteAt(i)) { j++; } if (j == pattern.length) { return i - pattern.length + 1; } } return -1; } /** * Computes the failure function using a boot-strapping process, * where the pattern is matched against itself. */ private int[] computeFailure(byte[] pattern) { int[] failure = new int[pattern.length]; int j = 0; for (int i = 1; i < pattern.length; i++) { while (j > 0 && pattern[j] != pattern[i]) { j = failure[j - 1]; } if (pattern[j] == pattern[i]) { j++; } failure[i] = j; } return failure; } }
Add call to trimbuffer for issue #123 https://github.com/couchbase/couchbase-lite-android/issues/123
src/main/java/com/couchbase/cblite/support/CBLMultipartReader.java
Add call to trimbuffer for issue #123
<ide><path>rc/main/java/com/couchbase/cblite/support/CBLMultipartReader.java <ide> byte[] newBuffer = Arrays.copyOfRange(buffer.toByteArray(), location, buffer.length()); <ide> buffer.clear(); <ide> buffer.append(newBuffer, 0, newBuffer.length); <add> <add> } <add> <add> private void trimBuffer() { <add> int bufLen = buffer.length(); <add> int boundaryLen = getBoundary().length; <add> if (bufLen > boundaryLen) { <add> // Leave enough bytes in _buffer that we can find an incomplete boundary string <add> byte[] dataToAppend = Arrays.copyOfRange(buffer.toByteArray(), 0, bufLen - boundaryLen); <add> delegate.appendToPart(dataToAppend); <add> deleteUpThrough(bufLen - boundaryLen); <add> } <ide> <ide> } <ide> <ide> if (memcmp(buffer.toByteArray(), boundaryWithoutLeadingCRLF, boundaryWithoutLeadingCRLF.length)) { <ide> deleteUpThrough(boundaryWithoutLeadingCRLF.length); <ide> nextState = CBLMultipartReaderState.kInHeaders; <del> } <del> else { <add> } else { <ide> nextState = CBLMultipartReaderState.kInPrologue; <ide> } <ide> } <ide> } <ide> deleteUpThrough(r.getLocation() + r.getLength()); <ide> nextState = CBLMultipartReaderState.kInHeaders; <add> } else { <add> trimBuffer(); <ide> } <ide> break; <ide> } <ide> case kInHeaders: { <ide> // First check for the end-of-message string ("--" after separator): <ide> if (bufLen >= 2 && <del> memcmp(buffer.toByteArray(), eomBytes(), 2 )) { <add> memcmp(buffer.toByteArray(), eomBytes(), 2)) { <ide> state = CBLMultipartReaderState.kAtEnd; <ide> close(); <ide> return;
Java
apache-2.0
14b1b47b162009854eb6566eb233c1a783ff643b
0
bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball
package com.btr3.service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Base64; import java.io.UnsupportedEncodingException; import com.amazonaws.services.cloudformation.AmazonCloudFormationClient; import com.amazonaws.services.cloudformation.model.DescribeStackResourceRequest; import com.amazonaws.services.ecs.AmazonECSClient; import com.amazonaws.services.ecs.model.ContainerOverride; import com.amazonaws.services.ecs.model.Failure; import com.amazonaws.services.ecs.model.RunTaskRequest; import com.amazonaws.services.ecs.model.RunTaskResult; import com.amazonaws.services.ecs.model.TaskOverride; import org.apache.commons.logging.impl.Log4JLogger; import org.apache.log4j.Logger; public class ExportService { private static Logger log = Logger.getLogger(Log4JLogger.class.getName()); private AmazonECSClient ecsClient = new AmazonECSClient(); private AmazonCloudFormationClient cloudformationClient = new AmazonCloudFormationClient(); private String getClusterId() { DescribeStackResourceRequest dsrr = new DescribeStackResourceRequest().withStackName("BTR-standard") .withLogicalResourceId("ECSCluster"); return cloudformationClient.describeStackResource(dsrr).getStackResourceDetail().getPhysicalResourceId(); } private String getWorkerTaskId() { DescribeStackResourceRequest dsrr = new DescribeStackResourceRequest().withStackName("baseball-dev") .withLogicalResourceId("WorkerTaskDefinition"); return cloudformationClient.describeStackResource(dsrr).getStackResourceDetail() .getPhysicalResourceId(); } public String getExportMetadata() { return new String("[{\n" + " \"name\": \"table\",\n" + " \"fields\": [\n" + " {\n" + " \"name\": \"orderBy\",\n" + " \"desc\": \"Order By\",\n" + " \"values\":\"selected\"\n" + " },\n" + " {\n" + " \"name\":\"direction\",\n" + " \"desc\":\"Direction\",\n" + " \"values\":[\n" + " {\"id\":\"desc\", \"name\": \"Descending\"},\n" + " {\"id\":\"asc\", \"name\":\"Ascending\"}\n" + " ]\n" + " }\n" + " ]\n" + " }]"); } public Map<String,String> submitJob(String jobDetails) { log.info("Job submitted with the criteria: " + jobDetails); Map<String,String> jobResult = new HashMap<String,String>(); // Get a unique id for this job String jobId = "stupid.csv"; // Base64 encode the job details String encoded = ""; try { encoded = Base64.getEncoder().encodeToString(jobDetails.getBytes("utf-8")); } catch(UnsupportedEncodingException e){ log.error("Could not encode:" + e.getMessage()); jobResult.put("Status", "Failed"); return jobResult; } ContainerOverride cor = new ContainerOverride().withCommand("/bin/bash", "-c", "stupid.csv", encoded); TaskOverride tor = new TaskOverride().withContainerOverrides(cor); RunTaskRequest rtr = new RunTaskRequest(); rtr.withTaskDefinition(getWorkerTaskId()); rtr.withCluster(getClusterId()); rtr.setOverrides(tor); RunTaskResult result = ecsClient.runTask(rtr); List<Failure> failures = result.getFailures(); if(failures.size()>0){ jobResult.put("Status", "Failed"); StringBuilder errors = new StringBuilder(); errors.append("Failures encountered when submitting export with details " + jobDetails + ".\r\n"); for(Failure failure : failures){ errors.append(failure.getReason() + "\r\n"); } log.error(errors.toString()); return jobResult; } jobResult.put("Status", "Success"); return jobResult; } }
api/src/main/java/com/btr3/service/ExportService.java
package com.btr3.service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Base64; import java.io.UnsupportedEncodingException; import com.amazonaws.services.cloudformation.AmazonCloudFormationClient; import com.amazonaws.services.cloudformation.model.DescribeStackResourceRequest; import com.amazonaws.services.ecs.AmazonECSClient; import com.amazonaws.services.ecs.model.ContainerOverride; import com.amazonaws.services.ecs.model.Failure; import com.amazonaws.services.ecs.model.RunTaskRequest; import com.amazonaws.services.ecs.model.RunTaskResult; import com.amazonaws.services.ecs.model.TaskOverride; import org.apache.commons.logging.impl.Log4JLogger; import org.apache.log4j.Logger; public class ExportService { private static Logger log = Logger.getLogger(Log4JLogger.class.getName()); private AmazonECSClient ecsClient = new AmazonECSClient(); private AmazonCloudFormationClient cloudformationClient = new AmazonCloudFormationClient(); private String getClusterId() { DescribeStackResourceRequest dsrr = new DescribeStackResourceRequest().withStackName("BTR-standard") .withLogicalResourceId("ECSCluster"); return cloudformationClient.describeStackResource(dsrr).getStackResourceDetail().getPhysicalResourceId(); } private String getWorkerTaskId() { DescribeStackResourceRequest dsrr = new DescribeStackResourceRequest().withStackName("baseball-dev") .withLogicalResourceId("WorkerTaskDefinition"); return cloudformationClient.describeStackResource(dsrr).getStackResourceDetail() .getPhysicalResourceId(); } public String getExportMetadata() { return new String("[{\n" + " \"name\": \"table\",\n" + " \"fields\": [\n" + " {\n" + " \"name\": \"orderBy\",\n" + " \"desc\": \"Order By\",\n" + " \"values\":\"selected\"\n" + " },\n" + " {\n" + " \"name\":\"direction\",\n" + " \"desc\":\"Direction\",\n" + " \"values\":[\n" + " {\"id\":\"desc\", \"name\": \"Descending\"},\n" + " {\"id\":\"asc\", \"name\":\"Ascending\"}\n" + " ]\n" + " }\n" + " ]\n" + " }]"); } public Map<String,String> submitJob(String jobDetails) { log.info("Job submitted with the criteria: " + jobDetails); Map<String,String> jobResult = new HashMap<String,String>(); // Get a unique id for this job String jobId = "stupid.csv"; // Base64 encode the job details try { String encoded = Base64.getEncoder().encodeToString(jobDetails.getBytes("utf-8")); } catch(UnsupportedEncodingException e){ log.error("Could not encode:" + e.getMessage()); jobResult.put("Status", "Failed"); return jobResult; } ContainerOverride cor = new ContainerOverride().withCommand("/bin/bash", "-c", "stupid.csv", encoded); TaskOverride tor = new TaskOverride().withContainerOverrides(cor); RunTaskRequest rtr = new RunTaskRequest(); rtr.withTaskDefinition(getWorkerTaskId()); rtr.withCluster(getClusterId()); rtr.setOverrides(tor); RunTaskResult result = ecsClient.runTask(rtr); List<Failure> failures = result.getFailures(); if(failures.size()>0){ jobResult.put("Status", "Failed"); StringBuilder errors = new StringBuilder(); errors.append("Failures encountered when submitting export with details " + jobDetails + ".\r\n"); for(Failure failure : failures){ errors.append(failure.getReason() + "\r\n"); } log.error(errors.toString()); return jobResult; } jobResult.put("Status", "Success"); return jobResult; } }
More checked exception bs
api/src/main/java/com/btr3/service/ExportService.java
More checked exception bs
<ide><path>pi/src/main/java/com/btr3/service/ExportService.java <ide> String jobId = "stupid.csv"; <ide> <ide> // Base64 encode the job details <add> String encoded = ""; <ide> try { <del> String encoded = Base64.getEncoder().encodeToString(jobDetails.getBytes("utf-8")); <add> encoded = Base64.getEncoder().encodeToString(jobDetails.getBytes("utf-8")); <ide> } catch(UnsupportedEncodingException e){ <ide> log.error("Could not encode:" + e.getMessage()); <ide> jobResult.put("Status", "Failed");
Java
agpl-3.0
121bca49ca8da4278aa02fd32dc63a310dfe5184
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
3ddce3dc-2e60-11e5-9284-b827eb9e62be
hello.java
3dd77e42-2e60-11e5-9284-b827eb9e62be
3ddce3dc-2e60-11e5-9284-b827eb9e62be
hello.java
3ddce3dc-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>3dd77e42-2e60-11e5-9284-b827eb9e62be <add>3ddce3dc-2e60-11e5-9284-b827eb9e62be
Java
agpl-3.0
6a36a15e1b6dcb6db2d1e191563ffdba531e8036
0
geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-server,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt2
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the Apache * License, Version 2.0. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.sld.editor.expert.server.service; import java.io.File; import java.io.FilenameFilter; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; import org.apache.commons.io.FileUtils; import org.geomajas.sld.NamedLayerInfo; import org.geomajas.sld.StyledLayerDescriptorInfo; import org.geomajas.sld.UserLayerInfo; import org.geomajas.sld.editor.expert.client.domain.RawSld; import org.geomajas.sld.editor.expert.client.domain.SldInfo; import org.geomajas.sld.editor.expert.client.domain.SldInfoImpl; import org.geomajas.sld.service.SldException; import org.jibx.runtime.BindingDirectory; import org.jibx.runtime.IBindingFactory; import org.jibx.runtime.IMarshallingContext; import org.jibx.runtime.IUnmarshallingContext; import org.jibx.runtime.JiBXException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; /** * Default implementation of the SLD service using an in-memory map. This service loads a configurable directory of SLD * files at startup. * * @author Jan De Moerloose * @author An Buyle */ public class InMemorySldServiceImpl implements org.geomajas.sld.editor.expert.server.service.SldService { private final Logger log = LoggerFactory.getLogger(InMemorySldServiceImpl.class); private static final String FILE_ENCODING = "UTF-8"; private Map<String, RawSld> allSlds = new ConcurrentHashMap<String, RawSld>(); private Resource directory; @PostConstruct void init() throws SldException { if (getDirectory() != null) { try { if (getDirectory().getFile().exists()) { if (getDirectory().getFile().isDirectory()) { File[] sldFiles = getDirectory().getFile().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".sld") || name.endsWith(".xml"); } }); for (File file : sldFiles) { RawSld raw = new RawSld(); raw.setXml(FileUtils.readFileToString(file, FILE_ENCODING)); String fileName = StringUtils.stripFilenameExtension(file.getName()); StyledLayerDescriptorInfo tmp = parseXml(fileName, raw.getXml()); raw.setName(fileName); raw.setTitle(tmp.getTitle()); raw.setVersion(tmp.getVersion()); log.info("added sld '{}' to service", fileName); allSlds.put(raw.getName(), raw); } } } } catch (Exception e) { // NOSONAR throw new SldException("Could not initialize SLD service", e); } } } // --------------------------------------------------------------- public Resource getDirectory() { return directory; } public void setDirectory(Resource directory) { this.directory = directory; } public List<SldInfo> findTemplates() throws SldException { List<SldInfo> res = new ArrayList<SldInfo>(); for (RawSld raw : allSlds.values()) { res.add(new SldInfoImpl(raw.getName(), raw.getTitle())); } return res; } public RawSld findTemplateByName(String name) throws SldException { return allSlds.get(name); } /** * Convert StyledLayerDescriptorInfo to raw xml. * * @param sldi * @return rawSld * @throws SldException */ public RawSld toXml(StyledLayerDescriptorInfo sldi) throws SldException { try { if (sldi.getVersion() == null) { sldi.setVersion("1.0.0"); } return parseSldI(sldi); } catch (JiBXException e) { throw new SldException("Validation error", e); } } /** * Convert raw xml to StyledLayerDescriptorInfo. * * @param sld * @return StyledLayerDescriptorInfo * @throws SldException */ public StyledLayerDescriptorInfo toSldI(RawSld sld) throws SldException { try { return parseXml(sld.getName(), sld.getXml()); } catch (JiBXException e) { throw new SldException("Validation error", e); } } /** * Test by marshalling. * * @param sld * @throws SldException */ public void validate(StyledLayerDescriptorInfo sld) throws SldException { try { parseSldI(sld); } catch (JiBXException e) { throw new SldException("Validation error", e); } } /** * Test by unmarshalling. * * @param sld * @throws SldException */ public boolean validate(RawSld sld) throws SldException { try { parseXml("", sld.getXml()); return true; } catch (JiBXException e) { return false; } } // --------------------------------------------------------------- private StyledLayerDescriptorInfo parseXml(String name, String raw) throws JiBXException { IBindingFactory bfact = BindingDirectory.getFactory(StyledLayerDescriptorInfo.class); IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); Object object = uctx.unmarshalDocument(new StringReader(raw)); StyledLayerDescriptorInfo sld = (StyledLayerDescriptorInfo) object; if (sld.getName() == null) { sld.setName(name); } if (sld.getTitle() == null) { sld.setTitle(getTitle(sld, name)); } if (sld.getVersion() == null) { sld.setVersion("1.0.0"); } return sld; } private RawSld parseSldI(StyledLayerDescriptorInfo sld) throws JiBXException { RawSld res = new RawSld(); IBindingFactory bfact; bfact = BindingDirectory.getFactory(StyledLayerDescriptorInfo.class); IMarshallingContext mctx = bfact.createMarshallingContext(); StringWriter writer = new StringWriter(); mctx.setOutput(writer); mctx.getXmlWriter().setIndentSpaces(2, "\n", ' '); mctx.marshalDocument(sld); res.setXml(writer.toString()); res.setName(sld.getName()); res.setVersion(sld.getVersion()); res.setTitle(sld.getTitle() == null ? getTitle(sld, "?") : sld.getTitle()); return res; } private String getTitle(StyledLayerDescriptorInfo sld, String fallback) { if (sld.getChoiceList() != null && sld.getChoiceList().size() > 0) { NamedLayerInfo nli = sld.getChoiceList().get(0).getNamedLayer(); if (nli != null && nli.getName() != null) { return nli.getName(); } UserLayerInfo uli = sld.getChoiceList().get(0).getUserLayer(); if (uli != null && uli.getName() != null) { return uli.getName(); } } return fallback; } }
project/geomajas-project-sld-editor/expert-gwt/src/main/java/org/geomajas/sld/editor/expert/server/service/InMemorySldServiceImpl.java
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2013 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the Apache * License, Version 2.0. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.sld.editor.expert.server.service; import java.io.File; import java.io.FilenameFilter; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; import org.apache.commons.io.FileUtils; import org.geomajas.sld.NamedLayerInfo; import org.geomajas.sld.StyledLayerDescriptorInfo; import org.geomajas.sld.UserLayerInfo; import org.geomajas.sld.editor.expert.client.domain.RawSld; import org.geomajas.sld.editor.expert.client.domain.SldInfo; import org.geomajas.sld.editor.expert.client.domain.SldInfoImpl; import org.geomajas.sld.service.SldException; import org.jibx.runtime.BindingDirectory; import org.jibx.runtime.IBindingFactory; import org.jibx.runtime.IMarshallingContext; import org.jibx.runtime.IUnmarshallingContext; import org.jibx.runtime.JiBXException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; /** * Default implementation of the SLD service using an in-memory map. This service loads a configurable directory of SLD * files at startup. * * @author Jan De Moerloose * @author An Buyle */ public class InMemorySldServiceImpl implements org.geomajas.sld.editor.expert.server.service.SldService { private final Logger log = LoggerFactory.getLogger(InMemorySldServiceImpl.class); private static final String FILE_ENCODING = "UTF-8"; private Map<String, RawSld> allSlds = new ConcurrentHashMap<String, RawSld>(); private Resource directory; @PostConstruct void init() throws SldException { if (getDirectory() != null) { try { if (getDirectory().getFile().exists()) { if (getDirectory().getFile().isDirectory()) { File[] sldFiles = getDirectory().getFile().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".sld") || name.endsWith(".xml"); } }); for (File file : sldFiles) { RawSld raw = new RawSld(); raw.setXml(FileUtils.readFileToString(file, FILE_ENCODING)); String fileName = StringUtils.stripFilenameExtension(file.getName()); StyledLayerDescriptorInfo tmp = parseXml(fileName, raw.getXml()); raw.setName(fileName); raw.setTitle(tmp.getTitle()); raw.setVersion(tmp.getVersion()); log.info("added sld '{}' to service", fileName); allSlds.put(raw.getName(), raw); } } } } catch (Exception e) { // NOSONAR throw new SldException("Could not initialize SLD service", e); } } } // --------------------------------------------------------------- public Resource getDirectory() { return directory; } public void setDirectory(Resource directory) { this.directory = directory; } public List<SldInfo> findTemplates() throws SldException { List<SldInfo> res = new ArrayList<SldInfo>(); for (RawSld raw : allSlds.values()) { res.add(new SldInfoImpl(raw.getName(), raw.getTitle())); } return res; } public RawSld findTemplateByName(String name) throws SldException { return allSlds.get(name); } /** * Convert StyledLayerDescriptorInfo to raw xml. * * @param sldi * @return rawSld * @throws SldException */ public RawSld toXml(StyledLayerDescriptorInfo sldi) throws SldException { try { return parseSldI(sldi); } catch (JiBXException e) { throw new SldException("Validation error", e); } } /** * Convert raw xml to StyledLayerDescriptorInfo. * * @param sld * @return StyledLayerDescriptorInfo * @throws SldException */ public StyledLayerDescriptorInfo toSldI(RawSld sld) throws SldException { try { return parseXml(sld.getName(), sld.getXml()); } catch (JiBXException e) { throw new SldException("Validation error", e); } } /** * Test by marshalling. * * @param sld * @throws SldException */ public void validate(StyledLayerDescriptorInfo sld) throws SldException { try { parseSldI(sld); } catch (JiBXException e) { throw new SldException("Validation error", e); } } /** * Test by unmarshalling. * * @param sld * @throws SldException */ public boolean validate(RawSld sld) throws SldException { try { parseXml("", sld.getXml()); return true; } catch (JiBXException e) { return false; } } // --------------------------------------------------------------- private StyledLayerDescriptorInfo parseXml(String name, String raw) throws JiBXException { IBindingFactory bfact = BindingDirectory.getFactory(StyledLayerDescriptorInfo.class); IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); Object object = uctx.unmarshalDocument(new StringReader(raw)); StyledLayerDescriptorInfo sld = (StyledLayerDescriptorInfo) object; if (sld.getName() == null) { sld.setName(name); } if (sld.getTitle() == null) { sld.setTitle(getTitle(sld, name)); } return sld; } private RawSld parseSldI(StyledLayerDescriptorInfo sld) throws JiBXException { RawSld res = new RawSld(); IBindingFactory bfact; bfact = BindingDirectory.getFactory(StyledLayerDescriptorInfo.class); IMarshallingContext mctx = bfact.createMarshallingContext(); StringWriter writer = new StringWriter(); mctx.setOutput(writer); mctx.marshalDocument(sld); res.setXml(writer.toString()); res.setName(sld.getName()); res.setTitle(sld.getTitle() == null ? getTitle(sld, "?") : sld.getTitle()); return res; } private String getTitle(StyledLayerDescriptorInfo sld, String fallback) { if (sld.getChoiceList() != null && sld.getChoiceList().size() > 0) { NamedLayerInfo nli = sld.getChoiceList().get(0).getNamedLayer(); if (nli != null && nli.getName() != null) { return nli.getName(); } UserLayerInfo uli = sld.getChoiceList().get(0).getUserLayer(); if (uli != null && uli.getName() != null) { return uli.getName(); } } return fallback; } }
SLDE-14: pretty print XML, be more lenient on SLD-version property.
project/geomajas-project-sld-editor/expert-gwt/src/main/java/org/geomajas/sld/editor/expert/server/service/InMemorySldServiceImpl.java
SLDE-14: pretty print XML, be more lenient on SLD-version property.
<ide><path>roject/geomajas-project-sld-editor/expert-gwt/src/main/java/org/geomajas/sld/editor/expert/server/service/InMemorySldServiceImpl.java <ide> */ <ide> public RawSld toXml(StyledLayerDescriptorInfo sldi) throws SldException { <ide> try { <add> if (sldi.getVersion() == null) { <add> sldi.setVersion("1.0.0"); <add> } <ide> return parseSldI(sldi); <ide> } catch (JiBXException e) { <ide> throw new SldException("Validation error", e); <ide> if (sld.getTitle() == null) { <ide> sld.setTitle(getTitle(sld, name)); <ide> } <add> if (sld.getVersion() == null) { <add> sld.setVersion("1.0.0"); <add> } <ide> return sld; <ide> } <ide> <ide> IMarshallingContext mctx = bfact.createMarshallingContext(); <ide> StringWriter writer = new StringWriter(); <ide> mctx.setOutput(writer); <add> mctx.getXmlWriter().setIndentSpaces(2, "\n", ' '); <ide> mctx.marshalDocument(sld); <ide> res.setXml(writer.toString()); <ide> res.setName(sld.getName()); <add> res.setVersion(sld.getVersion()); <ide> res.setTitle(sld.getTitle() == null ? getTitle(sld, "?") : sld.getTitle()); <ide> return res; <ide> }
Java
agpl-3.0
error: pathspec 'algos/addition.java' did not match any file(s) known to git
87c52d380d4ccb801dfd2dd0c64e1291f2b44f93
1
oliverwreath/Algorithms,oliverwreath/Algorithms,oliverwreath/Algorithms
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package algos; import java.io.*; /** * * @author HunterX */ public class Basic { /** * @param args the command line arguments */ public static int[] swap(int a, int b){ a = a^b; b = a^b; a = a^b; return (new int[] {a, b}); } public static int addition( int a, int b ){ if( b == 0 ){ return a; } int sum = a^b; int carry = (a&b)<<1; return addition(sum, carry); } public static void main(String[] args) throws IOException{ // TODO code application logic here BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); int a = 345678; int b = 7654321; int [] ret = {0,0}; for(int i = 1; i <= 9 ; i++){ for(int j = 1; j <= 99 ; j++){ ret = swap(a, b); } } System.out.println(ret[0]+" "+ret[1]); int ret2 = addition(a, b); System.out.println(ret2); return ; } }
algos/addition.java
Create addition.java
algos/addition.java
Create addition.java
<ide><path>lgos/addition.java <add>/* <add> * To change this template, choose Tools | Templates <add> * and open the template in the editor. <add> */ <add>package algos; <add>import java.io.*; <add> <add>/** <add> * <add> * @author HunterX <add> */ <add>public class Basic { <add> <add> /** <add> * @param args the command line arguments <add> */ <add> <add> public static int[] swap(int a, int b){ <add> a = a^b; <add> b = a^b; <add> a = a^b; <add> return (new int[] {a, b}); <add> } <add> <add> public static int addition( int a, int b ){ <add> if( b == 0 ){ <add> return a; <add> } <add> int sum = a^b; <add> int carry = (a&b)<<1; <add> return addition(sum, carry); <add> } <add> <add> public static void main(String[] args) throws IOException{ <add> // TODO code application logic here <add> BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); <add> int a = 345678; <add> int b = 7654321; <add> int [] ret = {0,0}; <add> for(int i = 1; i <= 9 ; i++){ <add> for(int j = 1; j <= 99 ; j++){ <add> ret = swap(a, b); <add> } <add> } <add> System.out.println(ret[0]+" "+ret[1]); <add> int ret2 = addition(a, b); <add> System.out.println(ret2); <add> return ; <add> } <add>}
Java
apache-2.0
7b31effcb460a0a88cbe8c89a277e999fb54d38e
0
AlienQueen/wicket,selckin/wicket,topicusonderwijs/wicket,aldaris/wicket,freiheit-com/wicket,astrapi69/wicket,dashorst/wicket,topicusonderwijs/wicket,AlienQueen/wicket,freiheit-com/wicket,klopfdreh/wicket,astrapi69/wicket,aldaris/wicket,topicusonderwijs/wicket,apache/wicket,AlienQueen/wicket,dashorst/wicket,aldaris/wicket,selckin/wicket,mafulafunk/wicket,mosoft521/wicket,mosoft521/wicket,mosoft521/wicket,bitstorm/wicket,bitstorm/wicket,AlienQueen/wicket,bitstorm/wicket,bitstorm/wicket,klopfdreh/wicket,klopfdreh/wicket,bitstorm/wicket,selckin/wicket,mafulafunk/wicket,AlienQueen/wicket,apache/wicket,freiheit-com/wicket,astrapi69/wicket,klopfdreh/wicket,selckin/wicket,apache/wicket,mafulafunk/wicket,topicusonderwijs/wicket,freiheit-com/wicket,apache/wicket,dashorst/wicket,topicusonderwijs/wicket,mosoft521/wicket,apache/wicket,aldaris/wicket,aldaris/wicket,dashorst/wicket,dashorst/wicket,freiheit-com/wicket,mosoft521/wicket,selckin/wicket,klopfdreh/wicket,astrapi69/wicket
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.core.util.lang; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.OutputStream; import java.io.Serializable; import java.util.HashMap; import org.apache.wicket.Application; import org.apache.wicket.Component; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.application.IClassResolver; import org.apache.wicket.model.IDetachable; import org.apache.wicket.serialize.ISerializer; import org.apache.wicket.serialize.java.JavaSerializer; import org.apache.wicket.settings.IApplicationSettings; import org.apache.wicket.util.io.ByteCountingOutputStream; import org.apache.wicket.util.lang.Generics; import org.apache.wicket.util.string.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Object (de)serialization utilities. */ public class WicketObjects { /** log. */ private static final Logger log = LoggerFactory.getLogger(WicketObjects.class); private WicketObjects() { } /** * @param <T> * class type * @param className * Class to resolve * @return Resolved class * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") public static <T> Class<T> resolveClass(final String className) { Class<T> resolved = null; try { if (Application.exists()) { resolved = (Class<T>)Application.get() .getApplicationSettings() .getClassResolver() .resolveClass(className); } if (resolved == null) { resolved = (Class<T>)Class.forName(className, false, Thread.currentThread() .getContextClassLoader()); } } catch (ClassNotFoundException cnfx) { log.warn("Could not resolve class [" + className + "]", cnfx); } return resolved; } /** * Interface that enables users to plugin the way object sizes are calculated with Wicket. */ public static interface IObjectSizeOfStrategy { /** * Computes the size of an object. This typically is an estimation, not an absolute accurate * size. * * @param object * The serializable object to compute size of * @return The size of the object in bytes. */ long sizeOf(Serializable object); } /** * {@link IObjectSizeOfStrategy} that works by serializing the object to an instance of * {@link ByteCountingOutputStream}, which records the number of bytes written to it. Hence, * this gives the size of the object as it would be serialized,including all the overhead of * writing class headers etc. Not very accurate (the real memory consumption should be lower) * but the best we can do in a cheap way pre JDK 5. */ public static final class SerializingObjectSizeOfStrategy implements IObjectSizeOfStrategy { @Override public long sizeOf(Serializable object) { if (object == null) { return 0; } ISerializer serializer; if (Application.exists()) { serializer = Application.get().getFrameworkSettings().getSerializer(); } else { serializer = new JavaSerializer("SerializingObjectSizeOfStrategy"); } byte[] serialized = serializer.serialize(object); int size = -1; if (serialized != null) { size = serialized.length; } return size; } } private static final class ReplaceObjectInputStream extends ObjectInputStream { private final ClassLoader classloader; private final HashMap<String, Component> replacedComponents; private ReplaceObjectInputStream(InputStream in, HashMap<String, Component> replacedComponents, ClassLoader classloader) throws IOException { super(in); this.replacedComponents = replacedComponents; this.classloader = classloader; enableResolveObject(true); } // This override is required to resolve classes inside in different // bundle, i.e. // The classes can be resolved by OSGI classresolver implementation @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String className = desc.getName(); try { return Class.forName(className, true, classloader); } catch (ClassNotFoundException ex1) { // ignore this exception. log.debug("Class not found by using objects own classloader, trying the IClassResolver"); } Application application = Application.get(); IApplicationSettings applicationSettings = application.getApplicationSettings(); IClassResolver classResolver = applicationSettings.getClassResolver(); Class<?> candidate = null; try { candidate = classResolver.resolveClass(className); if (candidate == null) { candidate = super.resolveClass(desc); } } catch (WicketRuntimeException ex) { if (ex.getCause() instanceof ClassNotFoundException) { throw (ClassNotFoundException)ex.getCause(); } } return candidate; } @Override protected Object resolveObject(Object obj) throws IOException { Object replaced = replacedComponents.get(obj); if (replaced != null) { return replaced; } return super.resolveObject(obj); } } private static final class ReplaceObjectOutputStream extends ObjectOutputStream { private final HashMap<String, Component> replacedComponents; private ReplaceObjectOutputStream(OutputStream out, HashMap<String, Component> replacedComponents) throws IOException { super(out); this.replacedComponents = replacedComponents; enableReplaceObject(true); } @Override protected Object replaceObject(Object obj) throws IOException { if (obj instanceof Component) { final Component component = (Component)obj; String name = component.getPath(); replacedComponents.put(name, component); return name; } return super.replaceObject(obj); } } /** * Makes a deep clone of an object by serializing and deserializing it. The object must be fully * serializable to be cloned. This method will not clone wicket Components, it will just reuse * those instances so that the complete component tree is not copied over only the model data. * * @param object * The object to clone * @return A deep copy of the object */ public static Object cloneModel(final Object object) { if (object == null) { return null; } else { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(256); final HashMap<String, Component> replacedObjects = Generics.newHashMap(); ObjectOutputStream oos = new ReplaceObjectOutputStream(out, replacedObjects); oos.writeObject(object); ObjectInputStream ois = new ReplaceObjectInputStream(new ByteArrayInputStream( out.toByteArray()), replacedObjects, object.getClass().getClassLoader()); return ois.readObject(); } catch (ClassNotFoundException e) { throw new WicketRuntimeException("Internal error cloning object", e); } catch (IOException e) { throw new WicketRuntimeException("Internal error cloning object", e); } } } /** * Strategy for calculating sizes of objects. Note: I didn't make this an application setting as * we have enough of those already, and the typical way this probably would be used is that * install a different one according to the JDK version used, so varying them between * applications doesn't make a lot of sense. */ private static IObjectSizeOfStrategy objectSizeOfStrategy = new SerializingObjectSizeOfStrategy(); /** * Makes a deep clone of an object by serializing and deserializing it. The object must be fully * serializable to be cloned. No extra debug info is gathered. * * @param object * The object to clone * @return A deep copy of the object * @see #cloneModel(Object) */ public static Object cloneObject(final Object object) { if (object == null) { return null; } else { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(256); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(object); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream( out.toByteArray())) { // This override is required to resolve classes inside in different bundle, i.e. // The classes can be resolved by OSGI classresolver implementation @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String className = desc.getName(); try { return Class.forName(className, true, object.getClass() .getClassLoader()); } catch (ClassNotFoundException ex1) { // ignore this exception. log.debug("Class not found by using objects own classloader, trying the IClassResolver"); } Application application = Application.get(); IApplicationSettings applicationSettings = application.getApplicationSettings(); IClassResolver classResolver = applicationSettings.getClassResolver(); Class<?> candidate = null; try { candidate = classResolver.resolveClass(className); if (candidate == null) { candidate = super.resolveClass(desc); } } catch (WicketRuntimeException ex) { if (ex.getCause() instanceof ClassNotFoundException) { throw (ClassNotFoundException)ex.getCause(); } } return candidate; } }; return ois.readObject(); } catch (ClassNotFoundException e) { throw new WicketRuntimeException("Internal error cloning object", e); } catch (IOException e) { throw new WicketRuntimeException("Internal error cloning object", e); } } } /** * Creates a new instance using the current application's class resolver. Returns null if * className is null. * * @param className * The full class name * @return The new object instance */ public static Object newInstance(final String className) { if (!Strings.isEmpty(className)) { try { Class<?> c = WicketObjects.resolveClass(className); return c.newInstance(); } catch (Exception e) { throw new WicketRuntimeException("Unable to create " + className, e); } } return null; } /** * Sets the strategy for determining the sizes of objects. * * @param objectSizeOfStrategy * the strategy. Pass null to reset to the default. */ public static void setObjectSizeOfStrategy(IObjectSizeOfStrategy objectSizeOfStrategy) { if (objectSizeOfStrategy == null) { WicketObjects.objectSizeOfStrategy = new SerializingObjectSizeOfStrategy(); } else { WicketObjects.objectSizeOfStrategy = objectSizeOfStrategy; } log.info("using " + objectSizeOfStrategy + " for calculating object sizes"); } /** * Computes the size of an object. Note that this is an estimation, never an absolute accurate * size. * * @param object * Object to compute size of * @return The size of the object in bytes */ public static long sizeof(final Serializable object) { if (object instanceof Component) { ((Component) object).detach(); } else if (object instanceof IDetachable) { ((IDetachable) object).detach(); } return objectSizeOfStrategy.sizeOf(object); } }
wicket-core/src/main/java/org/apache/wicket/core/util/lang/WicketObjects.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.core.util.lang; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.OutputStream; import java.io.Serializable; import java.util.HashMap; import org.apache.wicket.Application; import org.apache.wicket.Component; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.application.IClassResolver; import org.apache.wicket.serialize.ISerializer; import org.apache.wicket.serialize.java.JavaSerializer; import org.apache.wicket.settings.IApplicationSettings; import org.apache.wicket.util.io.ByteCountingOutputStream; import org.apache.wicket.util.lang.Generics; import org.apache.wicket.util.string.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Object (de)serialization utilities. */ public class WicketObjects { /** log. */ private static final Logger log = LoggerFactory.getLogger(WicketObjects.class); private WicketObjects() { } /** * @param <T> * class type * @param className * Class to resolve * @return Resolved class * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") public static <T> Class<T> resolveClass(final String className) { Class<T> resolved = null; try { if (Application.exists()) { resolved = (Class<T>)Application.get() .getApplicationSettings() .getClassResolver() .resolveClass(className); } if (resolved == null) { resolved = (Class<T>)Class.forName(className, false, Thread.currentThread() .getContextClassLoader()); } } catch (ClassNotFoundException cnfx) { log.warn("Could not resolve class [" + className + "]", cnfx); } return resolved; } /** * Interface that enables users to plugin the way object sizes are calculated with Wicket. */ public static interface IObjectSizeOfStrategy { /** * Computes the size of an object. This typically is an estimation, not an absolute accurate * size. * * @param object * The serializable object to compute size of * @return The size of the object in bytes. */ long sizeOf(Serializable object); } /** * {@link IObjectSizeOfStrategy} that works by serializing the object to an instance of * {@link ByteCountingOutputStream}, which records the number of bytes written to it. Hence, * this gives the size of the object as it would be serialized,including all the overhead of * writing class headers etc. Not very accurate (the real memory consumption should be lower) * but the best we can do in a cheap way pre JDK 5. */ public static final class SerializingObjectSizeOfStrategy implements IObjectSizeOfStrategy { @Override public long sizeOf(Serializable object) { if (object == null) { return 0; } ISerializer serializer; if (Application.exists()) { serializer = Application.get().getFrameworkSettings().getSerializer(); } else { serializer = new JavaSerializer("SerializingObjectSizeOfStrategy"); } byte[] serialized = serializer.serialize(object); int size = -1; if (serialized != null) { size = serialized.length; } return size; } } private static final class ReplaceObjectInputStream extends ObjectInputStream { private final ClassLoader classloader; private final HashMap<String, Component> replacedComponents; private ReplaceObjectInputStream(InputStream in, HashMap<String, Component> replacedComponents, ClassLoader classloader) throws IOException { super(in); this.replacedComponents = replacedComponents; this.classloader = classloader; enableResolveObject(true); } // This override is required to resolve classes inside in different // bundle, i.e. // The classes can be resolved by OSGI classresolver implementation @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String className = desc.getName(); try { return Class.forName(className, true, classloader); } catch (ClassNotFoundException ex1) { // ignore this exception. log.debug("Class not found by using objects own classloader, trying the IClassResolver"); } Application application = Application.get(); IApplicationSettings applicationSettings = application.getApplicationSettings(); IClassResolver classResolver = applicationSettings.getClassResolver(); Class<?> candidate = null; try { candidate = classResolver.resolveClass(className); if (candidate == null) { candidate = super.resolveClass(desc); } } catch (WicketRuntimeException ex) { if (ex.getCause() instanceof ClassNotFoundException) { throw (ClassNotFoundException)ex.getCause(); } } return candidate; } @Override protected Object resolveObject(Object obj) throws IOException { Object replaced = replacedComponents.get(obj); if (replaced != null) { return replaced; } return super.resolveObject(obj); } } private static final class ReplaceObjectOutputStream extends ObjectOutputStream { private final HashMap<String, Component> replacedComponents; private ReplaceObjectOutputStream(OutputStream out, HashMap<String, Component> replacedComponents) throws IOException { super(out); this.replacedComponents = replacedComponents; enableReplaceObject(true); } @Override protected Object replaceObject(Object obj) throws IOException { if (obj instanceof Component) { final Component component = (Component)obj; String name = component.getPath(); replacedComponents.put(name, component); return name; } return super.replaceObject(obj); } } /** * Makes a deep clone of an object by serializing and deserializing it. The object must be fully * serializable to be cloned. This method will not clone wicket Components, it will just reuse * those instances so that the complete component tree is not copied over only the model data. * * @param object * The object to clone * @return A deep copy of the object */ public static Object cloneModel(final Object object) { if (object == null) { return null; } else { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(256); final HashMap<String, Component> replacedObjects = Generics.newHashMap(); ObjectOutputStream oos = new ReplaceObjectOutputStream(out, replacedObjects); oos.writeObject(object); ObjectInputStream ois = new ReplaceObjectInputStream(new ByteArrayInputStream( out.toByteArray()), replacedObjects, object.getClass().getClassLoader()); return ois.readObject(); } catch (ClassNotFoundException e) { throw new WicketRuntimeException("Internal error cloning object", e); } catch (IOException e) { throw new WicketRuntimeException("Internal error cloning object", e); } } } /** * Strategy for calculating sizes of objects. Note: I didn't make this an application setting as * we have enough of those already, and the typical way this probably would be used is that * install a different one according to the JDK version used, so varying them between * applications doesn't make a lot of sense. */ private static IObjectSizeOfStrategy objectSizeOfStrategy = new SerializingObjectSizeOfStrategy(); /** * Makes a deep clone of an object by serializing and deserializing it. The object must be fully * serializable to be cloned. No extra debug info is gathered. * * @param object * The object to clone * @return A deep copy of the object * @see #cloneModel(Object) */ public static Object cloneObject(final Object object) { if (object == null) { return null; } else { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(256); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(object); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream( out.toByteArray())) { // This override is required to resolve classes inside in different bundle, i.e. // The classes can be resolved by OSGI classresolver implementation @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String className = desc.getName(); try { return Class.forName(className, true, object.getClass() .getClassLoader()); } catch (ClassNotFoundException ex1) { // ignore this exception. log.debug("Class not found by using objects own classloader, trying the IClassResolver"); } Application application = Application.get(); IApplicationSettings applicationSettings = application.getApplicationSettings(); IClassResolver classResolver = applicationSettings.getClassResolver(); Class<?> candidate = null; try { candidate = classResolver.resolveClass(className); if (candidate == null) { candidate = super.resolveClass(desc); } } catch (WicketRuntimeException ex) { if (ex.getCause() instanceof ClassNotFoundException) { throw (ClassNotFoundException)ex.getCause(); } } return candidate; } }; return ois.readObject(); } catch (ClassNotFoundException e) { throw new WicketRuntimeException("Internal error cloning object", e); } catch (IOException e) { throw new WicketRuntimeException("Internal error cloning object", e); } } } /** * Creates a new instance using the current application's class resolver. Returns null if * className is null. * * @param className * The full class name * @return The new object instance */ public static Object newInstance(final String className) { if (!Strings.isEmpty(className)) { try { Class<?> c = WicketObjects.resolveClass(className); return c.newInstance(); } catch (Exception e) { throw new WicketRuntimeException("Unable to create " + className, e); } } return null; } /** * Sets the strategy for determining the sizes of objects. * * @param objectSizeOfStrategy * the strategy. Pass null to reset to the default. */ public static void setObjectSizeOfStrategy(IObjectSizeOfStrategy objectSizeOfStrategy) { if (objectSizeOfStrategy == null) { WicketObjects.objectSizeOfStrategy = new SerializingObjectSizeOfStrategy(); } else { WicketObjects.objectSizeOfStrategy = objectSizeOfStrategy; } log.info("using " + objectSizeOfStrategy + " for calculating object sizes"); } /** * Computes the size of an object. Note that this is an estimation, never an absolute accurate * size. * * @param object * Object to compute size of * @return The size of the object in bytes */ public static long sizeof(final Serializable object) { return objectSizeOfStrategy.sizeOf(object); } }
WICKET-4867 Detach the object before calculating its size
wicket-core/src/main/java/org/apache/wicket/core/util/lang/WicketObjects.java
WICKET-4867 Detach the object before calculating its size
<ide><path>icket-core/src/main/java/org/apache/wicket/core/util/lang/WicketObjects.java <ide> import org.apache.wicket.Component; <ide> import org.apache.wicket.WicketRuntimeException; <ide> import org.apache.wicket.application.IClassResolver; <add>import org.apache.wicket.model.IDetachable; <ide> import org.apache.wicket.serialize.ISerializer; <ide> import org.apache.wicket.serialize.java.JavaSerializer; <ide> import org.apache.wicket.settings.IApplicationSettings; <ide> */ <ide> public static long sizeof(final Serializable object) <ide> { <add> if (object instanceof Component) <add> { <add> ((Component) object).detach(); <add> } <add> else if (object instanceof IDetachable) <add> { <add> ((IDetachable) object).detach(); <add> } <add> <ide> return objectSizeOfStrategy.sizeOf(object); <ide> } <ide> }
Java
apache-2.0
e8c71967bff92ad64e55aacd69ab7cc249dfc678
0
JasonHZXie/Mycat-Server,RiverWeng/Mycat-Server,qwer233968/Mycat-Server,shang1991/Mycat-Server,kelvin-ma/Mycat-Server,aimer1027/Mycat-Server,enjoy0924/Mycat-Server,cshsh/Mycat-Server,yonglehou/Mycat-Server,ccvcd/Mycat-Server,aimer1027/Mycat-Server,vniu/Mycat-Server,yonglehou/Mycat-Server,belloner/Mycat-Server,qwer233968/Mycat-Server,linzhiqiang0514/Mycat-Server,lizhanhui/Mycat-Server,GeekTemo/Mycat-Server,shang1991/Mycat-Server,vniu/Mycat-Server,wyzssw/Mycat-Server,leader-us/Mycat-Server,tottiyq/Mycat-Server,micmiu/Mycat-Server,vniu/Mycat-Server,qwer233968/Mycat-Server,enjoy0924/Mycat-Server,magicdoom/Mycat-Server,huangsizhou/Mycat-Server,cailin186/Mycat-Server,fengshao0907/Mycat-Server,caizhihuan/Mycat-Server,lizhanhui/Mycat-Server,fengyapeng/Mycat-Server,kelvin-ma/Mycat-Server,cailin186/Mycat-Server,elijah513/Mycat-Server,fengshao0907/Mycat-Server,runfriends/Mycat-Server,jacky312/Mycat-Server,aimer1027/Mycat-Server,enjoy0924/Mycat-Server,qwer233968/Mycat-Server,shang1991/Mycat-Server,ccvcd/Mycat-Server,runfriends/Mycat-Server,belloner/Mycat-Server,huangsizhou/Mycat-Server,leader-us/Mycat-Server,ccvcd/Mycat-Server,cshsh/Mycat-Server,caizhihuan/Mycat-Server,linzhiqiang0514/Mycat-Server,taolong001/Mycat-Server,wyzssw/Mycat-Server,RiverWeng/Mycat-Server,vniu/Mycat-Server,magicdoom/Mycat-Server,JasonHZXie/Mycat-Server,accphuangxin/Mycat-Server,RiverWeng/Mycat-Server,RiverWeng/Mycat-Server,magicdoom/Mycat-Server,aimer1027/Mycat-Server,GeekTemo/Mycat-Server,accphuangxin/Mycat-Server,accphuangxin/Mycat-Server,belloner/Mycat-Server,belloner/Mycat-Server,wyzssw/Mycat-Server,cailin186/Mycat-Server,cshsh/Mycat-Server,fengshao0907/Mycat-Server,caizhihuan/Mycat-Server,JasonHZXie/Mycat-Server,fengyapeng/Mycat-Server,yonglehou/Mycat-Server,ifrenzyc/Mycat-Server,ifrenzyc/Mycat-Server,leader-us/Mycat-Server,jacky312/Mycat-Server,taolong001/Mycat-Server,zuoyuezong123/Mycat-Server,runfriends/Mycat-Server,ccvcd/Mycat-Server,wyzssw/Mycat-Server,zuoyuezong123/Mycat-Server,jacky312/Mycat-Server,enjoy0924/Mycat-Server,GeekTemo/Mycat-Server,zouyoujin/Mycat-Server,micmiu/Mycat-Server,taolong001/Mycat-Server,fengyapeng/Mycat-Server,tottiyq/Mycat-Server,kelvin-ma/Mycat-Server,huangsizhou/Mycat-Server,ifrenzyc/Mycat-Server,micmiu/Mycat-Server,caizhihuan/Mycat-Server,linzhiqiang0514/Mycat-Server,tottiyq/Mycat-Server,fengyapeng/Mycat-Server,runfriends/Mycat-Server,lizhanhui/Mycat-Server,zuoyuezong123/Mycat-Server,yonglehou/Mycat-Server,taolong001/Mycat-Server,zouyoujin/Mycat-Server,tottiyq/Mycat-Server,zouyoujin/Mycat-Server,shang1991/Mycat-Server,cailin186/Mycat-Server,lizhanhui/Mycat-Server,fengshao0907/Mycat-Server,leader-us/Mycat-Server,elijah513/Mycat-Server,zuoyuezong123/Mycat-Server,ifrenzyc/Mycat-Server,linzhiqiang0514/Mycat-Server,micmiu/Mycat-Server,jacky312/Mycat-Server,JasonHZXie/Mycat-Server,elijah513/Mycat-Server,kelvin-ma/Mycat-Server,zouyoujin/Mycat-Server,cshsh/Mycat-Server,huangsizhou/Mycat-Server,magicdoom/Mycat-Server,accphuangxin/Mycat-Server,GeekTemo/Mycat-Server,elijah513/Mycat-Server
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package org.opencloudb.mpp; import org.opencloudb.net.mysql.RowDataPacket; import org.opencloudb.util.ByteUtil; import org.opencloudb.util.LongUtil; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; /** * implement group function select a,count(*),sum(*) from A group by a * * @author wuzhih * */ public class RowDataPacketGrouper { private final MergeCol[] mergCols; private final int[] groupColumnIndexs; private ConcurrentLinkedQueue<RowDataPacket> result = new ConcurrentLinkedQueue<RowDataPacket>(); private boolean isMergAvg=false; private HavingCols havingCols; public RowDataPacketGrouper(int[] groupColumnIndexs, MergeCol[] mergCols,HavingCols havingCols) { super(); this.groupColumnIndexs = groupColumnIndexs; this.mergCols = mergCols; this.havingCols = havingCols; } public Collection<RowDataPacket> getResult() { if(!isMergAvg) { for (RowDataPacket row : result) { mergAvg(row); } isMergAvg=true; } if(havingCols != null){ filterHaving(); } return result; } private void filterHaving(){ if (havingCols.getColMeta() == null || result == null) { return; } Iterator<RowDataPacket> it = result.iterator(); byte[] right = havingCols.getRight().getBytes( StandardCharsets.UTF_8); int index = havingCols.getColMeta().getColIndex(); while (it.hasNext()){ RowDataPacket rowDataPacket = it.next(); switch (havingCols.getOperator()) { case "=": if (eq(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case ">": if (gt(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case "<": if (lt(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case ">=": if (gt(rowDataPacket.fieldValues.get(index),right) && eq(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case "<=": if (lt(rowDataPacket.fieldValues.get(index),right) && eq(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case "!=": if (neq(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; } } } private boolean lt(byte[] l, byte[] r) { return -1 != ByteUtil.compareNumberByte(l, r); } private boolean gt(byte[] l, byte[] r) { return 1 != ByteUtil.compareNumberByte(l, r); } private boolean eq(byte[] l, byte[] r) { return 0 != ByteUtil.compareNumberByte(l, r); } private boolean neq(byte[] l, byte[] r) { return 0 == ByteUtil.compareNumberByte(l, r); } public void addRow(RowDataPacket rowDataPkg) { for (RowDataPacket row : result) { if (sameGropuColums(rowDataPkg, row)) { aggregateRow(row, rowDataPkg); return; } } // not aggreated ,insert new result.add(rowDataPkg); } private void aggregateRow(RowDataPacket toRow, RowDataPacket newRow) { if (mergCols == null) { return; } for (MergeCol merg : mergCols) { if(merg.mergeType!=MergeCol.MERGE_AVG) { byte[] result = mertFields( toRow.fieldValues.get(merg.colMeta.colIndex), newRow.fieldValues.get(merg.colMeta.colIndex), merg.colMeta.colType, merg.mergeType); if (result != null) { toRow.fieldValues.set(merg.colMeta.colIndex, result); } } } } private void mergAvg(RowDataPacket toRow) { if (mergCols == null) { return; } for (MergeCol merg : mergCols) { if(merg.mergeType==MergeCol.MERGE_AVG) { byte[] result = mertFields( toRow.fieldValues.get(merg.colMeta.avgSumIndex), toRow.fieldValues.get(merg.colMeta.avgCountIndex), merg.colMeta.colType, merg.mergeType); if (result != null) { toRow.fieldValues.set(merg.colMeta.avgSumIndex, result); toRow.fieldValues.remove(merg.colMeta.avgCountIndex) ; toRow.fieldCount=toRow.fieldCount-1; } } } } private byte[] mertFields(byte[] bs, byte[] bs2, int colType, int mergeType) { // System.out.println("mergeType:"+ mergeType+" colType "+colType+ // " field:"+Arrays.toString(bs)+ " -> "+Arrays.toString(bs2)); if(bs2==null || bs2.length==0) { return bs; }else if(bs==null || bs.length==0) { return bs2; } switch (mergeType) { case MergeCol.MERGE_SUM: if (colType == ColMeta.COL_TYPE_NEWDECIMAL || colType == ColMeta.COL_TYPE_DOUBLE || colType == ColMeta.COL_TYPE_FLOAT || colType == ColMeta.COL_TYPE_DECIMAL) { Double vale = ByteUtil.getDouble(bs) + ByteUtil.getDouble(bs2); return vale.toString().getBytes(); // return String.valueOf(vale).getBytes(); } // continue to count case case MergeCol.MERGE_COUNT: { long s1 = Long.parseLong(new String(bs)); long s2 = Long.parseLong(new String(bs2)); long total = s1 + s2; return LongUtil.toBytes(total); } case MergeCol.MERGE_MAX: { // System.out.println("value:"+ // ByteUtil.getNumber(bs).doubleValue()); // System.out.println("value2:"+ // ByteUtil.getNumber(bs2).doubleValue()); // int compare = CompareUtil.compareDouble(ByteUtil.getNumber(bs) // .doubleValue(), ByteUtil.getNumber(bs2).doubleValue()); // return ByteUtil.compareNumberByte(bs, bs2); int compare = ByteUtil.compareNumberByte(bs, bs2); return (compare > 0) ? bs : bs2; } case MergeCol.MERGE_MIN: { // int compare = CompareUtil.compareDouble(ByteUtil.getNumber(bs) // .doubleValue(), ByteUtil.getNumber(bs2).doubleValue()); // int compare = ByteUtil.compareNumberArray(bs, bs2); //return (compare > 0) ? bs2 : bs; int compare = ByteUtil.compareNumberByte(bs, bs2); return (compare > 0) ? bs2 : bs; // return ByteUtil.compareNumberArray2(bs, bs2, 2); } case MergeCol.MERGE_AVG: { double aDouble = ByteUtil.getDouble(bs); long s2 = Long.parseLong(new String(bs2)); Double vale = aDouble / s2; return vale.toString().getBytes(); } default: return null; } } // private static final private boolean sameGropuColums(RowDataPacket newRow, RowDataPacket existRow) { if (groupColumnIndexs == null) {// select count(*) from aaa , or group // column return true; } for (int i = 0; i < groupColumnIndexs.length; i++) { if (!Arrays.equals(newRow.fieldValues.get(groupColumnIndexs[i]), existRow.fieldValues.get(groupColumnIndexs[i]))) { return false; } } return true; } }
src/main/java/org/opencloudb/mpp/RowDataPacketGrouper.java
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package org.opencloudb.mpp; import org.opencloudb.net.mysql.RowDataPacket; import org.opencloudb.util.ByteUtil; import org.opencloudb.util.LongUtil; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; /** * implement group function select a,count(*),sum(*) from A group by a * * @author wuzhih * */ public class RowDataPacketGrouper { private final MergeCol[] mergCols; private final int[] groupColumnIndexs; private ConcurrentLinkedQueue<RowDataPacket> result = new ConcurrentLinkedQueue<RowDataPacket>(); private boolean isMergAvg=false; private HavingCols havingCols; public RowDataPacketGrouper(int[] groupColumnIndexs, MergeCol[] mergCols,HavingCols havingCols) { super(); this.groupColumnIndexs = groupColumnIndexs; this.mergCols = mergCols; this.havingCols = havingCols; } public Collection<RowDataPacket> getResult() { if(!isMergAvg) { for (RowDataPacket row : result) { mergAvg(row); } isMergAvg=true; } if(havingCols != null){ filterHaving(); } return result; } private void filterHaving(){ if (havingCols.getColMeta() == null) { return; } Iterator<RowDataPacket> it = result.iterator(); byte[] right = havingCols.getRight().getBytes( StandardCharsets.UTF_8); int index = havingCols.getColMeta().getColIndex(); while (it.hasNext()){ RowDataPacket rowDataPacket = it.next(); switch (havingCols.getOperator()) { case "=": if (eq(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case ">": if (gt(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case "<": if (lt(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case ">=": if (gt(rowDataPacket.fieldValues.get(index),right) && eq(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case "<=": if (lt(rowDataPacket.fieldValues.get(index),right) && eq(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; case "!=": if (neq(rowDataPacket.fieldValues.get(index),right)) { it.remove(); } break; } } } private boolean lt(byte[] l, byte[] r) { return -1 != ByteUtil.compareNumberByte(l, r); } private boolean gt(byte[] l, byte[] r) { return 1 != ByteUtil.compareNumberByte(l, r); } private boolean eq(byte[] l, byte[] r) { return 0 != ByteUtil.compareNumberByte(l, r); } private boolean neq(byte[] l, byte[] r) { return 0 == ByteUtil.compareNumberByte(l, r); } public void addRow(RowDataPacket rowDataPkg) { for (RowDataPacket row : result) { if (sameGropuColums(rowDataPkg, row)) { aggregateRow(row, rowDataPkg); return; } } // not aggreated ,insert new result.add(rowDataPkg); } private void aggregateRow(RowDataPacket toRow, RowDataPacket newRow) { if (mergCols == null) { return; } for (MergeCol merg : mergCols) { if(merg.mergeType!=MergeCol.MERGE_AVG) { byte[] result = mertFields( toRow.fieldValues.get(merg.colMeta.colIndex), newRow.fieldValues.get(merg.colMeta.colIndex), merg.colMeta.colType, merg.mergeType); if (result != null) { toRow.fieldValues.set(merg.colMeta.colIndex, result); } } } } private void mergAvg(RowDataPacket toRow) { if (mergCols == null) { return; } for (MergeCol merg : mergCols) { if(merg.mergeType==MergeCol.MERGE_AVG) { byte[] result = mertFields( toRow.fieldValues.get(merg.colMeta.avgSumIndex), toRow.fieldValues.get(merg.colMeta.avgCountIndex), merg.colMeta.colType, merg.mergeType); if (result != null) { toRow.fieldValues.set(merg.colMeta.avgSumIndex, result); toRow.fieldValues.remove(merg.colMeta.avgCountIndex) ; toRow.fieldCount=toRow.fieldCount-1; } } } } private byte[] mertFields(byte[] bs, byte[] bs2, int colType, int mergeType) { // System.out.println("mergeType:"+ mergeType+" colType "+colType+ // " field:"+Arrays.toString(bs)+ " -> "+Arrays.toString(bs2)); if(bs2==null || bs2.length==0) { return bs; }else if(bs==null || bs.length==0) { return bs2; } switch (mergeType) { case MergeCol.MERGE_SUM: if (colType == ColMeta.COL_TYPE_NEWDECIMAL || colType == ColMeta.COL_TYPE_DOUBLE || colType == ColMeta.COL_TYPE_FLOAT || colType == ColMeta.COL_TYPE_DECIMAL) { Double vale = ByteUtil.getDouble(bs) + ByteUtil.getDouble(bs2); return vale.toString().getBytes(); // return String.valueOf(vale).getBytes(); } // continue to count case case MergeCol.MERGE_COUNT: { long s1 = Long.parseLong(new String(bs)); long s2 = Long.parseLong(new String(bs2)); long total = s1 + s2; return LongUtil.toBytes(total); } case MergeCol.MERGE_MAX: { // System.out.println("value:"+ // ByteUtil.getNumber(bs).doubleValue()); // System.out.println("value2:"+ // ByteUtil.getNumber(bs2).doubleValue()); // int compare = CompareUtil.compareDouble(ByteUtil.getNumber(bs) // .doubleValue(), ByteUtil.getNumber(bs2).doubleValue()); // return ByteUtil.compareNumberByte(bs, bs2); int compare = ByteUtil.compareNumberByte(bs, bs2); return (compare > 0) ? bs : bs2; } case MergeCol.MERGE_MIN: { // int compare = CompareUtil.compareDouble(ByteUtil.getNumber(bs) // .doubleValue(), ByteUtil.getNumber(bs2).doubleValue()); // int compare = ByteUtil.compareNumberArray(bs, bs2); //return (compare > 0) ? bs2 : bs; int compare = ByteUtil.compareNumberByte(bs, bs2); return (compare > 0) ? bs2 : bs; // return ByteUtil.compareNumberArray2(bs, bs2, 2); } case MergeCol.MERGE_AVG: { double aDouble = ByteUtil.getDouble(bs); long s2 = Long.parseLong(new String(bs2)); Double vale = aDouble / s2; return vale.toString().getBytes(); } default: return null; } } // private static final private boolean sameGropuColums(RowDataPacket newRow, RowDataPacket existRow) { if (groupColumnIndexs == null) {// select count(*) from aaa , or group // column return true; } for (int i = 0; i < groupColumnIndexs.length; i++) { if (!Arrays.equals(newRow.fieldValues.get(groupColumnIndexs[i]), existRow.fieldValues.get(groupColumnIndexs[i]))) { return false; } } return true; } }
添加having 支持。目前只支持 =,>,<,!=,>=,<=,空判断。
src/main/java/org/opencloudb/mpp/RowDataPacketGrouper.java
添加having 支持。目前只支持 =,>,<,!=,>=,<=,空判断。
<ide><path>rc/main/java/org/opencloudb/mpp/RowDataPacketGrouper.java <ide> } <ide> <ide> private void filterHaving(){ <del> if (havingCols.getColMeta() == null) { <add> if (havingCols.getColMeta() == null || result == null) { <ide> return; <ide> } <ide> Iterator<RowDataPacket> it = result.iterator();
Java
apache-2.0
748022eefc88dccac2b78fca6559886dfbbb4eee
0
OpenHFT/Chronicle-Map
/* * Copyright 2014 Higher Frequency Trading * * http://www.higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.map; import net.openhft.chronicle.hash.replication.AbstractReplication; import net.openhft.chronicle.hash.replication.TimeProvider; import net.openhft.chronicle.hash.serialization.BytesReader; import net.openhft.chronicle.hash.serialization.internal.BytesBytesInterop; import net.openhft.chronicle.hash.serialization.internal.DelegatingMetaBytesInterop; import net.openhft.chronicle.hash.serialization.internal.MetaBytesInterop; import net.openhft.chronicle.map.VanillaContext.ContextFactory; import net.openhft.lang.Maths; import net.openhft.lang.collection.ATSDirectBitSet; import net.openhft.lang.collection.SingleThreadedDirectBitSet; import net.openhft.lang.io.Bytes; import net.openhft.lang.io.MultiStoreBytes; import net.openhft.lang.threadlocal.ThreadLocalCopies; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicReferenceArray; import static net.openhft.chronicle.hash.hashing.Hasher.hash; import static net.openhft.chronicle.map.VanillaContext.SearchState.DELETED; import static net.openhft.chronicle.map.VanillaContext.SearchState.PRESENT; import static net.openhft.lang.MemoryUnit.*; import static net.openhft.lang.collection.DirectBitSet.NOT_FOUND; /** * <h2>A Replicating Multi Master HashMap</h2> <p>Each remote hash map, mirrors its changes over to * another remote hash map, neither hash map is considered the master store of data, each hash map * uses timestamps to reconcile changes. We refer to an instance of a remote hash-map as a node. A * node will be connected to any number of other nodes, for the first implementation the maximum * number of nodes will be fixed. The data that is stored locally in each node will become * eventually consistent. So changes made to one node, for example by calling put() will be * replicated over to the other node. To achieve a high level of performance and throughput, the * call to put() won’t block, with concurrentHashMap, It is typical to check the return code of some * methods to obtain the old value for example remove(). Due to the loose coupling and lock free * nature of this multi master implementation, this return value will only be the old value on the * nodes local data store. In other words the nodes are only concurrent locally. Its worth realising * that another node performing exactly the same operation may return a different value. However * reconciliation will ensure the maps themselves become eventually consistent. </p> * <h2>Reconciliation </h2> <p>If two ( or more nodes ) were to receive a change to their maps for * the same key but different values, say by a user of the maps, calling the put(key, value). Then, * initially each node will update its local store and each local store will hold a different value, * but the aim of multi master replication is to provide eventual consistency across the nodes. So, * with multi master when ever a node is changed it will notify the other nodes of its change. We * will refer to this notification as an event. The event will hold a timestamp indicating the time * the change occurred, it will also hold the state transition, in this case it was a put with a key * and value. Eventual consistency is achieved by looking at the timestamp from the remote node, if * for a given key, the remote nodes timestamp is newer than the local nodes timestamp, then the * event from the remote node will be applied to the local node, otherwise the event will be * ignored. </p> <p>However there is an edge case that we have to concern ourselves with, If two * nodes update their map at the same time with different values, we have to deterministically * resolve which update wins, because of eventual consistency both nodes should end up locally * holding the same data. Although it is rare two remote nodes could receive an update to their maps * at exactly the same time for the same key, we have to handle this edge case, its therefore * important not to rely on timestamps alone to reconcile the updates. Typically the update with the * newest timestamp should win, but in this example both timestamps are the same, and the decision * made to one node should be identical to the decision made to the other. We resolve this simple * dilemma by using a node identifier, each node will have a unique identifier, the update from the * node with the smallest identifier wins. </p> * * @param <K> the entries key type * @param <V> the entries value type */ final class ReplicatedChronicleMap<K, KI, MKI extends MetaBytesInterop<K, ? super KI>, V, VI, MVI extends MetaBytesInterop<V, ? super VI>> extends VanillaChronicleMap<K, KI, MKI, V, VI, MVI> implements Replica, Replica.EntryExternalizable, Replica.EntryResolver<K, V> { // for file, jdbc and UDP replication public static final int RESERVED_MOD_ITER = 8; public static final int ADDITIONAL_ENTRY_BYTES = 10; private static final long serialVersionUID = 0L; private static final Logger LOG = LoggerFactory.getLogger(ReplicatedChronicleMap.class); private static final long LAST_UPDATED_HEADER_SIZE = 128L * 8L; private final TimeProvider timeProvider; private final byte localIdentifier; transient Set<Closeable> closeables; private transient Bytes identifierUpdatedBytes; private transient ATSDirectBitSet modIterSet; private transient AtomicReferenceArray<ModificationIterator> modificationIterators; private transient long startOfModificationIterators; private boolean bootstrapOnlyLocalEntries; public ReplicatedChronicleMap(@NotNull ChronicleMapBuilder<K, V> builder, AbstractReplication replication) throws IOException { super(builder); this.timeProvider = builder.timeProvider(); this.localIdentifier = replication.identifier(); this.bootstrapOnlyLocalEntries = replication.bootstrapOnlyLocalEntries(); if (localIdentifier == -1) { throw new IllegalStateException("localIdentifier should not be -1"); } } private int assignedModIterBitSetSizeInBytes() { return (int) CACHE_LINES.align(BYTES.alignAndConvert(127 + RESERVED_MOD_ITER, BITS), BYTES); } @Override void initTransients() { super.initTransients(); modificationIterators = new AtomicReferenceArray<>(127 + RESERVED_MOD_ITER); closeables = new CopyOnWriteArraySet<>(); } long modIterBitSetSizeInBytes() { long bytes = BITS.toBytes(bitsPerSegmentInModIterBitSet() * actualSegments); return CACHE_LINES.align(bytes, BYTES); } private long bitsPerSegmentInModIterBitSet() { // min 128 * 8 to prevent false sharing on updating bits from different segments // TODO this doesn't prevent false sharing. There should be GAPS between per-segment bits return Maths.nextPower2(actualChunksPerSegment, 128L * 8L); } @Override long mapHeaderInnerSize() { return super.mapHeaderInnerSize() + LAST_UPDATED_HEADER_SIZE + (modIterBitSetSizeInBytes() * (128 + RESERVED_MOD_ITER)) + assignedModIterBitSetSizeInBytes(); } void setLastModificationTime(byte identifier, long timestamp) { final long offset = identifier * 8L; // purposely not volatile as this will impact performance, // and the worst that will happen is we'll end up loading more data on a bootstrap if (identifierUpdatedBytes.readLong(offset) < timestamp) identifierUpdatedBytes.writeLong(offset, timestamp); } @Override public long lastModificationTime(byte remoteIdentifier) { assert remoteIdentifier != this.identifier(); // purposely not volatile as this will impact performance, // and the worst that will happen is we'll end up loading more data on a bootstrap return identifierUpdatedBytes.readLong(remoteIdentifier * 8L); } @Override void onHeaderCreated() { long offset = super.mapHeaderInnerSize(); identifierUpdatedBytes = ms.bytes(offset, LAST_UPDATED_HEADER_SIZE).zeroOut(); offset += LAST_UPDATED_HEADER_SIZE; Bytes modDelBytes = ms.bytes(offset, assignedModIterBitSetSizeInBytes()).zeroOut(); offset += assignedModIterBitSetSizeInBytes(); startOfModificationIterators = offset; modIterSet = new ATSDirectBitSet(modDelBytes); } @Override public void clear() { // we have to make sure that every calls notifies on remove, // so that the replicators can pick it up for (Iterator<Entry<K, V>> iterator = entrySet().iterator(); iterator.hasNext(); ) { iterator.next(); iterator.remove(); } } void addCloseable(Closeable closeable) { closeables.add(closeable); } @Override public void close() { for (Closeable closeable : closeables) { try { closeable.close(); } catch (IOException e) { LOG.error("", e); } } super.close(); } @Override public byte identifier() { return localIdentifier; } @Override public Replica.ModificationIterator acquireModificationIterator( byte remoteIdentifier, @NotNull final ModificationNotifier modificationNotifier) { ModificationIterator modificationIterator = modificationIterators.get(remoteIdentifier); if (modificationIterator != null) return modificationIterator; synchronized (modificationIterators) { modificationIterator = modificationIterators.get(remoteIdentifier); if (modificationIterator != null) return modificationIterator; final Bytes bytes = ms.bytes(startOfModificationIterators + (modIterBitSetSizeInBytes() * remoteIdentifier), modIterBitSetSizeInBytes()); final ModificationIterator newModificationIterator = new ModificationIterator( bytes, modificationNotifier); modificationIterators.set(remoteIdentifier, newModificationIterator); modIterSet.set(remoteIdentifier); return newModificationIterator; } } void raiseChange(long segmentIndex, long pos) { for (long next = modIterSet.nextSetBit(0L); next > 0L; next = modIterSet.nextSetBit(next + 1L)) { try { modificationIterators.get((int) next).raiseChange(segmentIndex, pos); } catch (Exception e) { LOG.error("", e); } } } void dropChange(long segmentIndex, long pos) { for (long next = modIterSet.nextSetBit(0L); next > 0L; next = modIterSet.nextSetBit(next + 1L)) { try { modificationIterators.get((int) next).dropChange(segmentIndex, pos); } catch (Exception e) { LOG.error("", e); } } } public boolean identifierCheck(@NotNull Bytes entry, int chronicleId) { long start = entry.position(); try { final long keySize = keySizeMarshaller.readSize(entry); entry.skip(keySize + 8); // we skip 8 for the timestamp final byte identifier = entry.readByte(); return identifier == localIdentifier; } finally { entry.position(start); } } static class ReplicatedContext<K, KI, MKI extends MetaBytesInterop<K, ? super KI>, V, VI, MVI extends MetaBytesInterop<V, ? super VI>> extends VanillaContext<K, KI, MKI, V, VI, MVI> { ReplicatedContext() { super(); } ReplicatedContext(VanillaContext contextCache, int indexInContextCache) { super(contextCache, indexInContextCache); } ReplicatedChronicleMap<K, KI, MKI, V, VI, MVI> m() { return (ReplicatedChronicleMap<K, KI, MKI, V, VI, MVI>) m; } ///////////////////////////////////////////////// // Replication state long replicationBytesOffset; long timestamp; byte identifier; @Override void keyFound() { initReplicationBytesOffset0(); timestamp = entry.readLong(replicationBytesOffset); identifier = entry.readByte(replicationBytesOffset + 8L); state = entry.readBoolean(replicationBytesOffset + 9L) ? DELETED : PRESENT; } void initReplicationBytesOffset0() { replicationBytesOffset = keyOffset + keySize; } @Override void initKeyOffset0() { super.initKeyOffset0(); initReplicationBytesOffset0(); } void closeReplicationState() { if (replicationBytesOffset == 0L) return; closeReplicationState0(); } void closeReplicationState0() { replicationBytesOffset = 0L; timestamp = 0L; identifier = (byte) 0; } @Override void closeKeySearchDependants() { super.closeKeySearchDependants(); closeReplicationState(); } @Override void initValueSizeOffset0() { valueSizeOffset = replicationBytesOffset + ADDITIONAL_ENTRY_BYTES; } ///////////////////////////////////////////////// // Replication update long newTimestamp; byte newIdentifier; void initReplicationUpdate() { if (newIdentifier != 0) return; checkMapInit(); initReplicationUpdate0(); } void initReplicationUpdate0() { newTimestamp = m().timeProvider.currentTime(); newIdentifier = m().identifier(); } boolean remoteUpdate() { return newIdentifier != m().identifier(); } void closeReplicationUpdate() { if (newIdentifier == 0) return; closeReplicationUpdate0(); } void closeReplicationUpdate0() { newTimestamp = 0L; newIdentifier = (byte) 0; } @Override void initRemoveDependencies() { super.initRemoveDependencies(); initReplicationUpdate(); } void writeReplicationBytes() { entry.writeLong(replicationBytesOffset, newTimestamp); entry.writeByte(replicationBytesOffset + 8L, newIdentifier); } void writeDeleted() { entry.writeBoolean(replicationBytesOffset + 9L, true); } void writePresent() { entry.writeBoolean(replicationBytesOffset + 9L, false); } @Override long sizeOfEverythingBeforeValue(long keySize, long valueSize) { return super.sizeOfEverythingBeforeValue(keySize, valueSize) + ADDITIONAL_ENTRY_BYTES; } @Override boolean put0() { try { switch (state) { case PRESENT: case DELETED: if (!shouldIgnore()) { initValueBytes(); putValue(); break; } else { return false; } case ABSENT: putEntry(); } state = PRESENT; return true; } finally { closeReplicationUpdate(); } } @Override boolean freeListBitsSet() { // As of now, ReplicatedChMap's remove() never clear the bits return true; } @Override void initPutDependencies() { super.initPutDependencies(); initReplicationUpdate(); } @Override void writeNewValueAndSwitch() { super.writeNewValueAndSwitch(); writeReplicationBytes(); updateChange(); timestamp = newTimestamp; identifier = newIdentifier; } @Override void beforePutPos() { writePresent(); } class PseudoMetaBytesInterop implements MetaBytesInterop<Object, Object> { @Override public boolean startsWith(Object interop, Bytes bytes, Object o) { throw new UnsupportedOperationException(); } @Override public long hash(Object interop, Object o) { throw new UnsupportedOperationException(); } @Override public long size(Object writer, Object o) { throw new UnsupportedOperationException(); } @Override public void write(Object writer, Bytes bytes, Object o) { bytes.skip(newValueSize); } } final MetaBytesInterop<V, VI> pseudoMetaValueInterop = (MetaBytesInterop<V, VI>) new PseudoMetaBytesInterop(); @Override boolean remove0() { if (containsKey()) { if (!shouldIgnore()) { writeReplicationBytes(); writeDeleted(); updateChange(); size(size() - 1L); state = DELETED; return true; } else { return false; } } else { if (pos >= 0L) { if (!shouldIgnore()) { writeReplicationBytes(); updateChange(); } } else { newValue = (V) pseudoMetaValueInterop; metaValueInterop = (MVI) pseudoMetaValueInterop; newValueSize = m.valueSizeMarshaller.minEncodableSize(); put0(); size(size() - 1L); writeDeleted(); state = DELETED; } return false; } } void updateChange() { if (remoteUpdate()) { m().dropChange(segmentIndex, pos); } else { m().raiseChange(segmentIndex, pos); } } @Override void closeRemove() { closeReplicationUpdate(); } boolean shouldIgnore() { assert identifier != 0 && newIdentifier != 0 : "Own entry replication state or " + "update replication state is not initialized"; if (timestamp < newTimestamp) return false; if (timestamp > newTimestamp) return true; return identifier > newIdentifier; } public void dirtyEntries(final long dirtyFromTimeStamp, final ReplicatedChronicleMap.ModificationIterator modIter, final boolean bootstrapOnlyLocalEntries) { readLock().lock(); try { hashLookup.forEach(new HashLookup.EntryConsumer() { @Override public void accept(long hash, long pos) { ReplicatedContext.this.pos = pos; initKeyFromPos(); keyFound(); assert timestamp > 0L; if (timestamp >= dirtyFromTimeStamp && (!bootstrapOnlyLocalEntries || identifier == m().identifier())) modIter.raiseChange(segmentIndex, pos); } }); } finally { readLock().unlock(); } } } enum ReplicatedContextFactory implements ContextFactory<ReplicatedContext> { INSTANCE; @Override public ReplicatedContext createContext(VanillaContext root, int indexInContextCache) { return new ReplicatedContext(root, indexInContextCache); } @Override public ReplicatedContext createRootContext() { return new ReplicatedContext(); } @Override public Class<ReplicatedContext> contextClass() { return ReplicatedContext.class; } } @Override ReplicatedContext<K, KI, MKI, V, VI, MVI> rawContext() { return VanillaContext.get(ReplicatedContextFactory.INSTANCE); } @Override VanillaContext rawBytesContext() { return VanillaContext.get(BytesReplicatedContextFactory.INSTANCE); } static class BytesReplicatedContext extends ReplicatedContext<Bytes, BytesBytesInterop, DelegatingMetaBytesInterop<Bytes, BytesBytesInterop>, Bytes, BytesBytesInterop, DelegatingMetaBytesInterop<Bytes, BytesBytesInterop>> { BytesReplicatedContext() { super(); } BytesReplicatedContext(VanillaContext contextCache, int indexInContextCache) { super(contextCache, indexInContextCache); } @Override void initKeyModel0() { initBytesKeyModel0(); } @Override void initKey0(Bytes key) { initBytesKey0(key); } @Override void initValueModel0() { initBytesValueModel0(); } @Override void initNewValue0(Bytes newValue) { initNewBytesValue0(newValue); } @Override void closeValue0() { closeBytesValue0(); } @Override public Bytes get() { return getBytes(); } @Override public Bytes getUsing(Bytes usingValue) { return getBytesUsing(usingValue); } } enum BytesReplicatedContextFactory implements ContextFactory<BytesReplicatedContext> { INSTANCE; @Override public BytesReplicatedContext createContext(VanillaContext root, int indexInContextCache) { return new BytesReplicatedContext(root, indexInContextCache); } @Override public BytesReplicatedContext createRootContext() { return new BytesReplicatedContext(); } @Override public Class<BytesReplicatedContext> contextClass() { return BytesReplicatedContext.class; } } @Override VanillaContext<K, KI, MKI, V, VI, MVI> acquireContext(K key) { ReplicatedAcquireContext<K, KI, MKI, V, VI, MVI> c = VanillaContext.get(ReplicatedAcquireContextFactory.INSTANCE); c.initMap(this); c.initKey(key); return c; } static class ReplicatedAcquireContext<K, KI, MKI extends MetaBytesInterop<K, ? super KI>, V, VI, MVI extends MetaBytesInterop<V, ? super VI>> extends ReplicatedContext<K, KI, MKI, V, VI, MVI> { ReplicatedAcquireContext() { super(); } ReplicatedAcquireContext(VanillaContext contextCache, int indexInContextCache) { super(contextCache, indexInContextCache); } @Override public boolean put(V newValue) { return acquirePut(newValue); } @Override public boolean remove() { return acquireRemove(); } @Override public void close() { acquireClose(); } } enum ReplicatedAcquireContextFactory implements ContextFactory<ReplicatedAcquireContext> { INSTANCE; @Override public ReplicatedAcquireContext createContext(VanillaContext root, int indexInContextCache) { return new ReplicatedAcquireContext(root, indexInContextCache); } @Override public ReplicatedAcquireContext createRootContext() { return new ReplicatedAcquireContext(); } @Override public Class<ReplicatedAcquireContext> contextClass() { return ReplicatedAcquireContext.class; } } public int sizeOfEntry(@NotNull Bytes entry, int chronicleId) { long start = entry.position(); try { final long keySize = keySizeMarshaller.readSize(entry); entry.skip(keySize + 8); // we skip 8 for the timestamp final byte identifier = entry.readByte(); if (identifier != localIdentifier) { // although unlikely, this may occur if the entry has been updated return 0; } final boolean isDeleted = entry.readBoolean(); long valueSize; if (!isDeleted) { valueSize = valueSizeMarshaller.readSize(entry); } else { valueSize = 0L; } alignment.alignPositionAddr(entry); long result = (entry.position() + valueSize - start); // entries can be larger than Integer.MAX_VALUE as we are restricted to the size we can // make a byte buffer assert result < Integer.MAX_VALUE; return (int) result; } finally { entry.position(start); } } /** * This method does not set a segment lock, A segment lock should be obtained before calling * this method, especially when being used in a multi threaded context. */ @Override public void writeExternalEntry(@NotNull Bytes entry, @NotNull Bytes destination, int chronicleId) { final long initialLimit = entry.limit(); final long keySize = keySizeMarshaller.readSize(entry); final long keyPosition = entry.position(); entry.skip(keySize); final long keyLimit = entry.position(); final long timeStamp = entry.readLong(); final byte identifier = entry.readByte(); if (identifier != localIdentifier) { // although unlikely, this may occur if the entry has been updated return; } final boolean isDeleted = entry.readBoolean(); long valueSize; if (!isDeleted) { valueSize = valueSizeMarshaller.readSize(entry); } else { valueSize = 0L; } final long valuePosition = entry.position(); keySizeMarshaller.writeSize(destination, keySize); valueSizeMarshaller.writeSize(destination, valueSize); destination.writeStopBit(timeStamp); destination.writeByte(identifier); destination.writeBoolean(isDeleted); // write the key entry.position(keyPosition); entry.limit(keyLimit); destination.write(entry); boolean debugEnabled = LOG.isDebugEnabled(); String message = null; if (debugEnabled) { if (isDeleted) { LOG.debug("WRITING ENTRY TO DEST - into local-id={}, remove(key={})", localIdentifier, entry.toString().trim()); } else { message = String.format( "WRITING ENTRY TO DEST - into local-id=%d, put(key=%s,", localIdentifier, entry.toString().trim()); } } if (isDeleted) return; entry.limit(initialLimit); entry.position(valuePosition); // skipping the alignment, as alignment wont work when we send the data over the wire. alignment.alignPositionAddr(entry); // writes the value entry.limit(entry.position() + valueSize); destination.write(entry); if (debugEnabled) { LOG.debug(message + "value=" + entry.toString().trim() + ")"); } } /** * This method does not set a segment lock, A segment lock should be obtained before calling * this method, especially when being used in a multi threaded context. */ @Override public void readExternalEntry(@NotNull BytesReplicatedContext context, @NotNull Bytes source) { // TODO cache contexts per map -- don't init map on each readExternalEntry() context.initMap(this); try { final long keySize = keySizeMarshaller.readSize(source); final long valueSize = valueSizeMarshaller.readSize(source); final long timeStamp = source.readStopBit(); final byte id = source.readByte(); final boolean isDeleted = source.readBoolean(); final byte remoteIdentifier; if (id != 0) { remoteIdentifier = id; } else { throw new IllegalStateException("identifier can't be 0"); } if (remoteIdentifier == ReplicatedChronicleMap.this.identifier()) { // this may occur when working with UDP, as we may receive our own data return; } context.newTimestamp = timeStamp; context.newIdentifier = remoteIdentifier; final long keyPosition = source.position(); final long keyLimit = keyPosition + keySize; source.limit(keyLimit); context.metaKeyInterop = DelegatingMetaBytesInterop.instance(); context.keySize = keySize; context.initBytesKey00(source); boolean debugEnabled = LOG.isDebugEnabled(); context.updateLock().lock(); if (isDeleted) { if (debugEnabled) { LOG.debug("READING FROM SOURCE - into local-id={}, remote={}, remove(key={})", localIdentifier, remoteIdentifier, source.toString().trim() ); } context.remove(); setLastModificationTime(remoteIdentifier, timeStamp); return; } String message = null; if (debugEnabled) { message = String.format( "READING FROM SOURCE - into local-id=%d, remote-id=%d, put(key=%s,", localIdentifier, remoteIdentifier, source.toString().trim()); } final long valuePosition = keyLimit; final long valueLimit = valuePosition + valueSize; // compute hash => segment and locate the entry context.containsKey(); context.metaValueInterop = DelegatingMetaBytesInterop.instance(); context.newValueSize = valueSize; source.limit(valueLimit); source.position(valuePosition); context.initNewBytesValue00(source); context.initPutDependencies(); context.put0(); setLastModificationTime(remoteIdentifier, timeStamp); if (debugEnabled) { LOG.debug(message + "value=" + source.toString().trim() + ")"); } } finally { context.closeMap(); } } @Override Set<Entry<K, V>> newEntrySet() { return new EntrySet(); } @Override public K key(@NotNull Bytes entry, K usingKey) { final long start = entry.position(); try { long keySize = keySizeMarshaller.readSize(entry); ThreadLocalCopies copies = keyReaderProvider.getCopies(null); return keyReaderProvider.get(copies, originalKeyReader).read(entry, keySize); } finally { entry.position(start); } } @Override public V value(@NotNull Bytes entry, V usingValue) { final long start = entry.position(); try { entry.skip(keySizeMarshaller.readSize(entry)); //timeStamp entry.readLong(); final byte identifier = entry.readByte(); if (identifier != localIdentifier) { return null; } final boolean isDeleted = entry.readBoolean(); long valueSize; if (!isDeleted) { valueSize = valueSizeMarshaller.readSize(entry); assert valueSize > 0; } else { return null; } alignment.alignPositionAddr(entry); ThreadLocalCopies copies = valueReaderProvider.getCopies(null); BytesReader<V> valueReader = valueReaderProvider.get(copies, originalValueReader); return valueReader.read(entry, valueSize, usingValue); } finally { entry.position(start); } } @Override public boolean wasRemoved(@NotNull Bytes entry) { final long start = entry.position(); try { return entry.readBoolean(keySizeMarshaller.readSize(entry) + 9L); } finally { entry.position(start); } } /** * <p>Once a change occurs to a map, map replication requires that these changes are picked up * by another thread, this class provides an iterator like interface to poll for such changes. * </p> <p>In most cases the thread that adds data to the node is unlikely to be the same thread * that replicates the data over to the other nodes, so data will have to be marshaled between * the main thread storing data to the map, and the thread running the replication. </p> <p>One * way to perform this marshalling, would be to pipe the data into a queue. However, This class * takes another approach. It uses a bit set, and marks bits which correspond to the indexes of * the entries that have changed. It then provides an iterator like interface to poll for such * changes. </p> * * @author Rob Austin. */ class ModificationIterator implements Replica.ModificationIterator { private final ModificationNotifier modificationNotifier; private final SingleThreadedDirectBitSet changesForUpdates; // to getVolatile when reading changes bits, because we iterate when without lock. // hardly this is needed on x86, probably on other architectures too. // Anyway getVolatile is cheap. private final ATSDirectBitSet changesForIteration; private final int segmentIndexShift; private final long posMask; private final ReplicatedContext<K, KI, MKI, V, VI, MVI> context = (ReplicatedContext<K, KI, MKI, V, VI, MVI>) mapContext(); // records the current position of the cursor in the bitset private long position = -1L; /** * @param bytes the back the bitset, used to mark which entries have changed * @param modificationNotifier called when ever there is a change applied */ public ModificationIterator(@NotNull final Bytes bytes, @NotNull final ModificationNotifier modificationNotifier) { this.modificationNotifier = modificationNotifier; long bitsPerSegment = bitsPerSegmentInModIterBitSet(); segmentIndexShift = Long.numberOfTrailingZeros(bitsPerSegment); posMask = bitsPerSegment - 1L; changesForUpdates = new SingleThreadedDirectBitSet(bytes); changesForIteration = new ATSDirectBitSet(bytes); } /** * used to merge multiple segments and positions into a single index used by the bit map * * @param segmentIndex the index of the maps segment * @param pos the position within this {@code segmentIndex} * @return and index the has combined the {@code segmentIndex} and {@code pos} into a * single value */ private long combine(long segmentIndex, long pos) { return (segmentIndex << segmentIndexShift) | pos; } void raiseChange(long segmentIndex, long pos) { changesForUpdates.set(combine(segmentIndex, pos)); modificationNotifier.onChange(); } void dropChange(long segmentIndex, long pos) { changesForUpdates.clear(combine(segmentIndex, pos)); } /** * you can continue to poll hasNext() until data becomes available. If are are in the middle * of processing an entry via {@code nextEntry}, hasNext will return true until the bit is * cleared * * @return true if there is an entry */ @Override public boolean hasNext() { final long position = this.position; return changesForIteration.nextSetBit(position == NOT_FOUND ? 0L : position) != NOT_FOUND || (position > 0L && changesForIteration.nextSetBit(0L) != NOT_FOUND); } /** * @param entryCallback call this to get an entry, this class will take care of the locking * @return true if an entry was processed */ @Override public boolean nextEntry(@NotNull EntryCallback entryCallback, int chronicleId) { long position = this.position; while (true) { long oldPosition = position; position = changesForIteration.nextSetBit(oldPosition + 1L); if (position == NOT_FOUND) { if (oldPosition == NOT_FOUND) { this.position = NOT_FOUND; return false; } continue; } this.position = position; int segmentIndex = (int) (position >>> segmentIndexShift); if (context.segmentIndex != segmentIndex) { context.closeSegmentIndex(); context.segmentIndex = segmentIndex; context.initLocks(); context.initSegment(); } context.updateLock().lock(); try { if (changesForUpdates.get(position)) { entryCallback.onBeforeEntry(); final long segmentPos = position & posMask; context.reuse(segmentPos); // if the entry should be ignored, we'll move the next entry if (entryCallback.shouldBeIgnored(context.entry, chronicleId)) { changesForUpdates.clear(position); continue; } // it may not be successful if the buffer can not be re-sized so we will // process it later, by NOT clearing the changes.clear(position) boolean success = entryCallback.onEntry(context.entry, chronicleId); entryCallback.onAfterEntry(); if (success) changesForUpdates.clear(position); return success; } // if the position was already cleared by another thread // while we were trying to obtain segment lock (for example, in onRelocation()), // go to pick up next (next iteration in while (true) loop) } finally { context.updateLock().unlock(); } } } @Override public void dirtyEntries(long fromTimeStamp) { try (ReplicatedContext<K, KI, MKI, V, VI, MVI> context = (ReplicatedContext<K, KI, MKI, V, VI, MVI>) mapContext()) { // iterate over all the segments and mark bit in the modification iterator // that correspond to entries with an older timestamp for (int i = 0; i < actualSegments; i++) { context.segmentIndex = i; context.initSegment(); try { context.dirtyEntries(fromTimeStamp, this, bootstrapOnlyLocalEntries); } finally { context.closeSegmentIndex(); } } } } } }
src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java
/* * Copyright 2014 Higher Frequency Trading * * http://www.higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.map; import net.openhft.chronicle.hash.replication.AbstractReplication; import net.openhft.chronicle.hash.replication.TimeProvider; import net.openhft.chronicle.hash.serialization.BytesReader; import net.openhft.chronicle.hash.serialization.internal.BytesBytesInterop; import net.openhft.chronicle.hash.serialization.internal.DelegatingMetaBytesInterop; import net.openhft.chronicle.hash.serialization.internal.MetaBytesInterop; import net.openhft.chronicle.map.VanillaContext.ContextFactory; import net.openhft.lang.Maths; import net.openhft.lang.collection.ATSDirectBitSet; import net.openhft.lang.collection.SingleThreadedDirectBitSet; import net.openhft.lang.io.Bytes; import net.openhft.lang.io.MultiStoreBytes; import net.openhft.lang.threadlocal.ThreadLocalCopies; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicReferenceArray; import static net.openhft.chronicle.hash.hashing.Hasher.hash; import static net.openhft.chronicle.map.VanillaContext.SearchState.DELETED; import static net.openhft.chronicle.map.VanillaContext.SearchState.PRESENT; import static net.openhft.lang.MemoryUnit.*; import static net.openhft.lang.collection.DirectBitSet.NOT_FOUND; /** * <h2>A Replicating Multi Master HashMap</h2> <p>Each remote hash map, mirrors its changes over to * another remote hash map, neither hash map is considered the master store of data, each hash map * uses timestamps to reconcile changes. We refer to an instance of a remote hash-map as a node. A * node will be connected to any number of other nodes, for the first implementation the maximum * number of nodes will be fixed. The data that is stored locally in each node will become * eventually consistent. So changes made to one node, for example by calling put() will be * replicated over to the other node. To achieve a high level of performance and throughput, the * call to put() won’t block, with concurrentHashMap, It is typical to check the return code of some * methods to obtain the old value for example remove(). Due to the loose coupling and lock free * nature of this multi master implementation, this return value will only be the old value on the * nodes local data store. In other words the nodes are only concurrent locally. Its worth realising * that another node performing exactly the same operation may return a different value. However * reconciliation will ensure the maps themselves become eventually consistent. </p> * <h2>Reconciliation </h2> <p>If two ( or more nodes ) were to receive a change to their maps for * the same key but different values, say by a user of the maps, calling the put(key, value). Then, * initially each node will update its local store and each local store will hold a different value, * but the aim of multi master replication is to provide eventual consistency across the nodes. So, * with multi master when ever a node is changed it will notify the other nodes of its change. We * will refer to this notification as an event. The event will hold a timestamp indicating the time * the change occurred, it will also hold the state transition, in this case it was a put with a key * and value. Eventual consistency is achieved by looking at the timestamp from the remote node, if * for a given key, the remote nodes timestamp is newer than the local nodes timestamp, then the * event from the remote node will be applied to the local node, otherwise the event will be * ignored. </p> <p>However there is an edge case that we have to concern ourselves with, If two * nodes update their map at the same time with different values, we have to deterministically * resolve which update wins, because of eventual consistency both nodes should end up locally * holding the same data. Although it is rare two remote nodes could receive an update to their maps * at exactly the same time for the same key, we have to handle this edge case, its therefore * important not to rely on timestamps alone to reconcile the updates. Typically the update with the * newest timestamp should win, but in this example both timestamps are the same, and the decision * made to one node should be identical to the decision made to the other. We resolve this simple * dilemma by using a node identifier, each node will have a unique identifier, the update from the * node with the smallest identifier wins. </p> * * @param <K> the entries key type * @param <V> the entries value type */ final class ReplicatedChronicleMap<K, KI, MKI extends MetaBytesInterop<K, ? super KI>, V, VI, MVI extends MetaBytesInterop<V, ? super VI>> extends VanillaChronicleMap<K, KI, MKI, V, VI, MVI> implements Replica, Replica.EntryExternalizable, Replica.EntryResolver<K, V> { // for file, jdbc and UDP replication public static final int RESERVED_MOD_ITER = 8; public static final int ADDITIONAL_ENTRY_BYTES = 10; private static final long serialVersionUID = 0L; private static final Logger LOG = LoggerFactory.getLogger(ReplicatedChronicleMap.class); private static final long LAST_UPDATED_HEADER_SIZE = 128L * 8L; private final TimeProvider timeProvider; private final byte localIdentifier; transient Set<Closeable> closeables; private transient Bytes identifierUpdatedBytes; private transient ATSDirectBitSet modIterSet; private transient AtomicReferenceArray<ModificationIterator> modificationIterators; private transient long startOfModificationIterators; private boolean bootstrapOnlyLocalEntries; public ReplicatedChronicleMap(@NotNull ChronicleMapBuilder<K, V> builder, AbstractReplication replication) throws IOException { super(builder); this.timeProvider = builder.timeProvider(); this.localIdentifier = replication.identifier(); this.bootstrapOnlyLocalEntries = replication.bootstrapOnlyLocalEntries(); if (localIdentifier == -1) { throw new IllegalStateException("localIdentifier should not be -1"); } } private int assignedModIterBitSetSizeInBytes() { return (int) CACHE_LINES.align(BYTES.alignAndConvert(127 + RESERVED_MOD_ITER, BITS), BYTES); } @Override void initTransients() { super.initTransients(); modificationIterators = new AtomicReferenceArray<>(127 + RESERVED_MOD_ITER); closeables = new CopyOnWriteArraySet<>(); } long modIterBitSetSizeInBytes() { long bytes = BITS.toBytes(bitsPerSegmentInModIterBitSet() * actualSegments); return CACHE_LINES.align(bytes, BYTES); } private long bitsPerSegmentInModIterBitSet() { // min 128 * 8 to prevent false sharing on updating bits from different segments // TODO this doesn't prevent false sharing. There should be GAPS between per-segment bits return Maths.nextPower2(actualChunksPerSegment, 128L * 8L); } @Override long mapHeaderInnerSize() { return super.mapHeaderInnerSize() + LAST_UPDATED_HEADER_SIZE + (modIterBitSetSizeInBytes() * (128 + RESERVED_MOD_ITER)) + assignedModIterBitSetSizeInBytes(); } void setLastModificationTime(byte identifier, long timestamp) { final long offset = identifier * 8L; // purposely not volatile as this will impact performance, // and the worst that will happen is we'll end up loading more data on a bootstrap if (identifierUpdatedBytes.readLong(offset) < timestamp) identifierUpdatedBytes.writeLong(offset, timestamp); } @Override public long lastModificationTime(byte remoteIdentifier) { assert remoteIdentifier != this.identifier(); // purposely not volatile as this will impact performance, // and the worst that will happen is we'll end up loading more data on a bootstrap return identifierUpdatedBytes.readLong(remoteIdentifier * 8L); } @Override void onHeaderCreated() { long offset = super.mapHeaderInnerSize(); identifierUpdatedBytes = ms.bytes(offset, LAST_UPDATED_HEADER_SIZE).zeroOut(); offset += LAST_UPDATED_HEADER_SIZE; Bytes modDelBytes = ms.bytes(offset, assignedModIterBitSetSizeInBytes()).zeroOut(); offset += assignedModIterBitSetSizeInBytes(); startOfModificationIterators = offset; modIterSet = new ATSDirectBitSet(modDelBytes); } @Override public void clear() { // we have to make sure that every calls notifies on remove, // so that the replicators can pick it up for (Iterator<Entry<K, V>> iterator = entrySet().iterator(); iterator.hasNext(); ) { iterator.next(); iterator.remove(); } } void addCloseable(Closeable closeable) { closeables.add(closeable); } @Override public void close() { for (Closeable closeable : closeables) { try { closeable.close(); } catch (IOException e) { LOG.error("", e); } } super.close(); } @Override public byte identifier() { return localIdentifier; } @Override public Replica.ModificationIterator acquireModificationIterator( byte remoteIdentifier, @NotNull final ModificationNotifier modificationNotifier) { ModificationIterator modificationIterator = modificationIterators.get(remoteIdentifier); if (modificationIterator != null) return modificationIterator; synchronized (modificationIterators) { modificationIterator = modificationIterators.get(remoteIdentifier); if (modificationIterator != null) return modificationIterator; final Bytes bytes = ms.bytes(startOfModificationIterators + (modIterBitSetSizeInBytes() * remoteIdentifier), modIterBitSetSizeInBytes()); final ModificationIterator newModificationIterator = new ModificationIterator( bytes, modificationNotifier); modificationIterators.set(remoteIdentifier, newModificationIterator); modIterSet.set(remoteIdentifier); return newModificationIterator; } } void raiseChange(long segmentIndex, long pos) { for (long next = modIterSet.nextSetBit(0L); next > 0L; next = modIterSet.nextSetBit(next + 1L)) { try { modificationIterators.get((int) next).raiseChange(segmentIndex, pos); } catch (Exception e) { LOG.error("", e); } } } void dropChange(long segmentIndex, long pos) { for (long next = modIterSet.nextSetBit(0L); next > 0L; next = modIterSet.nextSetBit(next + 1L)) { try { modificationIterators.get((int) next).dropChange(segmentIndex, pos); } catch (Exception e) { LOG.error("", e); } } } public boolean identifierCheck(@NotNull Bytes entry, int chronicleId) { long start = entry.position(); try { final long keySize = keySizeMarshaller.readSize(entry); entry.skip(keySize + 8); // we skip 8 for the timestamp final byte identifier = entry.readByte(); return identifier == localIdentifier; } finally { entry.position(start); } } static class ReplicatedContext<K, KI, MKI extends MetaBytesInterop<K, ? super KI>, V, VI, MVI extends MetaBytesInterop<V, ? super VI>> extends VanillaContext<K, KI, MKI, V, VI, MVI> { ReplicatedContext() { super(); } ReplicatedContext(VanillaContext contextCache, int indexInContextCache) { super(contextCache, indexInContextCache); } ReplicatedChronicleMap<K, KI, MKI, V, VI, MVI> m() { return (ReplicatedChronicleMap<K, KI, MKI, V, VI, MVI>) m; } ///////////////////////////////////////////////// // Replication state long replicationBytesOffset; long timestamp; byte identifier; @Override void keyFound() { initReplicationBytesOffset0(); timestamp = entry.readLong(replicationBytesOffset); identifier = entry.readByte(replicationBytesOffset + 8L); state = entry.readBoolean(replicationBytesOffset + 9L) ? DELETED : PRESENT; } void initReplicationBytesOffset0() { replicationBytesOffset = keyOffset + keySize; } @Override void initKeyOffset0() { super.initKeyOffset0(); initReplicationBytesOffset0(); } void closeReplicationState() { if (replicationBytesOffset == 0L) return; closeReplicationState0(); } void closeReplicationState0() { replicationBytesOffset = 0L; timestamp = 0L; identifier = (byte) 0; } @Override void closeKeySearchDependants() { super.closeKeySearchDependants(); closeReplicationState(); } @Override void initValueSizeOffset0() { valueSizeOffset = replicationBytesOffset + ADDITIONAL_ENTRY_BYTES; } ///////////////////////////////////////////////// // Replication update long newTimestamp; byte newIdentifier; void initReplicationUpdate() { if (newIdentifier != 0) return; checkMapInit(); initReplicationUpdate0(); } void initReplicationUpdate0() { newTimestamp = m().timeProvider.currentTime(); newIdentifier = m().identifier(); } boolean remoteUpdate() { return newIdentifier != m().identifier(); } void closeReplicationUpdate() { if (newIdentifier == 0) return; closeReplicationUpdate0(); } void closeReplicationUpdate0() { newTimestamp = 0L; newIdentifier = (byte) 0; } @Override void initRemoveDependencies() { super.initRemoveDependencies(); initReplicationUpdate(); } void writeReplicationBytes() { entry.writeLong(replicationBytesOffset, newTimestamp); entry.writeByte(replicationBytesOffset + 8L, newIdentifier); } void writeDeleted() { entry.writeBoolean(replicationBytesOffset + 9L, true); } void writePresent() { entry.writeBoolean(replicationBytesOffset + 9L, false); } @Override boolean put0() { try { switch (state) { case PRESENT: case DELETED: if (!shouldIgnore()) { initValueBytes(); putValue(); break; } else { return false; } case ABSENT: putEntry(); } state = PRESENT; return true; } finally { closeReplicationUpdate(); } } @Override boolean freeListBitsSet() { // As of now, ReplicatedChMap's remove() never clear the bits return true; } @Override void initPutDependencies() { super.initPutDependencies(); initReplicationUpdate(); } @Override void writeNewValueAndSwitch() { super.writeNewValueAndSwitch(); writeReplicationBytes(); updateChange(); timestamp = newTimestamp; identifier = newIdentifier; } @Override void beforePutPos() { writePresent(); } class PseudoMetaBytesInterop implements MetaBytesInterop<Object, Object> { @Override public boolean startsWith(Object interop, Bytes bytes, Object o) { throw new UnsupportedOperationException(); } @Override public long hash(Object interop, Object o) { throw new UnsupportedOperationException(); } @Override public long size(Object writer, Object o) { throw new UnsupportedOperationException(); } @Override public void write(Object writer, Bytes bytes, Object o) { bytes.skip(newValueSize); } } final MetaBytesInterop<V, VI> pseudoMetaValueInterop = (MetaBytesInterop<V, VI>) new PseudoMetaBytesInterop(); @Override boolean remove0() { if (containsKey()) { if (!shouldIgnore()) { writeReplicationBytes(); writeDeleted(); updateChange(); size(size() - 1L); state = DELETED; return true; } else { return false; } } else { if (pos >= 0L) { if (!shouldIgnore()) { writeReplicationBytes(); updateChange(); } } else { newValue = (V) pseudoMetaValueInterop; metaValueInterop = (MVI) pseudoMetaValueInterop; newValueSize = m.valueSizeMarshaller.minEncodableSize(); put0(); size(size() - 1L); writeDeleted(); state = DELETED; } return false; } } void updateChange() { if (remoteUpdate()) { m().dropChange(segmentIndex, pos); } else { m().raiseChange(segmentIndex, pos); } } @Override void closeRemove() { closeReplicationUpdate(); } boolean shouldIgnore() { assert identifier != 0 && newIdentifier != 0 : "Own entry replication state or " + "update replication state is not initialized"; if (timestamp < newTimestamp) return false; if (timestamp > newTimestamp) return true; return identifier > newIdentifier; } public void dirtyEntries(final long dirtyFromTimeStamp, final ReplicatedChronicleMap.ModificationIterator modIter, final boolean bootstrapOnlyLocalEntries) { readLock().lock(); try { hashLookup.forEach(new HashLookup.EntryConsumer() { @Override public void accept(long hash, long pos) { ReplicatedContext.this.pos = pos; initKeyFromPos(); keyFound(); assert timestamp > 0L; if (timestamp >= dirtyFromTimeStamp && (!bootstrapOnlyLocalEntries || identifier == m().identifier())) modIter.raiseChange(segmentIndex, pos); } }); } finally { readLock().unlock(); } } } enum ReplicatedContextFactory implements ContextFactory<ReplicatedContext> { INSTANCE; @Override public ReplicatedContext createContext(VanillaContext root, int indexInContextCache) { return new ReplicatedContext(root, indexInContextCache); } @Override public ReplicatedContext createRootContext() { return new ReplicatedContext(); } @Override public Class<ReplicatedContext> contextClass() { return ReplicatedContext.class; } } @Override ReplicatedContext<K, KI, MKI, V, VI, MVI> rawContext() { return VanillaContext.get(ReplicatedContextFactory.INSTANCE); } @Override VanillaContext rawBytesContext() { return VanillaContext.get(BytesReplicatedContextFactory.INSTANCE); } static class BytesReplicatedContext extends ReplicatedContext<Bytes, BytesBytesInterop, DelegatingMetaBytesInterop<Bytes, BytesBytesInterop>, Bytes, BytesBytesInterop, DelegatingMetaBytesInterop<Bytes, BytesBytesInterop>> { BytesReplicatedContext() { super(); } BytesReplicatedContext(VanillaContext contextCache, int indexInContextCache) { super(contextCache, indexInContextCache); } @Override void initKeyModel0() { initBytesKeyModel0(); } @Override void initKey0(Bytes key) { initBytesKey0(key); } @Override void initValueModel0() { initBytesValueModel0(); } @Override void initNewValue0(Bytes newValue) { initNewBytesValue0(newValue); } @Override void closeValue0() { closeBytesValue0(); } @Override public Bytes get() { return getBytes(); } @Override public Bytes getUsing(Bytes usingValue) { return getBytesUsing(usingValue); } } enum BytesReplicatedContextFactory implements ContextFactory<BytesReplicatedContext> { INSTANCE; @Override public BytesReplicatedContext createContext(VanillaContext root, int indexInContextCache) { return new BytesReplicatedContext(root, indexInContextCache); } @Override public BytesReplicatedContext createRootContext() { return new BytesReplicatedContext(); } @Override public Class<BytesReplicatedContext> contextClass() { return BytesReplicatedContext.class; } } @Override VanillaContext<K, KI, MKI, V, VI, MVI> acquireContext(K key) { ReplicatedAcquireContext<K, KI, MKI, V, VI, MVI> c = VanillaContext.get(ReplicatedAcquireContextFactory.INSTANCE); c.initMap(this); c.initKey(key); return c; } static class ReplicatedAcquireContext<K, KI, MKI extends MetaBytesInterop<K, ? super KI>, V, VI, MVI extends MetaBytesInterop<V, ? super VI>> extends ReplicatedContext<K, KI, MKI, V, VI, MVI> { ReplicatedAcquireContext() { super(); } ReplicatedAcquireContext(VanillaContext contextCache, int indexInContextCache) { super(contextCache, indexInContextCache); } @Override public boolean put(V newValue) { return acquirePut(newValue); } @Override public boolean remove() { return acquireRemove(); } @Override public void close() { acquireClose(); } } enum ReplicatedAcquireContextFactory implements ContextFactory<ReplicatedAcquireContext> { INSTANCE; @Override public ReplicatedAcquireContext createContext(VanillaContext root, int indexInContextCache) { return new ReplicatedAcquireContext(root, indexInContextCache); } @Override public ReplicatedAcquireContext createRootContext() { return new ReplicatedAcquireContext(); } @Override public Class<ReplicatedAcquireContext> contextClass() { return ReplicatedAcquireContext.class; } } public int sizeOfEntry(@NotNull Bytes entry, int chronicleId) { long start = entry.position(); try { final long keySize = keySizeMarshaller.readSize(entry); entry.skip(keySize + 8); // we skip 8 for the timestamp final byte identifier = entry.readByte(); if (identifier != localIdentifier) { // although unlikely, this may occur if the entry has been updated return 0; } final boolean isDeleted = entry.readBoolean(); long valueSize; if (!isDeleted) { valueSize = valueSizeMarshaller.readSize(entry); } else { valueSize = 0L; } alignment.alignPositionAddr(entry); long result = (entry.position() + valueSize - start); // entries can be larger than Integer.MAX_VALUE as we are restricted to the size we can // make a byte buffer assert result < Integer.MAX_VALUE; return (int) result; } finally { entry.position(start); } } /** * This method does not set a segment lock, A segment lock should be obtained before calling * this method, especially when being used in a multi threaded context. */ @Override public void writeExternalEntry(@NotNull Bytes entry, @NotNull Bytes destination, int chronicleId) { final long initialLimit = entry.limit(); final long keySize = keySizeMarshaller.readSize(entry); final long keyPosition = entry.position(); entry.skip(keySize); final long keyLimit = entry.position(); final long timeStamp = entry.readLong(); final byte identifier = entry.readByte(); if (identifier != localIdentifier) { // although unlikely, this may occur if the entry has been updated return; } final boolean isDeleted = entry.readBoolean(); long valueSize; if (!isDeleted) { valueSize = valueSizeMarshaller.readSize(entry); } else { valueSize = 0L; } final long valuePosition = entry.position(); keySizeMarshaller.writeSize(destination, keySize); valueSizeMarshaller.writeSize(destination, valueSize); destination.writeStopBit(timeStamp); destination.writeByte(identifier); destination.writeBoolean(isDeleted); // write the key entry.position(keyPosition); entry.limit(keyLimit); destination.write(entry); boolean debugEnabled = LOG.isDebugEnabled(); String message = null; if (debugEnabled) { if (isDeleted) { LOG.debug("WRITING ENTRY TO DEST - into local-id={}, remove(key={})", localIdentifier, entry.toString().trim()); } else { message = String.format( "WRITING ENTRY TO DEST - into local-id=%d, put(key=%s,", localIdentifier, entry.toString().trim()); } } if (isDeleted) return; entry.limit(initialLimit); entry.position(valuePosition); // skipping the alignment, as alignment wont work when we send the data over the wire. alignment.alignPositionAddr(entry); // writes the value entry.limit(entry.position() + valueSize); destination.write(entry); if (debugEnabled) { LOG.debug(message + "value=" + entry.toString().trim() + ")"); } } /** * This method does not set a segment lock, A segment lock should be obtained before calling * this method, especially when being used in a multi threaded context. */ @Override public void readExternalEntry(@NotNull BytesReplicatedContext context, @NotNull Bytes source) { // TODO cache contexts per map -- don't init map on each readExternalEntry() context.initMap(this); try { final long keySize = keySizeMarshaller.readSize(source); final long valueSize = valueSizeMarshaller.readSize(source); final long timeStamp = source.readStopBit(); final byte id = source.readByte(); final boolean isDeleted = source.readBoolean(); final byte remoteIdentifier; if (id != 0) { remoteIdentifier = id; } else { throw new IllegalStateException("identifier can't be 0"); } if (remoteIdentifier == ReplicatedChronicleMap.this.identifier()) { // this may occur when working with UDP, as we may receive our own data return; } context.newTimestamp = timeStamp; context.newIdentifier = remoteIdentifier; final long keyPosition = source.position(); final long keyLimit = keyPosition + keySize; source.limit(keyLimit); context.metaKeyInterop = DelegatingMetaBytesInterop.instance(); context.keySize = keySize; context.initBytesKey00(source); boolean debugEnabled = LOG.isDebugEnabled(); context.updateLock().lock(); if (isDeleted) { if (debugEnabled) { LOG.debug("READING FROM SOURCE - into local-id={}, remote={}, remove(key={})", localIdentifier, remoteIdentifier, source.toString().trim() ); } context.remove(); setLastModificationTime(remoteIdentifier, timeStamp); return; } String message = null; if (debugEnabled) { message = String.format( "READING FROM SOURCE - into local-id=%d, remote-id=%d, put(key=%s,", localIdentifier, remoteIdentifier, source.toString().trim()); } final long valuePosition = keyLimit; final long valueLimit = valuePosition + valueSize; // compute hash => segment and locate the entry context.containsKey(); context.metaValueInterop = DelegatingMetaBytesInterop.instance(); context.newValueSize = valueSize; source.limit(valueLimit); source.position(valuePosition); context.initNewBytesValue00(source); context.initPutDependencies(); context.put0(); setLastModificationTime(remoteIdentifier, timeStamp); if (debugEnabled) { LOG.debug(message + "value=" + source.toString().trim() + ")"); } } finally { context.closeMap(); } } @Override Set<Entry<K, V>> newEntrySet() { return new EntrySet(); } @Override public K key(@NotNull Bytes entry, K usingKey) { final long start = entry.position(); try { long keySize = keySizeMarshaller.readSize(entry); ThreadLocalCopies copies = keyReaderProvider.getCopies(null); return keyReaderProvider.get(copies, originalKeyReader).read(entry, keySize); } finally { entry.position(start); } } @Override public V value(@NotNull Bytes entry, V usingValue) { final long start = entry.position(); try { entry.skip(keySizeMarshaller.readSize(entry)); //timeStamp entry.readLong(); final byte identifier = entry.readByte(); if (identifier != localIdentifier) { return null; } final boolean isDeleted = entry.readBoolean(); long valueSize; if (!isDeleted) { valueSize = valueSizeMarshaller.readSize(entry); assert valueSize > 0; } else { return null; } alignment.alignPositionAddr(entry); ThreadLocalCopies copies = valueReaderProvider.getCopies(null); BytesReader<V> valueReader = valueReaderProvider.get(copies, originalValueReader); return valueReader.read(entry, valueSize, usingValue); } finally { entry.position(start); } } @Override public boolean wasRemoved(@NotNull Bytes entry) { final long start = entry.position(); try { return entry.readBoolean(keySizeMarshaller.readSize(entry) + 9L); } finally { entry.position(start); } } /** * <p>Once a change occurs to a map, map replication requires that these changes are picked up * by another thread, this class provides an iterator like interface to poll for such changes. * </p> <p>In most cases the thread that adds data to the node is unlikely to be the same thread * that replicates the data over to the other nodes, so data will have to be marshaled between * the main thread storing data to the map, and the thread running the replication. </p> <p>One * way to perform this marshalling, would be to pipe the data into a queue. However, This class * takes another approach. It uses a bit set, and marks bits which correspond to the indexes of * the entries that have changed. It then provides an iterator like interface to poll for such * changes. </p> * * @author Rob Austin. */ class ModificationIterator implements Replica.ModificationIterator { private final ModificationNotifier modificationNotifier; private final SingleThreadedDirectBitSet changesForUpdates; // to getVolatile when reading changes bits, because we iterate when without lock. // hardly this is needed on x86, probably on other architectures too. // Anyway getVolatile is cheap. private final ATSDirectBitSet changesForIteration; private final int segmentIndexShift; private final long posMask; private final ReplicatedContext<K, KI, MKI, V, VI, MVI> context = (ReplicatedContext<K, KI, MKI, V, VI, MVI>) mapContext(); // records the current position of the cursor in the bitset private long position = -1L; /** * @param bytes the back the bitset, used to mark which entries have changed * @param modificationNotifier called when ever there is a change applied */ public ModificationIterator(@NotNull final Bytes bytes, @NotNull final ModificationNotifier modificationNotifier) { this.modificationNotifier = modificationNotifier; long bitsPerSegment = bitsPerSegmentInModIterBitSet(); segmentIndexShift = Long.numberOfTrailingZeros(bitsPerSegment); posMask = bitsPerSegment - 1L; changesForUpdates = new SingleThreadedDirectBitSet(bytes); changesForIteration = new ATSDirectBitSet(bytes); } /** * used to merge multiple segments and positions into a single index used by the bit map * * @param segmentIndex the index of the maps segment * @param pos the position within this {@code segmentIndex} * @return and index the has combined the {@code segmentIndex} and {@code pos} into a * single value */ private long combine(long segmentIndex, long pos) { return (segmentIndex << segmentIndexShift) | pos; } void raiseChange(long segmentIndex, long pos) { changesForUpdates.set(combine(segmentIndex, pos)); modificationNotifier.onChange(); } void dropChange(long segmentIndex, long pos) { changesForUpdates.clear(combine(segmentIndex, pos)); } /** * you can continue to poll hasNext() until data becomes available. If are are in the middle * of processing an entry via {@code nextEntry}, hasNext will return true until the bit is * cleared * * @return true if there is an entry */ @Override public boolean hasNext() { final long position = this.position; return changesForIteration.nextSetBit(position == NOT_FOUND ? 0L : position) != NOT_FOUND || (position > 0L && changesForIteration.nextSetBit(0L) != NOT_FOUND); } /** * @param entryCallback call this to get an entry, this class will take care of the locking * @return true if an entry was processed */ @Override public boolean nextEntry(@NotNull EntryCallback entryCallback, int chronicleId) { long position = this.position; while (true) { long oldPosition = position; position = changesForIteration.nextSetBit(oldPosition + 1L); if (position == NOT_FOUND) { if (oldPosition == NOT_FOUND) { this.position = NOT_FOUND; return false; } continue; } this.position = position; int segmentIndex = (int) (position >>> segmentIndexShift); if (context.segmentIndex != segmentIndex) { context.closeSegmentIndex(); context.segmentIndex = segmentIndex; context.initLocks(); context.initSegment(); } context.updateLock().lock(); try { if (changesForUpdates.get(position)) { entryCallback.onBeforeEntry(); final long segmentPos = position & posMask; context.reuse(segmentPos); // if the entry should be ignored, we'll move the next entry if (entryCallback.shouldBeIgnored(context.entry, chronicleId)) { changesForUpdates.clear(position); continue; } // it may not be successful if the buffer can not be re-sized so we will // process it later, by NOT clearing the changes.clear(position) boolean success = entryCallback.onEntry(context.entry, chronicleId); entryCallback.onAfterEntry(); if (success) changesForUpdates.clear(position); return success; } // if the position was already cleared by another thread // while we were trying to obtain segment lock (for example, in onRelocation()), // go to pick up next (next iteration in while (true) loop) } finally { context.updateLock().unlock(); } } } @Override public void dirtyEntries(long fromTimeStamp) { try (ReplicatedContext<K, KI, MKI, V, VI, MVI> context = (ReplicatedContext<K, KI, MKI, V, VI, MVI>) mapContext()) { // iterate over all the segments and mark bit in the modification iterator // that correspond to entries with an older timestamp for (int i = 0; i < actualSegments; i++) { context.segmentIndex = i; context.initSegment(); try { context.dirtyEntries(fromTimeStamp, this, bootstrapOnlyLocalEntries); } finally { context.closeSegmentIndex(); } } } } } }
Fixed bug in ReplicatedChronicleMap
src/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java
Fixed bug in ReplicatedChronicleMap
<ide><path>rc/main/java/net/openhft/chronicle/map/ReplicatedChronicleMap.java <ide> } <ide> <ide> @Override <add> long sizeOfEverythingBeforeValue(long keySize, long valueSize) { <add> return super.sizeOfEverythingBeforeValue(keySize, valueSize) + ADDITIONAL_ENTRY_BYTES; <add> } <add> <add> @Override <ide> boolean put0() { <ide> try { <ide> switch (state) {
Java
apache-2.0
f912e0694a30f1955bff971f7fe3415e6a72de9d
0
webfirmframework/wff,webfirmframework/wff
/* * Copyright 2014-2019 Web Firm Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webfirmframework.wffweb.js; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.webfirmframework.wffweb.InvalidValueException; import com.webfirmframework.wffweb.util.StringUtil; /** * Utility methods to generate JavaScript code. * * @author WFF * @since 2.1.1 */ public final class JsUtil { private JsUtil() { throw new AssertionError(); } /** * @param jsKeyAndElementId * The map containing key values. The key in * the map will be used as the key in the * generated js object. The value in the map * should be the id of the field. * @return the JavaScript object for the fields value. Sample : * <code>{username:document.getElementById('uId').value}</code> * @since 2.1.1 * @author WFF */ public static String getJsObjectForFieldsValue( final Map<String, Object> jsKeyAndElementId) { final StringBuilder builder = new StringBuilder(38); builder.append('{'); for (final Entry<String, Object> entry : jsKeyAndElementId.entrySet()) { builder.append(entry.getKey()).append(":document.getElementById('") .append(entry.getValue().toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param jsKeyAndElementId * The map containing key values. The key in * the map will be used as the key in the * generated js object. The value in the map * should be the id of the field. * @param alternativeFunction * alternative function name for * document.getElementById * * @return the JavaScript object for the fields value. Sample : * <code>{username:gebi('uId').value}</code> if the * alternativeFunction is gebi * @since 3.0.1 * @author WFF */ public static String getJsObjectForFieldsValue( final Map<String, Object> jsKeyAndElementId, final String alternativeFunction) { if (StringUtil.isBlank(alternativeFunction)) { throw new InvalidValueException( "alternativeFunction cannot be blank"); } final StringBuilder builder = new StringBuilder(38); builder.append('{'); for (final Entry<String, Object> entry : jsKeyAndElementId.entrySet()) { builder.append(entry.getKey()).append(':') .append(alternativeFunction).append("('") .append(entry.getValue().toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param ids * The set containing element ids. The id will be used as the * key in the generated js object. The value in the set * should be the id of the field. The id in the set should be * a valid JavaScript object key. * @return the JavaScript object for the fields value. Sample : * <code>{uId:document.getElementById('uId').value}</code> * @since 2.1.1 * @author WFF */ public static String getJsObjectForFieldsValue(final Set<Object> ids) { final StringBuilder builder = new StringBuilder(75); builder.append('{'); for (final Object id : ids) { builder.append(id.toString()).append(":document.getElementById('") .append(id.toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * * @param ids * The set containing element ids. The id * will be used as the key in the generated * js object. The value in the set should be * the id of the field. The id in the set * should be a valid JavaScript object key. * * @param alternativeFunction * alternative function name for * document.getElementById * * @return the JavaScript object for the fields value. Sample : * <code>{uId:gebi('uId').value} if alternativeFunction is gebi </code> * @since 3.0.1 * @author WFF */ public static String getJsObjectForFieldsValue(final Set<Object> ids, final String alternativeFunction) { if (StringUtil.isBlank(alternativeFunction)) { throw new InvalidValueException( "alternativeFunction cannot be blank"); } final StringBuilder builder = new StringBuilder(75); builder.append('{'); for (final Object id : ids) { builder.append(id.toString()).append(':') .append(alternativeFunction).append("('") .append(id.toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param ids * The string array containing element ids. The id will be * used as the key in the generated js object. The value in * the array should be the id of the field. The id in the * array should be a valid JavaScript object key. * @return the JavaScript object for the fields value. Sample : * <code>{uId:document.getElementById('uId'.value)}</code> * @since 2.1.3 * @author WFF */ public static String getJsObjectForFieldsValue(final String... ids) { final StringBuilder builder = new StringBuilder(38); builder.append('{'); for (final Object id : ids) { builder.append(id.toString()).append(":document.getElementById('") .append(id.toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param ids * The string array containing element ids. * The id will be used as the key in the * generated js object. The value in the * array should be the id of the field. The * id in the array should be a valid * JavaScript object key. * @param alternativeFunction * alternative function name for * document.getElementById * @return the JavaScript object for the fields value. Sample : * <code>{uId:document.getElementById('uId'.value)}</code> * @since 3.0.1 * @author WFF */ public static String getJsObjectForFieldsValueWithAltFun( final String alternativeFunction, final String... ids) { if (StringUtil.isBlank(alternativeFunction)) { throw new InvalidValueException( "alternativeFunction cannot be blank"); } final StringBuilder builder = new StringBuilder(38); builder.append('{'); for (final Object id : ids) { builder.append(id.toString()).append(':') .append(alternativeFunction).append("('") .append(id.toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param inputIds * input field ids such as input type text etc.. * @param checkboxIds * checkbox field ids such as input type checkbox * @return the JavaScript object for the fields value. Sample : * <code>{usernameInputId:document.getElementById('usernameInputId').value,dateExpiredCheckboxId:document.getElementById('dateExpiredCheckboxId').checked}</code> * @since 3.0.1 */ public static String getJsObjectForFieldsValue(final Set<Object> inputIds, final Set<Object> checkboxIds) { final StringBuilder builder = new StringBuilder(75); builder.append('{'); for (final Object id : inputIds) { builder.append(id.toString()).append(":document.getElementById('") .append(id.toString()).append("').value,"); } for (final Object id : checkboxIds) { builder.append(id.toString()).append(":document.getElementById('") .append(id.toString()).append("').checked,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * * @param inputIds * input field ids such as input type text * etc.. * @param checkboxIds * checkbox field ids such as input type * checkbox * @param alternativeFunction * alternative function name for * document.getElementById * @return the JavaScript object for the fields value. Sample : * <code>{usernameInputId:document.getElementById('usernameInputId').value,dateExpiredCheckboxId:document.getElementById('dateExpiredCheckboxId').checked}</code> * @since 3.0.1 */ public static String getJsObjectForFieldsValue(final Set<Object> inputIds, final Set<Object> checkboxIds, final String alternativeFunction) { if (StringUtil.isBlank(alternativeFunction)) { throw new InvalidValueException( "alternativeFunction cannot be blank"); } final StringBuilder builder = new StringBuilder(75); builder.append('{'); for (final Object id : inputIds) { builder.append(id.toString()).append(':') .append(alternativeFunction).append("('") .append(id.toString()).append("').value,"); } for (final Object id : checkboxIds) { builder.append(id.toString()).append(':') .append(alternativeFunction).append("('") .append(id.toString()).append("').checked,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } }
wffweb/src/main/java/com/webfirmframework/wffweb/js/JsUtil.java
/* * Copyright 2014-2019 Web Firm Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webfirmframework.wffweb.js; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.webfirmframework.wffweb.InvalidValueException; import com.webfirmframework.wffweb.util.StringUtil; /** * Utility methods to generate JavaScript code. * * @author WFF * @since 2.1.1 */ public final class JsUtil { private JsUtil() { throw new AssertionError(); } /** * @param jsKeyAndElementId * The map containing key values. The key in * the map will be used as the key in the * generated js object. The value in the map * should be the id of the field. * @return the JavaScript object for the fields value. Sample : * <code>{username:document.getElementById('uId').value}</code> * @since 2.1.1 * @author WFF */ public static String getJsObjectForFieldsValue( final Map<String, Object> jsKeyAndElementId) { final StringBuilder builder = new StringBuilder(38); builder.append('{'); for (final Entry<String, Object> entry : jsKeyAndElementId.entrySet()) { builder.append(entry.getKey()).append(":document.getElementById('") .append(entry.getValue().toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param jsKeyAndElementId * The map containing key values. The key in * the map will be used as the key in the * generated js object. The value in the map * should be the id of the field. * @param alternativeFunction * alternative function name for * document.getElementById * * @return the JavaScript object for the fields value. Sample : * <code>{username:gebi('uId').value}</code> if the * alternativeFunction is gebi * @since 3.0.1 * @author WFF */ public static String getJsObjectForFieldsValue( final Map<String, Object> jsKeyAndElementId, final String alternativeFunction) { if (StringUtil.isBlank(alternativeFunction)) { throw new InvalidValueException( "alternativeFunction cannot be blank"); } final StringBuilder builder = new StringBuilder(38); builder.append('{'); for (final Entry<String, Object> entry : jsKeyAndElementId.entrySet()) { builder.append(entry.getKey()).append(':') .append(alternativeFunction).append("('") .append(entry.getValue().toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param ids * The set containing element ids. The id will be used as the * key in the generated js object. The value in the set * should be the id of the field. The id in the set should be * a valid JavaScript object key. * @return the JavaScript object for the fields value. Sample : * <code>{uId:document.getElementById('uId').value}</code> * @since 2.1.1 * @author WFF */ public static String getJsObjectForFieldsValue(final Set<Object> ids) { final StringBuilder builder = new StringBuilder(75); builder.append('{'); for (final Object id : ids) { builder.append(id.toString()).append(":document.getElementById('") .append(id.toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * * @param ids * The set containing element ids. The id * will be used as the key in the generated * js object. The value in the set should be * the id of the field. The id in the set * should be a valid JavaScript object key. * * @param alternativeFunction * alternative function name for * document.getElementById * * @return the JavaScript object for the fields value. Sample : * <code>{uId:gebi('uId').value} if alternativeFunction is gebi </code> * @since 3.0.1 * @author WFF */ public static String getJsObjectForFieldsValue(final Set<Object> ids, final String alternativeFunction) { if (StringUtil.isBlank(alternativeFunction)) { throw new InvalidValueException( "alternativeFunction cannot be blank"); } final StringBuilder builder = new StringBuilder(75); builder.append('{'); for (final Object id : ids) { builder.append(id.toString()).append(":") .append(alternativeFunction).append("('") .append(id.toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param ids * The string array containing element ids. The id will be * used as the key in the generated js object. The value in * the array should be the id of the field. The id in the * array should be a valid JavaScript object key. * @return the JavaScript object for the fields value. Sample : * <code>{uId:document.getElementById('uId'.value)}</code> * @since 2.1.3 * @author WFF */ public static String getJsObjectForFieldsValue(final String... ids) { final StringBuilder builder = new StringBuilder(38); builder.append('{'); for (final Object id : ids) { builder.append(id.toString()).append(":document.getElementById('") .append(id.toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param ids * The string array containing element ids. * The id will be used as the key in the * generated js object. The value in the * array should be the id of the field. The * id in the array should be a valid * JavaScript object key. * @param alternativeFunction * alternative function name for * document.getElementById * @return the JavaScript object for the fields value. Sample : * <code>{uId:document.getElementById('uId'.value)}</code> * @since 3.0.1 * @author WFF */ public static String getJsObjectForFieldsValueWithAltFun( final String alternativeFunction, final String... ids) { if (StringUtil.isBlank(alternativeFunction)) { throw new InvalidValueException( "alternativeFunction cannot be blank"); } final StringBuilder builder = new StringBuilder(38); builder.append('{'); for (final Object id : ids) { builder.append(id.toString()).append(":") .append(alternativeFunction).append("('") .append(id.toString()).append("').value,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * @param inputIds * input field ids such as input type text etc.. * @param checkboxIds * checkbox field ids such as input type checkbox * @return the JavaScript object for the fields value. Sample : * <code>{usernameInputId:document.getElementById('usernameInputId').value,dateExpiredCheckboxId:document.getElementById('dateExpiredCheckboxId').checked}</code> * @since 3.0.1 */ public static String getJsObjectForFieldsValue(final Set<Object> inputIds, final Set<Object> checkboxIds) { final StringBuilder builder = new StringBuilder(75); builder.append('{'); for (final Object id : inputIds) { builder.append(id.toString()).append(":document.getElementById('") .append(id.toString()).append("').value,"); } for (final Object id : checkboxIds) { builder.append(id.toString()).append(":document.getElementById('") .append(id.toString()).append("').checked,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } /** * * @param inputIds * input field ids such as input type text * etc.. * @param checkboxIds * checkbox field ids such as input type * checkbox * @param alternativeFunction * alternative function name for * document.getElementById * @return the JavaScript object for the fields value. Sample : * <code>{usernameInputId:document.getElementById('usernameInputId').value,dateExpiredCheckboxId:document.getElementById('dateExpiredCheckboxId').checked}</code> * @since 3.0.1 */ public static String getJsObjectForFieldsValue(final Set<Object> inputIds, final Set<Object> checkboxIds, final String alternativeFunction) { if (StringUtil.isBlank(alternativeFunction)) { throw new InvalidValueException( "alternativeFunction cannot be blank"); } final StringBuilder builder = new StringBuilder(75); builder.append('{'); for (final Object id : inputIds) { builder.append(id.toString()).append(":") .append(alternativeFunction).append("('") .append(id.toString()).append("').value,"); } for (final Object id : checkboxIds) { builder.append(id.toString()).append(':') .append(alternativeFunction).append("('") .append(id.toString()).append("').checked,"); } builder.replace(builder.length() - 1, builder.length(), "}"); return builder.toString(); } }
Minor code optimization
wffweb/src/main/java/com/webfirmframework/wffweb/js/JsUtil.java
Minor code optimization
<ide><path>ffweb/src/main/java/com/webfirmframework/wffweb/js/JsUtil.java <ide> <ide> for (final Object id : ids) { <ide> <del> builder.append(id.toString()).append(":") <add> builder.append(id.toString()).append(':') <ide> .append(alternativeFunction).append("('") <ide> .append(id.toString()).append("').value,"); <ide> <ide> <ide> for (final Object id : ids) { <ide> <del> builder.append(id.toString()).append(":") <add> builder.append(id.toString()).append(':') <ide> .append(alternativeFunction).append("('") <ide> .append(id.toString()).append("').value,"); <ide> <ide> <ide> for (final Object id : inputIds) { <ide> <del> builder.append(id.toString()).append(":") <add> builder.append(id.toString()).append(':') <ide> .append(alternativeFunction).append("('") <ide> .append(id.toString()).append("').value,"); <ide>
Java
apache-2.0
dba059350e165ccadcc562837f32deadb78ef6b9
0
structurizr/java,klu2/structurizr-java
package com.structurizr.api; import com.structurizr.Workspace; import com.structurizr.io.json.JsonReader; import com.structurizr.io.json.JsonWriter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.*; import java.text.SimpleDateFormat; import java.util.Base64; import java.util.Date; import java.util.Properties; public class StructurizrClient { private static final Log log = LogFactory.getLog(StructurizrClient.class); public static final String STRUCTURIZR_API_URL = "structurizr.api.url"; public static final String STRUCTURIZR_API_KEY = "structurizr.api.key"; public static final String STRUCTURIZR_API_SECRET = "structurizr.api.secret"; private static final String WORKSPACE_PATH = "/workspace/"; private String url; private String apiKey; private String apiSecret; /** the location where a copy of the workspace will be archived when it is retrieved from the server */ private File workspaceArchiveLocation = new File("."); /** * Creates a new Structurizr client based upon configuration in a structurizr.properties file * on the classpath with the following name-value pairs: * - structurizr.api.url * - structurizr.api.key * - structurizr.api.secret */ public StructurizrClient() { try { Properties properties = new Properties(); InputStream in = StructurizrClient.class.getClassLoader().getResourceAsStream("structurizr.properties"); if (in != null) { properties.load(in); setUrl(properties.getProperty(STRUCTURIZR_API_URL)); this.apiKey = properties.getProperty(STRUCTURIZR_API_KEY); this.apiSecret = properties.getProperty(STRUCTURIZR_API_SECRET); in.close(); } } catch (Exception e) { log.error(e); } } /** * Creates a new Structurizr client with the specified API URL, key and secret. */ public StructurizrClient(String url, String apiKey, String apiSecret) { setUrl(url); this.apiKey = apiKey; this.apiSecret = apiSecret; } public String getUrl() { return url; } public void setUrl(String url) { if (url != null) { if (url.endsWith("/")) { this.url = url.substring(0, url.length() - 1); } else { this.url = url; } } } /** * Gets the location where a copy of the workspace is archived when it is retrieved from the server. * * @return a File instance representing a directory, or null if this client instance is not archiving */ public File getWorkspaceArchiveLocation() { return this.workspaceArchiveLocation; } /** * Sets the location where a copy of the workspace will be archived whenever it is retrieved from * the server. Set this to null if you don't want archiving. * * @param workspaceArchiveLocation a File instance representing a directory, or null if * you don't want archiving */ public void setWorkspaceArchiveLocation(File workspaceArchiveLocation) { this.workspaceArchiveLocation = workspaceArchiveLocation; } /** * Gets the workspace with the given ID. * * @param workspaceId the ID of your workspace * @return a Workspace instance * @throws Exception if there are problems related to the network, authorization, JSON deserialization, etc */ public Workspace getWorkspace(long workspaceId) throws Exception { log.info("Getting workspace with ID " + workspaceId); CloseableHttpClient httpClient = HttpClients.createSystem(); HttpGet httpGet = new HttpGet(url + WORKSPACE_PATH + workspaceId); addHeaders(httpGet, "", ""); debugRequest(httpGet, null); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { debugResponse(response); String json = EntityUtils.toString(response.getEntity()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { archiveWorkspace(workspaceId, json); return new JsonReader().read(new StringReader(json)); } else { ApiError apiError = ApiError.parse(json); throw new StructurizrClientException(apiError.getMessage()); } } } /** * Updates the given workspace. * * @param workspaceId the ID of your workspace * @param workspace the workspace instance to update * @throws Exception if there are problems related to the network, authorization, JSON serialization, etc */ public void putWorkspace(long workspaceId, Workspace workspace) throws Exception { log.info("Putting workspace with ID " + workspaceId); if (workspace == null) { throw new IllegalArgumentException("A workspace must be supplied"); } else if (workspaceId <= 0) { throw new IllegalArgumentException("The workspace ID must be set"); } workspace.setId(workspaceId); CloseableHttpClient httpClient = HttpClients.createSystem(); HttpPut httpPut = new HttpPut(url + WORKSPACE_PATH + workspaceId); JsonWriter jsonWriter = new JsonWriter(false); StringWriter stringWriter = new StringWriter(); jsonWriter.write(workspace, stringWriter); StringEntity stringEntity = new StringEntity(stringWriter.toString(), ContentType.APPLICATION_JSON); httpPut.setEntity(stringEntity); addHeaders(httpPut, EntityUtils.toString(stringEntity), ContentType.APPLICATION_JSON.toString()); debugRequest(httpPut, EntityUtils.toString(stringEntity)); try (CloseableHttpResponse response = httpClient.execute(httpPut)) { debugResponse(response); log.debug(EntityUtils.toString(response.getEntity())); } } /** * Fetches the workspace with the given workspaceId from the server and merges its layout information with * the given workspace. All models from the the new workspace are taken, only the old layout information is preserved. * * @param workspaceId the ID of your workspace * @param workspace the new workspace * @throws Exception if you are not allowed to update the workspace with the given ID or there are any network troubles */ public void mergeWorkspace(long workspaceId, Workspace workspace) throws Exception { log.info("Merging workspace with ID " + workspaceId); Workspace currentWorkspace = getWorkspace(workspaceId); if (currentWorkspace != null) { workspace.getViews().copyLayoutInformationFrom(currentWorkspace.getViews()); } putWorkspace(workspaceId, workspace); } private void debugRequest(HttpRequestBase httpRequest, String content) { log.debug(httpRequest.getMethod() + " " + httpRequest.getURI().getPath()); Header[] headers = httpRequest.getAllHeaders(); for (Header header : headers) { log.debug(header.getName() + ": " + header.getValue()); } if (content != null) { log.debug(content); } } private void debugResponse(CloseableHttpResponse response) { log.debug(response.getStatusLine()); } private void addHeaders(HttpRequestBase httpRequest, String content, String contentType) throws Exception { String httpMethod = httpRequest.getMethod(); String path = httpRequest.getURI().getPath(); String contentMd5 = new Md5Digest().generate(content); String nonce = "" + System.currentTimeMillis(); HashBasedMessageAuthenticationCode hmac = new HashBasedMessageAuthenticationCode(apiSecret); HmacContent hmacContent = new HmacContent(httpMethod, path, contentMd5, contentType, nonce); httpRequest.addHeader(HttpHeaders.AUTHORIZATION, new HmacAuthorizationHeader(apiKey, hmac.generate(hmacContent.toString())).format()); httpRequest.addHeader(HttpHeaders.NONCE, nonce); httpRequest.addHeader(HttpHeaders.CONTENT_MD5, Base64.getEncoder().encodeToString(contentMd5.getBytes("UTF-8"))); httpRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType); } private void archiveWorkspace(long workspaceId, String json) { if (this.workspaceArchiveLocation == null) { return; } File archiveFile = new File(workspaceArchiveLocation, createArchiveFileName(workspaceId)); try { FileWriter fileWriter = new FileWriter(archiveFile); fileWriter.write(json); fileWriter.flush(); fileWriter.close(); try { log.debug("Workspace from server archived to " + archiveFile.getCanonicalPath()); } catch (IOException ioe) { log.debug("Workspace from server archived to " + archiveFile.getAbsolutePath()); } } catch (Exception e) { log.warn("Could not archive JSON to " + archiveFile.getAbsolutePath()); } } private String createArchiveFileName(long workspaceId) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); return "structurizr-" + workspaceId + "-" + sdf.format(new Date()) + ".json"; } }
structurizr-client/src/com/structurizr/api/StructurizrClient.java
package com.structurizr.api; import com.structurizr.Workspace; import com.structurizr.io.json.JsonReader; import com.structurizr.io.json.JsonWriter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.*; import java.text.SimpleDateFormat; import java.util.Base64; import java.util.Date; import java.util.Properties; public class StructurizrClient { private static final Log log = LogFactory.getLog(StructurizrClient.class); public static final String STRUCTURIZR_API_URL = "structurizr.api.url"; public static final String STRUCTURIZR_API_KEY = "structurizr.api.key"; public static final String STRUCTURIZR_API_SECRET = "structurizr.api.secret"; private static final String WORKSPACE_PATH = "/workspace/"; private String url; private String apiKey; private String apiSecret; /** the location where a copy of the workspace will be archived when it is retrieved from the server */ private File workspaceArchiveLocation = new File("."); /** * Creates a new Structurizr client based upon configuration in a structurizr.properties file * on the classpath with the following name-value pairs: * - structurizr.api.url * - structurizr.api.key * - structurizr.api.secret */ public StructurizrClient() { try { Properties properties = new Properties(); InputStream in = StructurizrClient.class.getClassLoader().getResourceAsStream("structurizr.properties"); if (in != null) { properties.load(in); setUrl(properties.getProperty(STRUCTURIZR_API_URL)); this.apiKey = properties.getProperty(STRUCTURIZR_API_KEY); this.apiSecret = properties.getProperty(STRUCTURIZR_API_SECRET); in.close(); } } catch (Exception e) { log.error(e); } } /** * Creates a new Structurizr client with the specified API URL, key and secret. */ public StructurizrClient(String url, String apiKey, String apiSecret) { setUrl(url); this.apiKey = apiKey; this.apiSecret = apiSecret; } public String getUrl() { return url; } public void setUrl(String url) { if (url != null) { if (url.endsWith("/")) { this.url = url.substring(0, url.length() - 1); } else { this.url = url; } } } /** * Gets the location where a copy of the workspace is archived when it is retrieved from the server. * * @return a File instance representing a directory, or null if this client instance is not archiving */ public File getWorkspaceArchiveLocation() { return this.workspaceArchiveLocation; } /** * Sets the location where a copy of the workspace will be archived whenever it is retrieved from * the server. Set this to null if you don't want archiving. * * @param workspaceArchiveLocation a File instance representing a directory, or null if * you don't want archiving */ public void setWorkspaceArchiveLocation(File workspaceArchiveLocation) { this.workspaceArchiveLocation = workspaceArchiveLocation; } /** * Gets the workspace with the given ID. * * @param workspaceId the ID of your workspace * @return a Workspace instance * @throws Exception if there are problems related to the network, authorization, JSON deserialization, etc */ public Workspace getWorkspace(long workspaceId) throws Exception { log.info("Getting workspace with ID " + workspaceId); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url + WORKSPACE_PATH + workspaceId); addHeaders(httpGet, "", ""); debugRequest(httpGet, null); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { debugResponse(response); String json = EntityUtils.toString(response.getEntity()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { archiveWorkspace(workspaceId, json); return new JsonReader().read(new StringReader(json)); } else { ApiError apiError = ApiError.parse(json); throw new StructurizrClientException(apiError.getMessage()); } } } /** * Updates the given workspace. * * @param workspaceId the ID of your workspace * @param workspace the workspace instance to update * @throws Exception if there are problems related to the network, authorization, JSON serialization, etc */ public void putWorkspace(long workspaceId, Workspace workspace) throws Exception { log.info("Putting workspace with ID " + workspaceId); if (workspace == null) { throw new IllegalArgumentException("A workspace must be supplied"); } else if (workspaceId <= 0) { throw new IllegalArgumentException("The workspace ID must be set"); } workspace.setId(workspaceId); CloseableHttpClient httpClient = HttpClients.createSystem(); HttpPut httpPut = new HttpPut(url + WORKSPACE_PATH + workspaceId); JsonWriter jsonWriter = new JsonWriter(false); StringWriter stringWriter = new StringWriter(); jsonWriter.write(workspace, stringWriter); StringEntity stringEntity = new StringEntity(stringWriter.toString(), ContentType.APPLICATION_JSON); httpPut.setEntity(stringEntity); addHeaders(httpPut, EntityUtils.toString(stringEntity), ContentType.APPLICATION_JSON.toString()); debugRequest(httpPut, EntityUtils.toString(stringEntity)); try (CloseableHttpResponse response = httpClient.execute(httpPut)) { debugResponse(response); log.debug(EntityUtils.toString(response.getEntity())); } } /** * Fetches the workspace with the given workspaceId from the server and merges its layout information with * the given workspace. All models from the the new workspace are taken, only the old layout information is preserved. * * @param workspaceId the ID of your workspace * @param workspace the new workspace * @throws Exception if you are not allowed to update the workspace with the given ID or there are any network troubles */ public void mergeWorkspace(long workspaceId, Workspace workspace) throws Exception { log.info("Merging workspace with ID " + workspaceId); Workspace currentWorkspace = getWorkspace(workspaceId); if (currentWorkspace != null) { workspace.getViews().copyLayoutInformationFrom(currentWorkspace.getViews()); } putWorkspace(workspaceId, workspace); } private void debugRequest(HttpRequestBase httpRequest, String content) { log.debug(httpRequest.getMethod() + " " + httpRequest.getURI().getPath()); Header[] headers = httpRequest.getAllHeaders(); for (Header header : headers) { log.debug(header.getName() + ": " + header.getValue()); } if (content != null) { log.debug(content); } } private void debugResponse(CloseableHttpResponse response) { log.debug(response.getStatusLine()); } private void addHeaders(HttpRequestBase httpRequest, String content, String contentType) throws Exception { String httpMethod = httpRequest.getMethod(); String path = httpRequest.getURI().getPath(); String contentMd5 = new Md5Digest().generate(content); String nonce = "" + System.currentTimeMillis(); HashBasedMessageAuthenticationCode hmac = new HashBasedMessageAuthenticationCode(apiSecret); HmacContent hmacContent = new HmacContent(httpMethod, path, contentMd5, contentType, nonce); httpRequest.addHeader(HttpHeaders.AUTHORIZATION, new HmacAuthorizationHeader(apiKey, hmac.generate(hmacContent.toString())).format()); httpRequest.addHeader(HttpHeaders.NONCE, nonce); httpRequest.addHeader(HttpHeaders.CONTENT_MD5, Base64.getEncoder().encodeToString(contentMd5.getBytes("UTF-8"))); httpRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType); } private void archiveWorkspace(long workspaceId, String json) { if (this.workspaceArchiveLocation == null) { return; } File archiveFile = new File(workspaceArchiveLocation, createArchiveFileName(workspaceId)); try { FileWriter fileWriter = new FileWriter(archiveFile); fileWriter.write(json); fileWriter.flush(); fileWriter.close(); try { log.debug("Workspace from server archived to " + archiveFile.getCanonicalPath()); } catch (IOException ioe) { log.debug("Workspace from server archived to " + archiveFile.getAbsolutePath()); } } catch (Exception e) { log.warn("Could not archive JSON to " + archiveFile.getAbsolutePath()); } } private String createArchiveFileName(long workspaceId) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); return "structurizr-" + workspaceId + "-" + sdf.format(new Date()) + ".json"; } }
HttpClient now uses system properties for proxy servers. etc.
structurizr-client/src/com/structurizr/api/StructurizrClient.java
HttpClient now uses system properties for proxy servers. etc.
<ide><path>tructurizr-client/src/com/structurizr/api/StructurizrClient.java <ide> public Workspace getWorkspace(long workspaceId) throws Exception { <ide> log.info("Getting workspace with ID " + workspaceId); <ide> <del> CloseableHttpClient httpClient = HttpClients.createDefault(); <add> CloseableHttpClient httpClient = HttpClients.createSystem(); <ide> HttpGet httpGet = new HttpGet(url + WORKSPACE_PATH + workspaceId); <ide> addHeaders(httpGet, "", ""); <ide> debugRequest(httpGet, null); <ide> SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); <ide> return "structurizr-" + workspaceId + "-" + sdf.format(new Date()) + ".json"; <ide> } <del> <add> <ide> }
JavaScript
agpl-3.0
57b063db846d82f5eb30f0bb2b42920ad82d83eb
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
// При добавлении нового элемента ParagraphContent, добавить его обработку в // следующие функции: // Internal_Recalculate1, Internal_Recalculate2, Draw, Internal_RemoveBackward, // Internal_RemoveForward, Add, Internal_GetStartPos, Internal_MoveCursorBackward, // Internal_MoveCursorForward, Internal_AddTextPr, Internal_GetContentPosByXY, // Selection_SetEnd, Selection_CalculateTextPr, IsEmpty, Selection_IsEmpty, // Cursor_IsStart, Cursor_IsEnd, Is_ContentOnFirstPage var type_Paragraph = 0x0001; var UnknownValue = null; // Класс Paragraph function Paragraph(DrawingDocument, Parent, PageNum, X, Y, XLimit, YLimit) { this.Id = g_oIdCounter.Get_NewId(); this.Prev = null; this.Next = null; this.Index = -1; this.Parent = Parent; this.PageNum = PageNum; this.X = X; this.Y = Y; this.XLimit = XLimit; this.YLimit = YLimit; this.CompiledPr = { Pr : null, // Скомпилированный (окончательный стиль параграфа) NeedRecalc : true // Нужно ли пересчитать скомпилированный стиль }; this.Pr = new CParaPr(); // Рассчитанное положение рамки this.CalculatedFrame = { L : 0, // Внутренний рект, по которому идет рассчет T : 0, W : 0, H : 0, L2 : 0, // Внешний рект, с учетом границ T2 : 0, W2 : 0, H2 : 0, PageIndex : 0 }; // Данный TextPr будет относится только к символу конца параграфа this.TextPr = new ParaTextPr(); this.TextPr.Parent = this; this.Bounds = new CDocumentBounds( X, Y, X_Right_Field, Y ); this.RecalcInfo = new CParaRecalcInfo(); this.Pages = new Array(); // Массив страниц (CParaPage) this.Lines = new Array(); // Массив строк (CParaLine) // Добавляем в контент элемент "конец параграфа" this.Content = new Array(); this.Content[0] = new ParaEnd(); this.Content[1] = new ParaEmpty(); this.Numbering = new ParaNumbering(); this.CurPos = { X : 0, Y : 0, ContentPos : 0, Line : -1, RealX : 0, // позиция курсора, без учета расположения букв RealY : 0, // это актуально для клавиш вверх и вниз PagesPos : 0 // позиция в массиве this.Pages }; this.Selection = { Start : false, Use : false, StartPos : 0, EndPos : 0, Flag : selectionflag_Common }; this.NeedReDraw = true; this.DrawingDocument = DrawingDocument; this.LogicDocument = editor.WordControl.m_oLogicDocument; this.TurnOffRecalcEvent = false; this.ApplyToAll = false; // Специальный параметр, используемый в ячейках таблицы. // True, если ячейка попадает в выделение по ячейкам. this.Lock = new CLock(); // Зажат ли данный параграф другим пользователем if ( false === g_oIdCounter.m_bLoad ) { this.Lock.Set_Type( locktype_Mine, false ); CollaborativeEditing.Add_Unlock2( this ); } this.DeleteCollaborativeMarks = true; this.DeleteCommentOnRemove = true; // Удаляем ли комменты в функциях Internal_Content_Remove this.m_oContentChanges = new CContentChanges(); // список изменений(добавление/удаление элементов) // Свойства необходимые для презентаций this.PresentationPr = { Level : 0, Bullet : new CPresentationBullet() }; this.FontMap = { Map : {}, NeedRecalc : true }; this.SearchResults = new Object(); this.SpellChecker = new CParaSpellChecker(); // Добавляем данный класс в таблицу Id (обязательно в конце конструктора) g_oTableId.Add( this, this.Id ); } Paragraph.prototype = { GetType : function() { return type_Paragraph; }, GetId : function() { return this.Id; }, SetId : function(newId) { g_oTableId.Reset_Id( this, newId, this.Id ); this.Id = newId; }, Get_Id : function() { return this.GetId(); }, Set_Id : function(newId) { return this.SetId( newId ); }, Use_Wrap : function() { if ( undefined != this.Get_FramePr() ) return false; return true; }, Use_YLimit : function() { if ( undefined != this.Get_FramePr() && this.Parent instanceof CDocument ) return false; return true; }, Set_Pr : function(oNewPr) { var Pr_old = this.Pr; var Pr_new = oNewPr; History.Add( this, { Type : historyitem_Paragraph_Pr, Old : Pr_old, New : Pr_new } ); this.Pr = oNewPr; }, Copy : function(Parent) { var Para = new Paragraph(this.DrawingDocument, Parent, 0, 0, 0, 0, 0); // Копируем настройки Para.Set_Pr(this.Pr.Copy()); Para.TextPr.Set_Value( this.TextPr.Value ); // Удаляем содержимое нового параграфа Para.Internal_Content_Remove2(0, Para.Content.length); // Копируем содержимое параграфа var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( true === Item.Is_RealContent() ) Para.Internal_Content_Add( Para.Content.length, Item.Copy(), false ); } return Para; }, Get_AllDrawingObjects : function(DrawingObjs) { if ( undefined === DrawingObjs ) DrawingObjs = new Array(); var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; if ( para_Drawing === Item.Type ) DrawingObjs.push( Item ); } return DrawingObjs; }, Get_AllParagraphs_ByNumbering : function(NumPr, ParaArray) { var _NumPr = this.Numbering_Get(); if ( undefined != _NumPr && _NumPr.NumId === NumPr.NumId && ( _NumPr.Lvl === NumPr.Lvl || undefined === NumPr.Lvl ) ) ParaArray.push( this ); var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; if ( para_Drawing === Item.Type ) Item.Get_AllParagraphs_ByNumbering( NumPr, ParaArray ); } }, Get_PageBounds : function(PageIndex) { return this.Pages[PageIndex].Bounds; }, Get_EmptyHeight : function() { var Pr = this.Get_CompiledPr(); var EndTextPr = Pr.TextPr.Copy(); EndTextPr.Merge( this.TextPr.Value ); g_oTextMeasurer.SetTextPr( EndTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII ); return g_oTextMeasurer.GetHeight(); }, Reset : function (X,Y, XLimit, YLimit, PageNum) { this.X = X; this.Y = Y; this.XLimit = XLimit; this.YLimit = YLimit; this.PageNum = PageNum; // При первом пересчете параграфа this.Parent.RecalcInfo.Can_RecalcObject() всегда будет true, а вот при повторных уже нет if ( true === this.Parent.RecalcInfo.Can_RecalcObject() ) { var Ranges = this.Parent.CheckRange( X, Y, XLimit, Y, Y, Y, X, XLimit, this.PageNum, true ); if ( Ranges.length > 0 ) { if ( Math.abs(Ranges[0].X0 - X ) < 0.001 ) this.X_ColumnStart = Ranges[0].X1; else this.X_ColumnStart = X; if ( Math.abs(Ranges[Ranges.length - 1].X1 - XLimit ) < 0.001 ) this.X_ColumnEnd = Ranges[Ranges.length - 1].X0; else this.X_ColumnEnd = XLimit; } else { this.X_ColumnStart = X; this.X_ColumnEnd = XLimit; } } }, // Копируем свойства параграфа CopyPr : function(OtherParagraph) { return this.CopyPr_Open(OtherParagraph); /* var bHistory = History.Is_On(); History.TurnOff(); OtherParagraph.X = this.X; OtherParagraph.XLimit = this.XLimit; if ( "undefined" != typeof(OtherParagraph.NumPr) ) OtherParagraph.Numbering_Remove(); var NumPr = this.Numbering_Get(); if ( null != NumPr ) { OtherParagraph.Numbering_Add( NumPr.NumId, NumPr.Lvl ); } // Копируем прямые настройки параграфа в конце, потому что, например, нумерация может // их изменить. OtherParagraph.Pr = Common_CopyObj( this.Pr ); OtherParagraph.Style_Add( this.Style_Get(), true ); if ( true === bHistory ) History.TurnOn(); */ }, // Копируем свойства параграфа при открытии и копировании CopyPr_Open : function(OtherParagraph) { OtherParagraph.X = this.X; OtherParagraph.XLimit = this.XLimit; if ( "undefined" != typeof(OtherParagraph.NumPr) ) OtherParagraph.Numbering_Remove(); var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { OtherParagraph.Numbering_Set( NumPr.NumId, NumPr.Lvl ); } var Bullet = this.Get_PresentationNumbering(); if ( numbering_presentationnumfrmt_None != Bullet.Get_Type() ) OtherParagraph.Add_PresentationNumbering( Bullet.Copy() ); OtherParagraph.Set_PresentationLevel( this.PresentationPr.Level ); // Копируем прямые настройки параграфа в конце, потому что, например, нумерация может // их изменить. var oOldPr = OtherParagraph.Pr; OtherParagraph.Pr = this.Pr.Copy(); History.Add( OtherParagraph, { Type : historyitem_Paragraph_Pr, Old : oOldPr, New : OtherParagraph.Pr } ); OtherParagraph.Style_Add( this.Style_Get(), true ); }, // Добавляем элемент в содержимое параграфа. (Здесь передвигаются все позиции // CurPos.ContentPos, Selection.StartPos, Selection.EndPos) Internal_Content_Add : function (Pos, Item, bCorrectPos) { if ( true === Item.Is_RealContent() ) { var ClearPos = this.Internal_Get_ClearPos( Pos ); History.Add( this, { Type : historyitem_Paragraph_AddItem, Pos : ClearPos, EndPos : ClearPos, Items : [ Item ] } ); } this.Content.splice( Pos, 0, Item ); if ( this.CurPos.ContentPos >= Pos ) this.Set_ContentPos( this.CurPos.ContentPos + 1, bCorrectPos ); if ( this.Selection.StartPos >= Pos ) this.Selection.StartPos++; if ( this.Selection.EndPos >= Pos ) this.Selection.EndPos++; if ( this.Numbering.Pos >= Pos ) this.Numbering.Pos++; // Также передвинем всем метки переносов страниц и строк var LinesCount = this.Lines.length; for ( var CurLine = 0; CurLine < LinesCount; CurLine++ ) { if ( this.Lines[CurLine].StartPos > Pos ) this.Lines[CurLine].StartPos++; if ( this.Lines[CurLine].EndPos + 1 > Pos ) this.Lines[CurLine].EndPos++; var RangesCount = this.Lines[CurLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos > Pos ) this.Lines[CurLine].Ranges[CurRange].StartPos++; } } // TODO: Как только мы избавимся от ParaNumbering в контенте параграфа, можно будет здесь такую обработку убрать // и делать ее конкретно на Replace // Передвинем все метки поиска for ( var CurSearch in this.SearchResults ) { if ( this.SearchResults[CurSearch].StartPos >= Pos ) this.SearchResults[CurSearch].StartPos++; if ( this.SearchResults[CurSearch].EndPos >= Pos ) this.SearchResults[CurSearch].EndPos++; } // Передвинем все метки слов для проверки орфографии this.SpellChecker.Update_OnAdd( this, Pos, Item ); }, Internal_Content_Add2 : function (Pos, Item, bCorrectPos) { if ( true === Item.Is_RealContent() ) { var ClearPos = this.Internal_Get_ClearPos( Pos ); History.Add( this, { Type : historyitem_Paragraph_AddItem, Pos : ClearPos, EndPos : ClearPos, Items : [ Item ] } ); } this.Content.splice( Pos, 0, Item ); // Передвинем все метки поиска for ( var CurSearch in this.SearchResults ) { if ( this.SearchResults[CurSearch].StartPos >= Pos ) this.SearchResults[CurSearch].StartPos++; if ( this.SearchResults[CurSearch].EndPos >= Pos ) this.SearchResults[CurSearch].EndPos++; } }, // Добавляем несколько элементов в конец параграфа. Internal_Content_Concat : function(Items) { // Добавляем только постоянные элементы параграфа var NewItems = new Array(); var ItemsCount = Items.length; for ( var Index = 0; Index < ItemsCount; Index++ ) { if ( true === Items[Index].Is_RealContent() ) NewItems.push( Items[Index] ); } if ( NewItems.length <= 0 ) return; var StartPos = this.Content.length; this.Content = this.Content.concat( NewItems ); History.Add( this, { Type : historyitem_Paragraph_AddItem, Pos : this.Internal_Get_ClearPos( StartPos ), EndPos : this.Internal_Get_ClearPos( this.Content.length - 1 ), Items : NewItems } ); this.RecalcInfo.Set_Type_0_Spell( pararecalc_0_Spell_All ); }, // Удаляем элемент из содержимого параграфа. (Здесь передвигаются все позиции // CurPos.ContentPos, Selection.StartPos, Selection.EndPos) Internal_Content_Remove : function (Pos) { var Item = this.Content[Pos]; if ( true === Item.Is_RealContent() ) { var ClearPos = this.Internal_Get_ClearPos( Pos ); History.Add( this, { Type : historyitem_Paragraph_RemoveItem, Pos : ClearPos, EndPos : ClearPos, Items : [ Item ] } ); } if ( this.Selection.StartPos <= this.Selection.EndPos ) { if ( this.Selection.StartPos > Pos ) this.Selection.StartPos--; if ( this.Selection.EndPos > Pos ) this.Selection.EndPos--; } else { if ( this.Selection.StartPos > Pos ) this.Selection.StartPos--; if ( this.Selection.EndPos > Pos ) this.Selection.EndPos--; } if ( this.Numbering.Pos > Pos ) this.Numbering.Pos--; // Также передвинем всем метки переносов страниц и строк var LinesCount = this.Lines.length; for ( var CurLine = 0; CurLine < LinesCount; CurLine++ ) { if ( this.Lines[CurLine].StartPos > Pos ) this.Lines[CurLine].StartPos--; if ( this.Lines[CurLine].EndPos >= Pos ) this.Lines[CurLine].EndPos--; var RangesCount = this.Lines[CurLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos > Pos ) this.Lines[CurLine].Ranges[CurRange].StartPos--; } } // TODO: Как только мы избавимся от ParaNumbering в контенте параграфа, можно будет здесь такую обработку убрать // и делать ее конкретно на Replace // Передвинем все метки поиска for ( var CurSearch in this.SearchResults ) { if ( this.SearchResults[CurSearch].StartPos > Pos ) this.SearchResults[CurSearch].StartPos--; if ( this.SearchResults[CurSearch].EndPos > Pos ) this.SearchResults[CurSearch].EndPos--; } this.Content.splice( Pos, 1 ); if ( this.CurPos.ContentPos > Pos ) this.Set_ContentPos( this.CurPos.ContentPos - 1 ); // Комментарий удаляем после, чтобы не нарушить позиции if ( true === this.DeleteCommentOnRemove && ( para_CommentStart === Item.Type || para_CommentEnd === Item.Type ) ) { // Удаляем комментарий, если у него было удалено начало или конец if ( para_CommentStart === Item.Type ) editor.WordControl.m_oLogicDocument.Comments.Set_StartInfo( Item.Id, 0, 0, 0, 0, null ); else editor.WordControl.m_oLogicDocument.Comments.Set_EndInfo( Item.Id, 0, 0, 0, 0, null ); editor.WordControl.m_oLogicDocument.Remove_Comment( Item.Id, true ); } // Передвинем все метки слов для проверки орфографии this.SpellChecker.Update_OnRemove( this, Pos, 1 ); }, // Удаляем несколько элементов Internal_Content_Remove2 : function(Pos, Count) { var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var CommentsToDelete = new Object(); for ( var Index = Pos; Index < Pos + Count; Index++ ) { var ItemType = this.Content[Index].Type; if ( true === this.DeleteCommentOnRemove && (para_CommentStart === ItemType || para_CommentEnd === ItemType) ) { if ( para_CommentStart === ItemType ) DocumentComments.Set_StartInfo( this.Content[Index].Id, 0, 0, 0, 0, null ); else DocumentComments.Set_EndInfo( this.Content[Index].Id, 0, 0, 0, 0, null ); CommentsToDelete[this.Content[Index].Id] = 1; } } var LastArray = this.Content.slice( Pos, Pos + Count ); // Добавляем только постоянные элементы параграфа var LastItems = new Array(); var ItemsCount = LastArray.length; for ( var Index = 0; Index < ItemsCount; Index++ ) { if ( true === LastArray[Index].Is_RealContent() ) LastItems.push( LastArray[Index] ); } History.Add( this, { Type : historyitem_Paragraph_RemoveItem, Pos : this.Internal_Get_ClearPos( Pos ), EndPos : this.Internal_Get_ClearPos(Pos + Count - 1), Items : LastItems } ); if ( this.CurPos.ContentPos > Pos ) { if ( this.CurPos.ContentPos > Pos + Count ) this.Set_ContentPos( this.CurPos.ContentPos - Count, true, -1 ); else this.Set_ContentPos( Pos, true, -1 ); } if ( this.Selection.StartPos <= this.Selection.EndPos ) { if ( this.Selection.StartPos > Pos ) { if ( this.Selection.StartPos > Pos + Count ) this.Selection.StartPos -= Count; else this.Selection.StartPos = Pos; } if ( this.Selection.EndPos > Pos ) { if ( this.Selection.EndPos >= Pos + Count ) this.Selection.EndPos -= Count; else this.Selection.EndPos = Math.max( 0, Pos - 1 ); } } else { if ( this.Selection.StartPos > Pos ) { if ( this.Selection.StartPos >= Pos + Count ) this.Selection.StartPos -= Count; else this.Selection.StartPos = Math.max( 0, Pos - 1 ); } if ( this.Selection.EndPos > Pos ) { if ( this.Selection.EndPos > Pos + Count ) this.Selection.EndPos -= Count; else this.Selection.EndPos = Pos; } } // Также передвинем всем метки переносов страниц и строк var LinesCount = this.Lines.length; for ( var CurLine = 0; CurLine < LinesCount; CurLine++ ) { if ( this.Lines[CurLine].StartPos > Pos ) { if ( this.Lines[CurLine].StartPos > Pos + Count ) this.Lines[CurLine].StartPos -= Count; else this.Lines[CurLine].StartPos = Math.max( 0 , Pos ); } if ( this.Lines[CurLine].EndPos >= Pos ) { if ( this.Lines[CurLine].EndPos >= Pos + Count ) this.Lines[CurLine].EndPos -= Count; else this.Lines[CurLine].EndPos = Math.max( 0 , Pos ); } var RangesCount = this.Lines[CurLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos > Pos ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos > Pos + Count ) this.Lines[CurLine].Ranges[CurRange].StartPos -= Count; else this.Lines[CurLine].Ranges[CurRange].StartPos = Math.max( 0 , Pos ); } } } this.Content.splice( Pos, Count ); // Комментарии удаляем после, чтобы не нарушить позиции for ( var Id in CommentsToDelete ) { editor.WordControl.m_oLogicDocument.Remove_Comment( Id, true ); } // Передвинем все метки слов для проверки орфографии this.SpellChecker.Update_OnRemove( this, Pos, Count ); }, Internal_Check_EmptyHyperlink : function(Pos) { var Start = this.Internal_FindBackward( Pos, [ para_Text, para_Drawing, para_Space, para_Tab, para_PageNum, para_HyperlinkStart ] ); var End = this.Internal_FindForward ( Pos, [ para_Text, para_Drawing, para_Space, para_Tab, para_PageNum, para_HyperlinkEnd, para_End ] ); if ( true === Start.Found && para_HyperlinkStart === Start.Type && true === End.Found && para_HyperlinkEnd === End.Type ) { this.Internal_Content_Remove( End.LetterPos ); this.Internal_Content_Remove( Start.LetterPos ); } }, Clear_ContentChanges : function() { this.m_oContentChanges.Clear(); }, Add_ContentChanges : function(Changes) { this.m_oContentChanges.Add( Changes ); }, Refresh_ContentChanges : function() { this.m_oContentChanges.Refresh(); }, Internal_Get_ParaPos_By_Pos : function(ContentPos) { /* var CurLine = this.Lines.length - 1; for ( ; CurLine > 0; CurLine-- ) { if ( this.Lines[CurLine].StartPos <= ContentPos ) break; } var CurRange = this.Lines[CurLine].Ranges.length - 1; for ( ; CurRange > 0; CurRange-- ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos <= ContentPos ) break; } var CurPage = this.Pages.length - 1; for ( ; CurPage > 0; CurPage-- ) { if ( this.Pages[CurPage].StartLine <= CurLine ) break; } */ var _ContentPos = ContentPos; while ( undefined === this.Content[_ContentPos].CurPage ) { _ContentPos--; if ( _ContentPos < 0 ) return new CParaPos( 0, 0, 0, 0 ); } if ( _ContentPos === this.CurPos.ContentPos && -1 != this.CurPos.Line ) return new CParaPos( this.Content[_ContentPos].CurRange, this.CurPos.Line, this.Content[_ContentPos].CurPage, ContentPos ); return new CParaPos( this.Content[_ContentPos].CurRange, this.Content[_ContentPos].CurLine, this.Content[_ContentPos].CurPage, ContentPos ); }, Internal_Get_ParaPos_By_Page : function(Page) { var CurPage = Page; var CurLine = this.Pages[CurPage].StartLine; var CurRange = 0; var CurPos = this.Lines[CurLine].StartPos; return new CParaPos( CurRange, CurLine, CurPage, CurPos ); }, Internal_Update_ParaPos : function(CurPage, CurLine, CurRange, CurPos) { var _CurPage = CurPage; var _CurLine = CurLine; var _CurRange = CurRange; // Проверяем переход на новую страницу while ( _CurPage < this.Pages.length - 1 ) { if ( this.Lines[this.Pages[_CurPage + 1].StartLine].StartPos <= CurPos ) { _CurPage++; _CurLine = this.Pages[_CurPage].StartLine; _CurRange = 0; } else break; } while ( _CurLine < this.Lines.length - 1 ) { if ( this.Lines[_CurLine + 1].StartPos <= CurPos ) { _CurLine++; _CurRange = 0; } else break; } while ( _CurRange < this.Lines[_CurLine].Ranges.length - 1 ) { if ( this.Lines[_CurLine].Ranges[_CurRange + 1].StartPos <= CurPos ) { _CurRange++; } else break; } return new CParaPos( _CurRange, _CurLine, _CurPage, CurPos ); }, // Рассчитываем текст Internal_Recalculate_0 : function() { if ( pararecalc_0_None === this.RecalcInfo.Recalc_0_Type ) return; var Pr = this.Get_CompiledPr(); var ParaPr = Pr.ParaPr; var CurTextPr = Pr.TextPr; // Предполагается, что при вызове данной функции Content не содержит // рассчитанных переносов строк. g_oTextMeasurer.SetTextPr( CurTextPr ); // Под Descent мы будем понимать descent + linegap (которые записаны в шрифте) var TextAscent = 0; var TextHeight = 0; var TextDescent = 0; g_oTextMeasurer.SetFontSlot( fontslot_ASCII ); TextHeight = g_oTextMeasurer.GetHeight(); TextDescent = Math.abs( g_oTextMeasurer.GetDescender() ); TextAscent = TextHeight - TextDescent; TextAscent2 = g_oTextMeasurer.GetAscender(); var ContentLength = this.Content.length; if ( para_PresentationNumbering === this.Numbering.Type ) { var Item = this.Numbering; var Level = this.PresentationPr.Level; var Bullet = this.PresentationPr.Bullet; var BulletNum = 0; if ( Bullet.Get_Type() >= numbering_presentationnumfrmt_ArabicPeriod ) { var Prev = this.Prev; while ( null != Prev && type_Paragraph === Prev.GetType() ) { var PrevLevel = Prev.PresentationPr.Level; var PrevBullet = Prev.Get_PresentationNumbering(); // Если предыдущий параграф более низкого уровня, тогда его не учитываем if ( Level < PrevLevel ) { Prev = Prev.Prev; continue; } else if ( Level > PrevLevel ) break; else if ( PrevBullet.Get_Type() === Bullet.Get_Type() && PrevBullet.Get_StartAt() === PrevBullet.Get_StartAt() ) { if ( true != Prev.IsEmpty() ) BulletNum++; Prev = Prev.Prev; } else break; } } // Найдем настройки для первого текстового элемента var FirstTextPr = this.Internal_CalculateTextPr( this.Internal_GetStartPos() ); Item.Bullet = Bullet; Item.BulletNum = BulletNum + 1; Item.Measure( g_oTextMeasurer, FirstTextPr ); } for ( var Pos = 0; Pos < ContentLength; Pos++ ) { var Item = this.Content[Pos]; switch( Item.Type ) { case para_Text: case para_Space: case para_PageNum: { Item.Measure( g_oTextMeasurer, CurTextPr); break; } case para_Drawing: { Item.Parent = this; Item.DocumentContent = this.Parent; Item.DrawingDocument = this.Parent.DrawingDocument; Item.Measure( g_oTextMeasurer, CurTextPr); break; } case para_Tab: case para_NewLine: { Item.Measure( g_oTextMeasurer); break; } case para_TextPr: { Item.Parent = this; CurTextPr = this.Internal_CalculateTextPr( Pos ); Item.CalcValue = CurTextPr; // копировать не надо, т.к. CurTextPr здесь дальше не меняется, а в функции он создается изначально g_oTextMeasurer.SetTextPr( CurTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII ); TextDescent = Math.abs( g_oTextMeasurer.GetDescender() ); TextHeight = g_oTextMeasurer.GetHeight(); TextAscent = TextHeight - TextDescent; TextAscent2 = g_oTextMeasurer.GetAscender(); break; } case para_End: { var bEndCell = false; if ( null === this.Get_DocumentNext() && true === this.Parent.Is_TableCellContent() ) bEndCell = true; var EndTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); EndTextPr.Merge( this.TextPr.Value ); Item.TextPr = EndTextPr; g_oTextMeasurer.SetTextPr( EndTextPr ); Item.Measure( g_oTextMeasurer, bEndCell ); TextDescent = Math.abs( g_oTextMeasurer.GetDescender() ); TextHeight = g_oTextMeasurer.GetHeight(); TextAscent = TextHeight - TextDescent; TextAscent2 = g_oTextMeasurer.GetAscender(); g_oTextMeasurer.SetTextPr( CurTextPr ); break; } } Item.TextAscent = TextAscent; Item.TextDescent = TextDescent; Item.TextHeight = TextHeight; Item.TextAscent2 = TextAscent2; Item.YOffset = CurTextPr.Position; } this.RecalcInfo.Set_Type_0( pararecalc_0_None ); }, // Пересчет переносов строк в параграфе, с учетом возможного обтекания Internal_Recalculate_1_ : function(StartPos, CurPage, _CurLine) { var Pr = this.Get_CompiledPr(); var ParaPr = Pr.ParaPr; var CurLine = _CurLine; // Смещаемся в начало параграфа на первой странице или в начало страницы, если страница не первая var X, Y, XLimit, YLimit, _X, _XLimit; if ( 0 === CurPage || undefined != this.Get_FramePr() ) { X = this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; Y = this.Y; XLimit = this.XLimit - ParaPr.Ind.Right; YLimit = this.YLimit; _X = this.X; _XLimit = this.XLimit; } else { // Запрашиваем у документа начальные координаты на новой странице var PageStart = this.Parent.Get_PageContentStartPos( this.PageNum + CurPage ); X = ( 0 != CurLine ? PageStart.X + ParaPr.Ind.Left : PageStart.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine ); Y = PageStart.Y; XLimit = PageStart.XLimit - ParaPr.Ind.Right; YLimit = PageStart.YLimit; _X = PageStart.X; _XLimit = PageStart.XLimit; } // Предполагается, что при вызове данной функции Content не содержит // рассчитанных переносов строк в промежутке StartPos и EndPos. this.Pages.length = CurPage + 1; this.Pages[CurPage] = new CParaPage( _X, Y, _XLimit, YLimit, CurLine ); this.Pages[CurPage].TextPr = this.Internal_CalculateTextPr( StartPos, Pr ); var LineStart_Pos = StartPos; if ( 0 === CurPage ) { // Пересчитываем правую и левую границы параграфа if ( ParaPr.Ind.FirstLine <= 0 ) this.Bounds.Left = X; else this.Bounds.Left = this.X + ParaPr.Ind.Left; this.Bounds.Right = XLimit; } var bFirstItemOnLine = true; // контролируем первое появление текста на строке var bEmptyLine = true; // Есть ли в строке текст, картинки или др. видимые объекты var bStartWord = false; // началось ли слово в строке var bWord = false; var nWordStartPos = 0; var nWordLen = 0; var nSpaceLen = 0; var nSpacesCount = 0; var pLastTab = { TabPos : 0, X : 0, Value : -1, Item : null }; var bNewLine = false; var bNewRange = false; var bNewPage = false; var bExtendBoundToBottom = false; var bEnd = false; var bForceNewPage = false; var bBreakPageLine = false; if ( CurPage > 1 ) bAddNumbering = false; else if ( 0 === CurPage ) bAddNumbering = true; else { // Проверим, есть ли какие-нибудь реальные элементы (к которым можно было бы // дорисовать нумерацию) до стартовой позиции текущей страницы for ( var Pos = 0; Pos < StartPos; Pos++ ) { var Item = this.Content[Pos]; if ( true === Item.Can_AddNumbering() ) bAddNumbering = false; } } // Получаем промежутки обтекания, т.е. промежутки, которые нам нельзя использовать var Ranges = [];//this.Parent.CheckRange( X, Y, XLimit, Y, Y, Y, this.PageNum + CurPage, true ); var RangesCount = Ranges.length; // Под Descent мы будем понимать descent + linegap (которые записаны в шрифте) var TextAscent = 0; var TextDescent = 0; var TextAscent2 = 0; this.Lines.length = CurLine + 1; this.Lines[CurLine] = new CParaLine(StartPos); var LineTextAscent = 0; var LineTextDescent = 0; var LineTextAscent2 = 0; var LineAscent = 0; var LineDescent = 0; // Выставляем начальные сдвиги для промежутков. Начало промежутка = конец вырезаемого промежутка this.Lines[CurLine].Add_Range( X, (RangesCount == 0 ? XLimit : Ranges[0].X0) ); this.Lines[CurLine].Set_RangeStartPos( 0, StartPos ); for ( var Index = 1; Index < Ranges.length + 1; Index++ ) { this.Lines[CurLine].Add_Range( Ranges[Index - 1].X1, (Index == RangesCount ? XLimit : Ranges[Index].X0) ); } var CurRange = 0; var XEnd = 0; if ( RangesCount == 0 ) XEnd = XLimit; else XEnd = Ranges[0].X0; if ( this.Parent instanceof CDocument ) { // Начинаем параграф с новой страницы if ( 0 === CurPage && true === ParaPr.PageBreakBefore ) { // Если это первый элемент документа, тогда не надо начинать его с новой страницы var Prev = this.Get_DocumentPrev(); if ( null != Prev ) { // Добавляем разрыв страницы this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( StartPos - 1, this ); } return recalcresult_NextPage; } } else if ( true === this.Parent.RecalcInfo.Check_WidowControl( this, CurLine ) ) { this.Parent.RecalcInfo.Reset_WidowControl(); this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine( 0 ); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } return recalcresult_NextPage; } else if ( true === this.Parent.RecalcInfo.Check_KeepNext(this) && 0 === CurPage && null != this.Get_DocumentPrev() ) { this.Parent.RecalcInfo.Reset(); this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine( 0 ); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } return recalcresult_NextPage; } } var RecalcResult = recalcresult_NextElement; var bAddNumbering = this.Internal_CheckAddNumbering( CurPage, CurLine, CurRange ); for ( var Pos = LineStart_Pos; Pos < this.Content.length; Pos++ ) { if ( false === bStartWord && true === bFirstItemOnLine && Math.abs(XEnd - X) < 0.001 && RangesCount > 0 ) { if ( RangesCount == CurRange ) { Pos--; bNewLine = true; } else { Pos--; bNewRange = true; } } if ( true != bNewLine && true != bNewRange ) { var Item = this.Content[Pos]; Item.Parent = this; Item.DocumentContent = this.Parent; Item.DrawingDocument = this.Parent.DrawingDocument; if ( undefined != Item.TextAscent ) TextAscent = Item.TextAscent; if ( undefined != Item.TextAscent2 ) TextAscent2 = Item.TextAscent2; if ( undefined != Item.TextDescent ) TextDescent = Item.TextDescent; // Сохраним в элементе номер строки и отрезка Item.CurPage = CurPage; Item.CurLine = CurLine; Item.CurRange = CurRange; var bBreak = false; if ( true === bAddNumbering ) { // Проверим, возможно на текущем элементе стоит добавить нумерацию if ( true === Item.Can_AddNumbering() ) { var NumberingItem = this.Numbering; var NumberingType = this.Numbering.Type; if ( para_Numbering === NumberingType ) { var NumPr = ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) { // Так мы обнуляем все рассчитанные ширины данного элемента NumberingItem.Measure( g_oTextMeasurer, undefined ); } else { var Numbering = this.Parent.Get_Numbering(); var NumLvl = Numbering.Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl]; var NumSuff = NumLvl.Suff; var NumJc = NumLvl.Jc; var NumInfo = this.Parent.Internal_GetNumInfo( this.Id, NumPr ); var NumTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); NumTextPr.Merge( this.TextPr.Value ); NumTextPr.Merge( NumLvl.TextPr ); // Здесь измеряется только ширина символов нумерации, без суффикса NumberingItem.Measure( g_oTextMeasurer, Numbering, NumInfo, NumTextPr, NumPr ); // При рассчете высоты строки, если у нас параграф со списком, то размер символа // в списке влияет только на высоту строки над Baseline, но не влияет на высоту строки // ниже baseline. if ( LineAscent < NumberingItem.Height ) LineAscent = NumberingItem.Height; switch ( NumJc ) { case align_Right: { NumberingItem.WidthVisible = 0; break; } case align_Center: { NumberingItem.WidthVisible = NumberingItem.WidthNum / 2; X += NumberingItem.WidthNum / 2; break; } case align_Left: default: { NumberingItem.WidthVisible = NumberingItem.WidthNum; X += NumberingItem.WidthNum; break; } } switch( NumSuff ) { case numbering_suff_Nothing: { // Ничего не делаем break; } case numbering_suff_Space: { var OldTextPr = g_oTextMeasurer.GetTextPr(); g_oTextMeasurer.SetTextPr( NumTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII ); NumberingItem.WidthSuff = g_oTextMeasurer.Measure( " " ).Width; g_oTextMeasurer.SetTextPr( OldTextPr ); break; } case numbering_suff_Tab: { var NewX = null; var PageStart = this.Parent.Get_PageContentStartPos( this.PageNum + CurPage ); // Если у данного параграфа есть табы, тогда ищем среди них var TabsCount = ParaPr.Tabs.Get_Count(); // Добавим в качестве таба левую границу var TabsPos = new Array(); var bCheckLeft = true; for ( var Index = 0; Index < TabsCount; Index++ ) { var Tab = ParaPr.Tabs.Get(Index); var TabPos = Tab.Pos + PageStart.X; if ( true === bCheckLeft && TabPos > PageStart.X + ParaPr.Ind.Left ) { TabsPos.push( PageStart.X + ParaPr.Ind.Left ); bCheckLeft = false; } if ( tab_Clear != Tab.Value ) TabsPos.push( TabPos ); } if ( true === bCheckLeft ) TabsPos.push( PageStart.X + ParaPr.Ind.Left ); TabsCount++; for ( var Index = 0; Index < TabsCount; Index++ ) { var TabPos = TabsPos[Index]; if ( X < TabPos ) { NewX = TabPos; break; } } // Если табов нет, либо их позиции левее текущей позиции ставим таб по умолчанию if ( null === NewX ) { if ( X < PageStart.X + ParaPr.Ind.Left ) NewX = PageStart.X + ParaPr.Ind.Left; else { NewX = this.X; while ( X >= NewX ) NewX += Default_Tab_Stop; } } NumberingItem.WidthSuff = NewX - X; break; } } NumberingItem.Width = NumberingItem.WidthNum; NumberingItem.WidthVisible += NumberingItem.WidthSuff; X += NumberingItem.WidthSuff; this.Numbering.Pos = Pos; } } else if ( para_PresentationNumbering === NumberingType ) { var Bullet = this.PresentationPr.Bullet; if ( numbering_presentationnumfrmt_None != Bullet.Get_Type() ) { if ( ParaPr.Ind.FirstLine < 0 ) NumberingItem.WidthVisible = Math.max( NumberingItem.Width, this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine - X, this.X + ParaPr.Ind.Left - X ); else NumberingItem.WidthVisible = Math.max( this.X + ParaPr.Ind.Left + NumberingItem.Width - X, this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine - X, this.X + ParaPr.Ind.Left - X ); } X += NumberingItem.WidthVisible; this.Numbering.Pos = Pos; } bAddNumbering = false; } } switch( Item.Type ) { case para_Text: { bStartWord = true; // При проверке, убирается ли слово, мы должны учитывать ширину // предшевствующих пробелов. if ( LineTextAscent < TextAscent ) LineTextAscent = TextAscent; if ( LineTextAscent2 < TextAscent2 ) LineTextAscent2 = TextAscent2; if ( LineTextDescent < TextDescent ) LineTextDescent = TextDescent; if ( linerule_Exact === ParaPr.Spacing.LineRule ) { // Смещение не учитывается в метриках строки, когда расстояние между строк точное if ( LineAscent < TextAscent ) LineAscent = TextAscent; if ( LineDescent < TextDescent ) LineDescent = TextDescent; } else { if ( LineAscent < TextAscent + Item.YOffset ) LineAscent = TextAscent + Item.YOffset; if ( LineDescent < TextDescent - Item.YOffset ) LineDescent = TextDescent - Item.YOffset; } if ( !bWord ) { // Слово только началось. Делаем следующее: // 1) Если до него на строке ничего не было и данная строка не // имеет разрывов, тогда не надо проверять убирается ли слово в строке. // 2) В противном случае, проверяем убирается ли слово в промежутке. // Если слово только началось, и до него на строке ничего не было, и в строке нет разрывов, тогда не надо проверять убирается ли оно на строке. var LetterLen = Item.Width; if ( !bFirstItemOnLine || false === this.Internal_Check_Ranges(CurLine, CurRange) ) { if ( X + nSpaceLen + LetterLen > XEnd ) { if ( RangesCount == CurRange ) { bNewLine = true; Pos--; } else { bNewRange = true; Pos--; } } } if ( !bNewLine && !bNewRange ) { nWordStartPos = Pos; nWordLen = Item.Width; bWord = true; //this.Lines[CurLine].Words++; //if ( !bNewRange ) // this.Lines[CurLine].Ranges[CurRange].Words++; } } else { var LetterLen = Item.Width; if ( X + nSpaceLen + nWordLen + LetterLen > XEnd ) { if ( bFirstItemOnLine ) { // Слово оказалось единственным элементом в промежутке, и, все равно, // не умещается целиком. Делаем следующее: // // 1) Если у нас строка без вырезов, тогда ставим перенос строки на // текущей позиции. // 2) Если у нас строка с вырезом, и данный вырез не последний, тогда // ставим перенос внутри строки в начале слова. // 3) Если у нас строка с вырезом и вырез последний, тогда ставим перенос // строки в начале слова. if ( false === this.Internal_Check_Ranges(CurLine, CurRange) ) { Pos = nWordStartPos - 1; if ( RangesCount != CurRange ) bNewRange = true; else bNewLine = true; } else { bEmptyLine = false; X += nWordLen; Pos--; if ( RangesCount != CurRange ) bNewRange = true; else bNewLine = true; } } else { // Слово не убирается в промежутке. Делаем следующее: // 1) Если у нас строка без вырезов или текущей вырез последний, // тогда ставим перенос строки в начале слова. // 2) Если строка с вырезами и вырез не последний, ставим // перенос внутри строки в начале слова. Pos = nWordStartPos; if ( RangesCount == CurRange ) { Pos--; bNewLine = true; //this.Lines[CurLine].Words--; //this.Lines[CurLine].Ranges[CurRange].Words--; } else // if ( 0 != RangesCount && RangesCount != CurRange ) { Pos--; bNewRange = true; //this.Lines[CurLine].Ranges[CurRange].Words--; } } } if ( !bNewLine && !bNewRange ) { nWordLen += LetterLen; // Если текущий символ, например, дефис, тогда на нем заканчивается слово if ( true === Item.SpaceAfter ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; // Пробелы перед первым словом в строке не считаем //if ( this.Lines[CurLine].Words > 1 ) // this.Lines[CurLine].Spaces += nSpacesCount; //if ( this.Lines[CurLine].Ranges[CurRange].Words > 1 ) // this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; bWord = false; bFirstItemOnLine = false; bEmptyLine = false; nSpaceLen = 0; nWordLen = 0; nSpacesCount = 0; } } } break; } case para_Space: { bFirstItemOnLine = false; var SpaceLen = Item.Width; if ( bWord ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; // Пробелы перед первым словом в строке не считаем //if ( this.Lines[CurLine].Words > 1 ) // this.Lines[CurLine].Spaces += nSpacesCount; //if ( this.Lines[CurLine].Ranges[CurRange].Words > 1 ) // this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; bWord = false; bEmptyLine = false; nSpaceLen = 0; nWordLen = 0; nSpacesCount = 1; } else nSpacesCount++; // На пробеле не делаем перенос. Перенос строки или внутристрочный // перенос делаем при добавлении любого непробельного символа nSpaceLen += SpaceLen; break; } case para_Drawing: { if ( true === Item.Is_Inline() || true === this.Parent.Is_DrawingShape() ) { if ( true != Item.Is_Inline() ) Item.Set_DrawingType( drawing_Inline ); if ( true === bStartWord ) bFirstItemOnLine = false; // Если до этого было слово, тогда не надо проверять убирается ли оно, но если стояли пробелы, // тогда мы их учитываем при проверке убирается ли данный элемент, и добавляем только если // данный элемент убирается if ( bWord || nWordLen > 0 ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; // Пробелы перед первым словом в строке не считаем //if ( this.Lines[CurLine].Words > 1 ) // this.Lines[CurLine].Spaces += nSpacesCount; //if ( this.Lines[CurLine].Ranges[CurRange].Words > 1 ) // this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; bWord = false; nSpaceLen = 0; nSpacesCount = 0; nWordLen = 0; } if ( X + nSpaceLen + Item.Width > XEnd && ( false === bFirstItemOnLine || false === this.Internal_Check_Ranges( CurLine, CurRange ) ) ) { if ( RangesCount == CurRange ) { bNewLine = true; Pos--; } else { bNewRange = true; Pos--; } } else { // Добавляем длину пробелов до слова X += nSpaceLen; if ( linerule_Exact === ParaPr.Spacing.LineRule ) { if ( LineAscent < Item.Height ) LineAscent = Item.Height; if ( Item.Height > this.Lines[CurLine].Metrics.Ascent ) this.Lines[CurLine].Metrics.Ascent = Item.Height; } else { if ( LineAscent < Item.Height + Item.YOffset ) LineAscent = Item.Height + Item.YOffset; if ( Item.Height + Item.YOffset > this.Lines[CurLine].Metrics.Ascent ) this.Lines[CurLine].Metrics.Ascent = Item.Height + Item.YOffset; if ( -Item.YOffset > this.Lines[CurLine].Metrics.Descent ) this.Lines[CurLine].Metrics.Descent = -Item.YOffset; } X += Item.Width; bFirstItemOnLine = false; bEmptyLine = false; //this.Lines[CurLine].Words++; //this.Lines[CurLine].Ranges[CurRange].Words++; // Пробелы перед первым словом в строке не считаем //if ( this.Lines[CurLine].Words > 1 ) // this.Lines[CurLine].Spaces += nSpacesCount; //if ( this.Lines[CurLine].Ranges[CurRange].Words > 1 ) // this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; } nSpaceLen = 0; nSpacesCount = 0; } else { // Основная обработка происходит в Internal_Recalculate_2. Здесь обрабатывается единственный случай, // когда после второго пересчета с уже добавленной картинкой оказывается, что место в параграфе, где // идет картинка ушло на следующую страницу. В этом случае мы ставим перенос страницы перед картинкой. var LogicDocument = this.Parent; var LDRecalcInfo = LogicDocument.RecalcInfo; var DrawingObjects = LogicDocument.DrawingObjects; if ( true === LDRecalcInfo.Check_FlowObject(Item) && true === LDRecalcInfo.Is_PageBreakBefore() ) { LDRecalcInfo.Reset(); // Добавляем разрыв страницы. Если это первая страница, тогда ставим разрыв страницы в начале параграфа, // если нет, тогда в начале текущей строки. if ( null != this.Get_DocumentPrev() && true != this.Parent.Is_TableCellContent() && 0 === CurPage ) { // Мы должны из соответствующих FlowObjects удалить все Flow-объекты, идущие до этого места в параграфе for ( var TempPos = StartPos; TempPos < Pos; TempPos++ ) { var TempItem = this.Content[TempPos]; if ( para_Drawing === TempItem.Type && drawing_Anchor === TempItem.DrawingType && true === TempItem.Use_TextWrap() ) { DrawingObjects.removeById( TempItem.PageNum, TempItem.Get_Id() ); } } this.Internal_Content_Add( StartPos, new ParaPageBreakRenderer() ); this.Pages[CurPage].Set_EndLine( -1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } RecalcResult = recalcresult_NextPage; return; } else { if ( CurLine != this.Pages[CurPage].FirstLine ) { this.Internal_Content_Add( LineStart_Pos, new ParaPageBreakRenderer() ); this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } RecalcResult = recalcresult_NextPage; bBreak = true; break; } else { Pos--; bNewLine = true; bForceNewPage = true; } } // Если до этого было слово, тогда не надо проверять убирается ли оно if ( bWord || nWordLen > 0 ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; bWord = false; nSpaceLen = 0; nSpacesCount = 0; nWordLen = 0; } } } break; } case para_PageNum: { // Если до этого было слово, тогда не надо проверять убирается ли оно, но если стояли пробелы, // тогда мы их учитываем при проверке убирается ли данный элемент, и добавляем только если // данный элемент убирается if ( bWord || nWordLen > 0 ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; bWord = false; nSpaceLen = 0; nSpacesCount = 0; nWordLen = 0; } if ( true === bStartWord ) bFirstItemOnLine = false; if ( LineTextAscent < TextAscent ) LineTextAscent = TextAscent; if ( LineTextAscent2 < TextAscent2 ) LineTextAscent2 = TextAscent2; if ( LineTextDescent < TextDescent ) LineTextDescent = TextDescent; if ( linerule_Exact === ParaPr.Spacing.LineRule ) { if ( LineAscent < TextAscent ) LineAscent = TextAscent; if ( LineDescent < TextDescent ) LineDescent = TextDescent; } else { if ( LineAscent < TextAscent + Item.YOffset ) LineAscent = TextAscent + Item.YOffset; if ( LineDescent < TextDescent - Item.YOffset ) LineDescent = TextDescent - Item.YOffset; } if ( X + nSpaceLen + Item.Width > XEnd && ( false === bFirstItemOnLine || RangesCount > 0 ) ) { if ( RangesCount == CurRange ) { bNewLine = true; Pos--; } else { bNewRange = true; Pos--; } } else { // Добавляем длину пробелов до слова X += nSpaceLen; X += Item.Width; bFirstItemOnLine = false; bEmptyLine = false; } nSpaceLen = 0; nSpacesCount = 0; break; } case para_Tab: { if ( -1 != pLastTab.Value ) { var TempTabX = X; if ( bWord || nWordLen > 0 ) TempTabX += nSpaceLen + nWordLen; var TabItem = pLastTab.Item; var TabStartX = pLastTab.X; var TabRangeW = TempTabX - TabStartX; var TabValue = pLastTab.Value; var TabPos = pLastTab.TabPos; var TabCalcW = 0; if ( tab_Right === TabValue ) TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW), 0 ); else if ( tab_Center === TabValue ) TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW / 2), 0 ); if ( X + TabCalcW > XEnd ) TabCalcW = XEnd - X; TabItem.Width = TabCalcW; TabItem.WidthVisible = TabCalcW; pLastTab.Value = -1; X += TabCalcW; } // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; bWord = false; nSpaceLen = 0; nWordLen = 0; nSpacesCount = 0; this.Lines[CurLine].Ranges[CurRange].Spaces = 0; this.Lines[CurLine].Ranges[CurRange].TabPos = Pos; var PageStart = this.Parent.Get_PageContentStartPos( this.PageNum + CurPage ); if ( undefined != this.Get_FramePr() ) PageStart.X = 0; // Если у данного параграфа есть табы, тогда ищем среди них var TabsCount = ParaPr.Tabs.Get_Count(); // Добавим в качестве таба левую границу var TabsPos = new Array(); var bCheckLeft = true; for ( var Index = 0; Index < TabsCount; Index++ ) { var Tab = ParaPr.Tabs.Get(Index); var TabPos = Tab.Pos + PageStart.X; if ( true === bCheckLeft && TabPos > PageStart.X + ParaPr.Ind.Left ) { TabsPos.push( PageStart.X + ParaPr.Ind.Left ); bCheckLeft = false; } if ( tab_Clear != Tab.Value ) TabsPos.push( Tab ); } if ( true === bCheckLeft ) TabsPos.push( PageStart.X + ParaPr.Ind.Left ); TabsCount = TabsPos.length; var Tab = null; for ( var Index = 0; Index < TabsCount; Index++ ) { var TempTab = TabsPos[Index]; if ( X < TempTab.Pos + PageStart.X ) { Tab = TempTab; break; } } var NewX = null; // Если табов нет, либо их позиции левее текущей позиции ставим таб по умолчанию if ( null === Tab ) { if ( X < PageStart.X + ParaPr.Ind.Left ) NewX = PageStart.X + ParaPr.Ind.Left; else { NewX = this.X; while ( X >= NewX - 0.001 ) NewX += Default_Tab_Stop; } } else { // Если таб левый, тогда мы сразу смещаемся к нему if ( tab_Left === Tab.Value ) { NewX = Tab.Pos + PageStart.X; } else { pLastTab.TabPos = Tab.Pos + PageStart.X; pLastTab.Value = Tab.Value; pLastTab.X = X; pLastTab.Item = Item; Item.Width = 0; Item.WidthVisible = 0; } } if ( null != NewX ) { if ( NewX > XEnd && ( false === bFirstItemOnLine || RangesCount > 0 ) ) { nWordLen = NewX - X; if ( RangesCount == CurRange ) { bNewLine = true; Pos--; } else { bNewRange = true; Pos--; } } else { Item.Width = NewX - X; Item.WidthVisible = NewX - X; X = NewX; } } // Если перенос идет по строке, а не из-за обтекания, тогда разрываем перед табом, а если // из-за обтекания, тогда разрываем перед последним словом, идущим перед табом if ( RangesCount === CurRange ) { if ( true === bStartWord ) { bFirstItemOnLine = false; bEmptyLine = false; } nWordStartPos = Pos; } nSpacesCount = 0; bStartWord = true; bWord = true; nWordStartPos = Pos; break; } case para_TextPr: { break; } case para_NewLine: { if ( break_Page === Item.BreakType ) { // PageBreak вне самого верхнего документа не надо учитывать, поэтому мы его с радостью удаляем if ( !(this.Parent instanceof CDocument) ) { this.Internal_Content_Remove( Pos ); Pos--; break; } bNewPage = true; bNewLine = true; bBreakPageLine = true; } else { if ( RangesCount === CurRange ) { bNewLine = true; } else // if ( 0 != RangesCount && RangesCount != CurRange ) { bNewRange = true; } bEmptyLine = false; } X += nWordLen; if ( bWord && this.Lines[CurLine].Words > 1 ) this.Lines[CurLine].Spaces += nSpacesCount; if ( bWord && this.Lines[CurLine].Ranges[CurRange].Words > 1 ) this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; if ( bWord ) { bEmptyLine = false; bWord = false; X += nSpaceLen; nSpaceLen = 0; } break; } case para_End: { if ( true === bWord ) { bFirstItemOnLine = false; bEmptyLine = false; } // false === bExtendBoundToBottom, потому что это уже делалось для PageBreak if ( false === bExtendBoundToBottom ) { X += nWordLen; if ( bWord ) { this.Lines[CurLine].Spaces += nSpacesCount; this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; } if ( bWord ) { X += nSpaceLen; nSpaceLen = 0; } if ( -1 != pLastTab.Value ) { var TabItem = pLastTab.Item; var TabStartX = pLastTab.X; var TabRangeW = X - TabStartX; var TabValue = pLastTab.Value; var TabPos = pLastTab.TabPos; var TabCalcW = 0; if ( tab_Right === TabValue ) TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW), 0 ); else if ( tab_Center === TabValue ) TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW / 2), 0 ); if ( X + TabCalcW > XEnd ) TabCalcW = XEnd - X; TabItem.Width = TabCalcW; TabItem.WidthVisible = TabCalcW; pLastTab.Value = -1; X += TabCalcW; } } bNewLine = true; bEnd = true; break; } } if ( bBreak ) { break; } } // Переносим строку if ( bNewLine ) { pLastTab.Value = -1; nSpaceLen = 0; // Строка пустая, у нее надо выставить ненулевую высоту. Делаем как Word, выставляем высоту по размеру // текста, на котором закончилась данная строка. if ( true === bEmptyLine || LineAscent < 0.001 ) { if ( true === bEnd ) { TextAscent = Item.TextAscent; TextDescent = Item.TextDescent; TextAscent2 = Item.TextAscent2; } if ( LineTextAscent < TextAscent ) LineTextAscent = TextAscent; if ( LineTextAscent2 < TextAscent2 ) LineTextAscent2 = TextAscent2; if ( LineTextDescent < TextDescent ) LineTextDescent = TextDescent; if ( LineAscent < TextAscent ) LineAscent = TextAscent; if ( LineDescent < TextDescent ) LineDescent = TextDescent; } // Рассчитаем метрики строки this.Lines[CurLine].Metrics.Update( LineTextAscent, LineTextAscent2, LineTextDescent, LineAscent, LineDescent, ParaPr ); bFirstItemOnLine = true; bStartWord = false; bNewLine = false; bNewRange = false; // Перед тем как перейти к новой строке мы должны убедиться, что вся высота строки // убирается в промежутках. var TempDy = this.Lines[this.Pages[CurPage].FirstLine].Metrics.Ascent; if ( 0 === this.Pages[CurPage].FirstLine && ( 0 === CurPage || true === this.Parent.Is_TableCellContent() || true === ParaPr.PageBreakBefore ) ) TempDy += ParaPr.Spacing.Before; if ( 0 === this.Pages[CurPage].FirstLine ) { if ( ( true === ParaPr.Brd.First || 1 === CurPage ) && border_Single === ParaPr.Brd.Top.Value ) TempDy += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; else if ( false === ParaPr.Brd.First && border_Single === ParaPr.Brd.Between.Value ) TempDy += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; } var Top, Bottom; var Top2, Bottom2; // верх и низ без Pr.Spacing var LastPage_Bottom = this.Pages[CurPage].Bounds.Bottom; if ( true === this.Lines[CurLine].RangeY ) { Top = Y; Top2 = Y; this.Lines[CurLine].Top = Top - this.Pages[CurPage].Y; if ( 0 === CurLine ) { if ( 0 === CurPage || true === this.Parent.Is_TableCellContent() ) { Top2 = Top + ParaPr.Spacing.Before; Bottom2 = Top + ParaPr.Spacing.Before + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent; Bottom = Top + ParaPr.Spacing.Before + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent + this.Lines[0].Metrics.LineGap; if ( true === ParaPr.Brd.First && border_Single === ParaPr.Brd.Top.Value ) { Top2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; } else if ( false === ParaPr.Brd.First && border_Single === ParaPr.Brd.Between.Value ) { Top2 += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; Bottom2 += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; Bottom += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; } } else { // Параграф начинается с новой страницы Bottom2 = Top + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent; Bottom = Top + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent + this.Lines[0].Metrics.LineGap; if ( border_Single === ParaPr.Brd.Top.Value ) { Top2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; } } } else { Bottom2 = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent; Bottom = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; } if ( bEnd ) { Bottom += ParaPr.Spacing.After; // Если нижняя граница Between, тогда она учитывается в следующем параграфе if ( true === ParaPr.Brd.Last ) { if ( border_Single === ParaPr.Brd.Bottom.Value ) Bottom += ParaPr.Brd.Bottom.Size + ParaPr.Brd.Bottom.Space; } else { if ( border_Single === ParaPr.Brd.Between.Value ) Bottom += ParaPr.Brd.Between.Space; } if ( false === this.Parent.Is_TableCellContent() && Bottom > this.YLimit && Bottom - this.YLimit <= ParaPr.Spacing.After ) Bottom = this.YLimit; } this.Lines[CurLine].Bottom = Bottom - this.Pages[CurPage].Y; this.Bounds.Bottom = Bottom; this.Pages[CurPage].Bounds.Bottom = Bottom; } else { if ( 0 != CurLine ) { if ( CurLine != this.Pages[CurPage].FirstLine ) { Top = Y + TempDy + this.Lines[CurLine - 1].Metrics.Descent + this.Lines[CurLine - 1].Metrics.LineGap; Bottom = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; Top2 = Top; Bottom2 = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent; this.Lines[CurLine].Top = Top - this.Pages[CurPage].Y; if ( bEnd ) { Bottom += ParaPr.Spacing.After; // Если нижняя граница Between, тогда она учитывается в следующем параграфе if ( true === ParaPr.Brd.Last ) { if ( border_Single === ParaPr.Brd.Bottom.Value ) Bottom += ParaPr.Brd.Bottom.Size + ParaPr.Brd.Bottom.Space; } else { if ( border_Single === ParaPr.Brd.Between.Value ) Bottom += ParaPr.Brd.Between.Space; } if ( false === this.Parent.Is_TableCellContent() && Bottom > this.YLimit && Bottom - this.YLimit <= ParaPr.Spacing.After ) Bottom = this.YLimit; } this.Lines[CurLine].Bottom = Bottom - this.Pages[CurPage].Y; this.Bounds.Bottom = Bottom; this.Pages[CurPage].Bounds.Bottom = Bottom; } else { Top = this.Pages[CurPage].Y; Bottom = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; Top2 = Top; Bottom2 = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent; this.Lines[CurLine].Top = 0; if ( bEnd ) { Bottom += ParaPr.Spacing.After; // Если нижняя граница Between, тогда она учитывается в следующем параграфе if ( true === ParaPr.Brd.Last ) { if ( border_Single === ParaPr.Brd.Bottom.Value ) Bottom += ParaPr.Brd.Bottom.Size + ParaPr.Brd.Bottom.Space; } else { if ( border_Single === ParaPr.Brd.Between.Value ) Bottom += ParaPr.Brd.Between.Space; } if ( false === this.Parent.Is_TableCellContent() && Bottom > this.YLimit && Bottom - this.YLimit <= ParaPr.Spacing.After ) Bottom = this.YLimit; } this.Lines[CurLine].Bottom = Bottom - this.Pages[CurPage].Y; this.Bounds.Bottom = Bottom; this.Pages[CurPage].Bounds.Bottom = Bottom; } } else { Top = Y; Top2 = Y; if ( 0 === CurPage || true === this.Parent.Is_TableCellContent() || true === ParaPr.PageBreakBefore ) { Top2 = Top + ParaPr.Spacing.Before; Bottom = Top + ParaPr.Spacing.Before + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent + this.Lines[0].Metrics.LineGap; Bottom2 = Top + ParaPr.Spacing.Before + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent; if ( true === ParaPr.Brd.First && border_Single === ParaPr.Brd.Top.Value ) { Top2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; } else if ( false === ParaPr.Brd.First && border_Single === ParaPr.Brd.Between.Value ) { Top2 += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; Bottom2 += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; Bottom += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; } } else { // Параграф начинается с новой страницы Bottom = Top + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent + this.Lines[0].Metrics.LineGap; Bottom2 = Top + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent; if ( border_Single === ParaPr.Brd.Top.Value ) { Top2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; } } if ( bEnd ) { Bottom += ParaPr.Spacing.After; // Если нижняя граница Between, тогда она учитывается в следующем параграфе if ( true === ParaPr.Brd.Last ) { if ( border_Single === ParaPr.Brd.Bottom.Value ) Bottom += ParaPr.Brd.Bottom.Size + ParaPr.Brd.Bottom.Space; } else { if ( border_Single === ParaPr.Brd.Between.Value ) Bottom += ParaPr.Brd.Between.Space; } if ( false === this.Parent.Is_TableCellContent() && Bottom > this.YLimit && Bottom - this.YLimit <= ParaPr.Spacing.After ) Bottom = this.YLimit; } this.Lines[0].Top = Top - this.Pages[CurPage].Y; this.Lines[0].Bottom = Bottom - this.Pages[CurPage].Y; this.Bounds.Top = Top; this.Bounds.Bottom = Bottom; this.Pages[CurPage].Bounds.Top = Top; this.Pages[CurPage].Bounds.Bottom = Bottom; } } // Переносим строку по BreakPage, выясним есть ли в строке что-нибудь кроме BreakPage. Если нет, // тогда нам не надо проверять высоту строки и обтекание. var bBreakPageLineEmpty = false; if ( true === bBreakPageLine ) { bBreakPageLineEmpty = true; for ( var _Pos = Pos - 1; _Pos >= LineStart_Pos; _Pos-- ) { var _Item = this.Content[_Pos]; var _Type = _Item.Type; if ( para_Drawing === _Type || para_End === _Type || (para_NewLine === _Type && break_Line === _Item.BreakType) || para_PageNum === _Type || para_Space === _Type || para_Tab === _Type || para_Text === _Type ) { bBreakPageLineEmpty = false; break; } } } // Сначала проверяем не нужно ли сделать перенос страницы в данном месте // Перенос не делаем, если это первая строка на новой странице if ( true === this.Use_YLimit() && (Top > this.YLimit || Bottom2 > this.YLimit ) && ( CurLine != this.Pages[CurPage].FirstLine || ( 0 === CurPage && ( null != this.Get_DocumentPrev() || true === this.Parent.Is_TableCellContent() ) ) ) && false === bBreakPageLineEmpty ) { // Проверим висячую строку if ( this.Parent instanceof CDocument && true === this.Parent.RecalcInfo.Can_RecalcObject() && true === ParaPr.WidowControl && CurLine - this.Pages[CurPage].StartLine <= 1 && CurLine >= 1 && true != bBreakPageLine && ( 0 === CurPage && null != this.Get_DocumentPrev() ) ) { this.Parent.RecalcInfo.Set_WidowControl(this, CurLine - 1); RecalcResult = recalcresult_CurPage; break; } else { // Неразрывные абзацы не учитываются в таблицах if ( true === ParaPr.KeepLines && null != this.Get_DocumentPrev() && true != this.Parent.Is_TableCellContent() && 0 === CurPage ) { CurLine = 0; LineStart_Pos = 0; } // Восстанавливаем позицию нижней границы предыдущей страницы this.Pages[CurPage].Bounds.Bottom = LastPage_Bottom; this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } // Добавляем разрыв страницы RecalcResult = recalcresult_NextPage; break; } } bBreakPageLine = false; var Left = ( 0 != CurLine ? this.X + ParaPr.Ind.Left : this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine ); var Right = this.XLimit - ParaPr.Ind.Right; var PageFields = this.Parent.Get_PageFields( this.PageNum + CurPage ); var Ranges2; if ( true === this.Use_Wrap() ) Ranges2 = this.Parent.CheckRange( Left, Top, Right, Bottom, Top2, Bottom2, PageFields.X, PageFields.XLimit, this.PageNum + CurPage, true ); else Ranges2 = new Array(); // Проверяем совпали ли промежутки. Если совпали, тогда данная строчка рассчитана верно, // и мы переходим к следующей, если нет, тогда заново рассчитываем данную строчку, но // с новыми промежутками. // Заметим, что тут возможен случай, когда Ranges2 меньше, чем Ranges, такое может случится // при повторном обсчете строки. (После первого расчета мы выяснили что Ranges < Ranges2, // при повторном обсчете строки, т.к. она стала меньше, то у нее и рассчитанная высота могла // уменьшиться, а значит Ranges2 могло оказаться меньше чем Ranges). В таком случае не надо // делать повторный пересчет, иначе будет зависание. if ( -1 == FlowObjects_CompareRanges( Ranges, Ranges2 ) && true === FlowObjects_CheckInjection( Ranges, Ranges2 ) && false === bBreakPageLineEmpty ) { bEnd = false; Ranges = Ranges2; Pos = LineStart_Pos - 1; if ( 0 == CurLine ) X = this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else X = this.X + ParaPr.Ind.Left; this.Lines[CurLine].Reset(); //this.Lines[CurLine].Metrics.Update( TextAscent, TextAscent2, TextDescent, TextAscent, TextDescent, ParaPr ); LineTextAscent = 0; LineTextAscent2 = 0; LineTextDescent = 0; LineAscent = 0; LineDescent = 0; TextAscent = 0; TextDescent = 0; TextAscent2 = 0; RangesCount = Ranges.length; // Выставляем начальные сдвиги для промежутков. Начало промежутка = конец вырезаемого промежутка this.Lines[CurLine].Add_Range( ( 0 == CurLine ? this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine : this.X + ParaPr.Ind.Left ), (RangesCount == 0 ? XLimit : Ranges[0].X0) ); this.Lines[CurLine].Set_RangeStartPos( 0, Pos + 1 ); for ( var Index = 1; Index < Ranges.length + 1; Index++ ) { this.Lines[CurLine].Add_Range( Ranges[Index - 1].X1, (RangesCount == Index ? XLimit : Ranges[Index].X0) ); } CurRange = 0; XEnd = 0; if ( RangesCount == 0 ) XEnd = XLimit; else XEnd = Ranges[0].X0; bStartWord = false; bWord = false; bNewPage = false; bForceNewPage = false; bExtendBoundToBottom = false; nWordLen = 0; nSpacesCount = 0; bAddNumbering = this.Internal_CheckAddNumbering( CurPage, CurLine, CurRange ); } else { if ( 0 != CurLine ) this.Lines[CurLine].W = X - this.X - ParaPr.Ind.Left; else this.Lines[CurLine].W = X - this.X - ParaPr.Ind.Left - ParaPr.Ind.FirstLine; if ( 0 == CurRange ) { if ( 0 != CurLine ) this.Lines[CurLine].Ranges[CurRange].W = X - this.X - ParaPr.Ind.Left; else this.Lines[CurLine].Ranges[CurRange].W = X - this.X - ParaPr.Ind.Left - ParaPr.Ind.FirstLine; } else { if ( true === this.Lines[CurLine].Ranges[CurRange].FirstRange ) { if ( ParaPr.Ind.FirstLine < 0 ) Ranges[CurRange - 1].X1 += ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else Ranges[CurRange - 1].X1 += ParaPr.Ind.FirstLine; } this.Lines[CurLine].Ranges[CurRange].W = X - Ranges[CurRange - 1].X1; } if ( true === bNewPage ) { bNewPage = false; // Если это последний элемент параграфа, тогда нам не надо переносить текущий параграф // на новую страницу. Нам надо выставить границы так, чтобы следующий параграф начинался // с новой страницы. // TODO: заменить на функцию проверки var ____Pos = Pos + 1; var Next = this.Internal_FindForward( ____Pos, [ para_End, para_NewLine, para_Space, para_Text, para_Drawing, para_Tab, para_PageNum ] ); while ( true === Next.Found && para_Drawing === Next.Type && drawing_Anchor === this.Content[Next.LetterPos].Get_DrawingType() ) Next = this.Internal_FindForward( ++____Pos, [ para_End, para_NewLine, para_Space, para_Text, para_Drawing, para_Tab, para_PageNum ] ); if ( true === Next.Found && para_End === Next.Type ) { Item.Flags.NewLine = false; bExtendBoundToBottom = true; continue; } if ( true === this.Lines[CurLine].RangeY ) { this.Lines[CurLine].Y = Y - this.Pages[CurPage].Y; } else { if ( CurLine > 0 ) { // Первая линия на странице не должна двигаться if ( CurLine != this.Pages[CurPage].FirstLine ) Y += this.Lines[CurLine - 1].Metrics.Descent + this.Lines[CurLine - 1].Metrics.LineGap + this.Lines[CurLine].Metrics.Ascent; this.Lines[CurLine].Y = Y - this.Pages[CurPage].Y; } } this.Pages[CurPage].Set_EndLine( CurLine ); this.Lines[CurLine].Set_EndPos( Pos, this ); RecalcResult = recalcresult_NextPage; break; } else { if ( true === this.Lines[CurLine].RangeY ) { this.Lines[CurLine].Y = Y - this.Pages[CurPage].Y; } else { if ( CurLine > 0 ) { // Первая линия на странице не должна двигаться if ( CurLine != this.Pages[CurPage].FirstLine ) Y += this.Lines[CurLine - 1].Metrics.Descent + this.Lines[CurLine - 1].Metrics.LineGap + this.Lines[CurLine].Metrics.Ascent; this.Lines[CurLine].Y = Y - this.Pages[CurPage].Y; } } if ( ( true === bEmptyLine && RangesCount > 0 && LineStart_Pos < 0 ) || Pos < 0 ) X = this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else X = this.X + ParaPr.Ind.Left; } if ( !bEnd ) { // Если строка пустая в следствии того, что у нас было обтекание, тогда мы не // добавляем новую строку, а просто текущую смещаем ниже. if ( true === bEmptyLine && RangesCount > 0 ) { Pos = LineStart_Pos - 1; var RangesY = Ranges[0].Y1; for ( var Index = 1; Index < Ranges.length; Index++ ) { if ( RangesY > Ranges[Index].Y1 ) RangesY = Ranges[Index].Y1; } if ( Math.abs(RangesY - Y) < 0.01 ) Y = RangesY + 1; // смещаемся по 1мм else Y = RangesY + 0.001; if ( 0 === CurLine ) X = this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else X = this.X + ParaPr.Ind.Left; } else { this.Lines[CurLine].Set_EndPos( Pos, this ); CurLine++; if ( this.Parent instanceof CDocument && true === this.Parent.RecalcInfo.Check_WidowControl(this, CurLine) ) { this.Parent.RecalcInfo.Reset_WidowControl(); this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine( 0 ); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } RecalcResult = recalcresult_NextPage; break; } } this.Lines[CurLine] = new CParaLine(Pos + 1); //this.Lines[CurLine].Metrics.Update( TextAscent, TextAscent2, TextDescent, TextAscent, TextDescent, ParaPr ); LineTextAscent = 0; LineTextDescent = 0; LineTextAscent2 = 0; LineAscent = 0; LineDescent = 0; TextAscent = 0; TextDescent = 0; TextAscent2 = 0; // Верх следующей строки var TempY; if ( true === bEmptyLine && RangesCount > 0 ) { TempY = Y; this.Lines[CurLine].RangeY = true; } else { if ( CurLine > 0 ) { if ( CurLine != this.Pages[CurPage].FirstLine ) TempY = TempDy + Y + this.Lines[CurLine - 1].Metrics.Descent + this.Lines[CurLine - 1].Metrics.LineGap; else TempY = this.Pages[CurPage].Y; } else TempY = this.Y; } // Получаем промежутки обтекания, т.е. промежутки, которые нам нельзя использовать Ranges = [];//this.Parent.CheckRange( X, TempY, XLimit, TempY, TempY, TempY, this.PageNum + CurPage, true ); RangesCount = Ranges.length; // Выставляем начальные сдвиги для промежутков. Началао промежутка = конец вырезаемого промежутка this.Lines[CurLine].Add_Range( X, (RangesCount == 0 ? XLimit : Ranges[0].X0) ); this.Lines[CurLine].Set_RangeStartPos( 0, Pos + 1 ); for ( var Index = 1; Index < Ranges.length + 1; Index++ ) { this.Lines[CurLine].Add_Range( Ranges[Index - 1].X1, (RangesCount == Index ? XLimit : Ranges[Index].X0) ); } CurRange = 0; XEnd = 0; if ( RangesCount == 0 ) XEnd = XLimit; else XEnd = Ranges[0].X0; bWord = false; nWordLen = 0; nSpacesCount = 0; LineStart_Pos = Pos + 1; if ( true === bForceNewPage ) { this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine( 0 ); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } RecalcResult = recalcresult_NextPage; break; } bAddNumbering = this.Internal_CheckAddNumbering( CurPage, CurLine, CurRange ); } else { for ( var TempRange = CurRange + 1; TempRange <= RangesCount; TempRange++ ) this.Lines[CurLine].Set_RangeStartPos( TempRange, Pos + 1 ); this.Lines[CurLine].Set_EndPos( Pos, this ); // Проверим висячую строку if ( true === ParaPr.WidowControl && CurLine === this.Pages[CurPage].StartLine && CurLine >= 1 ) { // Проверим не встречается ли в предыдущей строке BreakPage, если да, тогда не учитываем WidowControl var bBreakPagePrevLine = false; var StartPos = (CurLine == 2 ? this.Lines[CurLine - 2].StartPos : this.Lines[CurLine - 1].StartPos ); var EndPos = this.Lines[CurLine - 1].EndPos; for ( var TempPos = StartPos; TempPos <= EndPos; TempPos++ ) { var TempItem = this.Content[TempPos]; if ( para_NewLine === TempItem.Type && break_Page === TempItem.BreakType ) { bBreakPagePrevLine = true; break; } } if ( this.Parent instanceof CDocument && true === this.Parent.RecalcInfo.Can_RecalcObject() && false === bBreakPagePrevLine && ( 1 === CurPage && null != this.Get_DocumentPrev() ) ) { this.Parent.RecalcInfo.Set_WidowControl(this, ( CurLine > 2 ? CurLine - 1 : 0 ) ); // Если у нас в параграфе 3 строки, тогда сразу начинаем параграф с новой строки RecalcResult = recalcresult_PrevPage; break; } } if ( true === bEnd && true === bExtendBoundToBottom ) { // Специальный случай с PageBreak, когда после самого PageBreak ничего нет // в параграфе this.Pages[CurPage].Bounds.Bottom = this.Pages[CurPage].YLimit; this.Bounds.Bottom = this.Pages[CurPage].YLimit; this.Lines[CurLine].Set_EndPos( Pos, this ); this.Pages[CurPage].Set_EndLine( CurLine ); for ( var TempRange = CurRange + 1; TempRange <= RangesCount; TempRange++ ) this.Lines[CurLine].Set_RangeStartPos( TempRange, Pos ); // Если у нас нумерация относится к знаку конца параграфа, тогда в такой // ситуации не рисуем нумерацию у такого параграфа. if ( Pos === this.Numbering.Pos ) this.Numbering.Pos = -1; } else { this.Lines[CurLine].Set_EndPos( Pos, this ); this.Pages[CurPage].Set_EndLine( CurLine ); for ( var TempRange = CurRange + 1; TempRange <= RangesCount; TempRange++ ) this.Lines[CurLine].Set_RangeStartPos( TempRange, Pos + 1 ); } } } bEmptyLine = true; } else if ( bNewRange ) { pLastTab.Value = -1; this.Lines[CurLine].Set_RangeStartPos( CurRange + 1, Pos + 1 ); nSpaceLen = 0; bNewRange = false; bFirstItemOnLine = true; bStartWord = false; if ( 0 == CurRange ) { if ( 0 != CurLine ) this.Lines[CurLine].Ranges[CurRange].W = X - this.X - ParaPr.Ind.Left; else this.Lines[CurLine].Ranges[CurRange].W = X - this.X - ParaPr.Ind.Left - ParaPr.Ind.FirstLine; } else { if ( true === this.Lines[CurLine].Ranges[CurRange].FirstRange ) { if ( ParaPr.Ind.FirstLine < 0 ) Ranges[CurRange - 1].X1 += ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else Ranges[CurRange - 1].X1 += ParaPr.Ind.FirstLine; } this.Lines[CurLine].Ranges[CurRange].W = X - Ranges[CurRange - 1].X1; } CurRange++; if ( 0 === CurLine && true === bEmptyLine ) { if ( ParaPr.Ind.FirstLine < 0 ) this.Lines[CurLine].Ranges[CurRange].X += ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else this.Lines[CurLine].Ranges[CurRange].X += ParaPr.Ind.FirstLine; this.Lines[CurLine].Ranges[CurRange].FirstRange = true; } X = this.Lines[CurLine].Ranges[CurRange].X; if ( CurRange == RangesCount ) XEnd = XLimit; else XEnd = Ranges[CurRange].X0; bWord = false; nWordLen = 0; nSpacesCount = 0; bAddNumbering = this.Internal_CheckAddNumbering( CurPage, CurLine, CurRange ); } } // TODO: пока таким образом мы делаем, this.Y - был верхним краем параграфа // Потом надо будет переделать. var StartLine = this.Pages[CurPage].FirstLine; var EndLine = this.Lines.length - 1; var TempDy = this.Lines[this.Pages[CurPage].FirstLine].Metrics.Ascent; if ( 0 === StartLine && ( 0 === CurPage || true === this.Parent.Is_TableCellContent() || true === ParaPr.PageBreakBefore ) ) TempDy += ParaPr.Spacing.Before; if ( 0 === StartLine ) { if ( ( true === ParaPr.Brd.First || 1 === CurPage ) && border_Single === ParaPr.Brd.Top.Value ) TempDy += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; else if ( false === ParaPr.Brd.First && border_Single === ParaPr.Brd.Between.Value ) TempDy += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; } for ( var Index = StartLine; Index <= EndLine; Index++ ) { this.Lines[Index].Y += TempDy; if ( this.Lines[Index].Metrics.LineGap < 0 ) this.Lines[Index].Y += this.Lines[Index].Metrics.LineGap; } return RecalcResult; }, // Пересчитываем сдвиги элементов внутри параграфа, в зависимости от align. // Пересчитываем текущую позицию курсора, и видимые ширины пробелов. Internal_Recalculate_2_ : function(StartPos, _CurPage, _CurLine) { // Здесь мы пересчитываем ширину пробелов (и в особенных случаях дополнительное // расстояние между символами) с учетом прилегания параграфа. // 1. Если align = left, тогда внутри каждого промежутка текста выравниваем его // к левой границе промежутка. // 2. Если align = right, тогда внутри каждого промежутка текста выравниваем его // к правой границе промежутка. // 3. Если align = center, тогда внутри каждого промежутка текста выравниваем его // по центру промежутка. // 4. Если align = justify, тогда // 4.1 Если внутри промежутка ровно 1 слово. // 4.1.1 Если промежуток в строке 1 и слово занимает почти всю строку, // добавляем в слове к каждой букве дополнительное расстояние между // символами, чтобы ширина слова совпала с шириной строки. // 4.1.2 Если промежуток первый, тогда слово приставляем к левой границе // промежутка // 4.1.3 Если промежуток последний, тогда приставляем слово к правой // границе промежутка // 4.1.4 Если промежуток ни первый, ни последний, тогда ставим слово по // середине промежутка // 4.2 Если слов больше 1, тогда, исходя из количества пробелов между словами в // промежутке, увеличиваем их на столько, чтобы правая граница последнего // слова совпала с правой границей промежутка var Pr = this.Get_CompiledPr2(false); var ParaPr = Pr.ParaPr; var CurRange = 0; var CurLine = _CurLine; var CurPage = _CurPage; // Если параграф переносится на новую страницу с первой строки if ( this.Pages[CurPage].EndLine < 0 ) return recalcresult_NextPage; var EndPos = this.Lines[this.Pages[CurPage].EndLine].EndPos; var JustifyWord = 0; var JustifySpace = 0; var Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; var bFirstLineItem = true; var Range = this.Lines[CurLine].Ranges[CurRange]; var RangesCount = this.Lines[CurLine].Ranges.length; var RangeWidth = Range.XEnd - Range.X; var X = 0; switch (ParaPr.Jc) { case align_Left : X = Range.X; break; case align_Right : X = Math.max(Range.X + RangeWidth - Range.W, Range.X ); break; case align_Center : X = Math.max(Range.X + (RangeWidth - Range.W) / 2, Range.X); break case align_Justify: { X = Range.X; if ( 1 == Range.Words ) { if ( 1 == RangesCount && this.Lines.length > 1 ) { // Подсчитаем количество букв в слове var LettersCount = 0; var TempPos = StartPos; var LastW = 0; var __CurLine = CurLine; var __CurRange = CurRange; while ( this.Content[TempPos].Type != para_End ) { var __Item = this.Content[TempPos]; if ( undefined != __Item.CurPage ) { if ( __CurLine != __Item.CurLine || __CurRange != __Item.Range ) break; } if ( para_Text == this.Content[TempPos].Type ) { LettersCount++; LastW = this.Content[TempPos].Width; } TempPos++; } // Либо слово целиком занимает строку, либо не целиком, но разница очень мала if ( RangeWidth - Range.W <= 0.05 * RangeWidth && LettersCount > 1 ) JustifyWord = (RangeWidth - Range.W) / (LettersCount - 1); } else if ( 0 == CurRange || ( CurLine == this.Lines.length - 1 && CurRange == this.Lines[CurLine].Ranges.length - 1 ) ) { // Ничего не делаем (выравниваем текст по левой границе) } else if ( CurRange == this.Lines[CurLine].Ranges.length - 1 ) { X = Range.X + RangeWidth - Range.W; } else { X = Range.X + (RangeWidth - Range.W) / 2; } } else { // Последний промежуток последней строки не надо растягивать по ширине. if ( Range.Spaces > 0 && ( CurLine != this.Lines.length - 1 || CurRange != this.Lines[CurLine].Ranges.length - 1 ) ) JustifySpace = (RangeWidth - Range.W) / Range.Spaces; else JustifySpace = 0; } break; } default : X = Range.X; break; } var SpacesCounter = this.Lines[CurLine].Ranges[CurRange].Spaces; this.Lines[CurLine].Ranges[CurRange].XVisible = X; this.Lines[CurLine].X = X - this.X; var LastW = 0; // параметр нужен для позиционирования Flow-объектов for ( var ItemNum = StartPos; ItemNum <= EndPos; ItemNum++ ) { var Item = this.Content[ItemNum]; if ( undefined != Item.CurPage ) { if ( CurLine < Item.CurLine ) { CurLine = Item.CurLine; CurRange = Item.CurRange; JustifyWord = 0; JustifySpace = 0; Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; bFirstLineItem = true; Range = this.Lines[CurLine].Ranges[CurRange]; RangesCount = this.Lines[CurLine].Ranges.length; RangeWidth = Range.XEnd - Range.X; switch (ParaPr.Jc) { case align_Left : X = Range.X; break; case align_Right : X = Math.max(Range.X + RangeWidth - Range.W, Range.X); break; case align_Center : X = Math.max(Range.X + (RangeWidth - Range.W) / 2, Range.X); break case align_Justify: { X = Range.X; if ( 1 == Range.Words ) { if ( 1 == RangesCount && this.Lines.length > 1 ) { // Подсчитаем количество букв в слове var LettersCount = 0; var TempPos = ItemNum + 1; var LastW = 0; var __CurLine = CurLine; var __CurRange = CurRange; while ( this.Content[TempPos].Type != para_End ) { var __Item = this.Content[TempPos]; if ( undefined != __Item.CurPage ) { if ( __CurLine != __Item.CurLine || __CurRange != __Item.Range ) break; } if ( para_Text == this.Content[TempPos].Type ) { LettersCount++; LastW = this.Content[TempPos].Width; } TempPos++; } // Либо слово целиком занимает строку, либо не целиком, но разница очень мала if ( RangeWidth - Range.W <= 0.05 * RangeWidth && LettersCount > 1 ) JustifyWord = (RangeWidth - Range.W) / (LettersCount - 1); } else if ( 0 == CurRange || ( CurLine == this.Lines.length - 1 && CurRange == this.Lines[CurLine].Ranges.length - 1 ) ) { // Ничего не делаем (выравниваем текст по левой границе) } else if ( CurRange == this.Lines[CurLine].Ranges.length - 1 ) { X = Range.X + RangeWidth - Range.W; } else { X = Range.X + (RangeWidth - Range.W) / 2; } } else { // Последний промежуток последней строки не надо растягивать по ширине. if ( Range.Spaces > 0 && ( CurLine != this.Lines.length - 1 || CurRange != this.Lines[CurLine].Ranges.length - 1 ) ) JustifySpace = (RangeWidth - Range.W) / Range.Spaces; else JustifySpace = 0; } break; } default : X = Range.X; break; } SpacesCounter = this.Lines[CurLine].Ranges[CurRange].Spaces; this.Lines[CurLine].Ranges[CurRange].XVisible = X; this.Lines[CurLine].X = X - this.X; } else if ( CurRange < Item.CurRange ) { CurRange = Item.CurRange; Range = this.Lines[CurLine].Ranges[CurRange]; RangeWidth = Range.XEnd - Range.X; switch (ParaPr.Jc) { case align_Left : X = Range.X; break; case align_Right : X = Math.max(Range.X + RangeWidth - Range.W, Range.X); break; case align_Center : X = Math.max(Range.X + (RangeWidth - Range.W) / 2, Range.X); break case align_Justify: { X = Range.X; if ( 1 == Range.Words ) { if ( 1 == RangesCount && this.Lines.length > 1 ) { // Подсчитаем количество букв в слове var LettersCount = 0; var TempPos = ItemNum + 1; var LastW = 0; var __CurLine = CurLine; var __CurRange = CurRange; while ( this.Content[TempPos].Type != para_End ) { var __Item = this.Content[TempPos]; if ( undefined != __Item.CurPage ) { if ( __CurLine != __Item.CurLine || __CurRange != __Item.Range ) break; } if ( para_Text == this.Content[TempPos].Type ) { LettersCount++; LastW = this.Content[TempPos].Width; } TempPos++; } // Либо слово целиком занимает строку, либо не целиком, но разница очень мала if ( RangeWidth - Range.W <= 0.05 * RangeWidth && LettersCount > 1 ) JustifyWord = (RangeWidth - Range.W) / (LettersCount - 1); } else if ( 0 == CurRange || ( CurLine == this.Lines.length - 1 && CurRange == this.Lines[CurLine].Ranges.length - 1 ) ) { // Ничего не делаем (выравниваем текст по левой границе) } else if ( CurRange == this.Lines[CurLine].Ranges.length - 1 ) { X = Range.X + RangeWidth - Range.W; } else { X = Range.X + (RangeWidth - Range.W) / 2; } } else { // Последний промежуток последней строки не надо растягивать по ширине. if ( Range.Spaces > 0 && ( CurLine != this.Lines.length - 1 || CurRange != this.Lines[CurLine].Ranges.length - 1 ) ) JustifySpace = (RangeWidth - Range.W) / Range.Spaces; else JustifySpace = 0; } break; } default : X = Range.X; break; } SpacesCounter = this.Lines[CurLine].Ranges[CurRange].Spaces; this.Lines[CurLine].Ranges[CurRange].XVisible = X; } } if ( ItemNum == this.CurPos.ContentPos ) { this.CurPos.X = X; this.CurPos.Y = Y; this.CurPos.PagesPos = CurPage; } if ( ItemNum == this.Numbering.Pos ) X += this.Numbering.WidthVisible; switch( Item.Type ) { case para_Text: { bFirstLineItem = false; if ( CurLine != this.Lines.length - 1 && JustifyWord > 0 ) Item.WidthVisible = Item.Width + JustifyWord; else Item.WidthVisible = Item.Width; X += Item.WidthVisible; LastW = Item.WidthVisible; break; } case para_Space: { if ( !bFirstLineItem && CurLine != this.Lines.length - 1 && SpacesCounter > 0 && (ItemNum > this.Lines[CurLine].Ranges[CurRange].SpacePos) ) { Item.WidthVisible = Item.Width + JustifySpace; SpacesCounter--; } else Item.WidthVisible = Item.Width; X += Item.WidthVisible; LastW = Item.WidthVisible; break; } case para_Drawing: { var DrawingObjects = this.Parent.DrawingObjects; var PageLimits = this.Parent.Get_PageLimits(this.PageNum + CurPage); var PageFields = this.Parent.Get_PageFields(this.PageNum + CurPage); var ColumnStartX = (0 === CurPage ? this.X_ColumnStart : this.Pages[CurPage].X); var ColumnEndX = (0 === CurPage ? this.X_ColumnEnd : this.Pages[CurPage].XLimit); var Top_Margin = Y_Top_Margin; var Bottom_Margin = Y_Bottom_Margin; var Page_H = Page_Height; if ( true === this.Parent.Is_TableCellContent() && true == Item.Use_TextWrap() ) { Top_Margin = 0; Bottom_Margin = 0; Page_H = 0; } if ( true != Item.Use_TextWrap() ) { PageFields.X = X_Left_Field; PageFields.Y = Y_Top_Field; PageFields.XLimit = X_Right_Field; PageFields.YLimit = Y_Bottom_Field; PageLimits.X = 0; PageLimits.Y = 0; PageLimits.XLimit = Page_Width; PageLimits.YLimit = Page_Height; } if ( true === Item.Is_Inline() || true === this.Parent.Is_DrawingShape() ) { Item.Update_Position( X, Y , this.Get_StartPage_Absolute() + CurPage, LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent, this.Pages[CurPage].Y, PageLimits ); bFirstLineItem = false; X += Item.WidthVisible; LastW = Item.WidthVisible; } else { // У нас Flow-объект. Если он с обтеканием, тогда мы останавливаем пересчет и // запоминаем текущий объект. В функции Internal_Recalculate_2 пересчитываем // его позицию и сообщаем ее внешнему классу. if ( true === Item.Use_TextWrap() ) { var LogicDocument = this.Parent; var LDRecalcInfo = this.Parent.RecalcInfo; var Page_abs = this.Get_StartPage_Absolute() + CurPage; if ( true === LDRecalcInfo.Can_RecalcObject() ) { // Обновляем позицию объекта Item.Update_Position( X, Y , this.Get_StartPage_Absolute() + CurPage, LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent, this.Pages[CurPage].Y, PageLimits); LDRecalcInfo.Set_FlowObject( Item, 0, recalcresult_NextElement ); return recalcresult_CurPage; } else if ( true === LDRecalcInfo.Check_FlowObject(Item) ) { // Если мы находимся с таблице, тогда делаем как Word, не пересчитываем предыдущую страницу, // даже если это необходимо. Такое поведение нужно для точного определения рассчиталась ли // данная страница окончательно или нет. Если у нас будет ветка с переходом на предыдущую страницу, // тогда не рассчитав следующую страницу мы о конечном рассчете текущей страницы не узнаем. // Если данный объект нашли, значит он уже был рассчитан и нам надо проверить номер страницы if ( Item.PageNum === Page_abs ) { // Все нормально, можно продолжить пересчет LDRecalcInfo.Reset(); } else if ( true === this.Parent.Is_TableCellContent() ) { // Картинка не на нужной странице, но так как это таблица // мы не персчитываем заново текущую страницу, а не предыдущую // Обновляем позицию объекта Item.Update_Position( X, Y , this.Get_StartPage_Absolute() + CurPage, LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent, this.Pages[CurPage].Y, PageLimits); LDRecalcInfo.Set_FlowObject( Item, 0, recalcresult_NextElement ); LDRecalcInfo.Set_PageBreakBefore( false ); return recalcresult_CurPage; } else { LDRecalcInfo.Set_PageBreakBefore( true ); DrawingObjects.removeById( Item.PageNum, Item.Get_Id() ); return recalcresult_PrevPage; } } else { // Либо данный элемент уже обработан, либо будет обработан в будущем } continue; } else { // Картинка ложится на или под текст, в данном случае пересчет можно спокойно продолжать Item.Update_Position( X, Y , this.Get_StartPage_Absolute() + CurPage, LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent, this.Pages[CurPage].Y, PageLimits); continue; } } break; } case para_PageNum: { bFirstLineItem = false; X += Item.WidthVisible; LastW = Item.WidthVisible; break; } case para_Tab: { X += Item.WidthVisible; break; } case para_TextPr: { break; } case para_End: { X += Item.Width; break; } case para_NewLine: { X += Item.WidthVisible; break; } case para_CommentStart: { var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var CommentId = Item.Id; var CommentY = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var CommentH = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; DocumentComments.Set_StartInfo( CommentId, this.Get_StartPage_Absolute() + CurPage, X, CommentY, CommentH, this.Id ); break; } case para_CommentEnd: { var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var CommentId = Item.Id; var CommentY = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var CommentH = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; DocumentComments.Set_EndInfo( CommentId, this.Get_StartPage_Absolute() + CurPage, X, CommentY, CommentH, this.Id ); break; } } } return recalcresult_NextElement; }, // Пересчитываем заданную позицию элемента или текущую позицию курсора. Internal_Recalculate_CurPos : function(Pos, UpdateCurPos, UpdateTarget, ReturnTarget) { if ( this.Lines.length <= 0 ) return { X : 0, Y : 0, Height : 0, Internal : { Line : 0, Page : 0, Range : 0 } }; var LinePos = this.Internal_Get_ParaPos_By_Pos( Pos ); var CurLine = LinePos.Line; var CurRange = LinePos.Range; var CurPage = LinePos.Page; if ( Pos === this.CurPos.ContentPos && -1 != this.CurPos.Line ) CurLine = this.CurPos.Line; var X = this.Lines[CurLine].Ranges[CurRange].XVisible; var Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; if ( Pos < this.Lines[CurLine].Ranges[CurRange].StartPos ) { if ( true === ReturnTarget ) return { X : X, Y : TargetY, Height : 0, Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; else return { X : X, Y : Y, PageNum : CurPage + this.Get_StartPage_Absolute(), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; } for ( var ItemNum = this.Lines[CurLine].Ranges[CurRange].StartPos; ItemNum < this.Content.length; ItemNum++ ) { var Item = this.Content[ItemNum]; if ( ItemNum === this.Numbering.Pos ) X += this.Numbering.WidthVisible; if ( Pos === ItemNum ) { // Если так случилось, что у нас заданная позиция идет до позиции с нумерацией, к которой привязана нумерация, // тогда добавляем ширину нумерации. var _X = X; if ( ItemNum < this.Numbering.Pos ) _X += this.Numbering.WidthVisible; if ( true === UpdateCurPos) { this.CurPos.X = _X; this.CurPos.Y = Y; this.CurPos.PagesPos = CurPage; if ( true === UpdateTarget ) { var CurTextPr = this.Internal_CalculateTextPr(ItemNum); g_oTextMeasurer.SetTextPr( CurTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII, CurTextPr.Get_FontKoef() ); var Height = g_oTextMeasurer.GetHeight(); var Descender = Math.abs( g_oTextMeasurer.GetDescender() ); var Ascender = Height - Descender; this.DrawingDocument.SetTargetSize( Height ); this.DrawingDocument.SetTargetColor( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b ); var TargetY = Y - Ascender - CurTextPr.Position; switch( CurTextPr.VertAlign ) { case vertalign_SubScript: { TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Sub; break; } case vertalign_SuperScript: { TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Super; break; } } var Page_Abs = this.Get_StartPage_Absolute() + CurPage; this.DrawingDocument.UpdateTarget( _X, TargetY, Page_Abs ); // TODO: Тут делаем, чтобы курсор не выходил за границы буквицы. На самом деле, надо делать, чтобы // курсор не выходил за границы строки, но для этого надо делать обрезку по строкам, а без нее // такой вариант будет смотреться плохо. if ( undefined != this.Get_FramePr() ) { var __Y0 = TargetY, __Y1 = TargetY + Height; var ___Y0 = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var ___Y1 = this.Pages[CurPage].Y + this.Lines[CurLine].Bottom; var __Y0 = Math.max( __Y0, ___Y0 ); var __Y1 = Math.min( __Y1, ___Y1 ); this.DrawingDocument.SetTargetSize( __Y1 - __Y0 ); this.DrawingDocument.UpdateTarget( _X, __Y0, Page_Abs ); } } } if ( true === ReturnTarget ) { var CurTextPr = this.Internal_CalculateTextPr(ItemNum); g_oTextMeasurer.SetTextPr( CurTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII, CurTextPr.Get_FontKoef() ); var Height = g_oTextMeasurer.GetHeight(); var Descender = Math.abs( g_oTextMeasurer.GetDescender() ); var Ascender = Height - Descender; var TargetY = Y - Ascender - CurTextPr.Position; switch( CurTextPr.VertAlign ) { case vertalign_SubScript: { TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Sub; break; } case vertalign_SuperScript: { TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Super; break; } } return { X : _X, Y : TargetY, Height : Height, Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; } else return { X : _X, Y : Y, PageNum : CurPage + this.Get_StartPage_Absolute(), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; } switch( Item.Type ) { case para_Text: case para_Space: case para_PageNum: case para_Tab: case para_TextPr: case para_End: case para_NewLine: { X += Item.WidthVisible; break; } case para_Drawing: { if ( drawing_Inline != Item.DrawingType ) break; X += Item.WidthVisible; break; } } } if ( true === ReturnTarget ) return { X : X, Y : TargetY, Height : Height, Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; else return { X : X, Y : Y, PageNum : CurPage + this.Get_StartPage_Absolute(), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; }, // Нужно ли добавлять нумерацию в начале данной строки Internal_CheckAddNumbering : function(CurPage, CurLine, CurRange) { var StartLine = this.Pages[CurPage].StartLine; var bRes = false; if ( CurLine != StartLine ) bRes = false; else { if ( CurPage > 1 ) bRes = false; else { var StartPos = this.Lines[CurLine].Ranges[CurRange].StartPos; bRes = true; // Проверим, есть ли какие-нибудь реальные элементы (к которым можно было бы // дорисовать нумерацию) до стартовой позиции текущей страницы for ( var Pos = 0; Pos < StartPos; Pos++ ) { var Item = this.Content[Pos]; if ( true === Item.Can_AddNumbering() ) { bRes = false; break; } } } } if ( true === bRes ) this.Numbering.Pos = -1; return bRes; }, // Можно ли объединить границы двух параграфов с заданными настройками Pr1, Pr2 Internal_CompareBrd : function(Pr1, Pr2) { // Сначала сравним правую и левую границы параграфов var Left_1 = Math.min( Pr1.Ind.Left, Pr1.Ind.Left + Pr1.Ind.FirstLine ); var Right_1 = Pr1.Ind.Right; var Left_2 = Math.min( Pr2.Ind.Left, Pr2.Ind.Left + Pr2.Ind.FirstLine ); var Right_2 = Pr2.Ind.Right; if ( Math.abs( Left_1 - Left_2 ) > 0.001 || Math.abs( Right_1 - Right_2 ) > 0.001 ) return false; if ( false === Pr1.Brd.Top.Compare( Pr2.Brd.Top ) || false === Pr1.Brd.Bottom.Compare( Pr2.Brd.Bottom ) || false === Pr1.Brd.Left.Compare( Pr2.Brd.Left ) || false === Pr1.Brd.Right.Compare( Pr2.Brd.Right ) || false === Pr1.Brd.Between.Compare( Pr2.Brd.Between ) ) return false; return true; }, // Проверяем не пустые ли границы Internal_Is_NullBorders : function (Borders) { if ( border_None != Borders.Top.Value || border_None != Borders.Bottom.Value || border_None != Borders.Left.Value || border_None != Borders.Right.Value || border_None != Borders.Between.Value ) return false; return true; }, Internal_Check_Ranges : function(CurLine, CurRange) { var Ranges = this.Lines[CurLine].Ranges; var RangesCount = Ranges.length; if ( RangesCount <= 1 ) return true; else if ( 2 === RangesCount ) { var Range0 = Ranges[0]; var Range1 = Ranges[1]; if ( Range0.XEnd - Range0.X < 0.001 && 1 === CurRange && Range1.XEnd - Range1.X >= 0.001 ) return true; else if ( Range1.XEnd - Range1.X < 0.001 && 0 === CurRange && Range0.XEnd - Range0.X >= 0.001 ) return true; else return false } else if ( 3 === RangesCount && 1 === CurRange ) { var Range0 = Ranges[0]; var Range2 = Ranges[2]; if ( Range0.XEnd - Range0.X < 0.001 && Range2.XEnd - Range2.X < 0.001 ) return true; else return false; } else return false; }, Internal_Get_NumberingTextPr : function() { var Pr = this.Get_CompiledPr(); var ParaPr = Pr.ParaPr; var NumPr = ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) return new CTextPr(); var Numbering = this.Parent.Get_Numbering(); var NumLvl = Numbering.Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl]; var NumTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); NumTextPr.Merge( this.TextPr.Value ); NumTextPr.Merge( NumLvl.TextPr ); NumTextPr.FontFamily.Name = NumTextPr.RFonts.Ascii.Name; return NumTextPr; }, Internal_Get_ClearPos : function(Pos) { // TODO: Переделать. Надо ускорить. При пересчете параграфа запоминать // все позиции элементов para_NewLineRendered, para_InlineBreak, para_PageBreakRendered, // para_FlowObjectAnchor, para_CollaborativeChangesEnd, para_CollaborativeChangesStart var Counter = 0; for ( var Index = 0; Index < Math.min(Pos, this.Content.length - 1); Index++ ) { if ( false === this.Content[Index].Is_RealContent() || para_Numbering === this.Content[Index].Type ) Counter++; } return Pos - Counter; }, Internal_Get_RealPos : function(Pos) { // TODO: Переделать. Надо ускорить. При пересчете параграфа запоминать // все позиции элементов para_NewLineRendered, para_InlineBreak, para_PageBreakRendered, // para_FlowObjectAnchor, para_CollaborativeChangesEnd, para_CollaborativeChangesStart var Counter = Pos; for ( var Index = 0; Index <= Math.min(Counter, this.Content.length - 1); Index++ ) { if ( false === this.Content[Index].Is_RealContent() || para_Numbering === this.Content[Index].Type ) Counter++; } return Counter; }, Internal_Get_ClearContentLength : function() { var Len = this.Content.length; var ClearLen = Len; for ( var Index = 0; Index < Len; Index++ ) { var Item = this.Content[Index]; if ( false === Item.Is_RealContent() ) ClearLen--; } return ClearLen; }, Recalculate_Fast : function() { }, Start_FromNewPage : function() { this.Pages.length = 1; // Добавляем разрыв страницы this.Pages[0].Set_EndLine( - 1 ); this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( - 1, this ); }, Reset_RecalculateCache : function() { }, Recalculate_Page : function(_PageIndex) { // Во время пересчета сбрасываем привязку курсора к строке. this.CurPos.Line = -1; var PageIndex = _PageIndex - this.PageNum; var CurPage, StartPos, CurLine; if ( 0 === PageIndex ) { CurPage = 0; StartPos = 0; CurLine = 0; } else { CurPage = PageIndex; if ( CurPage > 0 ) CurLine = this.Pages[CurPage - 1].EndLine + 1; else CurLine = 0; if ( CurLine > 0 ) StartPos = this.Lines[CurLine - 1].EndPos + 1; else StartPos = 0; } // Если параграф начинается с новой страницы, и у самого параграфа нет настройки начать с новой страницы if ( 1 === CurPage && this.Pages[0].EndLine < 0 && this.Parent instanceof CDocument && false === this.Get_CompiledPr2(false).ParaPr.PageBreakBefore ) { // Если у предыдущего параграфа стоит настройка "не отрывать от следующего". // И сам параграф не разбит на несколько страниц и не начинается с новой страницы, // тогда мы должны пересчитать предыдущую страницу, с учетом того, что предыдущий параграф // надо начать с новой страницы. var Curr = this.Get_DocumentPrev(); while ( null != Curr && type_Paragraph === Curr.GetType() ) { var CurrKeepNext = Curr.Get_CompiledPr2(false).ParaPr.KeepNext; if ( (true === CurrKeepNext && Curr.Pages.length > 1) || false === CurrKeepNext ) { break; } else { var Prev = Curr.Get_DocumentPrev(); if ( null === Prev || type_Paragraph != Prev.GetType() ) break; var PrevKeepNext = Prev.Get_CompiledPr2(false).ParaPr.KeepNext; if ( false === PrevKeepNext ) { if ( true === this.Parent.RecalcInfo.Can_RecalcObject() ) { this.Parent.RecalcInfo.Set_KeepNext(Curr); return recalcresult_PrevPage; } else break; } else Curr = Prev; } } } // Пересчет параграфа: // 1. Сначала рассчитаем новые переносы строк, при этом подсчитав количество // слов и пробелов между словами. // 2. Далее, в зависимости от прилегания(align) параграфа, проставим начальные // позиции строк и проставим видимые размеры пробелов. this.FontMap.NeedRecalc = true; this.Internal_Recalculate_0(); this.Internal_CheckSpelling(); var RecalcResult_1 = this.Internal_Recalculate_1_(StartPos, CurPage, CurLine); var RecalcResult_2 = this.Internal_Recalculate_2_(StartPos, CurPage, CurLine); if ( true === this.Parent.RecalcInfo.WidowControlReset ) this.Parent.RecalcInfo.Reset(); var RecalcResult = ( recalcresult_NextElement != RecalcResult_2 ? RecalcResult_2 : RecalcResult_1 ); return RecalcResult; }, RecalculateCurPos : function() { this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, true, false ); }, Recalculate_MinMaxContentWidth : function() { // Пересчитаем ширины всех элементов this.Internal_Recalculate_0(); var bWord = false; var nWordLen = 0; var nSpaceLen = 0; var nMinWidth = 0; var nMaxWidth = 0; var nCurMaxWidth = 0; var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; // TODO: Продумать здесь учет нумерации switch( Item.Type ) { case para_Text : { if ( false === bWord ) { bWord = true; nWordLen = Item.Width; } else { nWordLen += Item.Width; if ( true === Item.SpaceAfter ) { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; } } if ( nSpaceLen > 0 ) { nCurMaxWidth += nSpaceLen; nSpaceLen = 0; } nCurMaxWidth += Item.Width; break; } case para_Space: { if ( true === bWord ) { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; } // Мы сразу не добавляем ширину пробелов к максимальной ширине, потому что // пробелы, идущие в конце параграфа или перед переносом строки(явным), не // должны учитываться. nSpaceLen += Item.Width; break; } case para_Drawing: { if ( true === bWord ) { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; } if ( ( true === Item.Is_Inline() || true === this.Parent.Is_DrawingShape() ) && Item.Width > nMinWidth ) nMinWidth = Item.Width; if ( nSpaceLen > 0 ) { nCurMaxWidth += nSpaceLen; nSpaceLen = 0; } nCurMaxWidth += Item.Width; break; } case para_PageNum: { if ( true === bWord ) { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; } if ( Item.Width > nMinWidth ) nMinWidth = Item.Width; if ( nSpaceLen > 0 ) { nCurMaxWidth += nSpaceLen; nSpaceLen = 0; } nCurMaxWidth += Item.Width; break; } case para_Tab: { nWordLen += Item.Width; if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; if ( nSpaceLen > 0 ) { nCurMaxWidth += nSpaceLen; nSpaceLen = 0; } nCurMaxWidth += Item.Width; break; } case para_NewLine: { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; nSpaceLen = 0; if ( nCurMaxWidth > nMaxWidth ) nMaxWidth = nCurMaxWidth; nCurMaxWidth = 0; break; } case para_End: { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; if ( nCurMaxWidth > nMaxWidth ) nMaxWidth = nCurMaxWidth; break; } } } // добавляем 0.001, чтобы избавиться от погрешностей return { Min : ( nMinWidth > 0 ? nMinWidth + 0.001 : 0 ), Max : ( nMaxWidth > 0 ? nMaxWidth + 0.001 : 0 ) }; }, Draw : function(PageNum, pGraphics) { var CurPage = PageNum - this.PageNum; // Параграф начинается с новой страницы if ( this.Pages[CurPage].EndLine < 0 ) return; var Pr = this.Get_CompiledPr(); // Задаем обрезку, если данный параграф является рамкой var FramePr = this.Get_FramePr(); if ( undefined != FramePr && this.Parent instanceof CDocument ) { var PixelError = editor.WordControl.m_oLogicDocument.DrawingDocument.GetMMPerDot(1); var BoundsL = this.CalculatedFrame.L2 - PixelError; var BoundsT = this.CalculatedFrame.T2 - PixelError; var BoundsH = this.CalculatedFrame.H2 + 2 * PixelError; var BoundsW = this.CalculatedFrame.W2 + 2 * PixelError; /* var Brd = Pr.ParaPr.Brd; var BorderBottom = Brd.Bottom; if ( undefined != Brd.Bottom ) BoundsH += BorderBottom.Size + BorderBottom.Space; var BorderLeft = Brd.Left; if ( undefined != Brd.Left ) { BoundsL -= BorderLeft.Size + BorderLeft.Space; BoundsW += BorderLeft.Size + BorderLeft.Space; } var BorderRight = Brd.Right; if ( undefined != Brd.Right ) BoundsW += BorderRight.Size + BorderRight.Space; */ pGraphics.SaveGrState(); pGraphics.AddClipRect( BoundsL, BoundsT, BoundsW, BoundsH ); } // 1 часть отрисовки : // Рисуем слева от параграфа знак, если данный параграф зажат другим пользователем this.Internal_Draw_1( CurPage, pGraphics, Pr ); // 2 часть отрисовки : // Добавляем специальный символ слева от параграфа, для параграфов, у которых стоит хотя бы // одна из настроек: не разрывать абзац(KeepLines), не отрывать от следующего(KeepNext), // начать с новой страницы(PageBreakBefore) this.Internal_Draw_2( CurPage, pGraphics, Pr ); // 3 часть отрисовки : // Рисуем заливку параграфа и различные выделения текста (highlight, поиск, совместное редактирование). // Кроме этого рисуем боковые линии обводки параграфа. this.Internal_Draw_3( CurPage, pGraphics, Pr ); // 4 часть отрисовки : // Рисуем сами элементы параграфа this.Internal_Draw_4( CurPage, pGraphics, Pr ); // 5 часть отрисовки : // Рисуем различные подчеркивания и зачеркивания. this.Internal_Draw_5( CurPage, pGraphics, Pr ); // 6 часть отрисовки : // Рисуем верхнюю, нижнюю и промежуточную границы this.Internal_Draw_6( CurPage, pGraphics, Pr ); // Убираем обрезку if ( undefined != FramePr && this.Parent instanceof CDocument ) { pGraphics.RestoreGrState(); } }, Internal_Draw_1 : function(CurPage, pGraphics, Pr) { // Если данный параграф зажат другим пользователем, рисуем соответствующий знак if ( locktype_None != this.Lock.Get_Type() ) { if ( ( CurPage > 0 || false === this.Is_StartFromNewPage() || null === this.Get_DocumentPrev() ) ) { var X_min = -1 + Math.min( this.Pages[CurPage].X, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var Y_top = this.Pages[CurPage].Bounds.Top; var Y_bottom = this.Pages[CurPage].Bounds.Bottom; if ( true === editor.isCoMarksDraw || locktype_Mine != this.Lock.Get_Type() ) pGraphics.DrawLockParagraph(this.Lock.Get_Type(), X_min, Y_top, Y_bottom); } } }, Internal_Draw_2 : function(CurPage, pGraphics, Pr) { if ( true === editor.ShowParaMarks && ( ( 0 === CurPage && ( this.Pages.length <= 1 || this.Pages[1].FirstLine > 0 ) ) || ( 1 === CurPage && this.Pages.length > 1 && this.Pages[1].FirstLine === 0 ) ) && ( true === Pr.ParaPr.KeepNext || true === Pr.ParaPr.KeepLines || true === Pr.ParaPr.PageBreakBefore ) ) { var SpecFont = { FontFamily: { Name : "Arial", Index : -1 }, FontSize : 12, Italic : false, Bold : false }; var SpecSym = String.fromCharCode( 0x25AA ); pGraphics.SetFont( SpecFont ); pGraphics.b_color1( 0, 0, 0, 255 ); var CurLine = this.Pages[CurPage].FirstLine; var CurRange = 0; var X = this.Lines[CurLine].Ranges[CurRange].XVisible; var Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; var SpecW = 2.5; // 2.5 mm var SpecX = Math.min( X, this.X ) - SpecW; pGraphics.FillText( SpecX, Y, SpecSym ); } }, Internal_Draw_3 : function(CurPage, pGraphics, Pr) { var _Page = this.Pages[CurPage]; var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var bDrawComments = DocumentComments.Is_Use(); var CommentsFlag = DocumentComments.Check_CurrentDraw(); var CollaborativeChanges = 0; var StartPagePos = this.Lines[_Page.StartLine].StartPos; var DrawSearch = editor.WordControl.m_oLogicDocument.SearchEngine.Selection; // в PDF не рисуем метки совместного редактирования if ( undefined === pGraphics.RENDERER_PDF_FLAG ) { var Pos = 0; while ( Pos < StartPagePos ) { Item = this.Content[Pos]; if ( para_CollaborativeChangesEnd == Item.Type ) CollaborativeChanges--; else if ( para_CollaborativeChangesStart == Item.Type ) CollaborativeChanges++; Pos++; } } var CurTextPr = _Page.TextPr; var StartLine = _Page.StartLine; var EndLine = _Page.EndLine; var aHigh = new CParaDrawingRangeLines(); var aColl = new CParaDrawingRangeLines(); var aFind = new CParaDrawingRangeLines(); var aComm = new CParaDrawingRangeLines(); for ( var CurLine = StartLine; CurLine <= EndLine; CurLine++ ) { var _Line = this.Lines[CurLine]; var _LineMetrics = _Line.Metrics; var EndLinePos = _Line.EndPos; var Y0 = (_Page.Y + _Line.Y - _LineMetrics.Ascent); var Y1 = (_Page.Y + _Line.Y + _LineMetrics.Descent); if ( _LineMetrics.LineGap < 0 ) Y1 += _LineMetrics.LineGap; var RangesCount = _Line.Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var _Range = _Line.Ranges[CurRange]; aHigh.Clear(); aColl.Clear(); aFind.Clear(); aComm.Clear(); // Сначала проанализируем данную строку: в массивы aHigh, aColl, aFind // сохраним позиции начала и конца продолжительных одинаковых настроек // выделения, совместного редатирования и поиска соответственно. var X = _Range.XVisible; var StartPos = _Range.StartPos; var EndPos = ( CurRange === RangesCount - 1 ? EndLinePos : _Line.Ranges[CurRange + 1].StartPos - 1 ); for ( var Pos = StartPos; Pos <= EndPos; Pos++ ) { var Item = this.Content[Pos]; var bSearchResult = false; if ( true === DrawSearch ) { for ( var SId in this.SearchResults ) { var SResult = this.SearchResults[SId]; if ( Pos >= SResult.StartPos && Pos < SResult.EndPos ) { bSearchResult = true; break; } } } if ( Pos === this.Numbering.Pos ) { var NumberingType = this.Numbering.Type; var NumberingItem = this.Numbering; if ( para_Numbering === NumberingType ) { var NumPr = Pr.ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) break; var Numbering = this.Parent.Get_Numbering(); var NumLvl = Numbering.Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl]; var NumJc = NumLvl.Jc; var NumTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); NumTextPr.Merge( this.TextPr.Value ); NumTextPr.Merge( NumLvl.TextPr ); var X_start = X; if ( align_Right === NumJc ) X_start = X - NumberingItem.WidthNum; else if ( align_Center === NumJc ) X_start = X - NumberingItem.WidthNum / 2; // Если есть выделение текста, рисуем его сначала if ( highlight_None != NumTextPr.HighLight ) aHigh.Add( Y0, Y1, X_start, X_start + NumberingItem.WidthNum + NumberingItem.WidthSuff, 0, NumTextPr.HighLight.r, NumTextPr.HighLight.g, NumTextPr.HighLight.b ); if ( CollaborativeChanges > 0 ) aColl.Add( Y0, Y1, X_start, X_start + NumberingItem.WidthNum + NumberingItem.WidthSuff, 0, 0, 0, 0 ); X += NumberingItem.WidthVisible; } else if ( para_PresentationNumbering === NumberingType ) { X += NumberingItem.WidthVisible; } } switch( Item.Type ) { case para_PageNum: case para_Drawing: case para_Tab: case para_Text: { if ( para_Drawing === Item.Type && drawing_Anchor === Item.DrawingType ) break; if ( CommentsFlag != comments_NoComment && true === bDrawComments ) aComm.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0, { Active : CommentsFlag === comments_ActiveComment ? true : false } ); else if ( highlight_None != CurTextPr.HighLight ) aHigh.Add( Y0, Y1, X, X + Item.WidthVisible, 0, CurTextPr.HighLight.r, CurTextPr.HighLight.g, CurTextPr.HighLight.b ); if ( true === bSearchResult ) aFind.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); else if ( CollaborativeChanges > 0 ) aColl.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); if ( para_Drawing != Item.Type || drawing_Anchor != Item.DrawingType ) X += Item.WidthVisible; break; } case para_Space: { // Пробелы в конце строки (и строку состоящую из пробелов) не подчеркиваем, не зачеркиваем и не выделяем if ( Pos >= _Range.StartPos2 && Pos <= _Range.EndPos2 ) { if ( CommentsFlag != comments_NoComment && bDrawComments ) aComm.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0, { Active : CommentsFlag === comments_ActiveComment ? true : false } ); else if ( highlight_None != CurTextPr.HighLight ) aHigh.Add( Y0, Y1, X, X + Item.WidthVisible, 0, CurTextPr.HighLight.r, CurTextPr.HighLight.g, CurTextPr.HighLight.b ); } if ( true === bSearchResult ) aFind.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); else if ( CollaborativeChanges > 0 ) aColl.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); X += Item.WidthVisible; break; } case para_TextPr: { CurTextPr = Item.CalcValue; break; } case para_End: { if ( CollaborativeChanges > 0 ) aColl.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); X += Item.Width; break; } case para_NewLine: { X += Item.WidthVisible; break; } case para_CollaborativeChangesStart: { CollaborativeChanges++; break; } case para_CollaborativeChangesEnd: { CollaborativeChanges--; break; } case para_CommentStart: { if ( undefined === pGraphics.RENDERER_PDF_FLAG ) { var CommentId = Item.Id; var CommentY = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var CommentH = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; DocumentComments.Set_StartInfo( CommentId, this.Get_StartPage_Absolute() + CurPage, X, CommentY, CommentH, this.Id ); DocumentComments.Add_CurrentDraw( CommentId ); CommentsFlag = DocumentComments.Check_CurrentDraw(); } break; } case para_CommentEnd: { if ( undefined === pGraphics.RENDERER_PDF_FLAG ) { var CommentId = Item.Id; var CommentY = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var CommentH = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; DocumentComments.Set_EndInfo( CommentId, this.Get_StartPage_Absolute() + CurPage, X, CommentY, CommentH, this.Id ); DocumentComments.Remove_CurrentDraw( CommentId ); CommentsFlag = DocumentComments.Check_CurrentDraw(); } break; } } } //---------------------------------------------------------------------------------------------------------- // Заливка параграфа //---------------------------------------------------------------------------------------------------------- if ( (_Range.W > 0.001 || true === this.IsEmpty() ) && ( ( this.Pages.length - 1 === CurPage ) || ( CurLine < this.Pages[CurPage + 1].FirstLine ) ) && shd_Clear === Pr.ParaPr.Shd.Value ) { var TempX0 = this.Lines[CurLine].Ranges[CurRange].X; if ( 0 === CurRange ) TempX0 = Math.min( TempX0, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var TempX1 = this.Lines[CurLine].Ranges[CurRange].XEnd; var TempTop = this.Lines[CurLine].Top; var TempBottom = this.Lines[CurLine].Bottom; if ( 0 === CurLine ) { // Закрашиваем фон до параграфа, только если данный параграф не является первым // на странице, предыдущий параграф тоже имеет не пустой фон и у текущего и предыдущего // параграфов совпадают правая и левая границы фонов. var PrevEl = this.Get_DocumentPrev(); var PrevPr = null; var PrevLeft = 0; var PrevRight = 0; var CurLeft = Math.min( Pr.ParaPr.Ind.Left, Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var CurRight = Pr.ParaPr.Ind.Right; if ( null != PrevEl && type_Paragraph === PrevEl.GetType() ) { PrevPr = PrevEl.Get_CompiledPr2(); PrevLeft = Math.min( PrevPr.ParaPr.Ind.Left, PrevPr.ParaPr.Ind.Left + PrevPr.ParaPr.Ind.FirstLine ); PrevRight = PrevPr.ParaPr.Ind.Right; } // Если данный параграф находится в группе параграфов с одинаковыми границами(с хотябы одной // непустой), и он не первый, тогда закрашиваем вместе с расстоянием до параграфа if ( true === Pr.ParaPr.Brd.First ) { // Если следующий элемент таблица, тогда PrevPr = null if ( null === PrevEl || true === this.Is_StartFromNewPage() || null === PrevPr || shd_Nil === PrevPr.ParaPr.Shd.Value || PrevLeft != CurLeft || CurRight != PrevRight || false === this.Internal_Is_NullBorders(PrevPr.ParaPr.Brd) || false === this.Internal_Is_NullBorders(Pr.ParaPr.Brd) ) { if ( false === this.Is_StartFromNewPage() || null === PrevEl ) TempTop += Pr.ParaPr.Spacing.Before; } } } if ( this.Lines.length - 1 === CurLine ) { // Закрашиваем фон после параграфа, только если данный параграф не является последним, // на странице, следующий параграф тоже имеет не пустой фон и у текущего и следующего // параграфов совпадают правая и левая границы фонов. var NextEl = this.Get_DocumentNext(); var NextPr = null; var NextLeft = 0; var NextRight = 0; var CurLeft = Math.min( Pr.ParaPr.Ind.Left, Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var CurRight = Pr.ParaPr.Ind.Right; if ( null != NextEl && type_Paragraph === NextEl.GetType() ) { NextPr = NextEl.Get_CompiledPr2(); NextLeft = Math.min( NextPr.ParaPr.Ind.Left, NextPr.ParaPr.Ind.Left + NextPr.ParaPr.Ind.FirstLine ); NextRight = NextPr.ParaPr.Ind.Right; } if ( null != NextEl && type_Paragraph === NextEl.GetType() && true === NextEl.Is_StartFromNewPage() ) { TempBottom = this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; } // Если данный параграф находится в группе параграфов с одинаковыми границами(с хотябы одной // непустой), и он не последний, тогда закрашиваем вместе с расстоянием после параграфа else if ( true === Pr.ParaPr.Brd.Last ) { // Если следующий элемент таблица, тогда NextPr = null if ( null === NextEl || true === NextEl.Is_StartFromNewPage() || null === NextPr || shd_Nil === NextPr.ParaPr.Shd.Value || NextLeft != CurLeft || CurRight != NextRight || false === this.Internal_Is_NullBorders(NextPr.ParaPr.Brd) || false === this.Internal_Is_NullBorders(Pr.ParaPr.Brd) ) TempBottom -= Pr.ParaPr.Spacing.After; } } if ( 0 === CurRange ) { if ( Pr.ParaPr.Brd.Left.Value === border_Single ) TempX0 -= 1 + Pr.ParaPr.Brd.Left.Size + Pr.ParaPr.Brd.Left.Space; else TempX0 -= 1; } if ( this.Lines[CurLine].Ranges.length - 1 === CurRange ) { if ( Pr.ParaPr.Brd.Right.Value === border_Single ) TempX1 += 1 + Pr.ParaPr.Brd.Right.Size + Pr.ParaPr.Brd.Right.Space; else TempX1 += 1; } pGraphics.b_color1( Pr.ParaPr.Shd.Color.r, Pr.ParaPr.Shd.Color.g, Pr.ParaPr.Shd.Color.b, 255 ); pGraphics.rect(TempX0, this.Pages[CurPage].Y + TempTop, TempX1 - TempX0, TempBottom - TempTop); pGraphics.df(); } //---------------------------------------------------------------------------------------------------------- // Рисуем выделение текста //---------------------------------------------------------------------------------------------------------- var Element = aHigh.Get_Next(); while ( null != Element ) { pGraphics.b_color1( Element.r, Element.g, Element.b, 255 ); pGraphics.rect( Element.x0, Element.y0, Element.x1 - Element.x0, Element.y1 - Element.y0 ); pGraphics.df(); Element = aHigh.Get_Next(); } //---------------------------------------------------------------------------------------------------------- // Рисуем комментарии //---------------------------------------------------------------------------------------------------------- Element = aComm.Get_Next(); while ( null != Element ) { if ( Element.Additional.Active === true ) pGraphics.b_color1( 240, 200, 120, 255 ); else pGraphics.b_color1( 248, 231, 195, 255 ); pGraphics.rect( Element.x0, Element.y0, Element.x1 - Element.x0, Element.y1 - Element.y0 ); pGraphics.df(); Element = aComm.Get_Next(); } //---------------------------------------------------------------------------------------------------------- // Рисуем выделение совместного редактирования //---------------------------------------------------------------------------------------------------------- Element = aColl.Get_Next(); while ( null != Element ) { pGraphics.drawCollaborativeChanges( Element.x0, Element.y0, Element.x1 - Element.x0, Element.y1 - Element.y0 ); Element = aColl.Get_Next(); } //---------------------------------------------------------------------------------------------------------- // Рисуем выделение поиска //---------------------------------------------------------------------------------------------------------- Element = aFind.Get_Next(); while ( null != Element ) { pGraphics.drawSearchResult( Element.x0, Element.y0, Element.x1 - Element.x0, Element.y1 - Element.y0 ); Element = aFind.Get_Next(); } } //---------------------------------------------------------------------------------------------------------- // Рисуем боковые линии границы параграфа //---------------------------------------------------------------------------------------------------------- if ( ( this.Pages.length - 1 === CurPage ) || ( CurLine < this.Pages[CurPage + 1].FirstLine ) ) { var TempX0 = Math.min( this.Lines[CurLine].Ranges[0].X, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine); var TempX1 = this.Lines[CurLine].Ranges[this.Lines[CurLine].Ranges.length - 1].XEnd; if ( true === this.Is_LineDropCap() ) { TempX1 = TempX0 + this.Get_LineDropCapWidth(); } var TempTop = this.Lines[CurLine].Top; var TempBottom = this.Lines[CurLine].Bottom; if ( 0 === CurLine ) { if ( true === Pr.ParaPr.Brd.First && ( Pr.ParaPr.Brd.Top.Value === border_Single || shd_Clear === Pr.ParaPr.Shd.Value ) ) { if ( false === this.Is_StartFromNewPage() || null === this.Get_DocumentPrev() ) TempTop += Pr.ParaPr.Spacing.Before; } } if ( this.Lines.length - 1 === CurLine ) { var NextEl = this.Get_DocumentNext(); if ( null != NextEl && type_Paragraph === NextEl.GetType() && true === NextEl.Is_StartFromNewPage() ) TempBottom = this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; else if ( true === Pr.ParaPr.Brd.Last && ( Pr.ParaPr.Brd.Bottom.Value === border_Single || shd_Clear === Pr.ParaPr.Shd.Value ) ) TempBottom -= Pr.ParaPr.Spacing.After; } if ( Pr.ParaPr.Brd.Right.Value === border_Single ) { pGraphics.p_color( Pr.ParaPr.Brd.Right.Color.r, Pr.ParaPr.Brd.Right.Color.g, Pr.ParaPr.Brd.Right.Color.b, 255 ); pGraphics.drawVerLine( c_oAscLineDrawingRule.Right, TempX1 + 1 + Pr.ParaPr.Brd.Right.Size + Pr.ParaPr.Brd.Right.Space, this.Pages[CurPage].Y + TempTop, this.Pages[CurPage].Y + TempBottom, Pr.ParaPr.Brd.Right.Size ); } if ( Pr.ParaPr.Brd.Left.Value === border_Single ) { pGraphics.p_color( Pr.ParaPr.Brd.Left.Color.r, Pr.ParaPr.Brd.Left.Color.g, Pr.ParaPr.Brd.Left.Color.b, 255 ); pGraphics.drawVerLine( c_oAscLineDrawingRule.Left, TempX0 - 1 - Pr.ParaPr.Brd.Left.Size - Pr.ParaPr.Brd.Left.Space, this.Pages[CurPage].Y + TempTop, this.Pages[CurPage].Y + TempBottom, Pr.ParaPr.Brd.Left.Size ); } } } }, Internal_Draw_4 : function(CurPage, pGraphics, Pr) { var StartPagePos = this.Lines[this.Pages[CurPage].StartLine].StartPos; var HyperPos = this.Internal_FindBackward( StartPagePos, [para_HyperlinkStart, para_HyperlinkEnd] ); var bVisitedHyperlink = false; if ( true === HyperPos.Found && para_HyperlinkStart === HyperPos.Type ) bVisitedHyperlink = this.Content[HyperPos.LetterPos].Get_Visited(); var CurTextPr = this.Pages[CurPage].TextPr; // Выставляем шрифт и заливку текста pGraphics.SetTextPr( CurTextPr ); if ( true === bVisitedHyperlink ) pGraphics.b_color1( 128, 0, 151, 255 ); else pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); var StartLine = this.Pages[CurPage].StartLine; var EndLine = this.Pages[CurPage].EndLine; for ( var CurLine = StartLine; CurLine <= EndLine; CurLine++ ) { var StartPos = this.Lines[CurLine].StartPos; var EndPos = this.Lines[CurLine].EndPos; var bFirstLineItem = true; var CurRange = 0; var Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; var X = this.Lines[CurLine].Ranges[CurRange].XVisible; var bEnd = false; for ( var Pos = StartPos; Pos <= EndPos; Pos++ ) { var Item = this.Content[Pos]; // Отслеживаем изменение позиции (отрезок) // Изменении страницы и строки не отслеживаем if ( undefined != Item.CurRange ) { if ( Item.CurRange > CurRange ) { CurRange = Item.CurRange; X = this.Lines[CurLine].Ranges[CurRange].XVisible; } } var TempY = Y; switch( CurTextPr.VertAlign ) { case vertalign_SubScript: { Y -= vertalign_Koef_Sub * CurTextPr.FontSize * g_dKoef_pt_to_mm; break; } case vertalign_SuperScript: { Y -= vertalign_Koef_Super * CurTextPr.FontSize * g_dKoef_pt_to_mm; break; } } if ( Pos === this.Numbering.Pos ) { var NumberingItem = this.Numbering; if ( para_Numbering === this.Numbering.Type ) { var NumPr = Pr.ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) break; var Numbering = this.Parent.Get_Numbering(); var NumLvl = Numbering.Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl]; var NumSuff = NumLvl.Suff; var NumJc = NumLvl.Jc; var NumTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); // Word не рисует подчеркивание у символа списка, если оно пришло из настроек для // символа параграфа. var TextPr_temp = this.TextPr.Value.Copy(); TextPr_temp.Underline = undefined; NumTextPr.Merge( TextPr_temp ); NumTextPr.Merge( NumLvl.TextPr ); var X_start = X; if ( align_Right === NumJc ) X_start = X - NumberingItem.WidthNum; else if ( align_Center === NumJc ) X_start = X - NumberingItem.WidthNum / 2; pGraphics.b_color1( NumTextPr.Color.r, NumTextPr.Color.g, NumTextPr.Color.b, 255 ); // Рисуется только сам символ нумерации switch ( NumJc ) { case align_Right: NumberingItem.Draw( X - NumberingItem.WidthNum, Y, pGraphics, Numbering, NumTextPr, NumPr ); break; case align_Center: NumberingItem.Draw( X - NumberingItem.WidthNum / 2, Y, pGraphics, Numbering, NumTextPr, NumPr ); break; case align_Left: default: NumberingItem.Draw( X, Y, pGraphics, Numbering, NumTextPr, NumPr ); break; } if ( true === editor.ShowParaMarks && numbering_suff_Tab === NumSuff ) { var TempWidth = NumberingItem.WidthSuff; var TempRealWidth = 3.143; // ширина символа "стрелка влево" в шрифте Wingding3,10 var X1 = X; switch ( NumJc ) { case align_Right: break; case align_Center: X1 += NumberingItem.WidthNum / 2; break; case align_Left: default: X1 += NumberingItem.WidthNum; break; } var X0 = TempWidth / 2 - TempRealWidth / 2; pGraphics.SetFont( {FontFamily: { Name : "Wingdings 3", Index : -1 }, FontSize: 10, Italic: false, Bold : false} ); if ( X0 > 0 ) pGraphics.FillText2( X1 + X0, Y, String.fromCharCode( tab_Symbol ), 0, TempWidth ); else pGraphics.FillText2( X1, Y, String.fromCharCode( tab_Symbol ), TempRealWidth - TempWidth, TempWidth ); } if ( true === NumTextPr.Strikeout || true === NumTextPr.Underline ) pGraphics.p_color( NumTextPr.Color.r, NumTextPr.Color.g, NumTextPr.Color.b, 255 ); if ( true === NumTextPr.Strikeout ) pGraphics.drawHorLine(0, (Y - NumTextPr.FontSize * g_dKoef_pt_to_mm * 0.27), X_start, X_start + NumberingItem.WidthNum, (NumTextPr.FontSize / 18) * g_dKoef_pt_to_mm); if ( true === NumTextPr.Underline ) pGraphics.drawHorLine( 0, (Y + this.Lines[CurLine].Metrics.TextDescent * 0.4), X_start, X_start + NumberingItem.WidthNum, (NumTextPr.FontSize / 18) * g_dKoef_pt_to_mm); X += NumberingItem.WidthVisible; // Восстановим настройки pGraphics.SetTextPr( CurTextPr ); if ( true === bVisitedHyperlink ) pGraphics.b_color1( 128, 0, 151, 255 ); else pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); } else if ( para_PresentationNumbering === this.Numbering.Type ) { if ( true != this.IsEmpty() ) { // Найдем настройки для первого текстового элемента var FirstTextPr = this.Internal_CalculateTextPr( this.Internal_GetStartPos() ); if ( Pr.ParaPr.Ind.FirstLine < 0 ) NumberingItem.Draw( X, Y, pGraphics, FirstTextPr ); else NumberingItem.Draw( this.X + Pr.ParaPr.Ind.Left, Y, pGraphics, FirstTextPr ); } X += NumberingItem.WidthVisible; } } switch( Item.Type ) { case para_PageNum: case para_Drawing: case para_Tab: case para_Text: { if ( para_Drawing != Item.Type || drawing_Anchor != Item.DrawingType ) { bFirstLineItem = false; if ( para_PageNum != Item.Type ) Item.Draw( X, Y - Item.YOffset, pGraphics ); else Item.Draw( X, Y - Item.YOffset, pGraphics, this.Get_StartPage_Absolute() + CurPage, Pr.ParaPr.Jc ); X += Item.WidthVisible; } // Внутри отрисовки инлайн-автофигур могут изменится цвета и шрифт, поэтому восстанавливаем настройки if ( para_Drawing === Item.Type && drawing_Inline === Item.DrawingType ) { pGraphics.SetTextPr( CurTextPr ); pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); pGraphics.p_color( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); } break; } case para_Space: { Item.Draw( X, Y - Item.YOffset, pGraphics ); X += Item.WidthVisible; break; } case para_TextPr: { CurTextPr = Item.CalcValue;//this.Internal_CalculateTextPr( Pos ); pGraphics.SetTextPr( CurTextPr ); if ( true === bVisitedHyperlink ) pGraphics.b_color1( 128, 0, 151, 255 ); else pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } case para_End: { // Выставляем настройки для символа параграфа var EndTextPr = Item.TextPr; pGraphics.SetTextPr( EndTextPr ); pGraphics.b_color1( EndTextPr.Color.r, EndTextPr.Color.g, EndTextPr.Color.b, 255); bEnd = true; var bEndCell = false; if ( null === this.Get_DocumentNext() && true === this.Parent.Is_TableCellContent() ) bEndCell = true; Item.Draw( X, Y - Item.YOffset, pGraphics, bEndCell ); X += Item.Width; break; } case para_NewLine: { Item.Draw( X, Y - Item.YOffset, pGraphics ); X += Item.WidthVisible; break; } case para_HyperlinkStart: { bVisitedHyperlink = Item.Get_Visited(); if ( true === bVisitedHyperlink ) pGraphics.b_color1( 128, 0, 151, 255 ); else pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } case para_HyperlinkEnd: { bVisitedHyperlink = false; pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } } Y = TempY; } } }, Internal_Draw_5 : function(CurPage, pGraphics, Pr) { var _Page = this.Pages[CurPage]; var StartPagePos = this.Lines[_Page.StartLine].StartPos; var HyperPos = this.Internal_FindBackward( StartPagePos, [para_HyperlinkStart, para_HyperlinkEnd] ); var bVisitedHyperlink = false; if ( true === HyperPos.Found && para_HyperlinkStart === HyperPos.Type ) bVisitedHyperlink = this.Content[HyperPos.LetterPos].Get_Visited(); var CurTextPr = _Page.TextPr; // Выставляем цвет обводки var CurColor; if ( true === bVisitedHyperlink ) CurColor = new CDocumentColor( 128, 0, 151 ); else CurColor = new CDocumentColor( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b ); var StartLine = _Page.StartLine; var EndLine = _Page.EndLine; var CheckSpelling = this.SpellChecker.Get_DrawingInfo(); var aStrikeout = new CParaDrawingRangeLines(); var aDStrikeout = new CParaDrawingRangeLines(); var aUnderline = new CParaDrawingRangeLines(); var aSpelling = new CParaDrawingRangeLines(); for ( var CurLine = StartLine; CurLine <= EndLine; CurLine++ ) { var _Line = this.Lines[CurLine]; var EndLinePos = _Line.EndPos; var LineY = _Page.Y + _Line.Y; var Y = LineY; var LineM = _Line.Metrics; var LineM_D_04 = LineM.TextDescent * 0.4; var RangesCount = _Line.Ranges.length; aStrikeout.Clear(); aDStrikeout.Clear(); aUnderline.Clear(); aSpelling.Clear(); for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var _Range = _Line.Ranges[CurRange]; // Сначала проанализируем данную строку: в массивы aStrikeout, aDStrikeout, aUnderline // aSpelling сохраним позиции начала и конца продолжительных одинаковых настроек зачеркивания, // двойного зачеркивания, подчеркивания и подчеркивания орфографии. var X = _Range.XVisible; var StartPos = _Range.StartPos; var EndPos = ( CurRange === RangesCount - 1 ? EndLinePos : _Line.Ranges[CurRange + 1].StartPos - 1 ); for ( var Pos = StartPos; Pos <= EndPos; Pos++ ) { var Item = this.Content[Pos]; // Нумерацию подчеркиваем и зачеркиваем в Internal_Draw_4 if ( Pos === this.Numbering.Pos ) X += this.Numbering.WidthVisible; switch( Item.Type ) { case para_End: case para_NewLine: { X += Item.WidthVisible; break; } case para_PageNum: case para_Drawing: case para_Tab: case para_Text: { if ( para_Drawing != Item.Type || drawing_Anchor != Item.DrawingType ) { if ( true === CurTextPr.DStrikeout ) aDStrikeout.Add( Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); else if ( true === CurTextPr.Strikeout ) aStrikeout.Add( Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); if ( true === CurTextPr.Underline ) aUnderline.Add( Y + this.Lines[CurLine].Metrics.TextDescent * 0.4, Y + this.Lines[CurLine].Metrics.TextDescent * 0.4, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); if ( true === CheckSpelling[Pos] ) aSpelling.Add( Y + LineM_D_04, Y + LineM_D_04, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, 0, 0, 0 ); X += Item.WidthVisible; } break; } case para_Space: { // Пробелы в конце строки (и строку состоящую из пробелов) не подчеркиваем, не зачеркиваем и не выделяем if ( Pos >= _Range.StartPos2 && Pos <= _Range.EndPos2 ) { if ( true === CurTextPr.DStrikeout ) aDStrikeout.Add( Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); else if ( true === CurTextPr.Strikeout ) aStrikeout.Add( Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); if ( true === CurTextPr.Underline ) aUnderline.Add( Y + LineM_D_04, Y + LineM_D_04, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); } X += Item.WidthVisible; break; } case para_TextPr: { CurTextPr = Item.CalcValue; // Выставляем цвет обводки if ( true === bVisitedHyperlink ) CurColor.Set( 128, 0, 151, 255 ); else CurColor.Set( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); switch( CurTextPr.VertAlign ) { case vertalign_SubScript: { Y = LineY - vertalign_Koef_Sub * CurTextPr.FontSize * g_dKoef_pt_to_mm; break; } case vertalign_SuperScript: { Y = LineY - vertalign_Koef_Super * CurTextPr.FontSize * g_dKoef_pt_to_mm; break; } default : { Y = LineY; break; } } break; } case para_HyperlinkStart: { bVisitedHyperlink = Item.Get_Visited(); // Выставляем цвет обводки if ( true === bVisitedHyperlink ) CurColor.Set( 128, 0, 151, 255 ); else CurColor.Set( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } case para_HyperlinkEnd: { bVisitedHyperlink = false; CurColor.Set( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } } } } // Рисуем зачеркивание var Element = aStrikeout.Get_Next(); while ( null != Element ) { pGraphics.p_color( Element.r, Element.g, Element.b, 255 ); pGraphics.drawHorLine(c_oAscLineDrawingRule.Top, Element.y0, Element.x0, Element.x1, Element.w ); Element = aStrikeout.Get_Next(); } // Рисуем двойное зачеркивание Element = aDStrikeout.Get_Next(); while ( null != Element ) { pGraphics.p_color( Element.r, Element.g, Element.b, 255 ); pGraphics.drawHorLine2(c_oAscLineDrawingRule.Top, Element.y0, Element.x0, Element.x1, Element.w ); Element = aDStrikeout.Get_Next(); } // Рисуем подчеркивание aUnderline.Correct_w_ForUnderline(); Element = aUnderline.Get_Next(); while ( null != Element ) { pGraphics.p_color( Element.r, Element.g, Element.b, 255 ); pGraphics.drawHorLine(0, Element.y0, Element.x0, Element.x1, Element.w ); Element = aUnderline.Get_Next(); } // Рисуем подчеркивание орфографии pGraphics.p_color( 255, 0, 0, 255 ); var SpellingW = editor.WordControl.m_oDrawingDocument.GetMMPerDot(1); Element = aSpelling.Get_Next(); while ( null != Element ) { pGraphics.DrawSpellingLine(Element.y0, Element.x0, Element.x1, SpellingW); Element = aSpelling.Get_Next(); } } }, Internal_Draw_6 : function(CurPage, pGraphics, Pr) { var bEmpty = this.IsEmpty(); var X_left = Math.min( this.Pages[CurPage].X + Pr.ParaPr.Ind.Left, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var X_right = this.Pages[CurPage].XLimit - Pr.ParaPr.Ind.Right; if ( true === this.Is_LineDropCap() ) X_right = X_left + this.Get_LineDropCapWidth(); if ( Pr.ParaPr.Brd.Left.Value === border_Single ) X_left -= 1 + Pr.ParaPr.Brd.Left.Space; else X_left -= 1; if ( Pr.ParaPr.Brd.Right.Value === border_Single ) X_right += 1 + Pr.ParaPr.Brd.Right.Space; else X_right += 1; var LeftMW = -( border_Single === Pr.ParaPr.Brd.Left.Value ? Pr.ParaPr.Brd.Left.Size : 0 ); var RightMW = ( border_Single === Pr.ParaPr.Brd.Right.Value ? Pr.ParaPr.Brd.Right.Size : 0 ); // Рисуем линию до параграфа if ( true === Pr.ParaPr.Brd.First && border_Single === Pr.ParaPr.Brd.Top.Value && ( ( 0 === CurPage && ( false === this.Is_StartFromNewPage() || null === this.Get_DocumentPrev() ) ) || ( 1 === CurPage && true === this.Is_StartFromNewPage() ) ) ) { var Y_top = this.Pages[CurPage].Y; if ( 0 === CurPage ) Y_top += Pr.ParaPr.Spacing.Before; pGraphics.p_color( Pr.ParaPr.Brd.Top.Color.r, Pr.ParaPr.Brd.Top.Color.g, Pr.ParaPr.Brd.Top.Color.b, 255 ); // Учтем разрывы из-за обтекания var StartLine = this.Pages[CurPage].StartLine; var RangesCount = this.Lines[StartLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var X0 = ( 0 === CurRange ? X_left : this.Lines[StartLine].Ranges[CurRange].X ); var X1 = ( RangesCount - 1 === CurRange ? X_right : this.Lines[StartLine].Ranges[CurRange].XEnd ); if ( this.Lines[StartLine].Ranges[CurRange].W > 0.001 || ( true === bEmpty && 1 === RangesCount ) ) pGraphics.drawHorLineExt( c_oAscLineDrawingRule.Top, Y_top, X0, X1, Pr.ParaPr.Brd.Top.Size, LeftMW, RightMW ); } } else if ( false === Pr.ParaPr.Brd.First ) { var bDraw = false; var Size = 0; var Y = 0; if ( 1 === CurPage && true === this.Is_StartFromNewPage() && border_Single === Pr.ParaPr.Brd.Top.Value ) { pGraphics.p_color( Pr.ParaPr.Brd.Top.Color.r, Pr.ParaPr.Brd.Top.Color.g, Pr.ParaPr.Brd.Top.Color.b, 255 ); Size = Pr.ParaPr.Brd.Top.Size; Y = this.Pages[CurPage].Y + this.Lines[this.Pages[CurPage].FirstLine].Top; bDraw = true; } else if ( 0 === CurPage && false === this.Is_StartFromNewPage() && border_Single === Pr.ParaPr.Brd.Between.Value ) { pGraphics.p_color( Pr.ParaPr.Brd.Between.Color.r, Pr.ParaPr.Brd.Between.Color.g, Pr.ParaPr.Brd.Between.Color.b, 255 ); Size = Pr.ParaPr.Brd.Between.Size; Y = this.Pages[CurPage].Y; bDraw = true; } if ( true === bDraw ) { // Учтем разрывы из-за обтекания var StartLine = this.Pages[CurPage].StartLine; var RangesCount = this.Lines[StartLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var X0 = ( 0 === CurRange ? X_left : this.Lines[StartLine].Ranges[CurRange].X ); var X1 = ( RangesCount - 1 === CurRange ? X_right : this.Lines[StartLine].Ranges[CurRange].XEnd ); if ( this.Lines[StartLine].Ranges[CurRange].W > 0.001 || ( true === bEmpty && 1 === RangesCount ) ) pGraphics.drawHorLineExt( c_oAscLineDrawingRule.Top, Y, X0, X1, Size, LeftMW, RightMW ); } } } var CurLine = this.Pages[CurPage].EndLine; var bEnd = ( this.Content.length - 2 <= this.Lines[CurLine].EndPos ? true : false ); // Рисуем линию после параграфа if ( true === bEnd && true === Pr.ParaPr.Brd.Last && border_Single === Pr.ParaPr.Brd.Bottom.Value ) { var TempY = this.Pages[CurPage].Y; var NextEl = this.Get_DocumentNext(); var DrawLineRule = c_oAscLineDrawingRule.Bottom; if ( null != NextEl && type_Paragraph === NextEl.GetType() && true === NextEl.Is_StartFromNewPage() ) { TempY = this.Pages[CurPage].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; DrawLineRule = c_oAscLineDrawingRule.Top; } else { TempY = this.Pages[CurPage].Y + this.Lines[CurLine].Bottom - Pr.ParaPr.Spacing.After; DrawLineRule = c_oAscLineDrawingRule.Bottom; } pGraphics.p_color( Pr.ParaPr.Brd.Bottom.Color.r, Pr.ParaPr.Brd.Bottom.Color.g, Pr.ParaPr.Brd.Bottom.Color.b, 255 ); // Учтем разрывы из-за обтекания var EndLine = this.Pages[CurPage].EndLine; var RangesCount = this.Lines[EndLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var X0 = ( 0 === CurRange ? X_left : this.Lines[EndLine].Ranges[CurRange].X ); var X1 = ( RangesCount - 1 === CurRange ? X_right : this.Lines[EndLine].Ranges[CurRange].XEnd ); if ( this.Lines[EndLine].Ranges[CurRange].W > 0.001 || ( true === bEmpty && 1 === RangesCount ) ) pGraphics.drawHorLineExt( DrawLineRule, TempY, X0, X1, Pr.ParaPr.Brd.Bottom.Size, LeftMW, RightMW ); } } else if ( true === bEnd && false === Pr.ParaPr.Brd.Last && border_Single === Pr.ParaPr.Brd.Bottom.Value ) { var NextEl = this.Get_DocumentNext(); if ( null != NextEl && type_Paragraph === NextEl.GetType() && true === NextEl.Is_StartFromNewPage() ) { pGraphics.p_color( Pr.ParaPr.Brd.Bottom.Color.r, Pr.ParaPr.Brd.Bottom.Color.g, Pr.ParaPr.Brd.Bottom.Color.b, 255 ); // Учтем разрывы из-за обтекания var EndLine = this.Pages[CurPage].EndLine; var RangesCount = this.Lines[EndLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var X0 = ( 0 === CurRange ? X_left : this.Lines[EndLine].Ranges[CurRange].X ); var X1 = ( RangesCount - 1 === CurRange ? X_right : this.Lines[EndLine].Ranges[CurRange].XEnd ); if ( this.Lines[EndLine].Ranges[CurRange].W > 0.001 || ( true === bEmpty && 1 === RangesCount ) ) pGraphics.drawHorLineExt( c_oAscLineDrawingRule.Top, this.Pages[CurPage].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap, X0, X1, Pr.ParaPr.Brd.Bottom.Size, LeftMW, RightMW ); } } } }, ReDraw : function() { this.Parent.OnContentReDraw( this.Get_StartPage_Absolute(), this.Get_StartPage_Absolute() + this.Pages.length - 1 ); }, Shift : function(PageIndex, Dx, Dy) { if ( 0 === PageIndex ) { this.X += Dx; this.Y += Dy; this.XLimit += Dx; this.YLimit += Dy; } var Page_abs = PageIndex + this.Get_StartPage_Absolute(); this.Pages[PageIndex].Shift( Dx, Dy ); var StartLine = this.Pages[PageIndex].FirstLine; var EndLine = ( PageIndex >= this.Pages.length - 1 ? this.Lines.length - 1 : this.Pages[PageIndex + 1].FirstLine - 1 ); for ( var CurLine = StartLine; CurLine <= EndLine; CurLine++ ) this.Lines[CurLine].Shift( Dx, Dy ); // Пробегаемся по всем картинкам на данной странице и обновляем координаты var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type && Item.PageNum === Page_abs ) { Item.Shift( Dx, Dy ); } } }, Internal_Remove_CollaborativeMarks : function() { for ( var Pos = 0; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; if ( para_CollaborativeChangesEnd === Item.Type || para_CollaborativeChangesStart === Item.Type ) { this.Internal_Content_Remove(Pos); Pos--; } } }, // Удаляем элементы параграфа // nCount - количество удаляемых элементов, > 0 удаляем элементы после курсора // < 0 удаляем элементы до курсора // bOnlyText - true: удаляем только текст и пробелы, false - Удаляем любые элементы Remove : function(nCount, bOnlyText) { this.Internal_Remove_CollaborativeMarks(); this.RecalcInfo.Set_Type_0(pararecalc_0_All); // Сначала проверим имеется ли у нас селект if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( EndPos >= this.Content.length - 1 ) { for ( var Index = StartPos; Index < this.Content.length - 2; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type ) { var ObjId = Item.Get_Id(); this.Parent.DrawingObjects.Remove_ById( ObjId ); } } var Hyper_start = null; if ( StartPos < EndPos ) Hyper_start = this.Check_Hyperlink2( StartPos ); // Удаляем внутреннюю часть селекта (без знака параграфа) this.Internal_Content_Remove2( StartPos, this.Content.length - 2 - StartPos ); // После удаления позиции могли измениться StartPos = this.Selection.StartPos; EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Set_ContentPos( StartPos, true, -1 ); if ( null != Hyper_start ) { this.Internal_Content_Add( StartPos, new ParaTextPr() ); this.Internal_Content_Add( StartPos, new ParaHyperlinkEnd() ); } // Данный параграф надо объединить со следующим return false; } else { var Hyper_start = this.Check_Hyperlink2( StartPos ); var Hyper_end = this.Check_Hyperlink2( EndPos ); // Если встречалось какое-либо изменение настроек, сохраним его последние изменение var LastTextPr = null; for ( var Index = StartPos; Index < EndPos; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type ) { var ObjId = Item.Get_Id(); this.Parent.DrawingObjects.Remove_ById( ObjId ); } else if ( para_TextPr === Item.Type ) LastTextPr = Item; } this.Internal_Content_Remove2( StartPos, EndPos - StartPos ); // После удаления позиции могли измениться StartPos = this.Selection.StartPos; EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( null != LastTextPr ) this.Internal_Content_Add( StartPos, new ParaTextPr( LastTextPr.Value ) ); this.Set_ContentPos( StartPos, true, -1 ); if ( Hyper_start != Hyper_end ) { if ( null != Hyper_end ) { this.Internal_Content_Add( StartPos, Hyper_end ); this.Set_ContentPos( this.CurPos.ContentPos + 1 ); } if ( null != Hyper_start ) { this.Internal_Content_Add( StartPos, new ParaHyperlinkEnd() ); this.Set_ContentPos( this.CurPos.ContentPos + 1 ); } } else { // TODO: Пока селект реализован так, что тут начало гиперссылки не попадает в выделение, а конец попадает. // Поэтому добавляем конец гиперссылки, и потом проверяем пустая ли она. this.Internal_Content_Add( StartPos, new ParaHyperlinkEnd() ); this.Internal_Check_EmptyHyperlink( StartPos ); } } return; } if ( 0 == nCount ) return; var absCount = ( nCount < 0 ? -nCount : nCount ); for ( var Index = 0; Index < absCount; Index++ ) { var OldPos = this.CurPos.ContentPos; if ( nCount < 0 ) { if ( false === this.Internal_RemoveBackward(bOnlyText) ) return false; } else { if ( false === this.Internal_RemoveForward(bOnlyText) ) return false; } this.Internal_Check_EmptyHyperlink( OldPos ); } return true; }, Internal_RemoveBackward : function(bOnlyText) { var Line = this.Content; var CurPos = this.CurPos.ContentPos; if ( !bOnlyText ) { if ( CurPos == 0 ) return false; else { // Просто удаляем элемент предстоящий текущей позиции и уменьшаем текущую позицию this.Internal_Content_Remove( CurPos - 1 ); } } else { var LetterPos = CurPos - 1; var oPos = this.Internal_FindBackward( LetterPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( oPos.Found ) { if ( para_Drawing === oPos.Type ) { this.Parent.Select_DrawingObject( this.Content[oPos.LetterPos].Get_Id() ); } else { // Удаляем элемент в найденной позиции и уменьшаем текущую позицию this.Internal_Content_Remove( oPos.LetterPos ); this.Set_ContentPos( oPos.LetterPos, true, -1 ); } } else { // Мы стоим в начале параграфа и пытаемся удалить элемент влево. Действуем следующим образом: // 1. Если у нас параграф с нумерацией, тогда удаляем нумерацию, но при этом сохраняем // значения отступов так как это делается в Word. (аналогично работаем с нумерацией в презентациях) // 2. Если у нас отступ первой строки ненулевой, тогда: // 2.1 Если он положительный делаем его нулевым. // 2.2 Если он отрицательный сдвигаем левый отступ на значение отступа первой строки, // а сам отступ первой строки делаем нулевым. // 3. Если у нас ненулевой левый отступ, делаем его нулевым // 4. Если ничего из предыдущего не случается, тогда говорим родительскому классу, что удаление // не было выполнено. var Pr = this.Get_CompiledPr2(false).ParaPr; if ( undefined != this.Numbering_Get() ) { this.Numbering_Remove(); this.Set_Ind( { FirstLine : 0, Left : Math.max( Pr.Ind.Left, Pr.Ind.Left + Pr.Ind.FirstLine ) }, false ); } else if ( numbering_presentationnumfrmt_None != this.PresentationPr.Bullet.Get_Type() ) { this.Remove_PresentationNumbering(); } else if ( align_Right === Pr.Jc ) { this.Set_Align( align_Center ); } else if ( align_Center === Pr.Jc ) { this.Set_Align( align_Left ); } else if ( Math.abs(Pr.Ind.FirstLine) > 0.001 ) { if ( Pr.Ind.FirstLine > 0 ) this.Set_Ind( { FirstLine : 0 }, false ); else this.Set_Ind( { Left : Pr.Ind.Left + Pr.Ind.FirstLine, FirstLine : 0 }, false ); } else if ( Math.abs(Pr.Ind.Left) > 0.001 ) { this.Set_Ind( { Left : 0 }, false ); } else return false; } } return true; }, Internal_RemoveForward : function(bOnlyText) { var Line = this.Content; var CurPos = this.CurPos.ContentPos; if ( !bOnlyText ) { if ( CurPos == Line.length - 1 ) { return false; } else { // Просто удаляем элемент после текущей позиции this.Internal_Content_Remove( CurPos + 1 ); } } else { var LetterPos = CurPos; var oPos = this.Internal_FindForward( LetterPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( oPos.Found ) { if ( para_Drawing === oPos.Type ) { this.Parent.Select_DrawingObject( this.Content[oPos.LetterPos].Get_Id() ); } else { // Удаляем элемент в найденной позиции и меняем текущую позицию this.Internal_Content_Remove( oPos.LetterPos ); this.Set_ContentPos( oPos.LetterPos, true, -1 ); } } else { return false; } } return true; }, // Ищем первый элемент, при промотке вперед Internal_FindForward : function(CurPos, arrId) { var LetterPos = CurPos; var bFound = false; var Type = para_Unknown; if ( CurPos < 0 || CurPos >= this.Content.length ) return { Found : false }; while ( !bFound ) { Type = this.Content[LetterPos].Type; for ( var Id = 0; Id < arrId.length; Id++ ) { if ( arrId[Id] == Type ) { bFound = true; break; } } if ( bFound ) break; LetterPos++; if ( LetterPos > this.Content.length - 1 ) break; } return { LetterPos : LetterPos, Found : bFound, Type : Type }; }, // Ищем первый элемент, при промотке назад Internal_FindBackward : function(CurPos, arrId) { var LetterPos = CurPos; var bFound = false; var Type = para_Unknown; if ( CurPos < 0 || CurPos >= this.Content.length ) return { Found : false }; while ( !bFound ) { Type = this.Content[LetterPos].Type; for ( var Id = 0; Id < arrId.length; Id++ ) { if ( arrId[Id] == Type ) { bFound = true; break; } } if ( bFound ) break; LetterPos--; if ( LetterPos < 0 ) break; } return { LetterPos : LetterPos, Found : bFound, Type : Type }; }, Internal_CalculateTextPr : function (LetterPos, StartPr) { var Pr; if ( "undefined" != typeof(StartPr) ) { Pr = this.Get_CompiledPr(); StartPr.ParaPr = Pr.ParaPr; StartPr.TextPr = Pr.TextPr; } else { Pr = this.Get_CompiledPr2(false); } // Выствляем начальные настройки текста у данного параграфа var TextPr = Pr.TextPr.Copy(); // Ищем ближайший TextPr if ( LetterPos < 0 ) return TextPr; // Ищем предыдущие записи с изменением текстовых свойств var Pos = this.Internal_FindBackward( LetterPos, [para_TextPr] ); if ( true === Pos.Found ) { var CurTextPr = this.Content[Pos.LetterPos].Value; // Копируем настройки из символьного стиля if ( undefined != CurTextPr.RStyle ) { var Styles = this.Parent.Get_Styles(); var StyleTextPr = Styles.Get_Pr( CurTextPr.RStyle, styletype_Character).TextPr; TextPr.Merge( StyleTextPr ); } // Копируем прямые настройки TextPr.Merge( CurTextPr ); } TextPr.FontFamily.Name = TextPr.RFonts.Ascii.Name; TextPr.FontFamily.Index = TextPr.RFonts.Ascii.Index; return TextPr; }, Internal_GetLang : function(LetterPos) { var Lang = this.Get_CompiledPr2(false).TextPr.Lang.Copy(); // Ищем ближайший TextPr if ( LetterPos < 0 ) return Lang; // Ищем предыдущие записи с изменением текстовых свойств var Pos = this.Internal_FindBackward( LetterPos, [para_TextPr] ); if ( true === Pos.Found ) { var CurTextPr = this.Content[Pos.LetterPos].Value; // Копируем настройки из символьного стиля if ( undefined != CurTextPr.RStyle ) { var Styles = this.Parent.Get_Styles(); var StyleTextPr = Styles.Get_Pr( CurTextPr.RStyle, styletype_Character).TextPr; Lang.Merge( StyleTextPr.Lang ); } // Копируем прямые настройки Lang.Merge( CurTextPr.Lang ); } return Lang; }, Internal_GetTextPr : function(LetterPos) { var TextPr = new CTextPr(); // Ищем ближайший TextPr if ( LetterPos < 0 ) return TextPr; // Ищем предыдущие записи с изменением текстовых свойств var Pos = this.Internal_FindBackward( LetterPos, [para_TextPr] ); if ( true === Pos.Found ) { var CurTextPr = this.Content[Pos.LetterPos].Value; TextPr.Merge( CurTextPr ); } // Если ничего не нашли, то TextPr будет пустым, что тоже нормально return TextPr; }, // Добавляем новый элемент к содержимому параграфа (на текущую позицию) Add : function(Item) { var CurPos = this.CurPos.ContentPos; if ( "undefined" != typeof(Item.Parent) ) Item.Parent = this; switch (Item.Type) { case para_Text: { this.Internal_Content_Add( CurPos, Item ); break; } case para_Space: { this.Internal_Content_Add( CurPos, Item ); break; } case para_TextPr: { this.Internal_AddTextPr( Item.Value ); break; } case para_HyperlinkStart: { this.Internal_AddHyperlink( Item ); break; } case para_PageNum: case para_Tab: case para_Drawing: default: { this.Internal_Content_Add( CurPos, Item ); break; } } if ( para_TextPr != Item.Type ) this.DeleteCollaborativeMarks = true; this.RecalcInfo.Set_Type_0(pararecalc_0_All); }, // Данная функция вызывается, когда уже точно известно, что у нас либо выделение начинается с начала параграфа, либо мы стоим курсором в начале параграфа Add_Tab : function(bShift) { var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { if ( true != this.Selection.Use ) { var NumId = NumPr.NumId; var Lvl = NumPr.Lvl; var NumInfo = this.Parent.Internal_GetNumInfo( this.Id, NumPr ); if ( 0 === Lvl && NumInfo[Lvl] <= 1 ) { var Numbering = this.Parent.Get_Numbering(); var AbstractNum = Numbering.Get_AbstractNum(NumId); var NumLvl = AbstractNum.Lvl[Lvl]; var NumParaPr = NumLvl.ParaPr; var ParaPr = this.Get_CompiledPr2(false).ParaPr; if ( undefined != NumParaPr.Ind && undefined != NumParaPr.Ind.Left ) { var NewX = ParaPr.Ind.Left; if ( true != bShift ) NewX += Default_Tab_Stop; else { NewX -= Default_Tab_Stop; if ( NewX < 0 ) NewX = 0; if ( ParaPr.Ind.FirstLine < 0 && NewX + ParaPr.Ind.FirstLine < 0 ) NewX = -ParaPr.Ind.FirstLine; } AbstractNum.Change_LeftInd( NewX ); History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : undefined } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : undefined } ); // При добавлении списка в параграф, удаляем все собственные сдвиги this.Pr.Ind.FirstLine = undefined; this.Pr.Ind.Left = undefined; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } } else this.Numbering_IndDec_Level( !bShift ); } else this.Numbering_IndDec_Level( !bShift ); } else if ( true === this.Is_SelectionUse() ) { this.IncDec_Indent( !bShift ); } else { var ParaPr = this.Get_CompiledPr2(false).ParaPr; if ( true != bShift ) { if ( ParaPr.Ind.FirstLine < 0 ) { this.Set_Ind( { FirstLine : 0 }, false ); this.CompiledPr.NeedRecalc = true; } else if ( ParaPr.Ind.FirstLine < 12.5 ) { this.Set_Ind( { FirstLine : 12.5 }, false ); this.CompiledPr.NeedRecalc = true; } else if ( X_Right_Field - X_Left_Margin > ParaPr.Ind.Left + 25 ) { this.Set_Ind( { Left : ParaPr.Ind.Left + 12.5 }, false ); this.CompiledPr.NeedRecalc = true; } } else { if ( ParaPr.Ind.FirstLine > 0 ) { if ( ParaPr.Ind.FirstLine > 12.5 ) this.Set_Ind( { FirstLine : ParaPr.Ind.FirstLine - 12.5 }, false ); else this.Set_Ind( { FirstLine : 0 }, false ); this.CompiledPr.NeedRecalc = true; } else { var Left = ParaPr.Ind.Left + ParaPr.Ind.FirstLine; if ( Left < 0 ) { this.Set_Ind( { Left : -ParaPr.Ind.FirstLine }, false ); this.CompiledPr.NeedRecalc = true; } else { if ( Left > 12.5 ) this.Set_Ind( { Left : ParaPr.Ind.Left - 12.5 }, false ); else this.Set_Ind( { Left : -ParaPr.Ind.FirstLine }, false ); this.CompiledPr.NeedRecalc = true; } } } } }, // Расширяем параграф до позиции X Extend_ToPos : function(_X) { var Page = this.Pages[this.Pages.length - 1]; var X0 = Page.X; var X1 = Page.XLimit - X0; var X = _X - X0; if ( true === this.IsEmpty() ) { if ( Math.abs(X - X1 / 2) < 12.5 ) return this.Set_Align( align_Center ); else if ( X > X1 - 12.5 ) return this.Set_Align( align_Right ); else if ( X < 12.5 ) return this.Set_Ind( { FirstLine : 12.5 }, false ); } var Tabs = this.Get_CompiledPr2(false).ParaPr.Tabs.Copy(); var CurPos = this.Internal_GetEndPos(); if ( Math.abs(X - X1 / 2) < 12.5 ) Tabs.Add( new CParaTab( tab_Center, X1 / 2 ) ); else if ( X > X1 - 12.5 ) Tabs.Add( new CParaTab( tab_Right, X1 - 0.001 ) ); else Tabs.Add( new CParaTab( tab_Left, X ) ); this.Set_Tabs( Tabs ); this.Internal_Content_Add( CurPos, new ParaTab() ); }, Internal_IncDecFontSize : function(bIncrease, Value) { // Закон изменения размеров : // 1. Если значение меньше 8, тогда мы увеличиваем/уменьшаем по 1 (от 1 до 8) // 2. Если значение больше 72, тогда мы увеличиваем/уменьшаем по 10 (от 80 до бесконечности // 3. Если значение в отрезке [8,72], тогда мы переходим по следующим числам 8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72 var Sizes = [8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72]; var NewValue = Value; if ( true === bIncrease ) { if ( Value < Sizes[0] ) { if ( Value >= Sizes[0] - 1 ) NewValue = Sizes[0]; else NewValue = Math.floor(Value + 1); } else if ( Value >= Sizes[Sizes.length - 1] ) { NewValue = Math.min( 300, Math.floor( Value / 10 + 1 ) * 10 ); } else { for ( var Index = 0; Index < Sizes.length; Index++ ) { if ( Value < Sizes[Index] ) { NewValue = Sizes[Index]; break; } } } } else { if ( Value <= Sizes[0] ) { NewValue = Math.max( Math.floor( Value - 1 ), 1 ); } else if ( Value > Sizes[Sizes.length - 1] ) { if ( Value <= Math.floor( Sizes[Sizes.length - 1] / 10 + 1 ) * 10 ) NewValue = Sizes[Sizes.length - 1]; else NewValue = Math.floor( Math.ceil(Value / 10) - 1 ) * 10; } else { for ( var Index = Sizes.length - 1; Index >= 0; Index-- ) { if ( Value > Sizes[Index] ) { NewValue = Sizes[Index]; break; } } } } return NewValue; }, IncDec_FontSize : function(bIncrease) { this.RecalcInfo.Set_Type_0(pararecalc_0_All); var StartTextPr = this.Get_CompiledPr().TextPr; if ( true === this.ApplyToAll ) { var StartFontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( 0, new ParaTextPr( { FontSize : StartFontSize } ) ); for ( var Index = 1; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { if ( undefined != Item.Value.FontSize ) Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, Item.Value.FontSize ) ); else Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); } } // Выставляем настройки для символа параграфа if ( undefined != this.TextPr.Value.FontSize ) this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, this.TextPr.Value.FontSize ) ); else this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); return true; } // найдем текущую позицию var Line = this.Content; var CurPos = this.CurPos.ContentPos; if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } // Если селект продолжается до конца параграфа, не ставим отметку в конце var LastPos = this.Internal_GetEndPos(); var bEnd = false; if ( EndPos > LastPos ) { EndPos = LastPos; bEnd = true; } // Рассчитываем настройки, которые используются после селекта var TextPr_end = this.Internal_GetTextPr( EndPos ); var TextPr_start = this.Internal_GetTextPr( StartPos ); if ( undefined != TextPr_start.FontSize ) TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, TextPr_start.FontSize ); else TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( StartPos, new ParaTextPr( TextPr_start ) ); if ( false === bEnd ) this.Internal_Content_Add( EndPos + 1, new ParaTextPr( TextPr_end ) ); else { // Выставляем настройки для символа параграфа if ( undefined != this.TextPr.Value.FontSize ) this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, this.TextPr.Value.FontSize ) ); else this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); } for ( var Pos = StartPos + 1; Pos < EndPos; Pos++ ) { Item = this.Content[Pos]; if ( para_TextPr === Item.Type ) { if ( undefined != typeof(Item.Value.FontSize) ) Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, Item.Value.FontSize ) ); else Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); } } return true; } // 1. Если мы в конце параграфа, тогда добавляем запись о шрифте (применимо к знаку конца параграфа) // 2. Если справа или слева стоит пробел (начало параграфа или перенос строки(командный)), тогда ставим метку со шрифтом и фокусим канву. // 3. Если мы посередине слова, тогда меняем шрифт для данного слова var oEnd = this.Internal_FindForward ( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_End, para_NewLine] ); var oStart = this.Internal_FindBackward( CurPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); var CurType = this.Content[CurPos].Type; if ( !oEnd.Found ) return false; if ( para_End == oEnd.Type ) { // Вставляем запись о новых настройках перед концом параграфа, а текущую позицию выставляем на конец параграфа var Pos = oEnd.LetterPos; var TextPr_start = this.Internal_GetTextPr( Pos ); if ( undefined != TextPr_start.FontSize ) TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, TextPr_start.FontSize ); else TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_start ) ); this.Set_ContentPos( Pos + 1, true, -1 ); // Выставляем настройки для символа параграфа if ( undefined != typeof(this.TextPr.Value.FontSize) ) this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, this.TextPr.Value.FontSize ) ); else this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); return true; } else if ( para_PageNum === CurType || para_Drawing === CurType || para_Tab == CurType || para_Space == CurType || para_NewLine == CurType || !oStart.Found || para_NewLine == oEnd.Type || para_Space == oEnd.Type || para_NewLine == oStart.Type || para_Space == oStart.Type || para_Tab == oEnd.Type || para_Tab == oStart.Type || para_Drawing == oEnd.Type || para_Drawing == oStart.Type || para_PageNum == oEnd.Type || para_PageNum == oStart.Type ) { var TextPr_old = this.Internal_GetTextPr( CurPos ); var TextPr_new = TextPr_old.Copy(); if ( undefined != TextPr_new.FontSize ) TextPr_new.FontSize = this.Internal_IncDecFontSize( bIncrease, TextPr_new.FontSize ); else TextPr_new.FontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_old ) ); this.Internal_Content_Add( CurPos, new ParaEmpty(true) ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_new ) ); this.Set_ContentPos( CurPos + 1, true, -1 ); this.RecalculateCurPos(); return false; } else { // Мы находимся посередине слова. В начале слова ставим запись о новом размере шрифта, // а в конце слова старый размер шрифта. Кроме этого, надо заменить все записи о размерах шрифте внутри слова. // Найдем начало слова var oWordStart = this.Internal_FindBackward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_NewLine] ); if ( !oWordStart.Found ) oWordStart = this.Internal_FindForward( 0, [para_Text] ); else oWordStart.LetterPos++; var oWordEnd = this.Internal_FindForward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_End, para_NewLine] ); if ( !oWordStart.Found || !oWordEnd.Found ) return; // Рассчитываем настройки, которые используются после слова var TextPr_end = this.Internal_GetTextPr( oWordEnd.LetterPos ); var TextPr_start = this.Internal_GetTextPr( oWordStart.LetterPos ); if ( undefined != TextPr_start.FontSize ) TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, TextPr_start.FontSize ); else TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( oWordStart.LetterPos, new ParaTextPr( TextPr_start ) ); this.Internal_Content_Add( oWordEnd.LetterPos + 1 /* из-за предыдущего Internal_Content_Add */, new ParaTextPr( TextPr_end ) ); this.Set_ContentPos( CurPos + 1, true, -1 ); // Если внутри слова были изменения размера шрифта, тогда заменяем их. for ( var Pos = oWordStart.LetterPos + 1; Pos < oWordEnd.LetterPos; Pos++ ) { Item = this.Content[Pos]; if ( para_TextPr === Item.Type ) { if ( undefined != Item.Value.FontSize ) Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, Item.Value.FontSize ) ); else Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); } } return true; } }, IncDec_Indent : function(bIncrease) { var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { this.Numbering_IndDec_Level( bIncrease ); } else { var ParaPr = this.Get_CompiledPr2(false).ParaPr; var LeftMargin = ParaPr.Ind.Left; if ( UnknownValue === LeftMargin ) LeftMargin = 0; else if ( LeftMargin < 0 ) { this.Set_Ind( { Left : 0 }, false ); return; } var LeftMargin_new = 0; if ( true === bIncrease ) { if ( LeftMargin >= 0 ) { LeftMargin = 12.5 * parseInt(10 * LeftMargin / 125); LeftMargin_new = ( (LeftMargin - (10 * LeftMargin) % 125 / 10) / 12.5 + 1) * 12.5; } if ( LeftMargin_new < 0 ) LeftMargin_new = 12.5; } else { var TempValue = (125 - (10 * LeftMargin) % 125); TempValue = ( 125 === TempValue ? 0 : TempValue ); LeftMargin_new = Math.max( ( (LeftMargin + TempValue / 10) / 12.5 - 1 ) * 12.5, 0 ); } this.Set_Ind( { Left : LeftMargin_new }, false ); } var NewPresLvl = ( true === bIncrease ? Math.min( 8, this.PresentationPr.Level + 1 ) : Math.max( 0, this.PresentationPr.Level - 1 ) ); this.Set_PresentationLevel( NewPresLvl ); }, Cursor_GetPos : function() { return { X : this.CurPos.RealX, Y : this.CurPos.RealY }; }, Cursor_MoveLeft : function(Count, AddToSelect, Word) { if ( this.CurPos.ContentPos < 0 ) return false; if ( 0 == Count || !Count ) return; var absCount = ( Count < 0 ? -Count : Count ); for ( var Index = 0; Index < absCount; Index++ ) { if ( false === this.Internal_MoveCursorBackward(AddToSelect, Word) ) return false; } this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; return true; }, Cursor_MoveRight : function(Count, AddToSelect, Word) { if ( this.CurPos.ContentPos < 0 ) return false; if ( 0 == Count || !Count ) return; var absCount = ( Count < 0 ? -Count : Count ); for ( var Index = 0; Index < absCount; Index++ ) { if ( false === this.Internal_MoveCursorForward(AddToSelect, Word) ) return false; } this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; return true; }, Cursor_MoveUp : function(Count, AddToSelect) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( this.CurPos.ContentPos < 0 ) return false; if ( !Count || 0 == Count ) return; var absCount = ( Count < 0 ? -Count : Count ); // Пока сделаем для Count = 1 var CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; var Result = true; if ( true === this.Selection.Use ) { if ( true === AddToSelect ) { this.Set_ContentPos( this.Selection.EndPos, true, -1 ); // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.RecalculateCurPos(); this.CurPos.RealY = this.CurPos.Y; if ( 0 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; this.Selection.EndPos = this.Internal_GetStartPos(); } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine - 1, true, true ); this.CurPos.RealY = this.CurPos.Y; this.Selection.EndPos = this.CurPos.ContentPos; } if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return Result; } } else { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Set_ContentPos( StartPos, true, -1 ); this.Selection_Remove(); // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; if ( 0 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine - 1, true, true ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } } } else if ( true === AddToSelect ) { this.Selection.Use = true; this.Selection.StartPos = this.CurPos.ContentPos; // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.RecalculateCurPos(); this.CurPos.RealY = this.CurPos.Y; if ( 0 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; this.Selection.EndPos = this.Internal_GetStartPos(); } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine - 1, true, true ); this.CurPos.RealY = this.CurPos.Y; this.Selection.EndPos = this.CurPos.ContentPos; } if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return Result; } } else { if ( 0 == CurLine ) { // Возвращяем значение false, это означает, что надо перейти в // предыдущий элемент контента документа. return false; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine - 1, true, true ); this.CurPos.RealY = this.CurPos.Y; } } return Result; }, Cursor_MoveDown : function(Count, AddToSelect) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( this.CurPos.ContentPos < 0 ) return false; if ( !Count || 0 == Count ) return; var absCount = ( Count < 0 ? -Count : Count ); // Пока сделаем для Count = 1 var CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; var Result = true; if ( true === this.Selection.Use ) { if ( true === AddToSelect ) { this.Set_ContentPos( this.Selection.EndPos, true, -1 ); // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.RecalculateCurPos(); this.CurPos.RealY = this.CurPos.Y; if ( this.Lines.length - 1 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; this.Selection.EndPos = this.Content.length - 1; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine + 1, true, true ); this.CurPos.RealY = this.CurPos.Y; this.Selection.EndPos = this.CurPos.ContentPos; } if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return Result; } } else { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Set_ContentPos( Math.max( CursorPos_min, Math.min( EndPos, CursorPos_max ) ), true, -1 ); this.Selection_Remove(); // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; if ( this.Lines.length - 1 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine + 1, true, true ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } } } else if ( AddToSelect ) { this.Selection.Use = true; this.Selection.StartPos = this.CurPos.ContentPos; // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.RecalculateCurPos(); this.CurPos.RealY = this.CurPos.Y; if ( this.Lines.length - 1 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; this.Selection.EndPos = this.Content.length - 1; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine + 1, true, true ); this.CurPos.RealY = this.CurPos.Y; this.Selection.EndPos = this.CurPos.ContentPos; } if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return Result; } } else { if ( this.Lines.length - 1 == CurLine ) { // Возвращяем значение false, это означает, что надо перейти в // предыдущий элемент контента документа. return false; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine + 1, true, true ); this.CurPos.RealY = this.CurPos.Y; } } return Result; }, Cursor_MoveEndOfLine : function(AddToSelect) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( this.CurPos.ContentPos < 0 ) return false; if ( true === this.Selection.Use ) { if ( true === AddToSelect ) this.Set_ContentPos( this.Selection.EndPos, true, -1 ); else { this.Set_ContentPos( Math.max( CursorPos_min, Math.min( CursorPos_max, ( this.Selection.EndPos >= this.Selection.StartPos ? this.Selection.EndPos : this.Selection.StartPos ) ) ), true, -1 ); this.Selection_Remove(); } } var CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; var LineEndPos = ( CurLine >= this.Lines.length - 1 ? this.Internal_GetEndPos() : this.Lines[CurLine + 1].StartPos - 1 ); if ( true === this.Selection.Use && true === AddToSelect ) { this.Selection.EndPos = LineEndPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } } else if ( AddToSelect ) { this.Selection.StartPos = this.CurPos.ContentPos; this.Selection.Use = true; this.Selection.EndPos = LineEndPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } } else { this.Set_ContentPos( LineEndPos, true, -1 ); this.RecalculateCurPos(); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } }, Cursor_MoveStartOfLine : function(AddToSelect) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( this.CurPos.ContentPos < 0 ) return false; if ( true === this.Selection.Use ) { if ( true === AddToSelect ) this.Set_ContentPos( this.Selection.EndPos, true, -1 ); else { this.Set_ContentPos( ( this.Selection.StartPos <= this.Selection.EndPos ? this.Selection.StartPos : this.Selection.EndPos ), true, -1 ); this.Selection_Remove(); } } var CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; var LineStartPos = this.Lines[CurLine].StartPos; if ( true === this.Selection.Use && true === AddToSelect ) { this.Selection.EndPos = LineStartPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } } else if ( AddToSelect ) { this.Selection.EndPos = LineStartPos; this.Selection.StartPos = this.CurPos.ContentPos; this.Selection.Use = true; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } } else { this.Set_ContentPos( LineStartPos, true, -1 ); this.RecalculateCurPos(); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } }, Cursor_MoveToStartPos : function() { this.Selection.Use = false; this.Set_ContentPos( this.Internal_GetStartPos(), true, -1 ); }, Cursor_MoveToEndPos : function() { this.Selection.Use = false; this.Set_ContentPos( this.Internal_GetEndPos(), true, -1 ); }, Cursor_MoveUp_To_LastRow : function(X, Y, AddToSelect) { this.CurPos.RealX = X; this.CurPos.RealY = Y; // Перемещаем курсор в последнюю строку, с позицией, самой близкой по X this.Cursor_MoveAt( X, this.Lines.length - 1, true, true, this.PageNum ); if ( true === AddToSelect ) { if ( false === this.Selection.Use ) { this.Selection.Use = true; this.Selection.StartPos = this.Content.length - 1; } this.Selection.EndPos = this.CurPos.ContentPos; } }, Cursor_MoveDown_To_FirstRow : function(X, Y, AddToSelect) { this.CurPos.RealX = X; this.CurPos.RealY = Y; // Перемещаем курсор в последнюю строку, с позицией, самой близкой по X this.Cursor_MoveAt( X, 0, true, true, this.PageNum ); if ( true === AddToSelect ) { if ( false === this.Selection.Use ) { this.Selection.Use = true; this.Selection.StartPos = this.Internal_GetStartPos(); } this.Selection.EndPos = this.CurPos.ContentPos; } }, Cursor_MoveTo_Drawing : function(Id) { // Ставим курсор перед автофигурой с заданным Id var Pos = -1; var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type && Id === Item.Get_Id() ) Pos = Index; } if ( -1 === Pos ) return; this.Set_ContentPos( Pos, true, -1 ); this.RecalculateCurPos(); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; }, Set_ContentPos : function(Pos, bCorrectPos, Line) { this.CurPos.ContentPos = Pos; this.CurPos.Line = ( undefined === Line ? -1 : Line ); if ( false != bCorrectPos ) this.Internal_Correct_ContentPos(); }, Internal_Correct_ContentPos : function() { // 1. Ищем ближайший справа элемент // Это делается для того, чтобы если мы находимся в конце гиперссылки выйти из нее. var Count = this.Content.length; var CurPos = this.CurPos.ContentPos; while ( CurPos < Count - 1 ) { var Item = this.Content[CurPos]; var ItemType = Item.Type; if ( para_Text === ItemType || para_Space === ItemType || para_End === ItemType || para_Tab === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType || para_NewLine === ItemType || para_HyperlinkStart === ItemType ) break; CurPos++; } // 2. Ищем ближайший слева (текcт, пробел, картинку, нумерацию и т.д.) // Смещаемся к концу ближайшего левого элемента, чтобы продолжался набор с // настройками левого ближайшего элемента. while ( CurPos > 0 ) { CurPos--; var Item = this.Content[CurPos]; var ItemType = Item.Type; if ( para_Text === ItemType || para_Space === ItemType || para_End === ItemType || para_Tab === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType || para_NewLine === ItemType ) { this.CurPos.ContentPos = CurPos + 1; return; } else if ( para_HyperlinkEnd === ItemType ) { while ( CurPos < Count - 1 && para_TextPr === this.Content[CurPos + 1].Type ) CurPos++; this.CurPos.ContentPos = CurPos + 1; return; } } // 3. Если мы попали в начало параграфа, тогда пропускаем все TextPr if ( CurPos <= 0 ) { CurPos = 0; while ( para_TextPr === this.Content[CurPos].Type || para_CollaborativeChangesEnd === this.Content[CurPos].Type || para_CollaborativeChangesStart === this.Content[CurPos].Type ) CurPos++; this.CurPos.ContentPos = CurPos; } }, Get_CurPosXY : function() { return { X : this.CurPos.RealX, Y : this.CurPos.RealY }; }, Is_SelectionUse : function() { return this.Selection.Use; }, // Функция определяет начальную позицию курсора в параграфе Internal_GetStartPos : function() { var oPos = this.Internal_FindForward( 0, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End] ); if ( true === oPos.Found ) return oPos.LetterPos; return 0; }, // Функция определяет конечную позицию в параграфе Internal_GetEndPos : function() { var Res = this.Internal_FindBackward( this.Content.length - 1, [para_End] ); if ( true === Res.Found ) return Res.LetterPos; return 0; }, Internal_MoveCursorBackward : function (AddToSelect, Word) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( true === this.Selection.Use ) { if ( true === AddToSelect ) { this.Set_ContentPos( this.Selection.EndPos, true, -1 ); } else { // В случае селекта, убираем селект и перемещаем курсор в начало селекта var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Selection_Remove(); this.Set_ContentPos( StartPos, true, -1 ); return; } } if ( true === this.Selection.Use ) // Добавляем к селекту { var oPos; if ( true != Word ) oPos = this.Internal_FindBackward( this.CurPos.ContentPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End] ); else oPos = this.Internal_FindWordStart( this.CurPos.ContentPos - 1, CursorPos_min ); if ( oPos.Found ) { this.Selection.EndPos = oPos.LetterPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return true; } return true; } else { // TODO: Надо перейти в предыдущий элемент документа return false; } } else if ( true == AddToSelect ) { var oPos; if ( true != Word ) oPos = this.Internal_FindBackward( this.CurPos.ContentPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End] ); else oPos = this.Internal_FindWordStart( this.CurPos.ContentPos - 1, CursorPos_min ); // Селекта еще нет, добавляем с текущей позиции this.Selection.StartPos = this.CurPos.ContentPos; this.Selection.Use = true; if ( oPos.Found ) { this.Selection.EndPos = oPos.LetterPos; return true; } else { this.Selection.Use = false; // TODO: Надо перейти в предыдущий элемент документа return false; } } else { var oPos; if ( true != Word ) oPos = this.Internal_FindBackward( this.CurPos.ContentPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); else oPos = this.Internal_FindWordStart( this.CurPos.ContentPos - 1, CursorPos_min ); if ( oPos.Found ) { this.Set_ContentPos( oPos.LetterPos, true, -1 ); return true; } else { // Надо перейти в предыдущий элемент документа return false; } } }, Internal_FindWordStart : function(Pos, Pos_min) { var LetterPos = Pos; if ( Pos < Pos_min || Pos >= this.Content.length ) return { Found : false }; // На первом этапе ищем первый непробельный ( и не таб ) элемент while ( true ) { var Item = this.Content[LetterPos]; var Type = Item.Type; var bSpace = false; if ( para_TextPr === Type || para_Space === Type || para_HyperlinkStart === Type || para_HyperlinkEnd === Type || para_Tab === Type || para_Empty === Type || para_CommentStart === Type || para_CommentEnd === Type || para_CollaborativeChangesEnd === Type || para_CollaborativeChangesStart === Type || ( para_Text === Type && true === Item.Is_NBSP() ) ) bSpace = true; if ( true === bSpace ) { LetterPos--; if ( LetterPos < 0 ) break; } else break; } if ( LetterPos <= Pos_min ) return { LetterPos : Pos_min, Found : true, Type : this.Content[Pos_min].Type }; // На втором этапе мы смотрим на каком элементе мы встали: если это не текст, тогда // останавливаемся здесь. В противном случае сдвигаемся назад, пока не попали на первый // не текстовый элемент. if ( para_Text != this.Content[LetterPos].Type ) return { LetterPos : LetterPos, Found : true, Type : this.Content[LetterPos].Type }; else { var bPunctuation = this.Content[LetterPos].Is_Punctuation(); var TempPos = LetterPos; while ( TempPos > Pos_min ) { TempPos--; var Item = this.Content[TempPos] var TempType = Item.Type; if ( !( true != Item.Is_RealContent() || para_TextPr === TempType || ( para_Text === TempType && true != Item.Is_NBSP() && ( ( true === bPunctuation && true === Item.Is_Punctuation() ) || ( false === bPunctuation && false === Item.Is_Punctuation() ) ) ) || para_CommentStart === TempType || para_CommentEnd === TempType || para_HyperlinkEnd === TempType || para_HyperlinkEnd === TempType ) ) break; else LetterPos = TempPos; } return { LetterPos : LetterPos, Found : true, Type : this.Content[LetterPos].Type } } return { Found : false }; }, Internal_FindWordEnd : function(Pos, Pos_max) { var LetterPos = Pos; if ( Pos > Pos_max || Pos >= this.Content.length ) return { Found : false }; var bFirst = true; var bFirstPunctuation = false; // является ли первый найденный символ знаком препинания // На первом этапе ищем первый нетекстовый ( и не таб ) элемент while ( true ) { var Item = this.Content[LetterPos]; var Type = Item.Type; var bText = false; if ( para_TextPr === Type || para_HyperlinkStart === Type || para_HyperlinkEnd === Type || para_Empty === Type || ( para_Text === Type && true != Item.Is_NBSP() && ( true === bFirst || ( bFirstPunctuation === Item.Is_Punctuation() ) ) ) || para_CommentStart === Type || para_CommentEnd === Type || para_CollaborativeChangesEnd === Type || para_CollaborativeChangesStart === Type ) bText = true; if ( true === bText ) { if ( true === bFirst && para_Text === Type ) { bFirst = false; bFirstPunctuation = Item.Is_Punctuation(); } LetterPos++; if ( LetterPos > Pos_max || LetterPos >= this.Content.length ) break; } else break; } // Первый найденный элемент не текстовый, смещаемся вперед if ( true === bFirst ) LetterPos++; if ( LetterPos > Pos_max ) return { Found : false }; // На втором этапе мы смотрим на каком элементе мы встали: если это не пробел, тогда // останавливаемся здесь. В противном случае сдвигаемся вперед, пока не попали на первый // не пробельный элемент. if ( !(para_Space === this.Content[LetterPos].Type || ( para_Text === this.Content[LetterPos].Type && true === this.Content[LetterPos].Is_NBSP() ) ) ) return { LetterPos : LetterPos, Found : true, Type : this.Content[LetterPos].Type }; else { var TempPos = LetterPos; while ( TempPos < Pos_max ) { TempPos++; var Item = this.Content[TempPos] var TempType = Item.Type; if ( !( true != Item.Is_RealContent() || para_TextPr === TempType || para_Space === this.Content[LetterPos].Type || ( para_Text === this.Content[LetterPos].Type && true === this.Content[LetterPos].Is_NBSP() ) || para_CommentStart === TempType || para_CommentEnd === TempType || para_HyperlinkEnd === TempType || para_HyperlinkEnd === TempType ) ) break; else LetterPos = TempPos; } return { LetterPos : LetterPos, Found : true, Type : this.Content[LetterPos].Type } } return { Found : false }; }, Internal_MoveCursorForward : function (AddToSelect, Word) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( true === this.Selection.Use ) { if ( true === AddToSelect ) { this.Set_ContentPos( this.Selection.EndPos, false, -1 ); } else { // В случае селекта, убираем селект и перемещаем курсор в конец селекта var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Selection_Remove(); this.Set_ContentPos( Math.max( CursorPos_min, Math.min( EndPos, CursorPos_max ) ), true, -1 ); return true; } } if ( true == this.Selection.Use && true == AddToSelect ) { var oPos; if ( true != Word ) oPos = this.Internal_FindForward( this.CurPos.ContentPos + 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End, para_Empty] ); else oPos = this.Internal_FindWordEnd( this.CurPos.ContentPos, CursorPos_max + 1 ); if ( oPos.Found ) { this.Selection.EndPos = oPos.LetterPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } return true; } else { // TODO: Надо перейти в предыдущий элемент документа return false; } } else if ( true == AddToSelect ) { var oPos; if ( true != Word ) oPos = this.Internal_FindForward( this.CurPos.ContentPos + 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End, para_Empty] ); else oPos = this.Internal_FindWordEnd( this.CurPos.ContentPos, CursorPos_max + 1 ); // Селекта еще нет, добавляем с текущей позиции this.Selection.StartPos = this.CurPos.ContentPos; this.Selection.Use = true; if ( oPos.Found ) { this.Selection.EndPos = oPos.LetterPos; return true; } else { this.Selection.Use = false; // TODO: Надо перейти в предыдущий элемент документа return false; } } else { var oPos; if ( true != Word ) { oPos = this.Internal_FindForward( this.CurPos.ContentPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( oPos.Found ) oPos.LetterPos++; } else oPos = this.Internal_FindWordEnd( this.CurPos.ContentPos, CursorPos_max ); if ( oPos.Found ) { this.Set_ContentPos( oPos.LetterPos, true, -1 ); return true; } else { // TODO: Надо перейти в следующий элемент документа return false; } } }, Internal_Clear_EmptyTextPr : function() { var Count = this.Content.length; for ( var Pos = 0; Pos < Count - 1; Pos++ ) { if ( para_TextPr === this.Content[Pos].Type && para_TextPr === this.Content[Pos + 1].Type ) { this.Internal_Content_Remove( Pos ); Pos--; Count--; } } }, Internal_AddTextPr : function(TextPr) { this.Internal_Clear_EmptyTextPr(); if ( undefined != TextPr.FontFamily ) { var FName = TextPr.FontFamily.Name; var FIndex = TextPr.FontFamily.Index; TextPr.RFonts = new CRFonts(); TextPr.RFonts.Ascii = { Name : FName, Index : FIndex }; TextPr.RFonts.EastAsia = { Name : FName, Index : FIndex }; TextPr.RFonts.HAnsi = { Name : FName, Index : FIndex }; TextPr.RFonts.CS = { Name : FName, Index : FIndex }; } if ( true === this.ApplyToAll ) { this.Internal_Content_Add( 0, new ParaTextPr( TextPr ) ); // Внутри каждого TextPr меняем те настройки, которые пришли в TextPr. Например, // у нас изменен только размер шрифта, то изменяем запись о размере шрифта. for ( var Pos = 0; Pos < this.Content.length; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) this.Content[Pos].Apply_TextPr( TextPr ); } // Выставляем настройки для символа параграфа this.TextPr.Apply_TextPr( TextPr ); return; } // найдем текущую позицию var Line = this.Content; var CurPos = this.CurPos.ContentPos; if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } // Если селект продолжается до конца параграфа, не ставим отметку в конце var LastPos = this.Internal_GetEndPos(); var bEnd = false; if ( EndPos > LastPos ) { EndPos = LastPos; bEnd = true; } // Рассчитываем шрифт, который используется после слова var TextPr_end = this.Internal_GetTextPr( EndPos ); var TextPr_start = this.Internal_GetTextPr( StartPos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( StartPos, new ParaTextPr( TextPr_start ) ); if ( false === bEnd ) this.Internal_Content_Add( EndPos + 1, new ParaTextPr( TextPr_end ) ); else { // Выставляем настройки для символа параграфа this.TextPr.Apply_TextPr( TextPr ); } // Если внутри слова были изменения текстовых настроек, тогда удаляем только те записи, которые // меняются сейчас. Например, у нас изменен только размер шрифта, то удаляем запись о размере шрифта. for ( var Pos = StartPos + 1; Pos < EndPos; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) { this.Content[Pos].Apply_TextPr( TextPr ); } } return; } // При изменении шрифта ведем себе следующим образом: // 1. Если мы в конце параграфа, тогда добавляем запись о шрифте (применимо к знаку конца параграфа) // 2. Если справа или слева стоит пробел (начало параграфа или перенос строки(командный)), тогда ставим метку со шрифтом и фокусим канву. // 3. Если мы посередине слова, тогда меняем шрифт для данного слова var oEnd = this.Internal_FindForward ( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_End, para_NewLine] ); var oStart = this.Internal_FindBackward( CurPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); var CurType = this.Content[CurPos].Type; if ( !oEnd.Found ) return; if ( para_End == oEnd.Type ) { // Вставляем запись о новых настройках перед концом параграфа, а текущую позицию выставляем на конец параграфа var Pos = oEnd.LetterPos; var TextPr_start = this.Internal_GetTextPr( Pos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_start ) ); this.Set_ContentPos( Pos + 1, false, -1 ); if ( true === this.IsEmpty() && undefined === this.Numbering_Get() ) { // Выставляем настройки для символа параграфа this.TextPr.Apply_TextPr( TextPr ); } } else if ( para_PageNum === CurType || para_Drawing === CurType || para_Tab == CurType || para_Space == CurType || para_NewLine == CurType || !oStart.Found || para_NewLine == oEnd.Type || para_Space == oEnd.Type || para_NewLine == oStart.Type || para_Space == oStart.Type || para_Tab == oEnd.Type || para_Tab == oStart.Type || para_Drawing == oEnd.Type || para_Drawing == oStart.Type || para_PageNum == oEnd.Type || para_PageNum == oStart.Type ) { var TextPr_old = this.Internal_GetTextPr( CurPos ); var TextPr_new = TextPr_old.Copy(); TextPr_new.Merge( TextPr ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_old ) ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_new ) ); this.Set_ContentPos( CurPos + 1, false, -1 ); this.RecalculateCurPos(); } else { // Мы находимся посередине слова. В начале слова ставим запись о новом шрифте, // а в конце слова старый шрифт. Кроме этого, надо удалить все записи о шрифте внутри слова. // Найдем начало слова var oWordStart = this.Internal_FindBackward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_NewLine] ); if ( !oWordStart.Found ) oWordStart = this.Internal_FindForward( 0, [para_Text] ); else oWordStart.LetterPos++; var oWordEnd = this.Internal_FindForward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_End, para_NewLine] ); if ( !oWordStart.Found || !oWordEnd.Found ) return; // Рассчитываем настройки, которые используются после слова var TextPr_end = this.Internal_GetTextPr( oWordEnd.LetterPos ); var TextPr_start = this.Internal_GetTextPr( oWordStart.LetterPos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( oWordStart.LetterPos, new ParaTextPr( TextPr_start ) ); this.Internal_Content_Add( oWordEnd.LetterPos + 1 /* из-за предыдущего Internal_Content_Add */, new ParaTextPr( TextPr_end ) ); this.Set_ContentPos( CurPos + 1, false, -1 ); // Если внутри слова были изменения текстовых настроек, тогда удаляем только те записи, которые // меняются сейчас. Например, у нас изменен только размер шрифта, то удаляем запись о размере шрифта. for ( var Pos = oWordStart.LetterPos + 1; Pos < oWordEnd.LetterPos; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) this.Content[Pos].Apply_TextPr( TextPr ); } } }, Internal_AddHyperlink : function(Hyperlink_start) { // Создаем текстовую настройку для гиперссылки var Hyperlink_end = new ParaHyperlinkEnd(); var RStyle = editor.WordControl.m_oLogicDocument.Get_Styles().Get_Default_Hyperlink(); if ( true === this.ApplyToAll ) { // TODO: Надо выяснить, нужно ли в данном случае делать гиперссылку return; } var CurPos = this.CurPos.ContentPos; if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } // Если селект продолжается до конца параграфа, не ставим отметку в конце var LastPos = this.Internal_GetEndPos(); if ( EndPos > LastPos ) EndPos = LastPos; var TextPr_end = this.Internal_GetTextPr( EndPos ); var TextPr_start = this.Internal_GetTextPr( StartPos ); TextPr_start.RStyle = RStyle; TextPr_start.Underline = undefined; TextPr_start.Color = undefined; this.Internal_Content_Add( EndPos, new ParaTextPr( TextPr_end ) ); this.Internal_Content_Add( EndPos, Hyperlink_end ); this.Internal_Content_Add( StartPos, new ParaTextPr( TextPr_start ) ); this.Internal_Content_Add( StartPos, Hyperlink_start ); // Если внутри выделения были изменения текстовых настроек, тогда удаляем только те записи, которые // меняются сейчас. Например, у нас изменен только размер шрифта, то удаляем запись о размере шрифта. for ( var Pos = StartPos + 2; Pos < EndPos + 1; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) { var Item = this.Content[Pos]; Item.Set_RStyle( RStyle ); Item.Set_Underline( undefined ); Item.Set_Color( undefined ); } } return; } return; // При изменении шрифта ведем себе следующим образом: // 1. Если мы в конце параграфа, тогда добавляем запись о шрифте (применимо к знаку конца параграфа) // 2. Если справа или слева стоит пробел (начало параграфа или перенос строки(командный)), тогда ставим метку со шрифтом и фокусим канву. // 3. Если мы посередине слова, тогда меняем шрифт для данного слова var oEnd = this.Internal_FindForward ( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_End, para_NewLine] ); var oStart = this.Internal_FindBackward( CurPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); var CurType = this.Content[CurPos].Type; if ( !oEnd.Found ) return; if ( para_End == oEnd.Type ) { // Вставляем запись о новых настройках перед концом параграфа, а текущую позицию выставляем на конец параграфа var Pos = oEnd.LetterPos; var TextPr_start = this.Internal_GetTextPr( Pos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_start ) ); this.Set_ContentPos( Pos + 1, false, -1 ); } else if ( para_PageNum === CurType || para_Drawing === CurType || para_Tab == CurType || para_Space == CurType || para_NewLine == CurType || !oStart.Found || para_NewLine == oEnd.Type || para_Space == oEnd.Type || para_NewLine == oStart.Type || para_Space == oStart.Type || para_Tab == oEnd.Type || para_Tab == oStart.Type || para_Drawing == oEnd.Type || para_Drawing == oStart.Type || para_PageNum == oEnd.Type || para_PageNum == oStart.Type ) { var TextPr_old = this.Internal_GetTextPr( CurPos ); var TextPr_new = TextPr_old.Copy(); TextPr_new.Merge( TextPr ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_old ) ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_new ) ); this.Set_ContentPos( CurPos + 1, false, -1 ); this.RecalculateCurPos(); } else { // Мы находимся посередине слова. В начале слова ставим запись о новом шрифте, // а в конце слова старый шрифт. Кроме этого, надо удалить все записи о шрифте внутри слова. // Найдем начало слова var oWordStart = this.Internal_FindBackward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_NewLine] ); if ( !oWordStart.Found ) oWordStart = this.Internal_FindForward( 0, [para_Text] ); else oWordStart.LetterPos++; var oWordEnd = this.Internal_FindForward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_End, para_NewLine] ); if ( !oWordStart.Found || !oWordEnd.Found ) return; // Рассчитываем настройки, которые используются после слова var TextPr_end = this.Internal_GetTextPr( oWordEnd.LetterPos ); var TextPr_start = this.Internal_GetTextPr( oWordStart.LetterPos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( oWordStart.LetterPos, new ParaTextPr( TextPr_start ) ); this.Internal_Content_Add( oWordEnd.LetterPos + 1 /* из-за предыдущего Internal_Content_Add */, new ParaTextPr( TextPr_end ) ); this.Set_ContentPos( CurPos + 1, false, -1 ); // Если внутри слова были изменения текстовых настроек, тогда удаляем только те записи, которые // меняются сейчас. Например, у нас изменен только размер шрифта, то удаляем запись о размере шрифта. for ( var Pos = oWordStart.LetterPos + 1; Pos < oWordEnd.LetterPos; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) this.Content[Pos].Apply_TextPr( TextPr ); } } }, Internal_GetContentPosByXY : function(X,Y, bLine, PageNum, bCheckNumbering) { if ( this.Lines.length <= 0 ) return {Pos : 0, End:false, InText : false}; // Сначала определим на какую строку мы попали var PNum = 0; if ( "number" == typeof(PageNum) ) { PNum = PageNum - this.PageNum; } else PNum = 0; if ( PNum >= this.Pages.length ) { PNum = this.Pages.length - 1; bLine = true; Y = this.Lines.length - 1; } else if ( PNum < 0 ) { PNum = 0; bLine = true; Y = 0; } var bFindY = false; var CurLine = this.Pages[PNum].FirstLine; var CurLineY = this.Pages[PNum].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; var LastLine = ( PNum >= this.Pages.length - 1 ? this.Lines.length - 1 : this.Pages[PNum + 1].FirstLine - 1 ); if ( true === bLine ) CurLine = Y; else { while ( !bFindY ) { if ( Y < CurLineY ) break; if ( CurLine >= LastLine ) break; CurLine++; CurLineY = this.Lines[CurLine].Y + this.Pages[PNum].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; } } // Ищем позицию в строке var CurRange = 0; var CurX = this.Lines[CurLine].Ranges[CurRange].XVisible; var DiffX = 1000000;//this.XLimit; // километра для ограничения должно хватить var NumberingDiffX = 1000000;//this.XLimit; var DiffPos = -1; var bEnd = false; var bInText = false; var Result = { Pos : 0, End : false }; var StartPos = this.Lines[CurLine].StartPos; var ResultLine = -1; for ( var ItemNum = StartPos; ItemNum < this.Content.length; ItemNum++ ) { var Item = this.Content[ItemNum]; if ( undefined != Item.CurLine ) { if ( CurLine != Item.CurLine ) break; if ( CurRange != Item.CurRange ) { CurRange = Item.CurRange; CurX = this.Lines[CurLine].Ranges[CurRange].XVisible; } } var TempDx = 0; var bCheck = false; if ( ItemNum === this.Numbering.Pos ) { if ( para_Numbering === this.Numbering.Type ) { var NumberingItem = this.Numbering; var NumPr = this.Numbering_Get(); var NumJc = this.Parent.Get_Numbering().Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl].Jc; var NumX0 = CurX; var NumX1 = CurX; switch( NumJc ) { case align_Right: { NumX0 -= NumberingItem.WidthNum; break; } case align_Center: { NumX0 -= NumberingItem.WidthNum / 2; NumX1 += NumberingItem.WidthNum / 2; break; } case align_Left: default: { NumX1 += NumberingItem.WidthNum; break; } } if ( X >= NumX0 && X <= NumX1 ) NumberingDiffX = 0; } CurX += this.Numbering.WidthVisible; if ( -1 != DiffPos ) { DiffX = Math.abs( X - CurX ); DiffPos = ItemNum; } } switch( Item.Type ) { case para_Drawing: { if ( Item.DrawingType != drawing_Inline ) { bCheck = false; TempDx = 0; } else { TempDx = Item.WidthVisible; bCheck = true; } break; } case para_PageNum: case para_Text: TempDx = Item.WidthVisible; bCheck = true; break; case para_Space: TempDx = Item.WidthVisible; bCheck = true; break; case para_Tab: TempDx = Item.WidthVisible; bCheck = true; break; case para_NewLine: bCheck = true; TempDx = Item.WidthVisible; break; case para_End: bEnd = true; bCheck = true; TempDx = Item.WidthVisible; break; case para_TextPr: case para_CommentEnd: case para_CommentStart: case para_CollaborativeChangesEnd: case para_CollaborativeChangesStart: case para_HyperlinkEnd: case para_HyperlinkStart: bCheck = true; TempDx = 0; break; } if ( bCheck ) { if ( Math.abs( X - CurX ) < DiffX + 0.001 ) { DiffX = Math.abs( X - CurX ); DiffPos = ItemNum; } if ( true != bEnd && ItemNum === this.Lines[CurLine].EndPos && X > CurX + TempDx && para_NewLine != Item.Type ) { ResultLine = CurLine; DiffPos = ItemNum + 1; } // Заглушка для знака параграфа if ( bEnd ) { CurX += TempDx; if ( Math.abs( X - CurX ) < DiffX ) { Result.End = true; } break; } } if ( X >= CurX - 0.001 && X <= CurX + TempDx + 0.001 ) bInText = true; CurX += TempDx; } // По Х попали в какой-то элемент, проверяем по Y if ( true === bInText && Y >= this.Pages[PNum].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent - 0.01 && Y <= this.Pages[PNum].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap + 0.01 ) Result.InText = true; else Result.InText = false; if ( NumberingDiffX <= DiffX ) Result.Numbering = true; else Result.Numbering = false; Result.Pos = DiffPos; Result.Line = ResultLine; return Result; }, Internal_GetXYByContentPos : function(Pos) { return this.Internal_Recalculate_CurPos(Pos, false, false, false); }, Internal_Selection_CheckHyperlink : function() { // Если у нас начало селекта находится внутри гиперссылки, а конец // нет (или наоборот), тогда выделяем всю гиперссылку. var Direction = 1; var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; Direction = -1; } var Hyperlink_start = this.Check_Hyperlink2( StartPos ); var Hyperlink_end = this.Check_Hyperlink2( EndPos ); if ( null != Hyperlink_start && Hyperlink_end != Hyperlink_start ) StartPos = this.Internal_FindBackward( StartPos, [para_HyperlinkStart]).LetterPos; if ( null != Hyperlink_end && Hyperlink_end != Hyperlink_start ) EndPos = this.Internal_FindForward( EndPos, [para_HyperlinkEnd]).LetterPos + 1; if ( Direction > 0 ) { this.Selection.StartPos = StartPos; this.Selection.EndPos = EndPos; } else { this.Selection.StartPos = EndPos; this.Selection.EndPos = StartPos; } }, Check_Hyperlink : function(X, Y, PageNum) { var Result = this.Internal_GetContentPosByXY( X, Y, false, PageNum, false); if ( -1 != Result.Pos && true === Result.InText ) { var Find = this.Internal_FindBackward( Result.Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkStart === Find.Type ) return this.Content[Find.LetterPos]; } return null; }, Check_Hyperlink2 : function(Pos, bCheckEnd, bNoSelectCheck) { if ( undefined === bNoSelectCheck ) bNoSelectCheck = false; if ( undefined === bCheckEnd ) bCheckEnd = true; // TODO : Специальная заглушка, для конца селекта. Неплохо бы переделать. if ( true === bCheckEnd && Pos > 0 ) { while ( this.Content[Pos - 1].Type === para_TextPr || this.Content[Pos - 1].Type === para_HyperlinkEnd || this.Content[Pos - 1].Type === para_CollaborativeChangesStart || this.Content[Pos - 1].Type === para_CollaborativeChangesEnd ) { Pos--; if ( Pos <= 0 ) return null; } } // TODO: специальная заглушка, для случая, когда курсор стоит перед гиперссылкой, чтобы мы определяли данную ситуацию как попадание в гиперссылку if ( true === bNoSelectCheck ) { Pos = this.Internal_Correct_HyperlinkPos(Pos); } var Find = this.Internal_FindBackward( Pos - 1, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkStart === Find.Type ) return this.Content[Find.LetterPos]; return null; }, Internal_Correct_HyperlinkPos : function(_Pos) { var Pos = _Pos; var Count = this.Content.length; while ( Pos < Count ) { var TempType = this.Content[Pos].Type; if ( para_HyperlinkStart === TempType || para_TextPr === TempType || para_CollaborativeChangesEnd === TempType || para_CollaborativeChangesStart === TempType ) Pos++; else break; } return Pos; }, Hyperlink_Add : function(HyperProps) { var Hyperlink = new ParaHyperlinkStart(); Hyperlink.Set_Value( HyperProps.Value ); if ( "undefined" != typeof(HyperProps.ToolTip) && null != HyperProps.ToolTip ) Hyperlink.Set_ToolTip( HyperProps.ToolTip ); if ( true === this.Selection.Use ) { this.Add( Hyperlink ); } else if ( null != HyperProps.Text && "" != HyperProps.Text ) // добавлять ссылку, без селекта и с пустым текстом нельзя { var TextPr_hyper = this.Internal_GetTextPr(this.CurPos.ContentPos); var Styles = editor.WordControl.m_oLogicDocument.Get_Styles(); TextPr_hyper.RStyle = Styles.Get_Default_Hyperlink(); TextPr_hyper.Color = undefined; TextPr_hyper.Underline = undefined; var TextPr_old = this.Internal_GetTextPr(this.CurPos.ContentPos); var Pos = this.CurPos.ContentPos; this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_old ) ); this.Internal_Content_Add( Pos, new ParaHyperlinkEnd() ); this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_hyper ) ); this.Internal_Content_Add( Pos, Hyperlink ); for ( var NewPos = 0; NewPos < HyperProps.Text.length; NewPos++ ) { var Char = HyperProps.Text.charAt( NewPos ); if ( " " == Char ) this.Internal_Content_Add( Pos + 2 + NewPos, new ParaSpace() ); else this.Internal_Content_Add( Pos + 2 + NewPos, new ParaText(Char) ); } this.Set_ContentPos( Pos + 2, false, -1 ); // чтобы курсор встал после TextPr } }, Hyperlink_Modify : function(HyperProps) { var Hyperlink = null; var Pos = -1; if ( true === this.Selection.Use ) { var Hyper_start = this.Check_Hyperlink2( this.Selection.StartPos ); var Hyper_end = this.Check_Hyperlink2( this.Selection.EndPos ); if ( null != Hyper_start && Hyper_start === Hyper_end ) { Hyperlink = Hyper_start; Pos = this.Selection.StartPos; } } else { Hyperlink = this.Check_Hyperlink2( this.CurPos.ContentPos, false, true ); Pos = this.Internal_Correct_HyperlinkPos(this.CurPos.ContentPos); } if ( null != Hyperlink ) { if ( "undefined" != typeof( HyperProps.Value) && null != HyperProps.Value ) Hyperlink.Set_Value( HyperProps.Value ); if ( "undefined" != typeof( HyperProps.ToolTip) && null != HyperProps.ToolTip ) Hyperlink.Set_ToolTip( HyperProps.ToolTip ); if ( null != HyperProps.Text ) { var Find = this.Internal_FindBackward( Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true != Find.Found || para_HyperlinkStart != Find.Type ) return false; var Start = Find.LetterPos; var Find = this.Internal_FindForward( Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true != Find.Found || para_HyperlinkEnd != Find.Type ) return false; var End = Find.LetterPos; var TextPr = this.Internal_GetTextPr(End); TextPr.RStyle = editor.WordControl.m_oLogicDocument.Get_Styles().Get_Default_Hyperlink(); TextPr.Color = undefined; TextPr.Underline = undefined; // TODO: тут не должно быть картинок, но все-таки если будет такая ситуация, // тогда надо будет убрать записи о картинках. this.Internal_Content_Remove2( Start + 1, End - Start - 1 ); this.Internal_Content_Add( Start + 1, new ParaTextPr( TextPr ) ); for ( var NewPos = 0; NewPos < HyperProps.Text.length; NewPos++ ) { var Char = HyperProps.Text.charAt( NewPos ); if ( " " == Char ) this.Internal_Content_Add( Start + 2 + NewPos, new ParaSpace() ); else this.Internal_Content_Add( Start + 2 + NewPos, new ParaText(Char) ); } if ( true === this.Selection.Use ) { this.Selection.StartPos = Start + 1; this.Selection.EndPos = Start + 2 + HyperProps.Text.length; this.Set_ContentPos( this.Selection.EndPos ); } else this.Set_ContentPos( Start + 2, false ); // чтобы курсор встал после TextPr return true; } return false; } return false; }, Hyperlink_Remove : function() { var Pos = -1; if ( true === this.Selection.Use ) { var Hyper_start = this.Check_Hyperlink2( this.Selection.StartPos ); var Hyper_end = this.Check_Hyperlink2( this.Selection.EndPos ); if ( null != Hyper_start && Hyper_start === Hyper_end ) Pos = ( this.Selection.StartPos <= this.Selection.EndPos ? this.Selection.StartPos : this.Selection.EndPos ); } else { var Hyper_cur = this.Check_Hyperlink2( this.CurPos.ContentPos, false, true ); if ( null != Hyper_cur ) Pos = this.Internal_Correct_HyperlinkPos( this.CurPos.ContentPos ); } if ( -1 != Pos ) { var Find = this.Internal_FindForward( Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkEnd === Find.Type ) this.Internal_Content_Remove( Find.LetterPos ); var EndPos = Find.LetterPos - 2; Find = this.Internal_FindBackward( Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkStart === Find.Type ) this.Internal_Content_Remove( Find.LetterPos ); var StartPos = Find.LetterPos; var RStyle = editor.WordControl.m_oLogicDocument.Get_Styles().Get_Default_Hyperlink(); // TODO: когда появятся стили текста, тут надо будет переделать for ( var Index = StartPos; Index <= EndPos; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type && Item.Value.RStyle === RStyle ) { Item.Set_RStyle( undefined ); } } // Пересчитаем TextPr this.RecalcInfo.Set_Type_0( pararecalc_0_All ); this.Internal_Recalculate_0(); // Запускаем перерисовку this.ReDraw(); return true; } return false; }, Hyperlink_CanAdd : function(bCheckInHyperlink) { if ( true === bCheckInHyperlink ) { if ( true === this.Selection.Use ) { // Если у нас в выделение попадает начало или конец гиперссылки, или конец параграфа, или // у нас все выделение находится внутри гиперссылки, тогда мы не можем добавить новую. Во // всех остальных случаях разрешаем добавить. var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( EndPos < StartPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } // Проверяем не находимся ли мы внутри гиперссылки var Find = this.Internal_FindBackward( StartPos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkStart === Find.Type ) return false; for ( var Pos = StartPos; Pos < EndPos; Pos++ ) { var Item = this.Content[Pos]; switch ( Item.Type ) { case para_HyperlinkStart: case para_HyperlinkEnd: case para_End: return false; } } return true; } else { // Внутри гиперссылки мы не можем задать ниперссылку var Hyper_cur = this.Check_Hyperlink2( this.CurPos.ContentPos ); if ( null != Hyper_cur ) return false; else return true; } } else { if ( true === this.Selection.Use ) { // Если у нас в выделение попадает несколько гиперссылок или конец параграфа, тогда // возвращаем false, во всех остальных случаях true var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( EndPos < StartPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } var bHyper = false; for ( var Pos = StartPos; Pos < EndPos; Pos++ ) { var Item = this.Content[Pos]; switch ( Item.Type ) { case para_HyperlinkStart: { if ( true === bHyper ) return false; bHyper = true; break; } case para_HyperlinkEnd: { bHyper = true; break; } case para_End: return false; } } return true; } else { return true; } } }, Hyperlink_Check : function(bCheckEnd) { if ( true === this.Selection.Use ) { var Hyper_start = this.Check_Hyperlink2( this.Selection.StartPos ); var Hyper_end = this.Check_Hyperlink2( this.Selection.EndPos ); if ( Hyper_start === Hyper_end && null != Hyper_start ) return Hyper_start } else { var Hyper_cur = this.Check_Hyperlink2( this.CurPos.ContentPos, bCheckEnd ); if ( null != Hyper_cur ) return Hyper_cur; } return null; }, Cursor_MoveAt : function(X,Y, bLine, bDontChangeRealPos, PageNum) { var TempPos = this.Internal_GetContentPosByXY( X, Y, bLine, PageNum ); var Pos = TempPos.Pos; var Line = TempPos.Line; if ( -1 != Pos ) { this.Set_ContentPos( Pos, true, Line ); } this.Internal_Recalculate_CurPos(Pos, false, false, false ); if ( bDontChangeRealPos != true ) { this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } if ( true != bLine ) { this.CurPos.RealX = X; this.CurPos.RealY = Y; } }, Selection_SetStart : function(X,Y,PageNum, bTableBorder) { var Pos = this.Internal_GetContentPosByXY( X, Y, false, PageNum ); if ( -1 != Pos.Pos ) { if ( true === Pos.End ) this.Selection.StartPos = Pos.Pos + 1; else this.Selection.StartPos = Pos.Pos; this.Set_ContentPos( Pos.Pos, true , Pos.Line ); this.Selection.Use = true; this.Selection.Start = true; this.Selection.Flag = selectionflag_Common; } }, // Данная функция может использоваться как при движении, так и при окончательном выставлении селекта. // Если bEnd = true, тогда это конец селекта. Selection_SetEnd : function(X,Y,PageNum, MouseEvent, bTableBorder) { var PagesCount = this.Pages.length; if ( false === editor.isViewMode && null === this.Parent.Is_HdrFtr(true) && null == this.Get_DocumentNext() && PageNum - this.PageNum >= PagesCount - 1 && Y > this.Pages[PagesCount - 1].Bounds.Bottom && MouseEvent.ClickCount >= 2 ) return this.Parent.Extend_ToPos( X, Y ); this.CurPos.RealX = X; this.CurPos.RealY = Y; var Temp = this.Internal_GetContentPosByXY( X, Y, false, PageNum ); var Pos = Temp.Pos; if ( -1 != Pos ) { this.Set_ContentPos( Pos, true, Temp.Line ); if ( true === Temp.End ) { if ( PageNum - this.PageNum >= PagesCount - 1 && X > this.Lines[this.Lines.length - 1].Ranges[this.Lines[this.Lines.length - 1].Ranges.length - 1].W && MouseEvent.ClickCount >= 2 && Y <= this.Pages[PagesCount - 1].Bounds.Bottom ) { if ( false === editor.isViewMode && false === editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_None, { Type : changestype_2_Element_and_Type, Element : this, CheckType : changestype_Paragraph_Content } ) ) { History.Create_NewPoint(); History.Set_Additional_ExtendDocumentToPos(); this.Extend_ToPos( X ); this.Cursor_MoveToEndPos(); this.Document_SetThisElementCurrent(); editor.WordControl.m_oLogicDocument.Recalculate(); return; } } this.Selection.EndPos = Pos + 1; } else this.Selection.EndPos = Pos; if ( this.Selection.EndPos == this.Selection.StartPos && g_mouse_event_type_up === MouseEvent.Type ) { var NumPr = this.Numbering_Get(); if ( true === Temp.Numbering && undefined != NumPr ) { // Ставим именно 0, а не this.Internal_GetStartPos(), чтобы при нажатии на клавишу "направо" // мы оказывались в начале параграфа. this.Set_ContentPos( 0, true, -1 ); this.Parent.Document_SelectNumbering( NumPr ); } else { var Temp2 = MouseEvent.ClickCount % 2; if ( 1 >= MouseEvent.ClickCount ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Pos, true, Temp.Line ); this.RecalculateCurPos(); return; } else if ( 0 == Temp2 ) { var oStart; if ( this.Content[Pos].Type == para_Space ) { oStart = this.Internal_FindBackward( Pos, [ para_Text, para_NewLine ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); else if ( oStart.Type == para_NewLine ) { oStart.LetterPos++; // смещаемся на начало следующей строки } else { oStart = this.Internal_FindBackward( oStart.LetterPos, [ para_Tab, para_Space, para_NewLine ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); else { oStart = this.Internal_FindForward( oStart.LetterPos, [ para_Text ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); } } } else { oStart = this.Internal_FindBackward( Pos, [ para_Tab, para_Space, para_NewLine ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); else { oStart = this.Internal_FindForward( oStart.LetterPos, [ para_Text, para_NewLine ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); } } var oEnd = this.Internal_FindForward( Pos, [ para_Tab, para_Space, para_NewLine ] ); if ( !oEnd.Found ) oEnd.LetterPos = this.Content.length - 1; else if ( oEnd.Type != para_NewLine ) // при переносе строки селектим все до переноса строки { oEnd = this.Internal_FindForward( oEnd.LetterPos, [ para_Text ] ); if ( !oEnd.Found ) oEnd.LetterPos = this.Content.length - 1; } this.Selection.StartPos = oStart.LetterPos; this.Selection.EndPos = oEnd.LetterPos; this.Selection.Use = true; } else // ( 1 == Temp2 % 3 ) { // Селектим параграф целиком this.Selection.StartPos = this.Internal_GetStartPos(); this.Selection.EndPos = this.Content.length - 1; this.Selection.Use = true; } } } } if ( -1 === this.Selection.EndPos ) { //Temp = this.Internal_GetContentPosByXY( X, Y, false, PageNum ); return; } }, Selection_Stop : function(X,Y,PageNum, MouseEvent) { this.Selection.Start = false; }, Selection_Remove : function() { this.Selection.Use = false; this.Selection.Flag = selectionflag_Common; this.Selection_Clear(); }, Selection_Clear : function() { }, Selection_Draw_Page : function(Page_abs) { if ( true != this.Selection.Use ) return; var CurPage = Page_abs - this.Get_StartPage_Absolute(); if ( CurPage < 0 || CurPage >= this.Pages.length ) return; if ( 0 === CurPage && this.Pages[0].EndLine < 0 ) return; switch ( this.Selection.Flag ) { case selectionflag_Common: { // Делаем подсветку var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } var _StartLine = this.Pages[CurPage].StartLine; var _EndLine = this.Pages[CurPage].EndLine; if ( StartPos > this.Lines[_EndLine].EndPos + 1 || EndPos < this.Lines[_StartLine].StartPos ) return; else { StartPos = Math.max( StartPos, this.Lines[_StartLine].StartPos ); EndPos = Math.min( EndPos, ( _EndLine != this.Lines.length - 1 ? this.Lines[_EndLine].EndPos + 1 : this.Content.length - 1 ) ); } // Найдем линию, с которой начинается селект var StartParaPos = this.Internal_Get_ParaPos_By_Pos( StartPos ); var CurLine = StartParaPos.Line; var CurRange = StartParaPos.Range; var PNum = StartParaPos.Page; // Найдем начальный сдвиг в данном отрезке var StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; var Pos, Item; if ( this.Numbering.Pos >= this.Lines[CurLine].Ranges[CurRange].StartPos ) StartX += this.Numbering.WidthVisible; for ( Pos = this.Lines[CurLine].Ranges[CurRange].StartPos; Pos <= StartPos - 1; Pos++ ) { Item = this.Content[Pos]; if ( undefined != Item.WidthVisible && ( para_Drawing != Item.Type || drawing_Inline === Item.DrawingType ) ) StartX += Item.WidthVisible; } if ( this.Pages[PNum].StartLine > CurLine ) { CurLine = this.Pages[PNum].StartLine; CurRange = 0; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; StartPos = this.Lines[this.Pages[PNum].StartLine].StartPos; } var StartY = this.Pages[PNum].Y + this.Lines[CurLine].Top; var H = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; var W = 0; for ( Pos = StartPos; Pos < EndPos; Pos++ ) { Item = this.Content[Pos]; if ( undefined != Item.CurPage ) { if ( CurLine < Item.CurLine ) { this.DrawingDocument.AddPageSelection(Page_abs, StartX, StartY, W, H); CurLine = Item.CurLine; CurRange = Item.CurRange; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; StartY = this.Pages[PNum].Y + this.Lines[CurLine].Top; H = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; W = 0; } else if ( CurRange < Item.CurRange ) { this.DrawingDocument.AddPageSelection(Page_abs, StartX, StartY, W, H); CurRange = Item.CurRange; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; W = 0; } } if ( undefined != Item.WidthVisible ) { if ( para_Drawing != Item.Type || drawing_Inline === Item.DrawingType ) W += Item.WidthVisible; else Item.Draw_Selection(); } if ( Pos == EndPos - 1 ) { this.DrawingDocument.AddPageSelection(Page_abs, StartX, StartY, W, H); } } break; } case selectionflag_Numbering: { var ParaNum = this.Numbering; var NumberingPos = this.Numbering.Pos; if ( -1 === NumberingPos ) break; var ParaNumPos = this.Internal_Get_ParaPos_By_Pos(NumberingPos); if ( ParaNumPos.Page != CurPage ) break; var CurRange = ParaNumPos.Range; var CurLine = ParaNumPos.Line; var NumPr = this.Numbering_Get(); var SelectX = this.Lines[CurLine].Ranges[CurRange].XVisible; var SelectW = ParaNum.WidthVisible; var NumJc = this.Parent.Get_Numbering().Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl].Jc; switch ( NumJc ) { case align_Center: SelectX = this.Lines[CurLine].Ranges[CurRange].XVisible - ParaNum.WidthNum / 2; SelectW = ParaNum.WidthVisible + ParaNum.WidthNum / 2; break; case align_Right: SelectX = this.Lines[CurLine].Ranges[CurRange].XVisible - ParaNum.WidthNum; SelectW = ParaNum.WidthVisible + ParaNum.WidthNum; break; case align_Left: default: SelectX = this.Lines[CurLine].Ranges[CurRange].XVisible; SelectW = ParaNum.WidthVisible; break; } this.DrawingDocument.AddPageSelection(Page_abs, SelectX, this.Lines[CurLine].Top + this.Pages[CurPage].Y, SelectW, this.Lines[CurLine].Bottom - this.Lines[CurLine].Top); break; } } }, Selection_Check : function(X, Y, Page_Abs) { var PageIndex = Page_Abs - this.Get_StartPage_Absolute(); if ( PageIndex < 0 || PageIndex >= this.Pages.length || true != this.Selection.Use ) return false; var Start = this.Selection.StartPos; var End = this.Selection.EndPos; if ( Start > End ) { Start = this.Selection.EndPos; End = this.Selection.StartPos; } var ContentPos = this.Internal_GetContentPosByXY( X, Y, false, PageIndex + this.PageNum, false ); if ( -1 != ContentPos.Pos && Start <= ContentPos.Pos && End >= ContentPos.Pos ) return true; return false; }, Selection_CalculateTextPr : function() { if ( true === this.Selection.Use || true === this.ApplyToAll ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( true === this.ApplyToAll ) { StartPos = 0; EndPos = this.Content.length - 1; } if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( EndPos >= this.Content.length ) EndPos = this.Content.length - 1; if ( StartPos < 0 ) StartPos = 0; if ( StartPos == EndPos ) return this.Internal_CalculateTextPr( StartPos ); while ( this.Content[StartPos].Type == para_TextPr ) StartPos++; var oEnd = this.Internal_FindBackward( EndPos - 1, [ para_Text, para_Space ] ); if ( oEnd.Found ) EndPos = oEnd.LetterPos; else { while ( this.Content[EndPos].Type == para_TextPr ) EndPos--; } // Рассчитаем стиль в начале селекта var TextPr_start = this.Internal_CalculateTextPr( StartPos ); var TextPr_vis = TextPr_start; for ( var Pos = StartPos + 1; Pos < EndPos; Pos++ ) { var Item = this.Content[Pos]; if ( para_TextPr == Item.Type && Pos < this.Content.length - 1 && para_TextPr != this.Content[Pos + 1].Type ) { // Рассчитываем настройки в данной позиции var TextPr_cur = this.Internal_CalculateTextPr( Pos ); TextPr_vis = TextPr_vis.Compare( TextPr_cur ); } } return TextPr_vis; } else return new CTextPr(); }, Selection_SelectNumbering : function() { if ( undefined != this.Numbering_Get() ) { this.Selection.Use = true; this.Selection.Flag = selectionflag_Numbering; } }, Select_All : function() { this.Selection.Use = true; this.Selection.StartPos = this.Internal_GetStartPos(); this.Selection.EndPos = this.Content.length - 1; }, // Возвращаем выделенный текст Get_SelectedText : function(bClearText) { if ( true === this.ApplyToAll ) { var Str = ""; var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; switch ( Item.Type ) { case para_Drawing: case para_End: case para_Numbering: case para_PresentationNumbering: case para_PageNum: { if ( true === bClearText ) return null; break; } case para_Text : Str += Item.Value; break; case para_Space: case para_Tab : Str += " "; break; } } return Str; } if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( EndPos < StartPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } var Str = ""; for ( var Pos = StartPos; Pos < EndPos; Pos++ ) { var Item = this.Content[Pos]; switch ( Item.Type ) { case para_Drawing: case para_End: case para_Numbering: case para_PresentationNumbering: case para_PageNum: { if ( true === bClearText ) return null; break; } case para_Text : Str += Item.Value; break; case para_Space: case para_Tab : Str += " "; break; } } return Str; } return ""; }, Get_SelectedElementsInfo : function(Info) { Info.Set_Paragraph( this ); }, // Проверяем пустой ли параграф IsEmpty : function() { var Pos = this.Internal_FindForward( 0, [para_Tab, para_Drawing, para_PageNum, para_Text, para_Space, para_NewLine] ); return ( Pos.Found === true ? false : true ); }, // Проверяем, попали ли мы в текст Is_InText : function(X, Y, PageNum_Abs) { var PNum = PageNum_Abs - this.Get_StartPage_Absolute(); if ( PNum < 0 || PNum >= this.Pages.length ) return null; var Result = this.Internal_GetContentPosByXY( X, Y, false, PNum + this.PageNum, false); if ( true === Result.InText ) return this; return null; }, Is_UseInDocument : function() { if ( null != this.Parent ) return this.Parent.Is_UseInDocument(this.Get_Id()); return false; }, // Проверяем пустой ли селект Selection_IsEmpty : function(bCheckHidden) { if ( undefined === bCheckHidden ) bCheckHidden = true; // TODO: при добавлении новых элементов в параграф, добавить их сюда if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } var CheckArray = [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine]; if ( true === bCheckHidden ) CheckArray.push( para_End ); var Pos = this.Internal_FindForward( StartPos, CheckArray ); if ( true != Pos.Found ) return true; if ( Pos.LetterPos >= EndPos ) return true; return false; } return true; }, //----------------------------------------------------------------------------------- // Функции для работы с нумерацией параграфов в документах //----------------------------------------------------------------------------------- // Добавляем нумерацию к данному параграфу Numbering_Add : function(NumId, Lvl) { var ParaPr = this.Get_CompiledPr2(false).ParaPr; var NumPr_old = this.Numbering_Get(); this.Numbering_Remove(); var SelectionUse = this.Is_SelectionUse(); var SelectedOneElement = this.Parent.Selection_Is_OneElement(); // Рассчитаем количество табов, идущих в начале параграфа var Count = this.Content.length; var TabsCount = 0; var TabsPos = new Array(); for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; var ItemType = Item.Type; if ( para_Tab === ItemType ) { TabsCount++; TabsPos.push( Pos ); } else if ( para_Text === ItemType || para_Space === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType ) break; } // Рассчитаем левую границу и сдвиг первой строки с учетом начальных табов var X = ParaPr.Ind.Left + ParaPr.Ind.FirstLine; var LeftX = X; if ( TabsCount > 0 && ParaPr.Ind.FirstLine < 0 ) { X = ParaPr.Ind.Left; LeftX = X; TabsCount--; } var ParaTabsCount = ParaPr.Tabs.Get_Count(); while ( TabsCount ) { // Ищем ближайший таб var TabFound = false; for ( var TabIndex = 0; TabIndex < ParaTabsCount; TabIndex++ ) { var Tab = ParaPr.Tabs.Get(TabIndex); if ( Tab.Pos > X ) { X = Tab.Pos; TabFound = true; break; } } // Ищем по дефолтовому сдвигу if ( false === TabFound ) { var NewX = 0; while ( X >= NewX ) NewX += Default_Tab_Stop; X = NewX; } TabsCount--; } var Numbering = this.Parent.Get_Numbering(); var AbstractNum = Numbering.Get_AbstractNum(NumId); // Если у параграфа не было никакой нумерации изначально if ( undefined === NumPr_old ) { if ( true === SelectedOneElement || false === SelectionUse ) { // Проверим сначала предыдущий элемент, если у него точно такая же нумерация, тогда копируем его сдвиги var Prev = this.Get_DocumentPrev(); var PrevNumbering = ( null != Prev ? (type_Paragraph === Prev.GetType() ? Prev.Numbering_Get() : undefined) : undefined ); if ( undefined != PrevNumbering && NumId === PrevNumbering.NumId && Lvl === PrevNumbering.Lvl ) { var NewFirstLine = Prev.Pr.Ind.FirstLine; var NewLeft = Prev.Pr.Ind.Left; History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : NewFirstLine } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : NewLeft } ); // При добавлении списка в параграф, удаляем все собственные сдвиги this.Pr.Ind.FirstLine = NewFirstLine; this.Pr.Ind.Left = NewLeft; } else { // Выставляем заданную нумерацию и сдвиги Ind.Left = X + NumPr.ParaPr.Ind.Left var NumLvl = AbstractNum.Lvl[Lvl]; var NumParaPr = NumLvl.ParaPr; if ( undefined != NumParaPr.Ind && undefined != NumParaPr.Ind.Left ) { AbstractNum.Change_LeftInd( X + NumParaPr.Ind.Left ); History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : undefined } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : undefined } ); // При добавлении списка в параграф, удаляем все собственные сдвиги this.Pr.Ind.FirstLine = undefined; this.Pr.Ind.Left = undefined; } } this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, Lvl ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr_old, New : this.Pr.NumPr } ); } else { // Если выделено несколько параграфов, тогда уже по сдвигу X определяем уровень данной нумерации var LvlFound = -1; var LvlsCount = AbstractNum.Lvl.length; for ( var LvlIndex = 0; LvlIndex < LvlsCount; LvlIndex++ ) { var NumLvl = AbstractNum.Lvl[LvlIndex]; var NumParaPr = NumLvl.ParaPr; if ( undefined != NumParaPr.Ind && undefined != NumParaPr.Ind.Left && X <= NumParaPr.Ind.Left ) { LvlFound = LvlIndex; break; } } if ( -1 === LvlFound ) LvlFound = LvlsCount - 1; if ( undefined != this.Pr.Ind && undefined != NumParaPr.Ind && undefined != NumParaPr.Ind.Left ) { History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : undefined } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : undefined } ); // При добавлении списка в параграф, удаляем все собственные сдвиги this.Pr.Ind.FirstLine = undefined; this.Pr.Ind.Left = undefined; } this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, LvlFound ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr_old, New : this.Pr.NumPr } ); } // Удалим все табы идущие в начале параграфа TabsCount = TabsPos.length; while ( TabsCount ) { var Pos = TabsPos[TabsCount - 1]; this.Internal_Content_Remove( Pos ); TabsCount--; } } else { // просто меняем список, так чтобы он не двигался this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, Lvl ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr_old, New : this.Pr.NumPr } ); var Left = ParaPr.Ind.Left; var FirstLine = ParaPr.Ind.FirstLine; History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : Left } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : FirstLine } ); this.Pr.Ind.FirstLine = FirstLine; this.Pr.Ind.Left = Left; } // Если у параграфа выставлен стиль, тогда не меняем его, если нет, тогда выставляем стандартный // стиль для параграфа с нумерацией. if ( undefined === this.Style_Get() ) { this.Style_Add( this.Parent.Get_Styles().Get_Default_ParaList() ); } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Добавляем нумерацию к данному параграфу, не делая никаких дополнительных действий Numbering_Set : function(NumId, Lvl) { var NumPr_old = this.Pr.NumPr; this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, Lvl ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr_old, New : this.Pr.NumPr } ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Изменяем уровень нумерации Numbering_IndDec_Level : function(bIncrease) { var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { var NewLvl; if ( true === bIncrease ) NewLvl = Math.min( 8, NumPr.Lvl + 1 ); else NewLvl = Math.max( 0, NumPr.Lvl - 1 ); this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumPr.NumId, NewLvl ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr, New : this.Pr.NumPr } ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, // Добавление нумерации в параграф при открытии и копировании Numbering_Add_Open : function(NumId, Lvl) { this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, Lvl ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Numbering_Get : function() { var NumPr = this.Get_CompiledPr2(false).ParaPr.NumPr; if ( undefined != NumPr && 0 != NumPr.NumId ) return NumPr.Copy(); return undefined; }, // Удаляем нумерацию Numbering_Remove : function() { // Если у нас была задана нумерации в стиле, тогда чтобы ее отменить(не удаляя нумерацию в стиле) // мы проставляем NumPr с NumId undefined var OldNumPr = this.Numbering_Get(); var NewNumPr = undefined; if ( undefined != this.CompiledPr.Pr.ParaPr.StyleNumPr ) { NewNumPr = new CNumPr(); NewNumPr.Set( 0, 0 ); } History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : undefined != this.Pr.NumPr ? this.Pr.NumPr : undefined, New : NewNumPr } ); this.Pr.NumPr = NewNumPr; if ( undefined != this.Pr.Ind && undefined != OldNumPr ) { // При удалении нумерации из параграфа, если отступ первой строки > 0, тогда // увеличиваем левый отступ параграфа, а первую сторку делаем 0, а если отступ // первой строки < 0, тогда просто делаем оступ первой строки 0. if ( undefined === this.Pr.Ind.FirstLine || Math.abs( this.Pr.Ind.FirstLine ) < 0.001 ) { if ( undefined != OldNumPr && undefined != OldNumPr.NumId ) { var Lvl = this.Parent.Get_Numbering().Get_AbstractNum(OldNumPr.NumId).Lvl[OldNumPr.Lvl]; if ( undefined != Lvl && undefined != Lvl.ParaPr.Ind && undefined != Lvl.ParaPr.Ind.Left ) { var CurParaPr = this.Get_CompiledPr2(false).ParaPr; var Left = CurParaPr.Ind.Left + CurParaPr.Ind.FirstLine; History.Add( this, { Type : historyitem_Paragraph_Ind_Left, New : Left, Old : this.Pr.Ind.Left } ); History.Add( this, { Type : historyitem_Paragraph_Ind_First, New : 0, Old : this.Pr.Ind.FirstLine } ); this.Pr.Ind.Left = Left; this.Pr.Ind.FirstLine = 0; } } } else if ( this.Pr.Ind.FirstLine < 0 ) { History.Add( this, { Type : historyitem_Paragraph_Ind_First, New : 0, Old : this.Pr.Ind.FirstLine } ); this.Pr.Ind.FirstLine = 0; } else if ( undefined != this.Pr.Ind.Left && this.Pr.Ind.FirstLine > 0 ) { History.Add( this, { Type : historyitem_Paragraph_Ind_Left, New : this.Pr.Ind.Left + this.Pr.Ind.FirstLine, Old : this.Pr.Ind.Left } ); History.Add( this, { Type : historyitem_Paragraph_Ind_First, New : 0, Old : this.Pr.Ind.FirstLine } ); this.Pr.Ind.Left += this.Pr.Ind.FirstLine; this.Pr.Ind.FirstLine = 0; } } // При удалении проверяем стиль. Если данный стиль является стилем по умолчанию // для параграфов с нумерацией, тогда удаляем запись и о стиле. var StyleId = this.Style_Get(); var NumStyleId = this.Parent.Get_Styles().Get_Default_ParaList(); if ( StyleId === NumStyleId ) this.Style_Remove(); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Используется ли заданная нумерация в параграфе Numbering_IsUse: function(NumId, Lvl) { var bLvl = (undefined === Lvl ? false : true); var NumPr = this.Numbering_Get(); if ( undefined != NumPr && NumId === NumPr.NumId && ( false === bLvl || Lvl === NumPr.Lvl ) ) return true; return false; }, //----------------------------------------------------------------------------------- // Функции для работы с нумерацией параграфов в презентациях //----------------------------------------------------------------------------------- // Добавляем нумерацию к данному параграфу Add_PresentationNumbering : function(_Bullet) { var Bullet = _Bullet.Copy(); History.Add( this, { Type : historyitem_Paragraph_PresentationPr_Bullet, New : Bullet, Old : this.PresentationPr.Bullet } ); var OldType = this.PresentationPr.Bullet.Get_Type(); var NewType = Bullet.Get_Type(); this.PresentationPr.Bullet = Bullet; if ( OldType != NewType ) { var ParaPr = this.Get_CompiledPr2(false).ParaPr; var LeftInd = Math.min( ParaPr.Ind.Left, ParaPr.Ind.Left + ParaPr.Ind.FirstLine ); if ( numbering_presentationnumfrmt_None === NewType ) { this.Set_Ind( { FirstLine : 0, Left : LeftInd } ); } else if ( numbering_presentationnumfrmt_RomanLcPeriod === NewType || numbering_presentationnumfrmt_RomanUcPeriod === NewType ) { this.Set_Ind( { Left : LeftInd + 15.9, FirstLine : -15.9 } ); } else { this.Set_Ind( { Left : LeftInd + 14.3, FirstLine : -14.3 } ); } } }, Get_PresentationNumbering : function() { return this.PresentationPr.Bullet; }, // Удаляем нумерацию Remove_PresentationNumbering : function() { this.Add_PresentationNumbering( new CPresentationBullet() ); }, Set_PresentationLevel : function(Level) { if ( this.PresentationPr.Level != Level ) { History.Add( this, { Type : historyitem_Paragraph_PresentationPr_Level, Old : this.PresentationPr.Level, New : Level } ); this.PresentationPr.Level = Level; } }, //----------------------------------------------------------------------------------- // Формируем конечные свойства параграфа на основе стиля, возможной нумерации и прямых настроек. // Также учитываем настройки предыдущего и последующего параграфов. Get_CompiledPr : function() { var Pr = this.Get_CompiledPr2(); // При формировании конечных настроек параграфа, нужно учитывать предыдущий и последующий // параграфы. Например, для формирования интервала между параграфами. // max(Prev.After, Cur.Before) - реальное значение расстояния между параграфами. // Поэтому Prev.After = Prev.After (значение не меняем), а вот Cur.Before = max(Prev.After, Cur.Before) - Prev.After var StyleId = this.Style_Get(); var PrevEl = this.Get_DocumentPrev(); var NextEl = this.Get_DocumentNext(); var NumPr = this.Numbering_Get(); if ( null != PrevEl && type_Paragraph === PrevEl.GetType() ) { var PrevStyle = PrevEl.Style_Get(); var Prev_Pr = PrevEl.Get_CompiledPr2(false).ParaPr; var Prev_After = Prev_Pr.Spacing.After; var Prev_AfterAuto = Prev_Pr.Spacing.AfterAutoSpacing; var Cur_Before = Pr.ParaPr.Spacing.Before; var Cur_BeforeAuto = Pr.ParaPr.Spacing.BeforeAutoSpacing; var Prev_NumPr = PrevEl.Numbering_Get(); if ( PrevStyle === StyleId && true === Pr.ParaPr.ContextualSpacing ) { Pr.ParaPr.Spacing.Before = 0; } else { if ( true === Cur_BeforeAuto && PrevStyle === StyleId && undefined != Prev_NumPr && undefined != NumPr && Prev_NumPr.NumId === NumPr.NumId ) Pr.ParaPr.Spacing.Before = 0; else { Cur_Before = this.Internal_CalculateAutoSpacing( Cur_Before, Cur_BeforeAuto, this ); Prev_After = this.Internal_CalculateAutoSpacing( Prev_After, Prev_AfterAuto, this ); if ( true === Prev_Pr.ContextualSpacing && PrevStyle === StyleId ) Prev_After = 0; Pr.ParaPr.Spacing.Before = Math.max( Prev_After, Cur_Before ) - Prev_After; } } if ( false === this.Internal_Is_NullBorders(Pr.ParaPr.Brd) && true === this.Internal_CompareBrd( Prev_Pr, Pr.ParaPr ) ) Pr.ParaPr.Brd.First = false; else Pr.ParaPr.Brd.First = true; } else if ( null === PrevEl ) { if ( true === Pr.ParaPr.Spacing.BeforeAutoSpacing ) { Pr.ParaPr.Spacing.Before = 0; } } else if ( type_Table === PrevEl.GetType() ) { if ( true === Pr.ParaPr.Spacing.BeforeAutoSpacing ) { Pr.ParaPr.Spacing.Before = 14 * g_dKoef_pt_to_mm; } } if ( null != NextEl ) { if ( type_Paragraph === NextEl.GetType() ) { var NextStyle = NextEl.Style_Get(); var Next_Pr = NextEl.Get_CompiledPr2(false).ParaPr; var Next_Before = Next_Pr.Spacing.Before; var Next_BeforeAuto = Next_Pr.Spacing.BeforeAutoSpacing; var Cur_After = Pr.ParaPr.Spacing.After; var Cur_AfterAuto = Pr.ParaPr.Spacing.AfterAutoSpacing; var Next_NumPr = NextEl.Numbering_Get(); if ( NextStyle === StyleId && true === Pr.ParaPr.ContextualSpacing ) { Pr.ParaPr.Spacing.After = 0; } else { if ( true === Cur_AfterAuto && NextStyle === StyleId && undefined != Next_NumPr && undefined != NumPr && Next_NumPr.NumId === NumPr.NumId ) Pr.ParaPr.Spacing.After = 0; else { Pr.ParaPr.Spacing.After = this.Internal_CalculateAutoSpacing( Cur_After, Cur_AfterAuto, this ); } } if ( false === this.Internal_Is_NullBorders(Pr.ParaPr.Brd) && true === this.Internal_CompareBrd( Next_Pr, Pr.ParaPr ) ) Pr.ParaPr.Brd.Last = false; else Pr.ParaPr.Brd.Last = true; } else if ( type_Table === NextEl.GetType() ) { var TableFirstParagraph = NextEl.Get_FirstParagraph(); if ( null != TableFirstParagraph && undefined != TableFirstParagraph ) { var NextStyle = TableFirstParagraph.Style_Get(); var Next_Before = TableFirstParagraph.Get_CompiledPr2(false).ParaPr.Spacing.Before; var Next_BeforeAuto = TableFirstParagraph.Get_CompiledPr2(false).ParaPr.Spacing.BeforeAutoSpacing; var Cur_After = Pr.ParaPr.Spacing.After; var Cur_AfterAuto = Pr.ParaPr.Spacing.AfterAutoSpacing; if ( NextStyle === StyleId && true === Pr.ParaPr.ContextualSpacing ) { Cur_After = this.Internal_CalculateAutoSpacing( Cur_After, Cur_AfterAuto, this ); Next_Before = this.Internal_CalculateAutoSpacing( Next_Before, Next_BeforeAuto, this ); Pr.ParaPr.Spacing.After = Math.max( Next_Before, Cur_After ) - Cur_After; } else { Pr.ParaPr.Spacing.After = this.Internal_CalculateAutoSpacing( Pr.ParaPr.Spacing.After, Cur_AfterAuto, this ); } } } } else { Pr.ParaPr.Spacing.After = this.Internal_CalculateAutoSpacing( Pr.ParaPr.Spacing.After, Pr.ParaPr.Spacing.AfterAutoSpacing, this ); } return Pr; }, Recalc_CompiledPr : function() { this.CompiledPr.NeedRecalc = true; }, // Формируем конечные свойства параграфа на основе стиля, возможной нумерации и прямых настроек. // Без пересчета расстояния между параграфами. Get_CompiledPr2 : function(bCopy) { if ( true === this.CompiledPr.NeedRecalc ) { this.CompiledPr.Pr = this.Internal_CompileParaPr(); this.CompiledPr.NeedRecalc = false; } if ( false === bCopy ) return this.CompiledPr.Pr; else { // Отдаем копию объекта, чтобы никто не поменял извне настройки скомпилированного стиля var Pr = {}; Pr.TextPr = this.CompiledPr.Pr.TextPr.Copy(); Pr.ParaPr = this.CompiledPr.Pr.ParaPr.Copy(); return Pr; } }, // Формируем конечные свойства параграфа на основе стиля, возможной нумерации и прямых настроек. Internal_CompileParaPr : function() { var Styles = this.Parent.Get_Styles(); var Numbering = this.Parent.Get_Numbering(); var TableStyle = this.Parent.Get_TableStyleForPara(); var StyleId = this.Style_Get(); // Считываем свойства для текущего стиля var Pr = Styles.Get_Pr( StyleId, styletype_Paragraph, TableStyle ); // Если в стиле была задана нумерация сохраним это в специальном поле if ( undefined != Pr.ParaPr.NumPr ) Pr.ParaPr.StyleNumPr = Pr.ParaPr.NumPr.Copy(); var Lvl = -1; if ( undefined != this.Pr.NumPr ) { if ( undefined != this.Pr.NumPr.NumId && 0 != this.Pr.NumPr.NumId ) { Pr.ParaPr.Merge( Numbering.Get_ParaPr( this.Pr.NumPr.NumId, this.Pr.NumPr.Lvl ) ); Lvl = this.Pr.NumPr.Lvl; } } else if ( undefined != Pr.ParaPr.NumPr ) { if ( undefined != Pr.ParaPr.NumPr.NumId && 0 != Pr.ParaPr.NumPr.NumId ) { var AbstractNum = Numbering.Get_AbstractNum( Pr.ParaPr.NumPr.NumId ); Lvl = AbstractNum.Get_LvlByStyle( StyleId ); if ( -1 != Lvl ) {} else Pr.ParaPr.NumPr = undefined; } } Pr.ParaPr.StyleTabs = ( undefined != Pr.ParaPr.Tabs ? Pr.ParaPr.Tabs.Copy() : new CParaTabs() ); // Копируем прямые настройки параграфа. Pr.ParaPr.Merge( this.Pr ); if ( -1 != Lvl && undefined != Pr.ParaPr.NumPr ) Pr.ParaPr.NumPr.Lvl = Lvl; // Настройки рамки не наследуются if ( undefined === this.Pr.FramePr ) Pr.ParaPr.FramePr = undefined; else Pr.ParaPr.FramePr = this.Pr.FramePr.Copy(); return Pr; }, // Сообщаем параграфу, что ему надо будет пересчитать скомпилированный стиль // (Такое может случится, если у данного параграфа есть нумерация или задан стиль, // которые меняются каким-то внешним образом) Recalc_CompileParaPr : function() { this.CompiledPr.NeedRecalc = true; }, Internal_CalculateAutoSpacing : function(Value, UseAuto, Para) { var Result = Value; if ( true === UseAuto ) { if ( true === Para.Parent.Is_TableCellContent() ) Result = 0; else Result = 14 * g_dKoef_pt_to_mm; } return Result; }, Get_Paragraph_ParaPr_Copy : function() { var ParaPr = this.Pr.Copy(); return ParaPr; }, Paragraph_Format_Paste : function(TextPr, ParaPr, ApplyPara) { // Применяем текстовые настройки всегда if ( null != TextPr ) this.Add( new ParaTextPr( TextPr ) ); var _ApplyPara = ApplyPara; if ( false === _ApplyPara ) { if ( true === this.Selection.Use ) { _ApplyPara = true; var Start = this.Selection.StartPos; var End = this.Selection.EndPos; if ( Start > End ) { Start = this.Selection.EndPos; End = this.Selection.StartPos; } if ( true === this.Internal_FindForward( End, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End]).Found ) _ApplyPara = false; else if ( true === this.Internal_FindBackward( Start - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End]).Found ) _ApplyPara = false; } else _ApplyPara = true; } // Применяем настройки параграфа if ( true === _ApplyPara && null != ParaPr ) { // Ind if ( undefined != ParaPr.Ind ) this.Set_Ind( ParaPr.Ind, false ); // Jc if ( undefined != ParaPr.Jc ) this.Set_Align( ParaPr.Jc ); // Spacing if ( undefined != ParaPr.Spacing ) this.Set_Spacing( ParaPr.Spacing, false ); // PageBreakBefore if ( undefined != ParaPr.PageBreakBefore ) this.Set_PageBreakBefore( ParaPr.PageBreakBefore ); // KeepLines if ( undefined != ParaPr.KeepLines ) this.Set_KeepLines( ParaPr.KeepLines ); // ContextualSpacing if ( undefined != ParaPr.ContextualSpacing ) this.Set_ContextualSpacing( ParaPr.ContextualSpacing ); // Shd if ( undefined != ParaPr.Shd ) this.Set_Shd( ParaPr.Shd, false ); // NumPr if ( undefined != ParaPr.NumPr ) this.Numbering_Set( ParaPr.NumPr.NumId, ParaPr.NumPr.Lvl ); else this.Numbering_Remove(); // StyleId if ( undefined != ParaPr.PStyle ) this.Style_Add( ParaPr.PStyle, true ); else this.Style_Remove(); // Brd if ( undefined != ParaPr.Brd ) this.Set_Borders( ParaPr.Brd ); } }, Style_Get : function() { if ( undefined != this.Pr.PStyle ) return this.Pr.PStyle; return undefined; }, Style_Add : function(Id, bDoNotDeleteProps) { this.RecalcInfo.Set_Type_0(pararecalc_0_All); var Id_old = this.Pr.PStyle; if ( undefined === this.Pr.PStyle ) Id_old = null; else this.Style_Remove(); if ( null === Id ) return; // Если стиль является стилем по умолчанию для параграфа, тогда не надо его записывать. if ( Id != this.Parent.Get_Styles().Get_Default_Paragraph() ) { History.Add( this, { Type : historyitem_Paragraph_PStyle, Old : Id_old, New : Id } ); this.Pr.PStyle = Id; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; if ( true === bDoNotDeleteProps ) return; // TODO: По мере добавления элементов в стили параграфа и текста добавить их обработку здесь. // Не удаляем форматирование, при добавлении списка к данному параграфу var DefNumId = this.Parent.Get_Styles().Get_Default_ParaList(); if ( Id != DefNumId && ( Id_old != DefNumId || Id != this.Parent.Get_Styles().Get_Default_Paragraph() ) ) { this.Set_ContextualSpacing( undefined ); this.Set_Ind( new CParaInd(), true ); this.Set_Align( undefined ); this.Set_KeepLines( undefined ); this.Set_KeepNext( undefined ); this.Set_PageBreakBefore( undefined ); this.Set_Spacing( new CParaSpacing(), true ); this.Set_Shd( undefined, true ); this.Set_WidowControl( undefined ); this.Set_Tabs( new CParaTabs() ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Between ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Bottom ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Left ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Right ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Top ); // При изменении стиля убираются только те текстовые настроки внутри параграфа, // которые присутствуют в стиле. Пока мы удалим вообще все настроки. // TODO : переделать for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { this.Internal_Content_Remove( Index ); Index--; } } } }, // Добавление стиля в параграф при открытии и копировании Style_Add_Open : function(Id) { this.Pr.PStyle = Id; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Style_Remove : function() { if ( undefined != this.Pr.PStyle ) { History.Add( this, { Type : historyitem_Paragraph_PStyle, Old : this.Pr.PStyle, New : undefined } ); this.Pr.PStyle = undefined; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Проверяем находится ли курсор в конце параграфа Cursor_IsEnd : function(ContentPos) { if ( undefined === ContentPos ) ContentPos = this.CurPos.ContentPos; var oPos = this.Internal_FindForward( ContentPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( true === oPos.Found ) return false; else return true; }, // Проверяем находится ли курсор в начале параграфа Cursor_IsStart : function(ContentPos) { if ( undefined === ContentPos ) ContentPos = this.CurPos.ContentPos; var oPos = this.Internal_FindBackward( ContentPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( true === oPos.Found ) return false; else return true; }, // Проверим, начинается ли выделение с начала параграфа Selection_IsFromStart : function() { if ( true === this.Is_SelectionUse() ) { var StartPos = ( this.Selection.StartPos > this.Selection.EndPos ? this.Selection.EndPos : this.Selection.StartPos ); if ( true != this.Cursor_IsStart( StartPos ) ) return false; return true; } return false; }, // Очищение форматирования параграфа Clear_Formatting : function() { this.Style_Remove(); this.Numbering_Remove(); this.Set_ContextualSpacing(undefined); this.Set_Ind( new CParaInd(), true ); this.Set_Align( undefined, false ); this.Set_KeepLines( undefined ); this.Set_KeepNext( undefined ); this.Set_PageBreakBefore( undefined ); this.Set_Spacing( new CParaSpacing(), true ); this.Set_Shd( new CDocumentShd(), true ); this.Set_WidowControl( undefined ); this.Set_Tabs( new CParaTabs() ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Between ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Bottom ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Left ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Right ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Top ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Clear_TextFormatting : function() { var Styles = this.Parent.Get_Styles(); var DefHyper = Styles.Get_Default_Hyperlink(); // TODO: Сделать, чтобы данная функция работала по выделению for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { Item.Set_Bold( undefined ); Item.Set_Italic( undefined ); Item.Set_Strikeout( undefined ); Item.Set_Underline( undefined ); Item.Set_FontFamily( undefined ); Item.Set_FontSize( undefined ); Item.Set_Color( undefined ); Item.Set_VertAlign( undefined ); Item.Set_HighLight( undefined ); Item.Set_Spacing( undefined ); Item.Set_DStrikeout( undefined ); Item.Set_Caps( undefined ); Item.Set_SmallCaps( undefined ); Item.Set_Position( undefined ); Item.Set_RFonts2( undefined ); Item.Set_Lang( undefined ); if ( undefined === Item.Value.RStyle || Item.Value.RStyle != DefHyper ) { Item.Set_RStyle( undefined ); } } } }, Set_Ind : function(Ind, bDeleteUndefined) { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); if ( ( undefined != Ind.FirstLine || true === bDeleteUndefined ) && this.Pr.Ind.FirstLine !== Ind.FirstLine ) { History.Add( this, { Type : historyitem_Paragraph_Ind_First, New : Ind.FirstLine, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ) } ); this.Pr.Ind.FirstLine = Ind.FirstLine; } if ( ( undefined != Ind.Left || true === bDeleteUndefined ) && this.Pr.Ind.Left !== Ind.Left ) { History.Add( this, { Type : historyitem_Paragraph_Ind_Left, New : Ind.Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ) } ); this.Pr.Ind.Left = Ind.Left; } if ( ( undefined != Ind.Right || true === bDeleteUndefined ) && this.Pr.Ind.Right !== Ind.Right ) { History.Add( this, { Type : historyitem_Paragraph_Ind_Right, New : Ind.Right, Old : ( undefined != this.Pr.Ind.Right ? this.Pr.Ind.Right : undefined ) } ); this.Pr.Ind.Right = Ind.Right; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_Spacing : function(Spacing, bDeleteUndefined) { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( ( undefined != Spacing.Line || true === bDeleteUndefined ) && this.Pr.Spacing.Line !== Spacing.Line ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_Line, New : Spacing.Line, Old : ( undefined != this.Pr.Spacing.Line ? this.Pr.Spacing.Line : undefined ) } ); this.Pr.Spacing.Line = Spacing.Line; } if ( ( undefined != Spacing.LineRule || true === bDeleteUndefined ) && this.Pr.Spacing.LineRule !== Spacing.LineRule ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_LineRule, New : Spacing.LineRule, Old : ( undefined != this.Pr.Spacing.LineRule ? this.Pr.Spacing.LineRule : undefined ) } ); this.Pr.Spacing.LineRule = Spacing.LineRule; } if ( ( undefined != Spacing.Before || true === bDeleteUndefined ) && this.Pr.Spacing.Before !== Spacing.Before ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_Before, New : Spacing.Before, Old : ( undefined != this.Pr.Spacing.Before ? this.Pr.Spacing.Before : undefined ) } ); this.Pr.Spacing.Before = Spacing.Before; } if ( ( undefined != Spacing.After || true === bDeleteUndefined ) && this.Pr.Spacing.After !== Spacing.After ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_After, New : Spacing.After, Old : ( undefined != this.Pr.Spacing.After ? this.Pr.Spacing.After : undefined ) } ); this.Pr.Spacing.After = Spacing.After; } if ( ( undefined != Spacing.AfterAutoSpacing || true === bDeleteUndefined ) && this.Pr.Spacing.AfterAutoSpacing !== Spacing.AfterAutoSpacing ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_AfterAutoSpacing, New : Spacing.AfterAutoSpacing, Old : ( undefined != this.Pr.Spacing.AfterAutoSpacing ? this.Pr.Spacing.AfterAutoSpacing : undefined ) } ); this.Pr.Spacing.AfterAutoSpacing = Spacing.AfterAutoSpacing; } if ( ( undefined != Spacing.BeforeAutoSpacing || true === bDeleteUndefined ) && this.Pr.Spacing.BeforeAutoSpacing !== Spacing.BeforeAutoSpacing ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_BeforeAutoSpacing, New : Spacing.BeforeAutoSpacing, Old : ( undefined != this.Pr.Spacing.BeforeAutoSpacing ? this.Pr.Spacing.BeforeAutoSpacing : undefined ) } ); this.Pr.Spacing.BeforeAutoSpacing = Spacing.BeforeAutoSpacing; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_Align : function(Align) { if ( this.Pr.Jc != Align ) { History.Add( this, { Type : historyitem_Paragraph_Align, New : Align, Old : ( undefined != this.Pr.Jc ? this.Pr.Jc : undefined ) } ); this.Pr.Jc = Align; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_Shd : function(_Shd, bDeleteUndefined) { if ( undefined === _Shd ) { if ( undefined != this.Pr.Shd ) { History.Add( this, { Type : historyitem_Paragraph_Shd, New : undefined, Old : this.Pr.Shd } ); this.Pr.Shd = undefined; } } else { var Shd = new CDocumentShd(); Shd.Set_FromObject( _Shd ); if ( undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( ( undefined != Shd.Value || true === bDeleteUndefined ) && this.Pr.Shd.Value !== Shd.Value ) { History.Add( this, { Type : historyitem_Paragraph_Shd_Value, New : Shd.Value, Old : ( undefined != this.Pr.Shd.Value ? this.Pr.Shd.Value : undefined ) } ); this.Pr.Shd.Value = Shd.Value; } if ( undefined != Shd.Color || true === bDeleteUndefined ) { History.Add( this, { Type : historyitem_Paragraph_Shd_Color, New : Shd.Color, Old : ( undefined != this.Pr.Shd.Color ? this.Pr.Shd.Color : undefined ) } ); this.Pr.Shd.Color = Shd.Color; } } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_Tabs : function(Tabs) { var _Tabs = new CParaTabs(); var StyleTabs = this.Get_CompiledPr2(false).ParaPr.StyleTabs; // 1. Ищем табы, которые уже есть в стиле (такие добавлять не надо) for ( var Index = 0; Index < Tabs.Tabs.length; Index++ ) { var Value = StyleTabs.Get_Value( Tabs.Tabs[Index].Pos ); if ( -1 === Value ) _Tabs.Add( Tabs.Tabs[Index] ); } // 2. Ищем табы в стиле, которые нужно отменить for ( var Index = 0; Index < StyleTabs.Tabs.length; Index++ ) { var Value = _Tabs.Get_Value( StyleTabs.Tabs[Index].Pos ); if ( tab_Clear != StyleTabs.Tabs[Index] && -1 === Value ) _Tabs.Add( new CParaTab(tab_Clear, StyleTabs.Tabs[Index].Pos ) ); } History.Add( this, { Type : historyitem_Paragraph_Tabs, New : _Tabs, Old : this.Pr.Tabs } ); this.Pr.Tabs = _Tabs; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_ContextualSpacing : function(Value) { if ( Value != this.Pr.ContextualSpacing ) { History.Add( this, { Type : historyitem_Paragraph_ContextualSpacing, New : Value, Old : ( undefined != this.Pr.ContextualSpacing ? this.Pr.ContextualSpacing : undefined ) } ); this.Pr.ContextualSpacing = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_PageBreakBefore : function(Value) { if ( Value != this.Pr.PageBreakBefore ) { History.Add( this, { Type : historyitem_Paragraph_PageBreakBefore, New : Value, Old : ( undefined != this.Pr.PageBreakBefore ? this.Pr.PageBreakBefore : undefined ) } ); this.Pr.PageBreakBefore = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_KeepLines : function(Value) { if ( Value != this.Pr.KeepLines ) { History.Add( this, { Type : historyitem_Paragraph_KeepLines, New : Value, Old : ( undefined != this.Pr.KeepLines ? this.Pr.KeepLines : undefined ) } ); this.Pr.KeepLines = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_KeepNext : function(Value) { if ( Value != this.Pr.KeepNext ) { History.Add( this, { Type : historyitem_Paragraph_KeepNext, New : Value, Old : ( undefined != this.Pr.KeepNext ? this.Pr.KeepNext : undefined ) } ); this.Pr.KeepNext = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_WidowControl : function(Value) { if ( Value != this.Pr.WidowControl ) { History.Add( this, { Type : historyitem_Paragraph_WidowControl, New : Value, Old : ( undefined != this.Pr.WidowControl ? this.Pr.WidowControl : undefined ) } ); this.Pr.WidowControl = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_Borders : function(Borders) { if ( undefined === Borders ) return; var OldBorders = this.Get_CompiledPr2(false).ParaPr.Brd; if ( undefined != Borders.Between ) { var NewBorder = undefined; if ( undefined != Borders.Between.Value /*&& border_Single === Borders.Between.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Between.Color ? new CDocumentColor( Borders.Between.Color.r, Borders.Between.Color.g, Borders.Between.Color.b ) : new CDocumentColor( OldBorders.Between.Color.r, OldBorders.Between.Color.g, OldBorders.Between.Color.b ) ); NewBorder.Space = ( undefined != Borders.Between.Space ? Borders.Between.Space : OldBorders.Between.Space ); NewBorder.Size = ( undefined != Borders.Between.Size ? Borders.Between.Size : OldBorders.Between.Size ); NewBorder.Value = ( undefined != Borders.Between.Value ? Borders.Between.Value : OldBorders.Between.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Between, New : NewBorder, Old : this.Pr.Brd.Between } ); this.Pr.Brd.Between = NewBorder; } if ( undefined != Borders.Top ) { var NewBorder = undefined; if ( undefined != Borders.Top.Value /*&& border_Single === Borders.Top.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Top.Color ? new CDocumentColor( Borders.Top.Color.r, Borders.Top.Color.g, Borders.Top.Color.b ) : new CDocumentColor( OldBorders.Top.Color.r, OldBorders.Top.Color.g, OldBorders.Top.Color.b ) ); NewBorder.Space = ( undefined != Borders.Top.Space ? Borders.Top.Space : OldBorders.Top.Space ); NewBorder.Size = ( undefined != Borders.Top.Size ? Borders.Top.Size : OldBorders.Top.Size ); NewBorder.Value = ( undefined != Borders.Top.Value ? Borders.Top.Value : OldBorders.Top.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Top, New : NewBorder, Old : this.Pr.Brd.Top } ); this.Pr.Brd.Top = NewBorder; } if ( undefined != Borders.Right ) { var NewBorder = undefined; if ( undefined != Borders.Right.Value /*&& border_Single === Borders.Right.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Right.Color ? new CDocumentColor( Borders.Right.Color.r, Borders.Right.Color.g, Borders.Right.Color.b ) : new CDocumentColor( OldBorders.Right.Color.r, OldBorders.Right.Color.g, OldBorders.Right.Color.b ) ); NewBorder.Space = ( undefined != Borders.Right.Space ? Borders.Right.Space : OldBorders.Right.Space ); NewBorder.Size = ( undefined != Borders.Right.Size ? Borders.Right.Size : OldBorders.Right.Size ); NewBorder.Value = ( undefined != Borders.Right.Value ? Borders.Right.Value : OldBorders.Right.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Right, New : NewBorder, Old : this.Pr.Brd.Right } ); this.Pr.Brd.Right = NewBorder; } if ( undefined != Borders.Bottom ) { var NewBorder = undefined; if ( undefined != Borders.Bottom.Value /*&& border_Single === Borders.Bottom.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Bottom.Color ? new CDocumentColor( Borders.Bottom.Color.r, Borders.Bottom.Color.g, Borders.Bottom.Color.b ) : new CDocumentColor( OldBorders.Bottom.Color.r, OldBorders.Bottom.Color.g, OldBorders.Bottom.Color.b ) ); NewBorder.Space = ( undefined != Borders.Bottom.Space ? Borders.Bottom.Space : OldBorders.Bottom.Space ); NewBorder.Size = ( undefined != Borders.Bottom.Size ? Borders.Bottom.Size : OldBorders.Bottom.Size ); NewBorder.Value = ( undefined != Borders.Bottom.Value ? Borders.Bottom.Value : OldBorders.Bottom.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Bottom, New : NewBorder, Old : this.Pr.Brd.Bottom } ); this.Pr.Brd.Bottom = NewBorder; } if ( undefined != Borders.Left ) { var NewBorder = undefined; if ( undefined != Borders.Left.Value /*&& border_Single === Borders.Left.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Left.Color ? new CDocumentColor( Borders.Left.Color.r, Borders.Left.Color.g, Borders.Left.Color.b ) : new CDocumentColor( OldBorders.Left.Color.r, OldBorders.Left.Color.g, OldBorders.Left.Color.b ) ); NewBorder.Space = ( undefined != Borders.Left.Space ? Borders.Left.Space : OldBorders.Left.Space ); NewBorder.Size = ( undefined != Borders.Left.Size ? Borders.Left.Size : OldBorders.Left.Size ); NewBorder.Value = ( undefined != Borders.Left.Value ? Borders.Left.Value : OldBorders.Left.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Left, New : NewBorder, Old : this.Pr.Brd.Left } ); this.Pr.Brd.Left = NewBorder; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_Border : function(Border, HistoryType) { var OldValue; switch( HistoryType ) { case historyitem_Paragraph_Borders_Between: OldValue = this.Pr.Brd.Between; this.Pr.Brd.Between = Border; break; case historyitem_Paragraph_Borders_Bottom: OldValue = this.Pr.Brd.Bottom; this.Pr.Brd.Bottom = Border; break; case historyitem_Paragraph_Borders_Left: OldValue = this.Pr.Brd.Left; this.Pr.Brd.Left = Border; break; case historyitem_Paragraph_Borders_Right: OldValue = this.Pr.Brd.Right; this.Pr.Brd.Right = Border; break; case historyitem_Paragraph_Borders_Top: OldValue = this.Pr.Brd.Top; this.Pr.Brd.Top = Border; break; } History.Add( this, { Type : HistoryType, New : Border, Old : OldValue } ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Проверяем начинается ли текущий параграф с новой страницы. Is_StartFromNewPage : function() { // TODO: пока здесь стоит простая проверка. В будущем надо будет данную проверку улучшить. // Например, сейчас не учитывается случай, когда в начале параграфа стоит PageBreak. if ( ( this.Pages.length > 1 && 0 === this.Pages[1].FirstLine ) || ( null === this.Get_DocumentPrev() ) ) return true; return false; }, Internal_GetPage : function(Pos) { if ( undefined === Pos ) Pos = this.CurPos.ContentPos; return this.Internal_Get_ParaPos_By_Pos( Pos).Page; }, // Ищем графический объект по Id и удаляем запись он нем в параграфе Remove_DrawingObject : function(Id) { for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type && Id === Item.Get_Id() ) { var HdrFtr = this.Parent.Is_HdrFtr(true); if ( null != HdrFtr && true != Item.Is_Inline() ) HdrFtr.RecalcInfo.NeedRecalc = true; this.Internal_Content_Remove( Index ); return Index; } } return -1; }, Internal_CorrectAnchorPos : function(Result, Drawing, PageNum) { // Поправляем позицию var RelH = Drawing.PositionH.RelativeFrom; var RelV = Drawing.PositionV.RelativeFrom; var ContentPos = 0; if ( c_oAscRelativeFromH.Character != RelH || c_oAscRelativeFromV.Line != RelV ) { var CurLine = Result.Internal.Line; if ( c_oAscRelativeFromV.Line != RelV ) { var CurPage = Result.Internal.Page; CurLine = this.Pages[CurPage].StartLine; } var StartLinesPos = this.Lines[CurLine].StartPos; var EndLinesPos = this.Lines[CurLine].EndPos; var CurRange = this.Internal_Get_ParaPos_By_Pos( StartLinesPos).Range; Result.X = this.Lines[CurLine].Ranges[CurRange].X - 3.8; ContentPos = Math.min( StartLinesPos + 1, EndLinesPos ); } if ( c_oAscRelativeFromV.Line != RelV ) { var CurPage = Result.Internal.Page; var CurLine = this.Pages[CurPage].StartLine; Result.Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent; } if ( c_oAscRelativeFromH.Character === RelH ) { // Ничего не делаем } else if ( c_oAscRelativeFromV.Line === RelV ) { var CurLine = this.Internal_Get_ParaPos_By_Pos( Result.ContentPos).Line; Result.ContentPos = this.Lines[CurLine].StartPos; } else { Result.ContentPos = ContentPos; } }, // Получем ближающую возможную позицию курсора Get_NearestPos : function(PageNum, X, Y, bAnchor, Drawing) { var ContentPos = this.Internal_GetContentPosByXY( X, Y, false, PageNum ).Pos; var Result = this.Internal_Recalculate_CurPos( ContentPos, false, false, true ); // Сохраняем параграф и найденное место в параграфе Result.ContentPos = ContentPos; Result.Paragraph = this; if ( true === bAnchor && undefined != Drawing && null != Drawing ) this.Internal_CorrectAnchorPos( Result, Drawing, PageNum - this.PageNum ); return Result; }, Get_AnchorPos : function(Drawing) { // Ищем, где находится наш объект var ContentPos = -1; var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type && Item.Get_Id() === Drawing.Get_Id() ) { ContentPos = Index; break; } } var CurPage = this.Internal_Get_ParaPos_By_Pos( ContentPos).Page; if ( -1 === ContentPos ) return { X : 0, Y : 0, Height : 0 }; var Result = this.Internal_Recalculate_CurPos( ContentPos, false, false, true ); Result.Paragraph = this; Result.ContentPos = ContentPos; this.Internal_CorrectAnchorPos( Result, Drawing, CurPage ); return Result; }, Set_DocumentNext : function(Object) { History.Add( this, { Type : historyitem_Paragraph_DocNext, New : Object, Old : this.Next } ); this.Next = Object; }, Set_DocumentPrev : function(Object) { History.Add( this, { Type : historyitem_Paragraph_DocPrev, New : Object, Old : this.Prev } ); this.Prev = Object; }, Get_DocumentNext : function() { return this.Next; }, Get_DocumentPrev : function() { return this.Prev; }, Set_DocumentIndex : function(Index) { this.Index = Index; }, Set_Parent : function(ParentObject) { History.Add( this, { Type : historyitem_Paragraph_Parent, New : ParentObject, Old : this.Parent } ); this.Parent = ParentObject; }, Get_Parent : function() { return this.Parent; }, Is_ContentOnFirstPage : function() { // Если параграф сразу переносится на новую страницу, тогда это значение обычно -1 if ( this.Pages[0].EndLine < 0 ) return false; return true; }, Get_CurrentPage_Absolute : function() { // Обновляем позицию this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); return (this.Get_StartPage_Absolute() + this.CurPos.PagesPos); }, Get_CurrentPage_Relative : function() { // Обновляем позицию this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); return (this.PageNum + this.CurPos.PagesPos); }, // на вход подается строка с как минимум 1 символом (поэтому тут это не проверяем) DocumentSearch : function(Str, ElementType) { var Pr = this.Get_CompiledPr(); var StartPage = this.Get_StartPage_Absolute(); var SearchResults = new Array(); // Сначала найдем элементы поиска в данном параграфе for ( var Pos = 0; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; if ( para_Numbering === Item.Type || para_PresentationNumbering === Item.Type || para_TextPr === Item.Type ) continue; if ( (" " === Str[0] && para_Space === Item.Type) || ( para_Text === Item.Type && (Item.Value).toLowerCase() === Str[0].toLowerCase() ) ) { if ( 1 === Str.length ) SearchResults.push( { StartPos : Pos, EndPos : Pos + 1 } ); else { var bFind = true; var Pos2 = Pos + 1; // Проверяем for ( var Index = 1; Index < Str.length; Index++ ) { // Пропускаем записи TextPr while ( Pos2 < this.Content.length && ( para_TextPr === this.Content[Pos2].Type ) ) Pos2++; if ( ( Pos2 >= this.Content.length ) || (" " === Str[Index] && para_Space != this.Content[Pos2].Type) || ( " " != Str[Index] && ( ( para_Text != this.Content[Pos2].Type ) || ( para_Text === this.Content[Pos2].Type && this.Content[Pos2].Value.toLowerCase() != Str[Index].toLowerCase() ) ) ) ) { bFind = false; break; } Pos2++; } if ( true === bFind ) { SearchResults.push( { StartPos : Pos, EndPos : Pos2 } ); } } } } var MaxShowValue = 100; for ( var FoundIndex = 0; FoundIndex < SearchResults.length; FoundIndex++ ) { var Rects = new Array(); // Делаем подсветку var StartPos = SearchResults[FoundIndex].StartPos; var EndPos = SearchResults[FoundIndex].EndPos; // Найдем линию, с которой начинается селект var StartParaPos = this.Internal_Get_ParaPos_By_Pos( StartPos ); var CurLine = StartParaPos.Line; var CurRange = StartParaPos.Range; var PNum = StartParaPos.Page; // Найдем начальный сдвиг в данном отрезке var StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; var Pos, Item; for ( Pos = this.Lines[CurLine].Ranges[CurRange].StartPos; Pos <= StartPos - 1; Pos++ ) { Item = this.Content[Pos]; if ( Pos === this.Numbering.Pos ) StartX += this.Numbering.WidthVisible; if ( undefined != Item.WidthVisible && ( para_Drawing != Item.Type || drawing_Inline === Item.DrawingType ) ) StartX += Item.WidthVisible; } if ( this.Pages[PNum].StartLine > CurLine ) { CurLine = this.Pages[PNum].StartLine; CurRange = 0; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; StartPos = this.Lines[this.Pages[PNum].StartLine].StartPos; } var StartY = (this.Pages[PNum].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent); var EndY = (this.Pages[PNum].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent); if ( this.Lines[CurLine].Metrics.LineGap < 0 ) EndY += this.Lines[CurLine].Metrics.LineGap; var W = 0; for ( Pos = StartPos; Pos < EndPos; Pos++ ) { Item = this.Content[Pos]; if ( undefined != Item.CurPage ) { if ( Item.CurPage > PNum ) PNum = Item.CurPage; if ( CurLine < Item.CurLine ) { Rects.push( { PageNum : StartPage + PNum, X : StartX, Y : StartY, W : W, H : EndY - StartY } ); CurLine = Item.CurLine; CurRange = Item.CurRange; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; StartY = (this.Pages[PNum].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent); EndY = (this.Pages[PNum].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent); if ( this.Lines[CurLine].Metrics.LineGap < 0 ) EndY += this.Lines[CurLine].Metrics.LineGap; W = 0; } else if ( CurRange < Item.CurRange ) { Rects.push( { PageNum : StartPage + PNum, X : StartX, Y : StartY, W : W, H : EndY - StartY } ); CurRange = Item.CurRange; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; W = 0; } } if ( undefined != Item.WidthVisible ) W += Item.WidthVisible; if ( Pos == EndPos - 1 ) Rects.push( { PageNum : StartPage + PNum, X : StartX, Y : StartY, W : W, H : EndY - StartY } ); } var ResultStr = new String(); var _Str = ""; for ( var Pos = StartPos; Pos < EndPos; Pos++ ) { Item = this.Content[Pos]; if ( para_Text === Item.Type ) _Str += Item.Value; else if ( para_Space === Item.Type ) _Str += " "; } // Теперь мы должны сформировать строку if ( _Str.length >= MaxShowValue ) { ResultStr = "\<b\>"; for ( var Index = 0; Index < MaxShowValue - 1; Index++ ) ResultStr += _Str[Index]; ResultStr += "\</b\>..."; } else { ResultStr = "\<b\>" + _Str + "\</b\>"; var Pos_before = StartPos - 1; var Pos_after = EndPos; var LeaveCount = MaxShowValue - _Str.length; var bAfter = true; while ( LeaveCount > 0 && ( Pos_before >= 0 || Pos_after < this.Content.length ) ) { var TempPos = ( true === bAfter ? Pos_after : Pos_before ); var Flag = 0; while ( ( ( TempPos >= 0 && false === bAfter ) || ( TempPos < this.Content.length && true === bAfter ) ) && para_Text != this.Content[TempPos].Type && para_Space != this.Content[TempPos].Type ) { if ( true === bAfter ) { TempPos++; if ( TempPos >= this.Content.length ) { TempPos = Pos_before; bAfter = false; Flag++; } } else { TempPos--; if ( TempPos < 0 ) { TempPos = Pos_after; bAfter = true; Flag++; } } // Дошли до обоих концов параграфа if ( Flag >= 2 ) break; } if ( Flag >= 2 || !( ( TempPos >= 0 && false === bAfter ) || ( TempPos < this.Content.length && true === bAfter ) ) ) break; if ( true === bAfter ) { ResultStr += (para_Space === this.Content[TempPos].Type ? " " : this.Content[TempPos].Value); Pos_after = TempPos + 1; LeaveCount--; if ( Pos_before >= 0 ) bAfter = false; if ( Pos_after >= this.Content.length ) bAfter = false; } else { ResultStr = (para_Space === this.Content[TempPos].Type ? " " : this.Content[TempPos].Value) + ResultStr; Pos_before = TempPos - 1; LeaveCount--; if ( Pos_after < this.Content.length ) bAfter = true; if ( Pos_before < 0 ) bAfter = true; } } } this.DrawingDocument.AddPageSearch( ResultStr, Rects, ElementType ); } }, DocumentStatistics : function(Stats) { var bEmptyParagraph = true; var bWord = false; for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; var bSymbol = false; var bSpace = false; var bNewWord = false; if ( (para_Text === Item.Type && false === Item.Is_NBSP()) || (para_PageNum === Item.Type) ) { if ( false === bWord ) bNewWord = true; bWord = true; bSymbol = true; bSpace = false; bEmptyParagraph = false; } else if ( ( para_Text === Item.Type && true === Item.Is_NBSP() ) || para_Space === Item.Type || para_Tab === Item.Type ) { bWord = false; bSymbol = true; bSpace = true; } if ( true === bSymbol ) Stats.Add_Symbol( bSpace ); if ( true === bNewWord ) Stats.Add_Word(); } var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { bEmptyParagraph = false; this.Parent.Get_Numbering().Get_AbstractNum( NumPr.NumId).DocumentStatistics( NumPr.Lvl, Stats ); } if ( false === bEmptyParagraph ) Stats.Add_Paragraph(); }, TurnOff_RecalcEvent : function() { this.TurnOffRecalcEvent = true; }, TurnOn_RecalcEvent : function() { this.TurnOffRecalcEvent = false; }, Set_ApplyToAll : function(bValue) { this.ApplyToAll = bValue; }, Get_ApplyToAll : function() { return this.ApplyToAll; }, Update_CursorType : function(X, Y, PageIndex) { var text_transform = null; var cur_parent = this.Parent; if(this.Parent.Is_TableCellContent()) { while(isRealObject(cur_parent) && cur_parent.Is_TableCellContent()) { cur_parent = cur_parent.Parent.Row.Table.Parent; } } if(cur_parent.Parent instanceof WordShape) { if(isRealObject(cur_parent.Parent.transformText)) { text_transform = cur_parent.Parent.transformText; } } var MMData = new CMouseMoveData(); var Coords = this.DrawingDocument.ConvertCoordsToCursorWR( X, Y, this.Get_StartPage_Absolute() + ( PageIndex - this.PageNum ), text_transform ); MMData.X_abs = Coords.X; MMData.Y_abs = Coords.Y; var Hyperlink = this.Check_Hyperlink( X, Y, PageIndex ); var PNum = PageIndex - this.PageNum; if ( null != Hyperlink && ( PNum >= 0 && PNum < this.Pages.length && Y <= this.Pages[PNum].Bounds.Bottom && Y >= this.Pages[PNum].Bounds.Top ) ) { MMData.Type = c_oAscMouseMoveDataTypes.Hyperlink; MMData.Hyperlink = new CHyperlinkProperty( Hyperlink ); } else MMData.Type = c_oAscMouseMoveDataTypes.Common; if ( null != Hyperlink && true === global_keyboardEvent.CtrlKey ) this.DrawingDocument.SetCursorType( "pointer", MMData ); else this.DrawingDocument.SetCursorType( "default", MMData ); var PNum = Math.max( 0, Math.min( PageIndex - this.PageNum, this.Pages.length - 1 ) ); var Bounds = this.Pages[PNum].Bounds; if ( true === this.Lock.Is_Locked() && X < Bounds.Right && X > Bounds.Left && Y > Bounds.Top && Y < Bounds.Bottom ) { var _X = this.Pages[PNum].X; var _Y = this.Pages[PNum].Y; var MMData = new CMouseMoveData(); var Coords = this.DrawingDocument.ConvertCoordsToCursorWR( _X, _Y, this.Get_StartPage_Absolute() + ( PageIndex - this.PageNum ), text_transform ); MMData.X_abs = Coords.X - 5; MMData.Y_abs = Coords.Y; MMData.Type = c_oAscMouseMoveDataTypes.LockedObject; MMData.UserId = this.Lock.Get_UserId(); MMData.HaveChanges = this.Lock.Have_Changes(); MMData.LockedObjectType = c_oAscMouseMoveLockedObjectType.Common; editor.sync_MouseMoveCallback( MMData ); } }, Document_CreateFontMap : function(FontMap) { if ( true === this.FontMap.NeedRecalc ) { this.FontMap.Map = new Object(); if ( true === this.CompiledPr.NeedRecalc ) { this.CompiledPr.Pr = this.Internal_CompileParaPr(); this.CompiledPr.NeedRecalc = false; } var CurTextPr = this.CompiledPr.Pr.TextPr.Copy(); CurTextPr.Document_CreateFontMap( this.FontMap.Map ); CurTextPr.Merge( this.TextPr.Value ); CurTextPr.Document_CreateFontMap( this.FontMap.Map ); for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { // Выствляем начальные настройки текста у данного параграфа CurTextPr = this.CompiledPr.Pr.TextPr.Copy(); var _CurTextPr = Item.Value; // Копируем настройки из символьного стиля if ( undefined != _CurTextPr.RStyle ) { var Styles = this.Parent.Get_Styles(); var StyleTextPr = Styles.Get_Pr( _CurTextPr.RStyle, styletype_Character).TextPr; CurTextPr.Merge( StyleTextPr ); } // Копируем прямые настройки CurTextPr.Merge( _CurTextPr ); CurTextPr.Document_CreateFontMap( this.FontMap.Map ); } } this.FontMap.NeedRecalc = false; } for ( Key in this.FontMap.Map ) { FontMap[Key] = this.FontMap.Map[Key]; } }, Document_CreateFontCharMap : function(FontCharMap) { if ( true === this.CompiledPr.NeedRecalc ) { this.CompiledPr.Pr = this.Internal_CompileParaPr(); this.CompiledPr.NeedRecalc = false; } var CurTextPr = this.CompiledPr.Pr.TextPr.Copy(); FontCharMap.StartFont( CurTextPr.FontFamily.Name, CurTextPr.Bold, CurTextPr.Italic, CurTextPr.FontSize ); for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { // Выставляем начальные настройки текста у данного параграфа CurTextPr = this.CompiledPr.Pr.TextPr.Copy(); var _CurTextPr = Item.Value; // Копируем настройки из символьного стиля if ( undefined != _CurTextPr.RStyle ) { var Styles = this.Parent.Get_Styles(); var StyleTextPr = Styles.Get_Pr( _CurTextPr.RStyle, styletype_Character).TextPr; CurTextPr.Merge( StyleTextPr ); } // Копируем прямые настройки CurTextPr.Merge( _CurTextPr ); FontCharMap.StartFont( CurTextPr.FontFamily.Name, CurTextPr.Bold, CurTextPr.Italic, CurTextPr.FontSize ); } else if ( para_Text === Item.Type ) { FontCharMap.AddChar( Item.Value ); } else if ( para_Space === Item.Type ) { FontCharMap.AddChar( ' ' ); } else if ( para_Numbering === Item.Type ) { var ParaPr = this.CompiledPr.Pr.ParaPr; var NumPr = ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) continue; var Numbering = this.Parent.Get_Numbering(); var NumInfo = this.Parent.Internal_GetNumInfo( this.Id, NumPr ); var NumTextPr = this.CompiledPr.Pr.TextPr.Copy(); NumTextPr.Merge( this.TextPr.Value ); NumTextPr.Merge( NumLvl.TextPr ); Numbering.Document_CreateFontCharMap( FontCharMap, NumTextPr, NumPr, NumInfo ); FontCharMap.StartFont( CurTextPr.FontFamily.Name, CurTextPr.Bold, CurTextPr.Italic, CurTextPr.FontSize ); } else if ( para_PageNum === Item.Type ) { Item.Document_CreateFontCharMap( FontCharMap ); } } CurTextPr.Merge( this.TextPr.Value ); }, Document_Get_AllFontNames : function(AllFonts) { // Смотрим на знак конца параграфа this.TextPr.Value.Document_Get_AllFontNames( AllFonts ); var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { Item.Value.Document_Get_AllFontNames( AllFonts ); } else if ( para_Drawing === Item.Type ) { Item.documentGetAllFontNames( AllFonts ); } } }, // Обновляем линейку Document_UpdateRulersState : function() { var FramePr = this.Get_FramePr(); if ( undefined === FramePr ) this.Parent.DrawingDocument.Set_RulerState_Paragraph( null ); else { var Frame = this.CalculatedFrame; this.Parent.DrawingDocument.Set_RulerState_Paragraph( { L : Frame.L, T : Frame.T, R : Frame.L + Frame.W, B : Frame.T + Frame.H, PageIndex : Frame.PageIndex, Frame : this } ); } }, // Пока мы здесь проверяем только, находимся ли мы внутри гиперссылки Document_UpdateInterfaceState : function() { if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } var Hyper_start = this.Check_Hyperlink2( this.Selection.StartPos ); var Hyper_end = this.Check_Hyperlink2( this.Selection.EndPos ); if ( Hyper_start === Hyper_end && null != Hyper_start ) { // Вычислим строку var Find = this.Internal_FindBackward( this.Selection.StartPos, [para_HyperlinkStart] ); if ( true != Find.Found ) return; var Str = ""; for ( var Pos = Find.LetterPos + 1; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; var bBreak = false; switch ( Item.Type ) { case para_Drawing: case para_End: case para_Numbering: case para_PresentationNumbering: case para_PageNum: { Str = null; bBreak = true; break; } case para_Text : Str += Item.Value; break; case para_Space: case para_Tab : Str += " "; break; case para_HyperlinkEnd: { bBreak = true; break; } case para_HyperlinkStart: return; } if ( true === bBreak ) break; } var HyperProps = new CHyperlinkProperty( Hyper_start ); HyperProps.put_Text( Str ); editor.sync_HyperlinkPropCallback( HyperProps ); } this.SpellChecker.Document_UpdateInterfaceState( StartPos, EndPos ); } else { var Hyper_cur = this.Check_Hyperlink2( this.CurPos.ContentPos, false, true ); if ( null != Hyper_cur ) { // Вычислим строку var Find = this.Internal_FindBackward( this.CurPos.ContentPos, [para_HyperlinkStart] ); if ( true != Find.Found ) return; var Str = ""; for ( var Pos = Find.LetterPos + 1; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; var bBreak = false; switch ( Item.Type ) { case para_Drawing: case para_End: case para_Numbering: case para_PresentationNumbering: case para_PageNum: { Str = null; bBreak = true; break; } case para_Text : Str += Item.Value; break; case para_Space: case para_Tab : Str += " "; break; case para_HyperlinkEnd: { bBreak = true; break; } case para_HyperlinkStart: return; } if ( true === bBreak ) break; } var HyperProps = new CHyperlinkProperty( Hyper_cur ); HyperProps.put_Text( Str ); editor.sync_HyperlinkPropCallback( HyperProps ); } this.SpellChecker.Document_UpdateInterfaceState( this.CurPos.ContentPos, this.CurPos.ContentPos ); } }, // Функция, которую нужно вызвать перед удалением данного элемента PreDelete : function() { // Поскольку данный элемент удаляется, поэтому надо удалить все записи о // inline объектах в родительском классе, используемых в данном параграфе. // Кроме этого, если тут начинались или заканчивались комметарии, то их тоже // удаляем. this.Internal_Remove_CollaborativeMarks(); for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_CommentEnd === Item.Type || para_CommentStart === Item.Type ) { editor.WordControl.m_oLogicDocument.Remove_Comment( Item.Id, true ); } } }, //----------------------------------------------------------------------------------- // Функции для работы с номерами страниц //----------------------------------------------------------------------------------- Get_StartPage_Absolute : function() { return this.Parent.Get_StartPage_Absolute() + this.Get_StartPage_Relative(); }, Get_StartPage_Relative : function() { return this.PageNum; }, //----------------------------------------------------------------------------------- // Дополнительные функции //----------------------------------------------------------------------------------- Document_SetThisElementCurrent : function() { this.Parent.Set_CurrentElement( this.Index ); }, Is_ThisElementCurrent : function() { var Parent = this.Parent; if ( docpostype_Content === Parent.CurPos.Type && false === Parent.Selection.Use && this.Index === Parent.CurPos.ContentPos ) return this.Parent.Is_ThisElementCurrent(); return false; }, Is_Inline : function() { if ( undefined != this.Pr.FramePr ) return false; return true; }, Get_FramePr : function() { return this.Pr.FramePr; }, Set_FramePr : function(FramePr, bDelete) { var FramePr_old = this.Pr.FramePr; if ( undefined === bDelete ) bDelete = false; if ( true === bDelete ) { this.Pr.FramePr = undefined; History.Add( this, { Type : historyitem_Paragraph_FramePr, Old : FramePr_old, New : undefined } ); this.CompiledPr.NeedRecalc = true; return; } var FrameParas = this.Internal_Get_FrameParagraphs(); // Тут FramePr- объект класса из api.js CParagraphFrame if ( true === FramePr.FromDropCapMenu && 1 === FrameParas.length ) { // Здесь мы смотрим только на количество строк, шрифт, тип и горизонтальный отступ от текста var NewFramePr = FramePr_old.Copy(); if ( undefined != FramePr.DropCap ) { var OldLines = NewFramePr.Lines; NewFramePr.Init_Default_DropCap( FramePr.DropCap === c_oAscDropCap.Drop ? true : false ); NewFramePr.Lines = OldLines; } if ( undefined != FramePr.Lines ) { var AnchorPara = this.Get_FrameAnchorPara(); if ( null === AnchorPara || AnchorPara.Lines.length <= 0 ) return; var LineH = AnchorPara.Lines[0].Bottom - AnchorPara.Lines[0].Top; var LineTA = AnchorPara.Lines[0].Metrics.TextAscent2; var LineTD = AnchorPara.Lines[0].Metrics.TextDescent + AnchorPara.Lines[0].Metrics.LineGap; this.Set_Spacing( { LineRule : linerule_Exact, Line : FramePr.Lines * LineH }, false ); this.Update_DropCapByLines( this.Internal_CalculateTextPr( this.Internal_GetStartPos() ), FramePr.Lines, LineH, LineTA, LineTD ); } if ( undefined != FramePr.FontFamily ) { var FF = new ParaTextPr( { RFonts : { Ascii : { Name : FramePr.FontFamily.Name, Index : -1 } } } ); this.Select_All(); this.Add( FF ); this.Selection_Remove(); } if ( undefined != FramePr.HSpace ) NewFramePr.HSpace = FramePr.HSpace; this.Pr.FramePr = NewFramePr; } else { var NewFramePr = FramePr_old.Copy(); if ( undefined != FramePr.H ) NewFramePr.H = FramePr.H; if ( undefined != FramePr.HAnchor ) NewFramePr.HAnchor = FramePr.HAnchor; if ( undefined != FramePr.HRule ) NewFramePr.HRule = FramePr.HRule; if ( undefined != FramePr.HSpace ) NewFramePr.HSpace = FramePr.HSpace; if ( undefined != FramePr.Lines ) NewFramePr.Lines = FramePr.Lines; if ( undefined != FramePr.VAnchor ) NewFramePr.VAnchor = FramePr.VAnchor; if ( undefined != FramePr.VSpace ) NewFramePr.VSpace = FramePr.VSpace; // Потому что undefined - нормальное значение (и W всегда заполняется в интерфейсе) NewFramePr.W = FramePr.W; if ( undefined != FramePr.Wrap ) NewFramePr.Wrap = FramePr.Wrap; if ( undefined != FramePr.X ) NewFramePr.X = FramePr.X; if ( undefined != FramePr.XAlign ) NewFramePr.XAlign = FramePr.XAlign; if ( undefined != FramePr.Y ) NewFramePr.Y = FramePr.Y; if ( undefined != FramePr.YAlign ) NewFramePr.YAlign = FramePr.YAlign; this.Pr.FramePr = NewFramePr; } if ( undefined != FramePr.Brd ) { var Count = FrameParas.length; for ( var Index = 0; Index < Count; Index++ ) { FrameParas[Index].Set_Borders( FramePr.Brd ); } } if ( undefined != FramePr.Shd ) { var Count = FrameParas.length; for ( var Index = 0; Index < Count; Index++ ) { FrameParas[Index].Set_Shd( FramePr.Shd ); } } History.Add( this, { Type : historyitem_Paragraph_FramePr, Old : FramePr_old, New : this.Pr.FramePr } ); this.CompiledPr.NeedRecalc = true; }, Set_FramePr2 : function(FramePr) { History.Add( this, { Type : historyitem_Paragraph_FramePr, Old : this.Pr.FramePr, New : FramePr } ); this.Pr.FramePr = FramePr; this.CompiledPr.NeedRecalc = true; }, Set_FrameParaPr : function(Para) { Para.CopyPr( this ); this.Set_Spacing( { After : 0 }, false ); this.Numbering_Remove(); }, Get_FrameBounds : function(FrameX, FrameY, FrameW, FrameH) { var X0 = FrameX, Y0 = FrameY, X1 = FrameX + FrameW, Y1 = FrameY + FrameH; var Paras = this.Internal_Get_FrameParagraphs(); var Count = Paras.length; var FramePr = this.Get_FramePr(); if ( 0 >= Count ) return { X : X0, Y : Y0, W : X1 - X0, H : Y1 - Y0 }; for ( var Index = 0; Index < Count; Index++ ) { var Para = Paras[Index]; var ParaPr = Para.Get_CompiledPr2(false).ParaPr; var Brd = ParaPr.Brd; var _X0 = X0 + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; if ( undefined != Brd.Left && border_None != Brd.Left.Value ) _X0 -= Brd.Left.Size + Brd.Left.Space + 1; if ( _X0 < X0 ) X0 = _X0 var _X1 = X1 - ParaPr.Ind.Right; if ( undefined != Brd.Right && border_None != Brd.Right.Value ) _X1 += Brd.Right.Size + Brd.Right.Space + 1; if ( _X1 > X1 ) X1 = _X1; } var _Y1 = Y1; var BottomBorder = Paras[Count - 1].Get_CompiledPr2(false).ParaPr.Brd.Bottom; if ( undefined != BottomBorder && border_None != BottomBorder.Value ) _Y1 += BottomBorder.Size + BottomBorder.Space; if ( _Y1 > Y1 && ( heightrule_Auto === FramePr.HRule || ( heightrule_AtLeast === FramePr.HRule && FrameH >= FramePr.H ) ) ) Y1 = _Y1; return { X : X0, Y : Y0, W : X1 - X0, H : Y1 - Y0 }; }, Set_CalculatedFrame : function(L, T, W, H, L2, T2, W2, H2, PageIndex) { this.CalculatedFrame.T = T; this.CalculatedFrame.L = L; this.CalculatedFrame.W = W; this.CalculatedFrame.H = H; this.CalculatedFrame.T2 = T2; this.CalculatedFrame.L2 = L2; this.CalculatedFrame.W2 = W2; this.CalculatedFrame.H2 = H2; this.CalculatedFrame.PageIndex = PageIndex; }, Internal_Get_FrameParagraphs : function() { var FrameParas = new Array(); var FramePr = this.Get_FramePr(); if ( undefined === FramePr ) return FrameParas; FrameParas.push( this ); var Prev = this.Get_DocumentPrev(); while ( null != Prev ) { if ( type_Paragraph === Prev.GetType() ) { var PrevFramePr = Prev.Get_FramePr(); if ( undefined != PrevFramePr && true === FramePr.Compare( PrevFramePr ) ) { FrameParas.push( Prev ); Prev = Prev.Get_DocumentPrev(); } else break; } else break; } var Next = this.Get_DocumentNext(); while ( null != Next ) { if ( type_Paragraph === Next.GetType() ) { var NextFramePr = Next.Get_FramePr(); if ( undefined != NextFramePr && true === FramePr.Compare( NextFramePr ) ) { FrameParas.push( Next ); Next = Next.Get_DocumentNext(); } else break; } else break; } return FrameParas; }, Is_LineDropCap : function() { var FrameParas = this.Internal_Get_FrameParagraphs(); if ( 1 !== FrameParas.length || 1 !== this.Lines.length ) return false; return true; }, Get_LineDropCapWidth : function() { var W = this.Lines[0].Ranges[0].W; var ParaPr = this.Get_CompiledPr2(false).ParaPr; W += ParaPr.Ind.Left + ParaPr.Ind.FirstLine; return W; }, Change_Frame : function(X, Y, W, H, PageIndex) { var LogicDocument = editor.WordControl.m_oLogicDocument; var FramePr = this.Get_FramePr(); if ( undefined === FramePr || ( Math.abs( Y - this.CalculatedFrame.T ) < 0.001 && Math.abs( X - this.CalculatedFrame.L ) < 0.001 && Math.abs( W - this.CalculatedFrame.W ) < 0.001 && Math.abs( H - this.CalculatedFrame.H ) < 0.001 && PageIndex === this.CalculatedFrame.PageIndex ) ) return; var FrameParas = this.Internal_Get_FrameParagraphs(); if ( false === LogicDocument.Document_Is_SelectionLocked( changestype_None, { Type : changestype_2_ElementsArray_and_Type, Elements : FrameParas, CheckType : changestype_Paragraph_Content } ) ) { History.Create_NewPoint(); var NewFramePr = FramePr.Copy(); if ( Math.abs( X - this.CalculatedFrame.L ) > 0.001 ) { NewFramePr.X = X; NewFramePr.XAlign = undefined; NewFramePr.HAnchor = c_oAscHAnchor.Page; } if ( Math.abs( Y - this.CalculatedFrame.T ) > 0.001 ) { NewFramePr.Y = Y; NewFramePr.YAlign = undefined; NewFramePr.VAnchor = c_oAscVAnchor.Page; } if ( Math.abs( W - this.CalculatedFrame.W ) > 0.001 ) NewFramePr.W = W; if ( Math.abs( H - this.CalculatedFrame.H ) > 0.001 ) { if ( undefined != FramePr.DropCap && dropcap_None != FramePr.DropCap && 1 === FrameParas.length ) { var _H = Math.min( H, Page_Height ); NewFramePr.Lines = this.Update_DropCapByHeight( _H ); NewFramePr.HRule = linerule_Auto; } else { if ( H <= this.CalculatedFrame.H ) NewFramePr.HRule = linerule_Exact; else NewFramePr.HRule = linerule_AtLeast; NewFramePr.H = H; } } var Count = FrameParas.length; for ( var Index = 0; Index < Count; Index++ ) { var Para = FrameParas[Index]; Para.Set_FramePr( NewFramePr, false ); } LogicDocument.Recalculate(); LogicDocument.Document_UpdateInterfaceState(); } }, Supplement_FramePr : function(FramePr) { if ( undefined != FramePr.DropCap && dropcap_None != FramePr.DropCap ) { var _FramePr = this.Get_FramePr(); var FirstFramePara = this; var Prev = FirstFramePara.Get_DocumentPrev(); while ( null != Prev ) { if ( type_Paragraph === Prev.GetType() ) { var PrevFramePr = Prev.Get_FramePr(); if ( undefined != PrevFramePr && true === _FramePr.Compare( PrevFramePr ) ) { FirstFramePara = Prev; Prev = Prev.Get_DocumentPrev(); } else break; } else break; } var TextPr = FirstFramePara.Internal_CalculateTextPr(0); FramePr.FontFamily = { Name : TextPr.RFonts.Ascii.Name, Index : TextPr.RFonts.Ascii.Index }; } var FrameParas = this.Internal_Get_FrameParagraphs(); var Count = FrameParas.length; var ParaPr = FrameParas[0].Get_CompiledPr2(false).ParaPr.Copy(); for ( var Index = 1; Index < Count; Index++ ) { var TempPr= FrameParas[Index].Get_CompiledPr2(false).ParaPr; ParaPr = ParaPr.Compare(TempPr); } FramePr.Brd = ParaPr.Brd; FramePr.Shd = ParaPr.Shd; }, Can_AddDropCap : function() { var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { if ( para_Text === this.Content[Pos].Type ) return true; } return false; }, Split_DropCap : function(NewParagraph) { // Если есть выделение, тогда мы проверяем элементы, идущие до конца выделения, если есть что-то кроме текста // тогда мы добавляем в буквицу только первый текстовый элемент, иначе добавляем все от начала параграфа и до // конца выделения, кроме этого в буквицу добавляем все табы идущие в начале. var Count = this.Content.length; var EndPos = this.Selection.StartPos > this.Selection.EndPos ? this.Selection.StartPos : this.Selection.EndPos; var bSelection = false; var LastTextPr = null; if ( true === this.Selection.Use ) { var EndPos = Math.min( this.Selection.StartPos > this.Selection.EndPos ? this.Selection.StartPos : this.Selection.EndPos, this.Content.length ); bSelection = true; for (var Pos = 0; Pos < EndPos; Pos++ ) { var Type = this.Content[Pos].Type; if ( para_Text != Type && para_TextPr != Type && para_Tab != Type ) { bSelection = false; break; } else if ( para_TextPr === Type ) LastTextPr = this.Content[Pos]; } } if ( false === bSelection ) { var Pos = 0; for (; Pos < Count; Pos++ ) { var Type = this.Content[Pos].Type; if ( para_Text === Type ) break; else if ( para_TextPr === Type ) LastTextPr = this.Content[Pos]; } EndPos = Pos + 1; } for ( var Pos = 0; Pos < EndPos; Pos++ ) { NewParagraph.Internal_Content_Add(Pos, this.Content[Pos]); } var TextPr = this.Internal_CalculateTextPr(EndPos); this.Internal_Content_Remove2( 0, EndPos ); if ( null != LastTextPr ) this.Internal_Content_Add( 0, new ParaTextPr(LastTextPr.Value) ); return TextPr; }, Update_DropCapByLines : function(TextPr, Count, LineH, LineTA, LineTD) { // Мы должны сделать так, чтобы высота данного параграфа была точно Count * LineH this.Set_Spacing( { Before : 0, After : 0, LineRule : linerule_Exact, Line : Count * LineH - 0.001 }, false ); var FontSize = 72; TextPr.FontSize = FontSize; g_oTextMeasurer.SetTextPr(TextPr); g_oTextMeasurer.SetFontSlot(fontslot_ASCII, 1); var TDescent = null; var TAscent = null; var TempCount = this.Content.length; for ( var Index = 0; Index < TempCount; Index++ ) { var Item = this.Content[Index]; if ( para_Text === Item.Type ) { var Temp = g_oTextMeasurer.Measure2( Item.Value ); if ( null === TAscent || TAscent < Temp.Ascent ) TAscent = Temp.Ascent; if ( null === TDescent || TDescent > Temp.Ascent - Temp.Height ) TDescent = Temp.Ascent - Temp.Height; } } var THeight = 0; if ( null === TAscent || null === TDescent ) THeight = g_oTextMeasurer.GetHeight(); else THeight = -TDescent + TAscent; var EmHeight = THeight; var NewEmHeight = (Count - 1) * LineH + LineTA; var Koef = NewEmHeight / EmHeight; var NewFontSize = TextPr.FontSize * Koef; TextPr.FontSize = parseInt(NewFontSize * 2) / 2; g_oTextMeasurer.SetTextPr(TextPr); g_oTextMeasurer.SetFontSlot(fontslot_ASCII, 1); var TNewDescent = null; var TNewAscent = null; var TempCount = this.Content.length; for ( var Index = 0; Index < TempCount; Index++ ) { var Item = this.Content[Index]; if ( para_Text === Item.Type ) { var Temp = g_oTextMeasurer.Measure2( Item.Value ); if ( null === TNewAscent || TNewAscent < Temp.Ascent ) TNewAscent = Temp.Ascent; if ( null === TNewDescent || TNewDescent > Temp.Ascent - Temp.Height ) TNewDescent = Temp.Ascent - Temp.Height; } } var TNewHeight = 0; if ( null === TNewAscent || null === TNewDescent ) TNewHeight = g_oTextMeasurer.GetHeight(); else TNewHeight = -TNewDescent + TNewAscent; var Descent = g_oTextMeasurer.GetDescender(); var Ascent = g_oTextMeasurer.GetAscender(); var Dy = Descent * (LineH * Count) / ( Ascent - Descent ) + TNewHeight - TNewAscent + LineTD; var PTextPr = new ParaTextPr( { RFonts : { Ascii : { Name : TextPr.RFonts.Ascii.Name, Index : -1 } }, FontSize : TextPr.FontSize, Position : Dy } ); this.Select_All(); this.Add( PTextPr ); this.Selection_Remove(); }, Update_DropCapByHeight : function(Height) { // Ищем следующий параграф, к которому относится буквица var AnchorPara = this.Get_FrameAnchorPara(); if ( null === AnchorPara || AnchorPara.Lines.length <= 0 ) return 1; this.Set_Spacing( { LineRule : linerule_Exact, Line : Height }, false ); var LineH = AnchorPara.Lines[0].Bottom - AnchorPara.Lines[0].Top; var LineTA = AnchorPara.Lines[0].Metrics.TextAscent2; var LineTD = AnchorPara.Lines[0].Metrics.TextDescent + AnchorPara.Lines[0].Metrics.LineGap; // Посчитаем количество строк var LinesCount = Math.ceil( Height / LineH ); var TextPr = this.Internal_CalculateTextPr(this.Internal_GetStartPos()); g_oTextMeasurer.SetTextPr(TextPr); g_oTextMeasurer.SetFontSlot(fontslot_ASCII, 1); var TDescent = null; var TAscent = null; var TempCount = this.Content.length; for ( var Index = 0; Index < TempCount; Index++ ) { var Item = this.Content[Index]; if ( para_Text === Item.Type ) { var Temp = g_oTextMeasurer.Measure2( Item.Value ); if ( null === TAscent || TAscent < Temp.Ascent ) TAscent = Temp.Ascent; if ( null === TDescent || TDescent > Temp.Ascent - Temp.Height ) TDescent = Temp.Ascent - Temp.Height; } } var THeight = 0; if ( null === TAscent || null === TDescent ) THeight = g_oTextMeasurer.GetHeight(); else THeight = -TDescent + TAscent; var Koef = (Height - LineTD) / THeight; var NewFontSize = TextPr.FontSize * Koef; TextPr.FontSize = parseInt(NewFontSize * 2) / 2; g_oTextMeasurer.SetTextPr(TextPr); g_oTextMeasurer.SetFontSlot(fontslot_ASCII, 1); var TNewDescent = null; var TNewAscent = null; var TempCount = this.Content.length; for ( var Index = 0; Index < TempCount; Index++ ) { var Item = this.Content[Index]; if ( para_Text === Item.Type ) { var Temp = g_oTextMeasurer.Measure2( Item.Value ); if ( null === TNewAscent || TNewAscent < Temp.Ascent ) TNewAscent = Temp.Ascent; if ( null === TNewDescent || TNewDescent > Temp.Ascent - Temp.Height ) TNewDescent = Temp.Ascent - Temp.Height; } } var TNewHeight = 0; if ( null === TNewAscent || null === TNewDescent ) TNewHeight = g_oTextMeasurer.GetHeight(); else TNewHeight = -TNewDescent + TNewAscent; var Descent = g_oTextMeasurer.GetDescender(); var Ascent = g_oTextMeasurer.GetAscender(); var Dy = Descent * (Height) / ( Ascent - Descent ) + TNewHeight - TNewAscent + LineTD; var PTextPr = new ParaTextPr( { RFonts : { Ascii : { Name : TextPr.RFonts.Ascii.Name, Index : -1 } }, FontSize : TextPr.FontSize, Position : Dy } ); this.Select_All(); this.Add( PTextPr ); this.Selection_Remove(); return LinesCount; }, Get_FrameAnchorPara : function() { var FramePr = this.Get_FramePr(); if ( undefined === FramePr ) return null; var Next = this.Get_DocumentNext(); while ( null != Next ) { if ( type_Paragraph === Next.GetType() ) { var NextFramePr = Next.Get_FramePr(); if ( undefined === NextFramePr || false === FramePr.Compare( NextFramePr ) ) return Next; } Next = Next.Get_DocumentNext(); } return Next; }, // Разделяем данный параграф Split : function(NewParagraph, Pos) { if ( "undefined" === typeof(Pos) || null === Pos ) Pos = this.CurPos.ContentPos; // Копируем контент, начиная с текущей позиции в параграфе до конца параграфа, // в новый параграф (первым элементом выставляем настройки текста, рассчитанные // для текущей позиции). Проверим, находится ли данная позиция внутри гиперссылки, // если да, тогда в текущем параграфе закрываем гиперссылку, а в новом создаем ее копию. var Hyperlink = this.Check_Hyperlink2( Pos, false ); var TextPr = this.Internal_CalculateTextPr( Pos ); NewParagraph.DeleteCommentOnRemove = false; NewParagraph.Internal_Content_Remove2(0, NewParagraph.Content.length); NewParagraph.Internal_Content_Concat( this.Content.slice( Pos ) ); NewParagraph.Internal_Content_Add( 0, new ParaTextPr( TextPr ) ); NewParagraph.Set_ContentPos( 0 ); NewParagraph.DeleteCommentOnRemove = true; NewParagraph.TextPr.Value = this.TextPr.Value.Copy(); if ( null != Hyperlink ) NewParagraph.Internal_Content_Add( 1, Hyperlink.Copy() ); // Удаляем все элементы после текущей позиции и добавляем признак окончания параграфа. this.DeleteCommentOnRemove = false; this.Internal_Remove_CollaborativeMarks(); this.Internal_Content_Remove2( Pos, this.Content.length - Pos ); this.DeleteCommentOnRemove = true; if ( null != Hyperlink ) { // Добавляем конец гиперссылки и пустые текстовые настройки this.Internal_Content_Add( this.Content.length, new ParaHyperlinkEnd() ); this.Internal_Content_Add( this.Content.length, new ParaTextPr() ); } this.Internal_Content_Add( this.Content.length, new ParaEnd() ); this.Internal_Content_Add( this.Content.length, new ParaEmpty() ); // Копируем все настройки в новый параграф. Делаем это после того как определили контент параграфов. this.CopyPr( NewParagraph ); this.RecalcInfo.Set_Type_0(pararecalc_0_All); NewParagraph.RecalcInfo.Set_Type_0(pararecalc_0_All); }, // Присоединяем контент параграфа Para к текущему параграфу Concat : function(Para) { this.DeleteCommentOnRemove = false; this.Internal_Content_Remove2( this.Content.length - 2, 2 ); this.DeleteCommentOnRemove = true; // Убираем нумерацию, если она была у следующего параграфа Para.Numbering_Remove(); Para.Remove_PresentationNumbering(); this.Internal_Content_Concat( Para.Content ); this.RecalcInfo.Set_Type_0(pararecalc_0_All); }, // Копируем настройки параграфа и последние текстовые настройки в новый параграф Continue : function(NewParagraph) { // Копируем настройки параграфа this.CopyPr( NewParagraph ); // Копируем последние настройки текста var TextPr = this.Internal_CalculateTextPr( this.Internal_GetEndPos() ); NewParagraph.Internal_Content_Add( 0, new ParaTextPr( TextPr ) ); NewParagraph.TextPr.Value = this.TextPr.Value.Copy(); }, //----------------------------------------------------------------------------------- // Undo/Redo функции //----------------------------------------------------------------------------------- Undo : function(Data) { var Type = Data.Type; switch ( Type ) { case historyitem_Paragraph_AddItem: { var StartPos = this.Internal_Get_RealPos( Data.Pos ); var EndPos = this.Internal_Get_RealPos( Data.EndPos ); this.Content.splice( StartPos, EndPos - StartPos + 1 ); break; } case historyitem_Paragraph_RemoveItem: { var Pos = this.Internal_Get_RealPos( Data.Pos ); var Array_start = this.Content.slice( 0, Pos ); var Array_end = this.Content.slice( Pos ); this.Content = Array_start.concat( Data.Items, Array_end ); break; } case historyitem_Paragraph_Numbering: { var Old = Data.Old; if ( undefined != Old ) this.Pr.NumPr = Old; else this.Pr.NumPr = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Align: { this.Pr.Jc = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_First: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaSpacing(); this.Pr.Ind.FirstLine = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Left: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaSpacing(); this.Pr.Ind.Left = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Right: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaSpacing(); this.Pr.Ind.Right = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_ContextualSpacing: { this.Pr.ContextualSpacing = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepLines: { this.Pr.KeepLines = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepNext: { this.Pr.KeepNext = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PageBreakBefore: { this.Pr.PageBreakBefore = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Line: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.Line = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_LineRule: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.LineRule = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Before: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.Before = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_After: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.After = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_AfterAutoSpacing: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.AfterAutoSpacing = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_BeforeAutoSpacing: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.BeforeAutoSpacing = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Value: { if ( undefined != Data.Old && undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( undefined != Data.Old ) this.Pr.Shd.Value = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Color: { if ( undefined != Data.Old && undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( undefined != Data.Old ) this.Pr.Shd.Color = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd: { this.Pr.Shd = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_WidowControl: { this.Pr.WidowControl = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Tabs: { this.Pr.Tabs = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PStyle: { var Old = Data.Old; if ( undefined != Old ) this.Pr.PStyle = Old; else this.Pr.PStyle = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_DocNext: { this.Next = Data.Old; break; } case historyitem_Paragraph_DocPrev: { this.Prev = Data.Old; break; } case historyitem_Paragraph_Parent: { this.Parent = Data.Old; break; } case historyitem_Paragraph_Borders_Between: { this.Pr.Brd.Between = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Bottom: { this.Pr.Brd.Bottom = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Left: { this.Pr.Brd.Left = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Right: { this.Pr.Brd.Right = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Top: { this.Pr.Brd.Top = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Pr: { var Old = Data.Old; if ( undefined != Old ) this.Pr = Old; else this.Pr = new CParaPr(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PresentationPr_Bullet: { this.PresentationPr.Bullet = Data.Old; break; } case historyitem_Paragraph_PresentationPr_Level: { this.PresentationPr.Level = Data.Old; break; } case historyitem_Paragraph_FramePr: { this.Pr.FramePr = Data.Old; this.CompiledPr.NeedRecalc = true; break; } } this.RecalcInfo.Set_Type_0(pararecalc_0_All); this.RecalcInfo.Set_Type_0_Spell(pararecalc_0_Spell_All); }, Redo : function(Data) { var Type = Data.Type; switch ( Type ) { case historyitem_Paragraph_AddItem: { var Pos = this.Internal_Get_RealPos( Data.Pos ); var Array_start = this.Content.slice( 0, Pos ); var Array_end = this.Content.slice( Pos ); this.Content = Array_start.concat( Data.Items, Array_end ); break; } case historyitem_Paragraph_RemoveItem: { var StartPos = this.Internal_Get_RealPos( Data.Pos ); var EndPos = this.Internal_Get_RealPos( Data.EndPos ); this.Content.splice( StartPos, EndPos - StartPos + 1 ); break; } case historyitem_Paragraph_Numbering: { var New = Data.New; if ( undefined != New ) this.Pr.NumPr = New; else this.Pr.NumPr = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Align: { this.Pr.Jc = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_First: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); this.Pr.Ind.FirstLine = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Left: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); this.Pr.Ind.Left = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Right: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); this.Pr.Ind.Right = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_ContextualSpacing: { this.Pr.ContextualSpacing = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepLines: { this.Pr.KeepLines = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepNext: { this.Pr.KeepNext = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PageBreakBefore: { this.Pr.PageBreakBefore = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Line: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.Line = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_LineRule: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.LineRule = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Before: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.Before = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_After: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.After = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_AfterAutoSpacing: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.AfterAutoSpacing = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_BeforeAutoSpacing: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.BeforeAutoSpacing = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Value: { if ( undefined != Data.New && undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( undefined != Data.New ) this.Pr.Shd.Value = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Color: { if ( undefined != Data.New && undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( undefined != Data.New ) this.Pr.Shd.Color = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd: { this.Pr.Shd = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_WidowControl: { this.Pr.WidowControl = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Tabs: { this.Pr.Tabs = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PStyle: { var New = Data.New; if ( undefined != New ) this.Pr.PStyle = New; else this.Pr.PStyle = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_DocNext: { this.Next = Data.New; break; } case historyitem_Paragraph_DocPrev: { this.Prev = Data.New; break; } case historyitem_Paragraph_Parent: { this.Parent = Data.New; break; } case historyitem_Paragraph_Borders_Between: { this.Pr.Brd.Between = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Bottom: { this.Pr.Brd.Bottom = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Left: { this.Pr.Brd.Left = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Right: { this.Pr.Brd.Right = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Top: { this.Pr.Brd.Top = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Pr: { var New = Data.New; if ( undefined != New ) this.Pr = New; else this.Pr = new CParaPr(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PresentationPr_Bullet: { this.PresentationPr.Bullet = Data.New; break; } case historyitem_Paragraph_PresentationPr_Level: { this.PresentationPr.Level = Data.New; break; } case historyitem_Paragraph_FramePr: { this.Pr.FramePr = Data.New; this.CompiledPr.NeedRecalc = true; break; } } this.RecalcInfo.Set_Type_0(pararecalc_0_All); this.RecalcInfo.Set_Type_0_Spell(pararecalc_0_Spell_All); }, Get_SelectionState : function() { var ParaState = new Object(); ParaState.CurPos = { X : this.CurPos.X, Y : this.CurPos.Y, Line : this.CurPos.Line, ContentPos : this.Internal_Get_ClearPos(this.CurPos.ContentPos), RealX : this.CurPos.RealX, RealY : this.CurPos.RealY, PagesPos : this.CurPos.PagesPos }; ParaState.Selection = { Start : this.Selection.Start, Use : this.Selection.Use, StartPos : this.Internal_Get_ClearPos(this.Selection.StartPos), EndPos : this.Internal_Get_ClearPos(this.Selection.EndPos), Flag : this.Selection.Flag }; return [ ParaState ]; }, Set_SelectionState : function(State, StateIndex) { if ( State.length <= 0 ) return; var ParaState = State[StateIndex]; this.CurPos = { X : ParaState.CurPos.X, Y : ParaState.CurPos.Y, Line : ParaState.CurPos.Line, ContentPos : this.Internal_Get_RealPos(ParaState.CurPos.ContentPos), RealX : ParaState.CurPos.RealX, RealY : ParaState.CurPos.RealY, PagesPos : ParaState.CurPos.PagesPos }; this.Selection = { Start : ParaState.Selection.Start, Use : ParaState.Selection.Use, StartPos : this.Internal_Get_RealPos(ParaState.Selection.StartPos), EndPos : this.Internal_Get_RealPos(ParaState.Selection.EndPos), Flag : ParaState.Selection.Flag }; var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); this.Set_ContentPos( Math.max( CursorPos_min, Math.min( CursorPos_max, this.CurPos.ContentPos ) ) ); this.Selection.StartPos = Math.max( CursorPos_min, Math.min( CursorPos_max, this.Selection.StartPos ) ); this.Selection.EndPos = Math.max( CursorPos_min, Math.min( CursorPos_max, this.Selection.EndPos ) ); }, Get_ParentObject_or_DocumentPos : function() { return this.Parent.Get_ParentObject_or_DocumentPos(this.Index); }, Refresh_RecalcData : function(Data) { var Type = Data.Type; var bNeedRecalc = false; var CurPage = 0; switch ( Type ) { case historyitem_Paragraph_AddItem: case historyitem_Paragraph_RemoveItem: { for ( CurPage = this.Pages.length - 1; CurPage > 0; CurPage-- ) { if ( Data.Pos > this.Lines[this.Pages[CurPage].StartLine].StartPos ) break; } this.RecalcInfo.Set_Type_0(pararecalc_0_All); bNeedRecalc = true; break; } case historyitem_Paragraph_Numbering: case historyitem_Paragraph_PStyle: case historyitem_Paragraph_Pr: case historyitem_Paragraph_PresentationPr_Bullet: case historyitem_Paragraph_PresentationPr_Level: { this.RecalcInfo.Set_Type_0(pararecalc_0_All); bNeedRecalc = true; break; } case historyitem_Paragraph_Align: case historyitem_Paragraph_Ind_First: case historyitem_Paragraph_Ind_Left: case historyitem_Paragraph_Ind_Right: case historyitem_Paragraph_ContextualSpacing: case historyitem_Paragraph_KeepLines: case historyitem_Paragraph_KeepNext: case historyitem_Paragraph_PageBreakBefore: case historyitem_Paragraph_Spacing_Line: case historyitem_Paragraph_Spacing_LineRule: case historyitem_Paragraph_Spacing_Before: case historyitem_Paragraph_Spacing_After: case historyitem_Paragraph_Spacing_AfterAutoSpacing: case historyitem_Paragraph_Spacing_BeforeAutoSpacing: case historyitem_Paragraph_WidowControl: case historyitem_Paragraph_Tabs: case historyitem_Paragraph_Parent: case historyitem_Paragraph_Borders_Between: case historyitem_Paragraph_Borders_Bottom: case historyitem_Paragraph_Borders_Left: case historyitem_Paragraph_Borders_Right: case historyitem_Paragraph_Borders_Top: case historyitem_Paragraph_FramePr: { bNeedRecalc = true; break; } case historyitem_Paragraph_Shd_Value: case historyitem_Paragraph_Shd_Color: case historyitem_Paragraph_Shd: case historyitem_Paragraph_DocNext: case historyitem_Paragraph_DocPrev: { // Пересчитывать этот элемент не надо при таких изменениях break; } } if ( true === bNeedRecalc ) { // Сообщаем родительскому классу, что изменения произошли в элементе с номером this.Index и на странице this.PageNum return this.Refresh_RecalcData2(CurPage); } }, Refresh_RecalcData2 : function(CurPage) { if ( undefined === CurPage ) CurPage = 0; // Если Index < 0, значит данный элемент еще не был добавлен в родительский класс if ( this.Index >= 0 ) this.Parent.Refresh_RecalcData2( this.Index, this.PageNum + CurPage ); }, Check_HistoryUninon : function(Data1, Data2) { var Type1 = Data1.Type; var Type2 = Data2.Type; if ( historyitem_Paragraph_AddItem === Type1 && historyitem_Paragraph_AddItem === Type2 ) { if ( 1 === Data1.Items.length && 1 === Data2.Items.length && Data1.Pos === Data2.Pos - 1 && para_Text === Data1.Items[0].Type && para_Text === Data2.Items[0].Type ) return true; } return false; }, //----------------------------------------------------------------------------------- // Функции для совместного редактирования //----------------------------------------------------------------------------------- Document_Is_SelectionLocked : function(CheckType) { switch ( CheckType ) { case changestype_Paragraph_Content: case changestype_Paragraph_Properties: case changestype_Document_Content: case changestype_Document_Content_Add: case changestype_Image_Properties: { this.Lock.Check( this.Get_Id() ); break; } case changestype_Remove: { // Если у нас нет выделения, и курсор стоит в начале, мы должны проверить в том же порядке, в каком // идут проверки при удалении в команде Internal_Remove_Backward. if ( true != this.Selection.Use && true == this.Cursor_IsStart() ) { var Pr = this.Get_CompiledPr2(false).ParaPr; if ( undefined != this.Numbering_Get() || Math.abs(Pr.Ind.FirstLine) > 0.001 || Math.abs(Pr.Ind.Left) > 0.001 ) { // Надо проверить только текущий параграф, а это будет сделано далее } else { var Prev = this.Get_DocumentPrev(); if ( null != Prev && type_Paragraph === Prev.GetType() ) Prev.Lock.Check( Prev.Get_Id() ); } } // Если есть выделение, и знак параграфа попал в выделение ( и параграф выделен не целиком ) else if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( EndPos >= this.Content.length - 1 && StartPos > this.Internal_GetStartPos() ) { var Next = this.Get_DocumentNext(); if ( null != Next && type_Paragraph === Next.GetType() ) Next.Lock.Check( Next.Get_Id() ); } } this.Lock.Check( this.Get_Id() ); break; } case changestype_Delete: { // Если у нас нет выделения, и курсор стоит в конце, мы должны проверить следующий элемент if ( true != this.Selection.Use && true === this.Cursor_IsEnd() ) { var Next = this.Get_DocumentNext(); if ( null != Next && type_Paragraph === Next.GetType() ) Next.Lock.Check( Next.Get_Id() ); } // Если есть выделение, и знак параграфа попал в выделение и параграф выделен не целиком else if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( EndPos >= this.Content.length - 1 && StartPos > this.Internal_GetStartPos() ) { var Next = this.Get_DocumentNext(); if ( null != Next && type_Paragraph === Next.GetType() ) Next.Lock.Check( Next.Get_Id() ); } } this.Lock.Check( this.Get_Id() ); break; } case changestype_Document_SectPr: case changestype_Table_Properties: case changestype_Table_RemoveCells: case changestype_HdrFtr: { CollaborativeEditing.Add_CheckLock(true); break; } } }, Save_Changes : function(Data, Writer) { // Сохраняем изменения из тех, которые используются для Undo/Redo в бинарный файл. // Long : тип класса // Long : тип изменений Writer.WriteLong( historyitem_type_Paragraph ); var Type = Data.Type; // Пишем тип Writer.WriteLong( Type ); switch ( Type ) { case historyitem_Paragraph_AddItem: { // Long : Количество элементов // Array of : // { // Long : Позиция // Variable : Элемент // } var bArray = Data.UseArray; var Count = Data.Items.length; Writer.WriteLong( Count ); for ( var Index = 0; Index < Count; Index++ ) { if ( true === bArray ) Writer.WriteLong( Data.PosArray[Index] ); else Writer.WriteLong( Data.Pos + Index ); Data.Items[Index].Write_ToBinary(Writer); } break; } case historyitem_Paragraph_RemoveItem: { // Long : Количество удаляемых элементов // Array of Long : позиции удаляемых элементов var bArray = Data.UseArray; var Count = Data.Items.length; var StartPos = Writer.GetCurPosition(); Writer.Skip(4); var RealCount = Count; for ( var Index = 0; Index < Count; Index++ ) { if ( true === bArray ) { if ( false === Data.PosArray[Index] ) RealCount--; else Writer.WriteLong( Data.PosArray[Index] ); } else Writer.WriteLong( Data.Pos ); } var EndPos = Writer.GetCurPosition(); Writer.Seek( StartPos ); Writer.WriteLong( RealCount ); Writer.Seek( EndPos ); break; } case historyitem_Paragraph_Numbering: { // Bool : IsUndefined // Если false // Variable : NumPr (CNumPr) if ( undefined === Data.New ) Writer.WriteBool( true ); else { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } break; } case historyitem_Paragraph_Ind_First: case historyitem_Paragraph_Ind_Left: case historyitem_Paragraph_Ind_Right: case historyitem_Paragraph_Spacing_Line: case historyitem_Paragraph_Spacing_Before: case historyitem_Paragraph_Spacing_After: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === Data.New ) { Writer.WriteBool( true ); } else { Writer.WriteBool( false ); Writer.WriteDouble( Data.New ); } break; } case historyitem_Paragraph_Align: case historyitem_Paragraph_Spacing_LineRule: { // Bool : IsUndefined // Если false // Long : Value if ( undefined === Data.New ) { Writer.WriteBool( true ); } else { Writer.WriteBool( false ); Writer.WriteLong( Data.New ); } break; } case historyitem_Paragraph_ContextualSpacing: case historyitem_Paragraph_KeepLines: case historyitem_Paragraph_KeepNext: case historyitem_Paragraph_PageBreakBefore: case historyitem_Paragraph_Spacing_AfterAutoSpacing: case historyitem_Paragraph_Spacing_BeforeAutoSpacing: case historyitem_Paragraph_WidowControl: { // Bool : IsUndefined // Если false // Bool : Value if ( undefined === Data.New ) { Writer.WriteBool( true ); } else { Writer.WriteBool( false ); Writer.WriteBool( Data.New ); } break; } case historyitem_Paragraph_Shd_Value: { // Bool : IsUndefined // Если false // Byte : Value var New = Data.New; if ( undefined != New ) { Writer.WriteBool( false ); Writer.WriteByte( Data.New ); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_Shd_Color: { // Bool : IsUndefined // Если false // Variable : Color (CDocumentColor) var New = Data.New; if ( undefined != New ) { Writer.WriteBool( false ); Data.New.Write_ToBinary(Writer); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_Shd: { // Bool : IsUndefined // Если false // Variable : Shd (CDocumentShd) var New = Data.New; if ( undefined != New ) { Writer.WriteBool( false ); Data.New.Write_ToBinary(Writer); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_Tabs: { // Bool : IsUndefined // Есди false // Variable : CParaTabs if ( undefined != Data.New ) { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } else Writer.WriteBool(true); break; } case historyitem_Paragraph_PStyle: { // Bool : Удаляем ли // Если false // String : StyleId if ( undefined != Data.New ) { Writer.WriteBool( false ); Writer.WriteString2( Data.New ); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_DocNext: case historyitem_Paragraph_DocPrev: case historyitem_Paragraph_Parent: { // String : Id элемента if ( null != Data.New ) Writer.WriteString2( Data.New.Get_Id() ); else Writer.WriteString2( "" ); break; } case historyitem_Paragraph_Borders_Between: case historyitem_Paragraph_Borders_Bottom: case historyitem_Paragraph_Borders_Left: case historyitem_Paragraph_Borders_Right: case historyitem_Paragraph_Borders_Top: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( undefined != Data.New ) { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_Pr: { // Bool : удаляем ли if ( undefined === Data.New ) Writer.WriteBool( true ); else { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } break; } case historyitem_Paragraph_PresentationPr_Bullet: { // Variable : Bullet Data.New.Write_ToBinary( Writer ); break; } case historyitem_Paragraph_PresentationPr_Level: { // Long : Level Writer.WriteLong( Data.New ); break; } case historyitem_Paragraph_FramePr: { // Bool : IsUndefined // false -> // Variable : CFramePr if ( undefined === Data.New ) Writer.WriteBool( true ); else { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } break; } } return Writer; }, Load_Changes : function(Reader) { // Сохраняем изменения из тех, которые используются для Undo/Redo в бинарный файл. // Long : тип класса // Long : тип изменений var ClassType = Reader.GetLong(); if ( historyitem_type_Paragraph != ClassType ) return; var Type = Reader.GetLong(); switch ( Type ) { case historyitem_Paragraph_AddItem: { // Long : Количество элементов // Array of : // { // Long : Позиция // Variable : Элемент // } var Count = Reader.GetLong(); for ( var Index = 0; Index < Count; Index++ ) { var Pos = this.Internal_Get_RealPos( this.m_oContentChanges.Check( contentchanges_Add, Reader.GetLong() ) ); var Element = ParagraphContent_Read_FromBinary(Reader); if ( null != Element ) { if ( Element instanceof ParaCommentStart ) { var Comment = g_oTableId.Get_ById( Element.Id ); if ( null != Comment ) Comment.Set_StartInfo( 0, 0, 0, 0, this.Get_Id() ); } else if ( Element instanceof ParaCommentEnd ) { var Comment = g_oTableId.Get_ById( Element.Id ); if ( null != Comment ) Comment.Set_EndInfo( 0, 0, 0, 0, this.Get_Id() ); } // TODO: Подумать над тем как по минимуму вставлять отметки совместного редактирования this.Content.splice( Pos, 0, new ParaCollaborativeChangesEnd() ); this.Content.splice( Pos, 0, Element ); this.Content.splice( Pos, 0, new ParaCollaborativeChangesStart() ); CollaborativeEditing.Add_ChangedClass(this); } } this.DeleteCollaborativeMarks = false; break; } case historyitem_Paragraph_RemoveItem: { // Long : Количество удаляемых элементов // Array of Long : позиции удаляемых элементов var Count = Reader.GetLong(); for ( var Index = 0; Index < Count; Index++ ) { var ChangesPos = this.m_oContentChanges.Check( contentchanges_Remove, Reader.GetLong() ); // действие совпало, не делаем его if ( false === ChangesPos ) continue; var Pos = this.Internal_Get_RealPos( ChangesPos ); this.Content.splice( Pos, 1 ); } break; } case historyitem_Paragraph_Numbering: { // Bool : IsUndefined // Если false // Variable : NumPr (CNumPr) if ( true === Reader.GetBool() ) this.Pr.NumPr = undefined; else { this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Read_FromBinary(Reader); } this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Align: { // Bool : IsUndefined // Если false // Long : Value if ( true === Reader.GetBool() ) this.Pr.Jc = undefined; else this.Pr.Jc = Reader.GetLong(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_First: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); if ( true === Reader.GetBool() ) this.Pr.Ind.FirstLine = undefined; else this.Pr.Ind.FirstLine = Reader.GetDouble(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Left: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); if ( true === Reader.GetBool() ) this.Pr.Ind.Left = undefined; else this.Pr.Ind.Left = Reader.GetDouble(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Right: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); if ( true === Reader.GetBool() ) this.Pr.Ind.Right = undefined; else this.Pr.Ind.Right = Reader.GetDouble(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_ContextualSpacing: { // Bool : IsUndefined // Если false // Bool : Value if ( true === Reader.GetBool() ) this.Pr.ContextualSpacing = undefined; else this.Pr.ContextualSpacing = Reader.GetBool(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepLines: { // Bool : IsUndefined // Если false // Bool : Value if ( false === Reader.GetBool() ) this.Pr.KeepLines = Reader.GetBool(); else this.Pr.KeepLines = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepNext: { // Bool : IsUndefined // Если false // Bool : Value if ( false === Reader.GetBool() ) this.Pr.KeepNext = Reader.GetLong(); else this.Pr.KeepNext = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PageBreakBefore: { // Bool : IsUndefined // Если false // Bool : Value if ( false === Reader.GetBool() ) this.Pr.PageBreakBefore = Reader.GetBool(); else this.Pr.PageBreakBefore = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Line: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.Line = Reader.GetDouble(); else this.Pr.Spacing.Line = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_LineRule: { // Bool : IsUndefined // Если false // Long : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.LineRule = Reader.GetLong(); else this.Pr.Spacing.LineRule = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Before: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.Before = Reader.GetDouble(); else this.Pr.Spacing.Before = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_After: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.After = Reader.GetDouble(); else this.Pr.Spacing.After = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_AfterAutoSpacing: { // Bool : IsUndefined // Если false // Bool : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.AfterAutoSpacing = Reader.GetBool(); else this.Pr.Spacing.AfterAutoSpacing = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_BeforeAutoSpacing: { // Bool : IsUndefined // Если false // Bool : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.AfterAutoSpacing = Reader.GetBool(); else this.Pr.Spacing.BeforeAutoSpacing = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Value: { // Bool : IsUndefined // Если false // Byte : Value if ( false === Reader.GetBool() ) { if ( undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); this.Pr.Shd.Value = Reader.GetByte(); } else if ( undefined != this.Pr.Shd ) this.Pr.Shd.Value = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Color: { // Bool : IsUndefined // Если false // Variable : Color (CDocumentColor) if ( false === Reader.GetBool() ) { if ( undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); this.Pr.Shd.Color = new CDocumentColor(0,0,0); this.Pr.Shd.Color.Read_FromBinary(Reader); } else if ( undefined != this.Pr.Shd ) this.Pr.Shd.Color = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd: { // Bool : IsUndefined // Если false // Byte : Value if ( false === Reader.GetBool() ) { this.Pr.Shd = new CDocumentShd(); this.Pr.Shd.Read_FromBinary( Reader ); } else this.Pr.Shd = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_WidowControl: { // Bool : IsUndefined // Если false // Bool : Value if ( false === Reader.GetBool() ) this.Pr.WidowControl = Reader.GetBool(); else this.Pr.WidowControl = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Tabs: { // Bool : IsUndefined // Есди false // Variable : CParaTabs if ( false === Reader.GetBool() ) { this.Pr.Tabs = new CParaTabs(); this.Pr.Tabs.Read_FromBinary( Reader ); } else this.Pr.Tabs = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PStyle: { // Bool : Удаляем ли // Если false // String : StyleId if ( false === Reader.GetBool() ) this.Pr.PStyle = Reader.GetString2(); else this.Pr.PStyle = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_DocNext: { // String : Id элемента //this.Next = g_oTableId.Get_ById( Reader.GetString2() ); break; } case historyitem_Paragraph_DocPrev: { // String : Id элемента //this.Prev = g_oTableId.Get_ById( Reader.GetString2() ); break; } case historyitem_Paragraph_Parent: { // String : Id элемента this.Parent = g_oTableId.Get_ById( Reader.GetString2() ); break; } case historyitem_Paragraph_Borders_Between: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Between = new CDocumentBorder(); this.Pr.Brd.Between.Read_FromBinary( Reader ); } else this.Pr.Brd.Between = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Bottom: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Bottom = new CDocumentBorder(); this.Pr.Brd.Bottom.Read_FromBinary( Reader ); } else this.Pr.Brd.Bottom = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Left: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Left = new CDocumentBorder(); this.Pr.Brd.Left.Read_FromBinary( Reader ); } else this.Pr.Brd.Left = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Right: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Right = new CDocumentBorder(); this.Pr.Brd.Right.Read_FromBinary( Reader ); } else this.Pr.Brd.Right = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Top: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Top = new CDocumentBorder(); this.Pr.Brd.Top.Read_FromBinary( Reader ); } else this.Pr.Brd.Top = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Pr: { // Bool : IsUndefined if ( true === Reader.GetBool() ) this.Pr = new CParaPr(); else { this.Pr = new CParaPr(); this.Pr.Read_FromBinary( Reader ); } this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PresentationPr_Bullet: { // Variable : Bullet var Bullet = new CPresentationBullet(); Bullet.Read_FromBinary( Reader ); this.PresentationPr.Bullet = Bullet; break; } case historyitem_Paragraph_PresentationPr_Level: { // Long : Level this.PresentationPr.Level = Reader.GetLong(); break; } case historyitem_Paragraph_FramePr: { // Bool : IsUndefined // false -> // Variable : CFramePr if ( false === Reader.GetBool() ) { this.Pr.FramePr = new CFramePr(); this.Pr.FramePr.Read_FromBinary( Reader ); } else { this.Pr.FramePr = undefined; } this.CompiledPr.NeedRecalc = true; break; } } this.RecalcInfo.Set_Type_0(pararecalc_0_All); this.RecalcInfo.Set_Type_0_Spell(pararecalc_0_Spell_All); }, Write_ToBinary2 : function(Writer) { Writer.WriteLong( historyitem_type_Paragraph ); // String : Id // String : Id родительского класса // Variable : ParaPr // String : Id TextPr // Long : количество элементов, у которых Is_RealContent = true Writer.WriteString2( "" + this.Id ); Writer.WriteString2( this.Parent.Get_Id() ); // Writer.WriteString2( this.Parent.Get_Id() ); this.Pr.Write_ToBinary( Writer ); Writer.WriteString2( this.TextPr.Get_Id() ); var StartPos = Writer.GetCurPosition(); Writer.Skip( 4 ); var Len = this.Content.length; var Count = 0; for ( var Index = 0; Index < Len; Index++ ) { var Item = this.Content[Index]; if ( true === Item.Is_RealContent() ) { Item.Write_ToBinary( Writer ); Count++; } } var EndPos = Writer.GetCurPosition(); Writer.Seek( StartPos ); Writer.WriteLong( Count ); Writer.Seek( EndPos ); }, Read_FromBinary2 : function(Reader) { // String : Id // String : Id родительского класса // Variable : ParaPr // String : Id TextPr // Long : количество элементов, у которых Is_RealContent = true this.Id = Reader.GetString2(); this.DrawingDocument = editor.WordControl.m_oLogicDocument.DrawingDocument; var LinkData = new Object(); LinkData.Parent = Reader.GetString2(); this.Pr = new CParaPr(); this.Pr.Read_FromBinary( Reader ); // this.TextPr = g_oTableId.Get_ById( Reader.GetString2() ); LinkData.TextPr = Reader.GetString2(); CollaborativeEditing.Add_LinkData(this, LinkData); this.Content = new Array(); var Count = Reader.GetLong(); for ( var Index = 0; Index < Count; Index++ ) { var Element = ParagraphContent_Read_FromBinary(Reader); if ( null != Element ) this.Content.push( Element ); } CollaborativeEditing.Add_NewObject( this ); }, Load_LinkData : function(LinkData) { if ( "undefined" != typeof(LinkData.Parent) ) this.Parent = g_oTableId.Get_ById( LinkData.Parent ); if ( "undefined" != typeof(LinkData.TextPr) ) this.TextPr = g_oTableId.Get_ById( LinkData.TextPr ); }, Clear_CollaborativeMarks : function() { for ( var Pos = 0; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; if ( Item.Type == para_CollaborativeChangesEnd || Item.Type == para_CollaborativeChangesStart ) { this.Internal_Content_Remove( Pos ); Pos--; } } }, //----------------------------------------------------------------------------------- // Функции для работы с комментариями //----------------------------------------------------------------------------------- Add_Comment : function(Comment, bStart, bEnd) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( true === this.ApplyToAll ) { if ( true === bEnd ) { var PagePos = this.Internal_GetXYByContentPos( CursorPos_max ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_EndInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentEnd(Comment.Get_Id()); this.Internal_Content_Add( CursorPos_max, Item ); } if ( true === bStart ) { var PagePos = this.Internal_GetXYByContentPos( CursorPos_min ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_StartInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentStart(Comment.Get_Id()); this.Internal_Content_Add( CursorPos_min, Item ); } } else { if ( true === this.Selection.Use ) { var StartPos, EndPos; if ( this.Selection.StartPos < this.Selection.EndPos ) { StartPos = this.Selection.StartPos; EndPos = this.Selection.EndPos; } else { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } if ( true === bEnd ) { EndPos = Math.max( CursorPos_min, Math.min( CursorPos_max, EndPos ) ); var PagePos = this.Internal_GetXYByContentPos( EndPos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_EndInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentEnd(Comment.Get_Id()); this.Internal_Content_Add( EndPos, Item ); } if ( true === bStart ) { StartPos = Math.max( CursorPos_min, Math.min( CursorPos_max, StartPos ) ); var PagePos = this.Internal_GetXYByContentPos( StartPos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_StartInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentStart(Comment.Get_Id()); this.Internal_Content_Add( StartPos, Item ); } } else { if ( true === bEnd ) { var Pos = Math.max( CursorPos_min, Math.min( CursorPos_max, this.CurPos.ContentPos ) ); var PagePos = this.Internal_GetXYByContentPos( Pos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_EndInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentEnd(Comment.Get_Id()); this.Internal_Content_Add( Pos, Item ); } if ( true === bStart ) { var Pos = Math.max( CursorPos_min, Math.min( CursorPos_max, this.CurPos.ContentPos ) ); var PagePos = this.Internal_GetXYByContentPos( Pos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_StartInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentStart(Comment.Get_Id()); this.Internal_Content_Add( Pos, Item ); } } } }, Add_Comment2 : function(Comment, ObjectId) { var Pos = -1; var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type ) { Pos = Index; break; } } if ( -1 != Pos ) { var StartPos = Pos; var EndPos = Pos + 1; var PagePos = this.Internal_GetXYByContentPos( EndPos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_EndInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentEnd(Comment.Get_Id()); this.Internal_Content_Add( EndPos, Item ); var PagePos = this.Internal_GetXYByContentPos( StartPos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_StartInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentStart(Comment.Get_Id()); this.Internal_Content_Add( StartPos, Item ); } }, CanAdd_Comment : function() { if ( true === this.Selection.Use && true != this.Selection_IsEmpty() ) return true; return false; }, Remove_CommentMarks : function(Id) { var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; if ( ( para_CommentStart === Item.Type || para_CommentEnd === Item.Type ) && Id === Item.Id ) { if ( para_CommentStart === Item.Type ) DocumentComments.Set_StartInfo( Item.Id, 0, 0, 0, 0, null ); else DocumentComments.Set_EndInfo( Item.Id, 0, 0, 0, 0, null ); this.Internal_Content_Remove( Pos ); Pos--; Count--; } } }, Replace_MisspelledWord : function(Word, WordId) { var Element = this.SpellChecker.Elements[WordId]; var StartPos = Element.StartPos; var EndPos = Element.EndPos; for ( var Pos = EndPos; Pos >= StartPos; Pos-- ) { var ItemType = this.Content[Pos].Type; if ( para_TextPr != ItemType ) this.Internal_Content_Remove(Pos); } var Len = Word.length; for ( var Pos = 0; Pos < Len; Pos++ ) { this.Internal_Content_Add( StartPos + Pos, new ParaText( Word[Pos] ) ); } this.RecalcInfo.Set_Type_0( pararecalc_0_All ); this.Selection.Use = false; this.Selection.Start = false; this.Selection.StartPos = EndPos; this.Selection.EndPos = EndPos; this.Set_ContentPos( EndPos ); }, Ignore_MisspelledWord : function(WordId) { var Element = this.SpellChecker.Elements[WordId]; Element.Checked = true; this.ReDraw(); } }; var pararecalc_0_All = 0; var pararecalc_0_None = 1; var pararecalc_0_Spell_All = 0; var pararecalc_0_Spell_Pos = 1; var pararecalc_0_Spell_Lang = 2; var pararecalc_0_Spell_None = 3; function CParaRecalcInfo() { this.Recalc_0_Type = pararecalc_0_All; this.Recalc_0_Spell = { Type : pararecalc_0_All, StartPos : 0, EndPos : 0 }; } CParaRecalcInfo.prototype = { Set_Type_0 : function(Type) { this.Recalc_0_Type = Type; }, Set_Type_0_Spell : function(Type, StartPos, EndPos) { if ( pararecalc_0_Spell_All === this.Recalc_0_Spell.Type ) return; else if ( pararecalc_0_Spell_None === this.Recalc_0_Spell.Type || pararecalc_0_Spell_Lang === this.Recalc_0_Spell.Type ) { this.Recalc_0_Spell.Type = Type; if ( pararecalc_0_Spell_Pos === Type ) { this.Recalc_0_Spell.StartPos = StartPos; this.Recalc_0_Spell.EndPos = EndPos; } } else if ( pararecalc_0_Spell_Pos === this.Recalc_0_Spell.Type ) { if ( pararecalc_0_Spell_All === Type ) this.Recalc_0_Spell.Type = Type; else if ( pararecalc_0_Spell_Pos === Type ) { this.Recalc_0_Spell.StartPos = Math.min( StartPos, this.Recalc_0_Spell.StartPos ); this.Recalc_0_Spell.EndPos = Math.max( EndPos, this.Recalc_0_Spell.EndPos ); } } }, Update_Spell_OnChange : function(Pos, Count, bAdd) { if ( pararecalc_0_Spell_Pos === this.Recalc_0_Spell.Type ) { if ( true === bAdd ) { if ( this.Recalc_0_Spell.StartPos > Pos ) this.Recalc_0_Spell.StartPos++; if ( this.Recalc_0_Spell.EndPos >= Pos ) this.Recalc_0_Spell.EndPos++; } else { if ( this.Recalc_0_Spell.StartPos > Pos ) { if ( this.Recalc_0_Spell.StartPos > Pos + Count ) this.Recalc_0_Spell.StartPos -= Count; else this.Recalc_0_Spell.StartPos = Pos; } if ( this.Recalc_0_Spell.EndPos >= Pos ) { if ( this.Recalc_0_Spell.EndPos >= Pos + Count ) this.Recalc_0_Spell.EndPos -= Count; else this.Recalc_0_Spell.EndPos = Math.max( 0, Pos - 1 ); } } } } }; function CParaLineRange(X, XEnd) { this.X = X; this.XVisible = 0; this.W = 0; this.Words = 0; this.Spaces = 0; this.XEnd = XEnd; this.StartPos = 0; // Позиция в контенте параграфа, с которой начинается данный отрезок this.SpacePos = -1; // Позиция, с которой начинаем считать пробелы this.StartPos2 = -1; // Позиции начала и конца отрисовки выделения this.EndPos2 = -1; // текста(а также подчеркивания и зачеркивания) } CParaLineRange.prototype = { Shift : function(Dx, Dy) { this.X += Dx; this.XEnd += Dx; this.XVisible += Dx; } }; function CParaLineMetrics() { this.Ascent = 0; // Высота над BaseLine this.Descent = 0; // Высота после BaseLine this.TextAscent = 0; // Высота текста над BaseLine this.TextAscent2 = 0; // Высота текста над BaseLine this.TextDescent = 0; // Высота текста после BaseLine this.LineGap = 0; // Дополнительное расстояние между строками } CParaLineMetrics.prototype = { Update : function(TextAscent, TextAscent2, TextDescent, Ascent, Descent, ParaPr) { if ( TextAscent > this.TextAscent ) this.TextAscent = TextAscent; if ( TextAscent2 > this.TextAscent2 ) this.TextAscent2 = TextAscent2; if ( TextDescent > this.TextDescent ) this.TextDescent = TextDescent; if ( Ascent > this.Ascent ) this.Ascent = Ascent; if ( Descent > this.Descent ) this.Descent = Descent; if ( this.Ascent < this.TextAscent ) this.TextAscent = this.Ascent; if ( this.Descent < this.TextDescent ) this.TextDescent = this.Descent; this.LineGap = this.Recalculate_LineGap( ParaPr, this.TextAscent, this.TextDescent ); }, Recalculate_LineGap : function(ParaPr, TextAscent, TextDescent) { var LineGap = 0; switch ( ParaPr.Spacing.LineRule ) { case linerule_Auto: { LineGap = ( TextAscent + TextDescent ) * ( ParaPr.Spacing.Line - 1 ); break; } case linerule_Exact: { var ExactValue = Math.max( 1, ParaPr.Spacing.Line ); LineGap = ExactValue - ( TextAscent + TextDescent ); var Gap = this.Ascent + this.Descent - ExactValue; if ( Gap > 0 ) { var DescentDiff = this.Descent - this.TextDescent; if ( DescentDiff > 0 ) { if ( DescentDiff < Gap ) { this.Descent = this.TextDescent; Gap -= DescentDiff; } else { this.Descent -= Gap; Gap = 0; } } var AscentDiff = this.Ascent - this.TextAscent; if ( AscentDiff > 0 ) { if ( AscentDiff < Gap ) { this.Ascent = this.TextAscent; Gap -= AscentDiff; } else { this.Ascent -= Gap; Gap = 0; } } if ( Gap > 0 ) { // Уменьшаем пропорционально TextAscent и TextDescent var OldTA = this.TextAscent; var OldTD = this.TextDescent; var Sum = OldTA + OldTD; this.Ascent = OldTA * (Sum - Gap) / Sum; this.Descent = OldTD * (Sum - Gap) / Sum; } } else { this.Ascent -= Gap; // все в Ascent } LineGap = 0; break; } case linerule_AtLeast: { var LineGap1 = ParaPr.Spacing.Line; var LineGap2 = TextAscent + TextDescent; LineGap = Math.max( LineGap1, LineGap2 ) - ( TextAscent + TextDescent ); break; } } return LineGap; } } function CParaLine(StartPos) { this.Y = 0; // this.W = 0; this.Top = 0; this.Bottom = 0; this.Words = 0; this.Spaces = 0; // Количество пробелов между словами в строке (пробелы, идущие в конце строки, не учитываются) this.Metrics = new CParaLineMetrics(); this.Ranges = new Array(); // Массив CParaLineRanges this.RangeY = false; this.StartPos = StartPos; // Позиция в контенте параграфа, с которой начинается данная строка this.EndPos = StartPos; // Позиция последнего элемента в данной строке } CParaLine.prototype = { Add_Range : function(X, XEnd) { this.Ranges.push( new CParaLineRange( X, XEnd ) ); }, Shift : function(Dx, Dy) { var RangesCount = this.Ranges.length; for ( var Index = 0; Index < RangesCount; Index++ ) { this.Ranges[Index].Shift( Dx, Dy ); } }, Set_RangeStartPos : function(CurRange, StartPos) { if ( 0 === CurRange ) this.StartPos = StartPos; this.Ranges[CurRange].StartPos = StartPos; }, Reset : function(StartPos) { //this.Y = 0; // this.Top = 0; this.Bottom = 0; this.Words = 0; this.Spaces = 0; // Количество пробелов между словами в строке (пробелы, идущие в конце строки, не учитываются) this.Metrics = new CParaLineMetrics(); this.Ranges = new Array(); // Массив CParaLineRanges //this.RangeY = false; this.StartPos = StartPos; }, Set_EndPos : function(EndPos, Paragraph) { this.EndPos = EndPos; var Content = Paragraph.Content; var RangesCount = this.Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var Range = this.Ranges[CurRange]; var StartRangePos = Range.StartPos; var EndRangePos = ( CurRange === RangesCount - 1 ? EndPos : this.Ranges[CurRange + 1].StartPos - 1 ); var nSpacesCount = 0; var bWord = false; var nSpaceLen = 0; var nSpacePos = -1; var nStartPos2 = -1; var nEndPos2 = -1; Range.W = 0; Range.Words = 0; Range.Spaces = 0; for ( var Pos = StartRangePos; Pos <= EndRangePos; Pos++ ) { var Item = Content[Pos]; if ( Pos === Paragraph.Numbering.Pos ) Range.W += Paragraph.Numbering.WidthVisible; switch( Item.Type ) { case para_Text: { if ( true != bWord ) { bWord = true; Range.Words++; } Range.W += Item.Width; // Если текущий символ, например, дефис, тогда на нем заканчивается слово if ( true === Item.SpaceAfter ) { Range.W += nSpaceLen; // Пробелы перед первым словом в строке не считаем if ( Range.Words > 1 ) Range.Spaces += nSpacesCount; bWord = false; nSpaceLen = 0; nSpacesCount = 0; } if ( EndRangePos === Pos ) Range.W += nSpaceLen; if ( -1 === nSpacePos ) nSpacePos = Pos; if ( -1 === nStartPos2 ) nStartPos2 = Pos; nEndPos2 = Pos; break; } case para_Space: { if ( true === bWord ) { Range.W += nSpaceLen; // Пробелы перед первым словом в строке не считаем if ( Range.Words > 1 ) Range.Spaces += nSpacesCount; bWord = false; nSpacesCount = 1; nSpaceLen = 0; } else nSpacesCount++; nSpaceLen += Item.Width; break; } case para_Drawing: { Range.Words++; Range.W += nSpaceLen; Range.Spaces += nSpacesCount; bWord = false; nSpacesCount = 0; nSpaceLen = 0; if ( true === Item.Is_Inline() || true === Paragraph.Parent.Is_DrawingShape() ) { Range.W += Item.Width; if ( -1 === nSpacePos ) nSpacePos = Pos; if ( -1 === nStartPos2 ) nStartPos2 = Pos; nEndPos2 = Pos; } break; } case para_PageNum: { Range.Words++; Range.W += nSpaceLen; Range.Spaces += nSpacesCount; bWord = false; nSpacesCount = 0; nSpaceLen = 0; Range.W += Item.Width; if ( -1 === nSpacePos ) nSpacePos = Pos; if ( -1 === nStartPos2 ) nStartPos2 = Pos; nEndPos2 = Pos; break; } case para_Tab: { Range.W += Item.Width; Range.W += nSpaceLen; Range.Words = 0; Range.Spaces = 0; nSpaceLen = 0; nSpacesCount = 0; bWord = false; nSpacePos = -1; break; } case para_NewLine: { if ( bWord && Range.Words > 1 ) Range.Spaces += nSpacesCount; nSpacesCount = 0; bWord = false; break; } case para_End: { if ( true === bWord ) Range.Spaces += nSpacesCount; break; } } } Range.SpacePos = nSpacePos; Range.StartPos2 = ( nStartPos2 === -1 ? StartRangePos : nStartPos2 ); Range.EndPos2 = ( nEndPos2 === -1 ? EndRangePos : nEndPos2 ); } } }; function CDocumentBounds(Left, Top, Right, Bottom) { this.Bottom = Bottom; this.Left = Left; this.Right = Right; this.Top = Top; } CDocumentBounds.prototype = { Shift : function(Dx, Dy) { this.Bottom += Dy; this.Top += Dy; this.Left += Dx; this.Right += Dx; } }; function CParaPage(X, Y, XLimit, YLimit, FirstLine) { this.X = X; this.Y = Y; this.XLimit = XLimit; this.YLimit = YLimit; this.FirstLine = FirstLine; this.Bounds = new CDocumentBounds( X, Y, XLimit, Y ); this.StartLine = FirstLine; // Номер строки, с которой начинается данная страница this.EndLine = FirstLine; // Номер последней строки на данной странице this.TextPr = null; // Расситанные текстовые настройки для начала страницы } CParaPage.prototype = { Reset : function(X, Y, XLimit, YLimit, FirstLine) { this.X = X; this.Y = Y; this.XLimit = XLimit; this.YLimit = YLimit; this.FirstLine = FirstLine; this.Bounds = new CDocumentBounds( X, Y, XLimit, Y ); this.StartLine = FirstLine; }, Shift : function(Dx, Dy) { this.X += Dx; this.Y += Dy; this.XLimit += Dx; this.YLimit += Dy; this.Bounds.Shift( Dx, Dy ); }, Set_EndLine : function(EndLine) { this.EndLine = EndLine; } }; function CParaPos(Range, Line, Page, Pos) { this.Range = Range; // Номер промежутка в строке this.Line = Line; // Номер строки this.Page = Page; // Номер страницы this.Pos = Pos; // Позиция в общем массиве } // используется в Internal_Draw_3 и Internal_Draw_5 function CParaDrawingRangeLinesElement(y0, y1, x0, x1, w, r, g, b, Additional) { this.y0 = y0; this.y1 = y1; this.x0 = x0; this.x1 = x1; this.w = w; this.r = r; this.g = g; this.b = b; this.Additional = Additional; } function CParaDrawingRangeLines() { this.Elements = new Array(); } CParaDrawingRangeLines.prototype = { Clear : function() { this.Elements = new Array(); }, Add : function (y0, y1, x0, x1, w, r, g, b, Additional) { this.Elements.push( new CParaDrawingRangeLinesElement(y0, y1, x0, x1, w, r, g, b, Additional) ); }, Get_Next : function() { var Count = this.Elements.length; if ( Count <= 0 ) return null; // Соединяем, начиная с конца, чтобы проще было обрезать массив var Element = this.Elements[Count - 1]; Count--; while ( Count > 0 ) { var PrevEl = this.Elements[Count - 1]; if ( Math.abs( PrevEl.y0 - Element.y0 ) < 0.001 && Math.abs( PrevEl.y1 - Element.y1 ) < 0.001 && Math.abs( PrevEl.x1 - Element.x0 ) < 0.001 && Math.abs( PrevEl.w - Element.w ) < 0.001 && PrevEl.r === Element.r && PrevEl.g === Element.g && PrevEl.b === Element.b ) { Element.x0 = PrevEl.x0; Count--; } else break; } this.Elements.length = Count; return Element; }, Correct_w_ForUnderline : function() { var Count = this.Elements.length; if ( Count <= 0 ) return; var CurElements = new Array(); for ( var Index = 0; Index < Count; Index++ ) { var Element = this.Elements[Index]; var CurCount = CurElements.length; if ( 0 === CurCount ) CurElements.push( Element ); else { var PrevEl = CurElements[CurCount - 1]; if ( Math.abs( PrevEl.y0 - Element.y0 ) < 0.001 && Math.abs( PrevEl.y1 - Element.y1 ) < 0.001 && Math.abs( PrevEl.x1 - Element.x0 ) < 0.001 ) { // Сравниваем толщины линий if ( Element.w > PrevEl.w ) { for ( var Index2 = 0; Index2 < CurCount; Index2++ ) CurElements[Index2].w = Element.w; } else Element.w = PrevEl.w; CurElements.push( Element ); } else { CurElements.length = 0; CurElements.push( Element ); } } } } };
Word/Editor/Paragraph.js
// При добавлении нового элемента ParagraphContent, добавить его обработку в // следующие функции: // Internal_Recalculate1, Internal_Recalculate2, Draw, Internal_RemoveBackward, // Internal_RemoveForward, Add, Internal_GetStartPos, Internal_MoveCursorBackward, // Internal_MoveCursorForward, Internal_AddTextPr, Internal_GetContentPosByXY, // Selection_SetEnd, Selection_CalculateTextPr, IsEmpty, Selection_IsEmpty, // Cursor_IsStart, Cursor_IsEnd, Is_ContentOnFirstPage var type_Paragraph = 0x0001; var UnknownValue = null; // Класс Paragraph function Paragraph(DrawingDocument, Parent, PageNum, X, Y, XLimit, YLimit) { this.Id = g_oIdCounter.Get_NewId(); this.Prev = null; this.Next = null; this.Index = -1; this.Parent = Parent; this.PageNum = PageNum; this.X = X; this.Y = Y; this.XLimit = XLimit; this.YLimit = YLimit; this.CompiledPr = { Pr : null, // Скомпилированный (окончательный стиль параграфа) NeedRecalc : true // Нужно ли пересчитать скомпилированный стиль }; this.Pr = new CParaPr(); // Рассчитанное положение рамки this.CalculatedFrame = { L : 0, // Внутренний рект, по которому идет рассчет T : 0, W : 0, H : 0, L2 : 0, // Внешний рект, с учетом границ T2 : 0, W2 : 0, H2 : 0, PageIndex : 0 }; // Данный TextPr будет относится только к символу конца параграфа this.TextPr = new ParaTextPr(); this.TextPr.Parent = this; this.Bounds = new CDocumentBounds( X, Y, X_Right_Field, Y ); this.RecalcInfo = new CParaRecalcInfo(); this.Pages = new Array(); // Массив страниц (CParaPage) this.Lines = new Array(); // Массив строк (CParaLine) // Добавляем в контент элемент "конец параграфа" this.Content = new Array(); this.Content[0] = new ParaEnd(); this.Content[1] = new ParaEmpty(); this.Numbering = new ParaNumbering(); this.CurPos = { X : 0, Y : 0, ContentPos : 0, Line : -1, RealX : 0, // позиция курсора, без учета расположения букв RealY : 0, // это актуально для клавиш вверх и вниз PagesPos : 0 // позиция в массиве this.Pages }; this.Selection = { Start : false, Use : false, StartPos : 0, EndPos : 0, Flag : selectionflag_Common }; this.NeedReDraw = true; this.DrawingDocument = DrawingDocument; this.LogicDocument = editor.WordControl.m_oLogicDocument; this.TurnOffRecalcEvent = false; this.ApplyToAll = false; // Специальный параметр, используемый в ячейках таблицы. // True, если ячейка попадает в выделение по ячейкам. this.Lock = new CLock(); // Зажат ли данный параграф другим пользователем if ( false === g_oIdCounter.m_bLoad ) { this.Lock.Set_Type( locktype_Mine, false ); CollaborativeEditing.Add_Unlock2( this ); } this.DeleteCollaborativeMarks = true; this.DeleteCommentOnRemove = true; // Удаляем ли комменты в функциях Internal_Content_Remove this.m_oContentChanges = new CContentChanges(); // список изменений(добавление/удаление элементов) // Свойства необходимые для презентаций this.PresentationPr = { Level : 0, Bullet : new CPresentationBullet() }; this.FontMap = { Map : {}, NeedRecalc : true }; this.SearchResults = new Object(); this.SpellChecker = new CParaSpellChecker(); // Добавляем данный класс в таблицу Id (обязательно в конце конструктора) g_oTableId.Add( this, this.Id ); } Paragraph.prototype = { GetType : function() { return type_Paragraph; }, GetId : function() { return this.Id; }, SetId : function(newId) { g_oTableId.Reset_Id( this, newId, this.Id ); this.Id = newId; }, Get_Id : function() { return this.GetId(); }, Set_Id : function(newId) { return this.SetId( newId ); }, Use_Wrap : function() { if ( undefined != this.Get_FramePr() ) return false; return true; }, Use_YLimit : function() { if ( undefined != this.Get_FramePr() && this.Parent instanceof CDocument ) return false; return true; }, Set_Pr : function(oNewPr) { var Pr_old = this.Pr; var Pr_new = oNewPr; History.Add( this, { Type : historyitem_Paragraph_Pr, Old : Pr_old, New : Pr_new } ); this.Pr = oNewPr; }, Copy : function(Parent) { var Para = new Paragraph(this.DrawingDocument, Parent, 0, 0, 0, 0, 0); // Копируем настройки Para.Set_Pr(this.Pr.Copy()); Para.TextPr.Set_Value( this.TextPr.Value ); // Удаляем содержимое нового параграфа Para.Internal_Content_Remove2(0, Para.Content.length); // Копируем содержимое параграфа var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( true === Item.Is_RealContent() ) Para.Internal_Content_Add( Para.Content.length, Item.Copy(), false ); } return Para; }, Get_AllDrawingObjects : function(DrawingObjs) { if ( undefined === DrawingObjs ) DrawingObjs = new Array(); var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; if ( para_Drawing === Item.Type ) DrawingObjs.push( Item ); } return DrawingObjs; }, Get_AllParagraphs_ByNumbering : function(NumPr, ParaArray) { var _NumPr = this.Numbering_Get(); if ( undefined != _NumPr && _NumPr.NumId === NumPr.NumId && ( _NumPr.Lvl === NumPr.Lvl || undefined === NumPr.Lvl ) ) ParaArray.push( this ); var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; if ( para_Drawing === Item.Type ) Item.Get_AllParagraphs_ByNumbering( NumPr, ParaArray ); } }, Get_PageBounds : function(PageIndex) { return this.Pages[PageIndex].Bounds; }, Get_EmptyHeight : function() { var Pr = this.Get_CompiledPr(); var EndTextPr = Pr.TextPr.Copy(); EndTextPr.Merge( this.TextPr.Value ); g_oTextMeasurer.SetTextPr( EndTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII ); return g_oTextMeasurer.GetHeight(); }, Reset : function (X,Y, XLimit, YLimit, PageNum) { this.X = X; this.Y = Y; this.XLimit = XLimit; this.YLimit = YLimit; this.PageNum = PageNum; // При первом пересчете параграфа this.Parent.RecalcInfo.Can_RecalcObject() всегда будет true, а вот при повторных уже нет if ( true === this.Parent.RecalcInfo.Can_RecalcObject() ) { var Ranges = this.Parent.CheckRange( X, Y, XLimit, Y, Y, Y, X, XLimit, this.PageNum, true ); if ( Ranges.length > 0 ) { if ( Math.abs(Ranges[0].X0 - X ) < 0.001 ) this.X_ColumnStart = Ranges[0].X1; else this.X_ColumnStart = X; if ( Math.abs(Ranges[Ranges.length - 1].X1 - XLimit ) < 0.001 ) this.X_ColumnEnd = Ranges[Ranges.length - 1].X0; else this.X_ColumnEnd = XLimit; } else { this.X_ColumnStart = X; this.X_ColumnEnd = XLimit; } } }, // Копируем свойства параграфа CopyPr : function(OtherParagraph) { return this.CopyPr_Open(OtherParagraph); /* var bHistory = History.Is_On(); History.TurnOff(); OtherParagraph.X = this.X; OtherParagraph.XLimit = this.XLimit; if ( "undefined" != typeof(OtherParagraph.NumPr) ) OtherParagraph.Numbering_Remove(); var NumPr = this.Numbering_Get(); if ( null != NumPr ) { OtherParagraph.Numbering_Add( NumPr.NumId, NumPr.Lvl ); } // Копируем прямые настройки параграфа в конце, потому что, например, нумерация может // их изменить. OtherParagraph.Pr = Common_CopyObj( this.Pr ); OtherParagraph.Style_Add( this.Style_Get(), true ); if ( true === bHistory ) History.TurnOn(); */ }, // Копируем свойства параграфа при открытии и копировании CopyPr_Open : function(OtherParagraph) { OtherParagraph.X = this.X; OtherParagraph.XLimit = this.XLimit; if ( "undefined" != typeof(OtherParagraph.NumPr) ) OtherParagraph.Numbering_Remove(); var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { OtherParagraph.Numbering_Set( NumPr.NumId, NumPr.Lvl ); } var Bullet = this.Get_PresentationNumbering(); if ( numbering_presentationnumfrmt_None != Bullet.Get_Type() ) OtherParagraph.Add_PresentationNumbering( Bullet.Copy() ); OtherParagraph.Set_PresentationLevel( this.PresentationPr.Level ); // Копируем прямые настройки параграфа в конце, потому что, например, нумерация может // их изменить. var oOldPr = OtherParagraph.Pr; OtherParagraph.Pr = this.Pr.Copy(); History.Add( OtherParagraph, { Type : historyitem_Paragraph_Pr, Old : oOldPr, New : OtherParagraph.Pr } ); OtherParagraph.Style_Add( this.Style_Get(), true ); }, // Добавляем элемент в содержимое параграфа. (Здесь передвигаются все позиции // CurPos.ContentPos, Selection.StartPos, Selection.EndPos) Internal_Content_Add : function (Pos, Item, bCorrectPos) { if ( true === Item.Is_RealContent() ) { var ClearPos = this.Internal_Get_ClearPos( Pos ); History.Add( this, { Type : historyitem_Paragraph_AddItem, Pos : ClearPos, EndPos : ClearPos, Items : [ Item ] } ); } this.Content.splice( Pos, 0, Item ); if ( this.CurPos.ContentPos >= Pos ) this.Set_ContentPos( this.CurPos.ContentPos + 1, bCorrectPos ); if ( this.Selection.StartPos >= Pos ) this.Selection.StartPos++; if ( this.Selection.EndPos >= Pos ) this.Selection.EndPos++; if ( this.Numbering.Pos >= Pos ) this.Numbering.Pos++; // Также передвинем всем метки переносов страниц и строк var LinesCount = this.Lines.length; for ( var CurLine = 0; CurLine < LinesCount; CurLine++ ) { if ( this.Lines[CurLine].StartPos > Pos ) this.Lines[CurLine].StartPos++; if ( this.Lines[CurLine].EndPos + 1 > Pos ) this.Lines[CurLine].EndPos++; var RangesCount = this.Lines[CurLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos > Pos ) this.Lines[CurLine].Ranges[CurRange].StartPos++; } } // TODO: Как только мы избавимся от ParaNumbering в контенте параграфа, можно будет здесь такую обработку убрать // и делать ее конкретно на Replace // Передвинем все метки поиска for ( var CurSearch in this.SearchResults ) { if ( this.SearchResults[CurSearch].StartPos >= Pos ) this.SearchResults[CurSearch].StartPos++; if ( this.SearchResults[CurSearch].EndPos >= Pos ) this.SearchResults[CurSearch].EndPos++; } // Передвинем все метки слов для проверки орфографии this.SpellChecker.Update_OnAdd( this, Pos, Item ); }, Internal_Content_Add2 : function (Pos, Item, bCorrectPos) { if ( true === Item.Is_RealContent() ) { var ClearPos = this.Internal_Get_ClearPos( Pos ); History.Add( this, { Type : historyitem_Paragraph_AddItem, Pos : ClearPos, EndPos : ClearPos, Items : [ Item ] } ); } this.Content.splice( Pos, 0, Item ); // Передвинем все метки поиска for ( var CurSearch in this.SearchResults ) { if ( this.SearchResults[CurSearch].StartPos >= Pos ) this.SearchResults[CurSearch].StartPos++; if ( this.SearchResults[CurSearch].EndPos >= Pos ) this.SearchResults[CurSearch].EndPos++; } }, // Добавляем несколько элементов в конец параграфа. Internal_Content_Concat : function(Items) { // Добавляем только постоянные элементы параграфа var NewItems = new Array(); var ItemsCount = Items.length; for ( var Index = 0; Index < ItemsCount; Index++ ) { if ( true === Items[Index].Is_RealContent() ) NewItems.push( Items[Index] ); } if ( NewItems.length <= 0 ) return; var StartPos = this.Content.length; this.Content = this.Content.concat( NewItems ); History.Add( this, { Type : historyitem_Paragraph_AddItem, Pos : this.Internal_Get_ClearPos( StartPos ), EndPos : this.Internal_Get_ClearPos( this.Content.length - 1 ), Items : NewItems } ); this.RecalcInfo.Set_Type_0_Spell( pararecalc_0_Spell_All ); }, // Удаляем элемент из содержимого параграфа. (Здесь передвигаются все позиции // CurPos.ContentPos, Selection.StartPos, Selection.EndPos) Internal_Content_Remove : function (Pos) { var Item = this.Content[Pos]; if ( true === Item.Is_RealContent() ) { var ClearPos = this.Internal_Get_ClearPos( Pos ); History.Add( this, { Type : historyitem_Paragraph_RemoveItem, Pos : ClearPos, EndPos : ClearPos, Items : [ Item ] } ); } if ( this.Selection.StartPos <= this.Selection.EndPos ) { if ( this.Selection.StartPos > Pos ) this.Selection.StartPos--; if ( this.Selection.EndPos > Pos ) this.Selection.EndPos--; } else { if ( this.Selection.StartPos > Pos ) this.Selection.StartPos--; if ( this.Selection.EndPos > Pos ) this.Selection.EndPos--; } if ( this.Numbering.Pos > Pos ) this.Numbering.Pos--; // Также передвинем всем метки переносов страниц и строк var LinesCount = this.Lines.length; for ( var CurLine = 0; CurLine < LinesCount; CurLine++ ) { if ( this.Lines[CurLine].StartPos > Pos ) this.Lines[CurLine].StartPos--; if ( this.Lines[CurLine].EndPos >= Pos ) this.Lines[CurLine].EndPos--; var RangesCount = this.Lines[CurLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos > Pos ) this.Lines[CurLine].Ranges[CurRange].StartPos--; } } // TODO: Как только мы избавимся от ParaNumbering в контенте параграфа, можно будет здесь такую обработку убрать // и делать ее конкретно на Replace // Передвинем все метки поиска for ( var CurSearch in this.SearchResults ) { if ( this.SearchResults[CurSearch].StartPos > Pos ) this.SearchResults[CurSearch].StartPos--; if ( this.SearchResults[CurSearch].EndPos > Pos ) this.SearchResults[CurSearch].EndPos--; } this.Content.splice( Pos, 1 ); if ( this.CurPos.ContentPos > Pos ) this.Set_ContentPos( this.CurPos.ContentPos - 1 ); // Комментарий удаляем после, чтобы не нарушить позиции if ( true === this.DeleteCommentOnRemove && ( para_CommentStart === Item.Type || para_CommentEnd === Item.Type ) ) { // Удаляем комментарий, если у него было удалено начало или конец if ( para_CommentStart === Item.Type ) editor.WordControl.m_oLogicDocument.Comments.Set_StartInfo( Item.Id, 0, 0, 0, 0, null ); else editor.WordControl.m_oLogicDocument.Comments.Set_EndInfo( Item.Id, 0, 0, 0, 0, null ); editor.WordControl.m_oLogicDocument.Remove_Comment( Item.Id, true ); } // Передвинем все метки слов для проверки орфографии this.SpellChecker.Update_OnRemove( this, Pos, 1 ); }, // Удаляем несколько элементов Internal_Content_Remove2 : function(Pos, Count) { var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var CommentsToDelete = new Object(); for ( var Index = Pos; Index < Pos + Count; Index++ ) { var ItemType = this.Content[Index].Type; if ( true === this.DeleteCommentOnRemove && (para_CommentStart === ItemType || para_CommentEnd === ItemType) ) { if ( para_CommentStart === ItemType ) DocumentComments.Set_StartInfo( this.Content[Index].Id, 0, 0, 0, 0, null ); else DocumentComments.Set_EndInfo( this.Content[Index].Id, 0, 0, 0, 0, null ); CommentsToDelete[this.Content[Index].Id] = 1; } } var LastArray = this.Content.slice( Pos, Pos + Count ); // Добавляем только постоянные элементы параграфа var LastItems = new Array(); var ItemsCount = LastArray.length; for ( var Index = 0; Index < ItemsCount; Index++ ) { if ( true === LastArray[Index].Is_RealContent() ) LastItems.push( LastArray[Index] ); } History.Add( this, { Type : historyitem_Paragraph_RemoveItem, Pos : this.Internal_Get_ClearPos( Pos ), EndPos : this.Internal_Get_ClearPos(Pos + Count - 1), Items : LastItems } ); if ( this.CurPos.ContentPos > Pos ) { if ( this.CurPos.ContentPos > Pos + Count ) this.Set_ContentPos( this.CurPos.ContentPos - Count, true, -1 ); else this.Set_ContentPos( Pos, true, -1 ); } if ( this.Selection.StartPos <= this.Selection.EndPos ) { if ( this.Selection.StartPos > Pos ) { if ( this.Selection.StartPos > Pos + Count ) this.Selection.StartPos -= Count; else this.Selection.StartPos = Pos; } if ( this.Selection.EndPos > Pos ) { if ( this.Selection.EndPos >= Pos + Count ) this.Selection.EndPos -= Count; else this.Selection.EndPos = Math.max( 0, Pos - 1 ); } } else { if ( this.Selection.StartPos > Pos ) { if ( this.Selection.StartPos >= Pos + Count ) this.Selection.StartPos -= Count; else this.Selection.StartPos = Math.max( 0, Pos - 1 ); } if ( this.Selection.EndPos > Pos ) { if ( this.Selection.EndPos > Pos + Count ) this.Selection.EndPos -= Count; else this.Selection.EndPos = Pos; } } // Также передвинем всем метки переносов страниц и строк var LinesCount = this.Lines.length; for ( var CurLine = 0; CurLine < LinesCount; CurLine++ ) { if ( this.Lines[CurLine].StartPos > Pos ) { if ( this.Lines[CurLine].StartPos > Pos + Count ) this.Lines[CurLine].StartPos -= Count; else this.Lines[CurLine].StartPos = Math.max( 0 , Pos ); } if ( this.Lines[CurLine].EndPos >= Pos ) { if ( this.Lines[CurLine].EndPos >= Pos + Count ) this.Lines[CurLine].EndPos -= Count; else this.Lines[CurLine].EndPos = Math.max( 0 , Pos ); } var RangesCount = this.Lines[CurLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos > Pos ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos > Pos + Count ) this.Lines[CurLine].Ranges[CurRange].StartPos -= Count; else this.Lines[CurLine].Ranges[CurRange].StartPos = Math.max( 0 , Pos ); } } } this.Content.splice( Pos, Count ); // Комментарии удаляем после, чтобы не нарушить позиции for ( var Id in CommentsToDelete ) { editor.WordControl.m_oLogicDocument.Remove_Comment( Id, true ); } // Передвинем все метки слов для проверки орфографии this.SpellChecker.Update_OnRemove( this, Pos, Count ); }, Internal_Check_EmptyHyperlink : function(Pos) { var Start = this.Internal_FindBackward( Pos, [ para_Text, para_Drawing, para_Space, para_Tab, para_PageNum, para_HyperlinkStart ] ); var End = this.Internal_FindForward ( Pos, [ para_Text, para_Drawing, para_Space, para_Tab, para_PageNum, para_HyperlinkEnd, para_End ] ); if ( true === Start.Found && para_HyperlinkStart === Start.Type && true === End.Found && para_HyperlinkEnd === End.Type ) { this.Internal_Content_Remove( End.LetterPos ); this.Internal_Content_Remove( Start.LetterPos ); } }, Clear_ContentChanges : function() { this.m_oContentChanges.Clear(); }, Add_ContentChanges : function(Changes) { this.m_oContentChanges.Add( Changes ); }, Refresh_ContentChanges : function() { this.m_oContentChanges.Refresh(); }, Internal_Get_ParaPos_By_Pos : function(ContentPos) { /* var CurLine = this.Lines.length - 1; for ( ; CurLine > 0; CurLine-- ) { if ( this.Lines[CurLine].StartPos <= ContentPos ) break; } var CurRange = this.Lines[CurLine].Ranges.length - 1; for ( ; CurRange > 0; CurRange-- ) { if ( this.Lines[CurLine].Ranges[CurRange].StartPos <= ContentPos ) break; } var CurPage = this.Pages.length - 1; for ( ; CurPage > 0; CurPage-- ) { if ( this.Pages[CurPage].StartLine <= CurLine ) break; } */ var _ContentPos = ContentPos; while ( undefined === this.Content[_ContentPos].CurPage ) { _ContentPos--; if ( _ContentPos < 0 ) return new CParaPos( 0, 0, 0, 0 ); } if ( _ContentPos === this.CurPos.ContentPos && -1 != this.CurPos.Line ) return new CParaPos( this.Content[_ContentPos].CurRange, this.CurPos.Line, this.Content[_ContentPos].CurPage, ContentPos ); return new CParaPos( this.Content[_ContentPos].CurRange, this.Content[_ContentPos].CurLine, this.Content[_ContentPos].CurPage, ContentPos ); }, Internal_Get_ParaPos_By_Page : function(Page) { var CurPage = Page; var CurLine = this.Pages[CurPage].StartLine; var CurRange = 0; var CurPos = this.Lines[CurLine].StartPos; return new CParaPos( CurRange, CurLine, CurPage, CurPos ); }, Internal_Update_ParaPos : function(CurPage, CurLine, CurRange, CurPos) { var _CurPage = CurPage; var _CurLine = CurLine; var _CurRange = CurRange; // Проверяем переход на новую страницу while ( _CurPage < this.Pages.length - 1 ) { if ( this.Lines[this.Pages[_CurPage + 1].StartLine].StartPos <= CurPos ) { _CurPage++; _CurLine = this.Pages[_CurPage].StartLine; _CurRange = 0; } else break; } while ( _CurLine < this.Lines.length - 1 ) { if ( this.Lines[_CurLine + 1].StartPos <= CurPos ) { _CurLine++; _CurRange = 0; } else break; } while ( _CurRange < this.Lines[_CurLine].Ranges.length - 1 ) { if ( this.Lines[_CurLine].Ranges[_CurRange + 1].StartPos <= CurPos ) { _CurRange++; } else break; } return new CParaPos( _CurRange, _CurLine, _CurPage, CurPos ); }, // Рассчитываем текст Internal_Recalculate_0 : function() { if ( pararecalc_0_None === this.RecalcInfo.Recalc_0_Type ) return; var Pr = this.Get_CompiledPr(); var ParaPr = Pr.ParaPr; var CurTextPr = Pr.TextPr; // Предполагается, что при вызове данной функции Content не содержит // рассчитанных переносов строк. g_oTextMeasurer.SetTextPr( CurTextPr ); // Под Descent мы будем понимать descent + linegap (которые записаны в шрифте) var TextAscent = 0; var TextHeight = 0; var TextDescent = 0; g_oTextMeasurer.SetFontSlot( fontslot_ASCII ); TextHeight = g_oTextMeasurer.GetHeight(); TextDescent = Math.abs( g_oTextMeasurer.GetDescender() ); TextAscent = TextHeight - TextDescent; TextAscent2 = g_oTextMeasurer.GetAscender(); var ContentLength = this.Content.length; if ( para_PresentationNumbering === this.Numbering.Type ) { var Item = this.Numbering; var Level = this.PresentationPr.Level; var Bullet = this.PresentationPr.Bullet; var BulletNum = 0; if ( Bullet.Get_Type() >= numbering_presentationnumfrmt_ArabicPeriod ) { var Prev = this.Prev; while ( null != Prev && type_Paragraph === Prev.GetType() ) { var PrevLevel = Prev.PresentationPr.Level; var PrevBullet = Prev.Get_PresentationNumbering(); // Если предыдущий параграф более низкого уровня, тогда его не учитываем if ( Level < PrevLevel ) { Prev = Prev.Prev; continue; } else if ( Level > PrevLevel ) break; else if ( PrevBullet.Get_Type() === Bullet.Get_Type() && PrevBullet.Get_StartAt() === PrevBullet.Get_StartAt() ) { if ( true != Prev.IsEmpty() ) BulletNum++; Prev = Prev.Prev; } else break; } } // Найдем настройки для первого текстового элемента var FirstTextPr = this.Internal_CalculateTextPr( this.Internal_GetStartPos() ); Item.Bullet = Bullet; Item.BulletNum = BulletNum + 1; Item.Measure( g_oTextMeasurer, FirstTextPr ); } for ( var Pos = 0; Pos < ContentLength; Pos++ ) { var Item = this.Content[Pos]; switch( Item.Type ) { case para_Text: case para_Space: case para_PageNum: { Item.Measure( g_oTextMeasurer, CurTextPr); break; } case para_Drawing: { Item.Parent = this; Item.DocumentContent = this.Parent; Item.DrawingDocument = this.Parent.DrawingDocument; Item.Measure( g_oTextMeasurer, CurTextPr); break; } case para_Tab: case para_NewLine: { Item.Measure( g_oTextMeasurer); break; } case para_TextPr: { Item.Parent = this; CurTextPr = this.Internal_CalculateTextPr( Pos ); Item.CalcValue = CurTextPr; // копировать не надо, т.к. CurTextPr здесь дальше не меняется, а в функции он создается изначально g_oTextMeasurer.SetTextPr( CurTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII ); TextDescent = Math.abs( g_oTextMeasurer.GetDescender() ); TextHeight = g_oTextMeasurer.GetHeight(); TextAscent = TextHeight - TextDescent; TextAscent2 = g_oTextMeasurer.GetAscender(); break; } case para_End: { var bEndCell = false; if ( null === this.Get_DocumentNext() && true === this.Parent.Is_TableCellContent() ) bEndCell = true; var EndTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); EndTextPr.Merge( this.TextPr.Value ); Item.TextPr = EndTextPr; g_oTextMeasurer.SetTextPr( EndTextPr ); Item.Measure( g_oTextMeasurer, bEndCell ); TextDescent = Math.abs( g_oTextMeasurer.GetDescender() ); TextHeight = g_oTextMeasurer.GetHeight(); TextAscent = TextHeight - TextDescent; TextAscent2 = g_oTextMeasurer.GetAscender(); g_oTextMeasurer.SetTextPr( CurTextPr ); break; } } Item.TextAscent = TextAscent; Item.TextDescent = TextDescent; Item.TextHeight = TextHeight; Item.TextAscent2 = TextAscent2; Item.YOffset = CurTextPr.Position; } this.RecalcInfo.Set_Type_0( pararecalc_0_None ); }, // Пересчет переносов строк в параграфе, с учетом возможного обтекания Internal_Recalculate_1_ : function(StartPos, CurPage, _CurLine) { var Pr = this.Get_CompiledPr(); var ParaPr = Pr.ParaPr; var CurLine = _CurLine; // Смещаемся в начало параграфа на первой странице или в начало страницы, если страница не первая var X, Y, XLimit, YLimit, _X, _XLimit; if ( 0 === CurPage || undefined != this.Get_FramePr() ) { X = this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; Y = this.Y; XLimit = this.XLimit - ParaPr.Ind.Right; YLimit = this.YLimit; _X = this.X; _XLimit = this.XLimit; } else { // Запрашиваем у документа начальные координаты на новой странице var PageStart = this.Parent.Get_PageContentStartPos( this.PageNum + CurPage ); X = ( 0 != CurLine ? PageStart.X + ParaPr.Ind.Left : PageStart.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine ); Y = PageStart.Y; XLimit = PageStart.XLimit - ParaPr.Ind.Right; YLimit = PageStart.YLimit; _X = PageStart.X; _XLimit = PageStart.XLimit; } // Предполагается, что при вызове данной функции Content не содержит // рассчитанных переносов строк в промежутке StartPos и EndPos. this.Pages.length = CurPage + 1; this.Pages[CurPage] = new CParaPage( _X, Y, _XLimit, YLimit, CurLine ); this.Pages[CurPage].TextPr = this.Internal_CalculateTextPr( StartPos, Pr ); var LineStart_Pos = StartPos; if ( 0 === CurPage ) { // Пересчитываем правую и левую границы параграфа if ( ParaPr.Ind.FirstLine <= 0 ) this.Bounds.Left = X; else this.Bounds.Left = this.X + ParaPr.Ind.Left; this.Bounds.Right = XLimit; } var bFirstItemOnLine = true; // контролируем первое появление текста на строке var bEmptyLine = true; // Есть ли в строке текст, картинки или др. видимые объекты var bStartWord = false; // началось ли слово в строке var bWord = false; var nWordStartPos = 0; var nWordLen = 0; var nSpaceLen = 0; var nSpacesCount = 0; var pLastTab = { TabPos : 0, X : 0, Value : -1, Item : null }; var bNewLine = false; var bNewRange = false; var bNewPage = false; var bExtendBoundToBottom = false; var bEnd = false; var bForceNewPage = false; var bBreakPageLine = false; if ( CurPage > 1 ) bAddNumbering = false; else if ( 0 === CurPage ) bAddNumbering = true; else { // Проверим, есть ли какие-нибудь реальные элементы (к которым можно было бы // дорисовать нумерацию) до стартовой позиции текущей страницы for ( var Pos = 0; Pos < StartPos; Pos++ ) { var Item = this.Content[Pos]; if ( true === Item.Can_AddNumbering() ) bAddNumbering = false; } } // Получаем промежутки обтекания, т.е. промежутки, которые нам нельзя использовать var Ranges = [];//this.Parent.CheckRange( X, Y, XLimit, Y, Y, Y, this.PageNum + CurPage, true ); var RangesCount = Ranges.length; // Под Descent мы будем понимать descent + linegap (которые записаны в шрифте) var TextAscent = 0; var TextDescent = 0; var TextAscent2 = 0; this.Lines.length = CurLine + 1; this.Lines[CurLine] = new CParaLine(StartPos); var LineTextAscent = 0; var LineTextDescent = 0; var LineTextAscent2 = 0; var LineAscent = 0; var LineDescent = 0; // Выставляем начальные сдвиги для промежутков. Начало промежутка = конец вырезаемого промежутка this.Lines[CurLine].Add_Range( X, (RangesCount == 0 ? XLimit : Ranges[0].X0) ); this.Lines[CurLine].Set_RangeStartPos( 0, StartPos ); for ( var Index = 1; Index < Ranges.length + 1; Index++ ) { this.Lines[CurLine].Add_Range( Ranges[Index - 1].X1, (Index == RangesCount ? XLimit : Ranges[Index].X0) ); } var CurRange = 0; var XEnd = 0; if ( RangesCount == 0 ) XEnd = XLimit; else XEnd = Ranges[0].X0; if ( this.Parent instanceof CDocument ) { // Начинаем параграф с новой страницы if ( 0 === CurPage && true === ParaPr.PageBreakBefore ) { // Если это первый элемент документа, тогда не надо начинать его с новой страницы var Prev = this.Get_DocumentPrev(); if ( null != Prev ) { // Добавляем разрыв страницы this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( StartPos - 1, this ); } return recalcresult_NextPage; } } else if ( true === this.Parent.RecalcInfo.Check_WidowControl( this, CurLine ) ) { this.Parent.RecalcInfo.Reset_WidowControl(); this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine( 0 ); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } return recalcresult_NextPage; } else if ( true === this.Parent.RecalcInfo.Check_KeepNext(this) && 0 === CurPage && null != this.Get_DocumentPrev() ) { this.Parent.RecalcInfo.Reset(); this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine( 0 ); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } return recalcresult_NextPage; } } var RecalcResult = recalcresult_NextElement; var bAddNumbering = this.Internal_CheckAddNumbering( CurPage, CurLine, CurRange ); for ( var Pos = LineStart_Pos; Pos < this.Content.length; Pos++ ) { if ( false === bStartWord && true === bFirstItemOnLine && Math.abs(XEnd - X) < 0.001 && RangesCount > 0 ) { if ( RangesCount == CurRange ) { Pos--; bNewLine = true; } else { Pos--; bNewRange = true; } } if ( true != bNewLine && true != bNewRange ) { var Item = this.Content[Pos]; Item.Parent = this; Item.DocumentContent = this.Parent; Item.DrawingDocument = this.Parent.DrawingDocument; if ( undefined != Item.TextAscent ) TextAscent = Item.TextAscent; if ( undefined != Item.TextAscent2 ) TextAscent2 = Item.TextAscent2; if ( undefined != Item.TextDescent ) TextDescent = Item.TextDescent; // Сохраним в элементе номер строки и отрезка Item.CurPage = CurPage; Item.CurLine = CurLine; Item.CurRange = CurRange; var bBreak = false; if ( true === bAddNumbering ) { // Проверим, возможно на текущем элементе стоит добавить нумерацию if ( true === Item.Can_AddNumbering() ) { var NumberingItem = this.Numbering; var NumberingType = this.Numbering.Type; if ( para_Numbering === NumberingType ) { var NumPr = ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) { // Так мы обнуляем все рассчитанные ширины данного элемента NumberingItem.Measure( g_oTextMeasurer, undefined ); } else { var Numbering = this.Parent.Get_Numbering(); var NumLvl = Numbering.Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl]; var NumSuff = NumLvl.Suff; var NumJc = NumLvl.Jc; var NumInfo = this.Parent.Internal_GetNumInfo( this.Id, NumPr ); var NumTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); NumTextPr.Merge( this.TextPr.Value ); NumTextPr.Merge( NumLvl.TextPr ); // Здесь измеряется только ширина символов нумерации, без суффикса NumberingItem.Measure( g_oTextMeasurer, Numbering, NumInfo, NumTextPr, NumPr ); // При рассчете высоты строки, если у нас параграф со списком, то размер символа // в списке влияет только на высоту строки над Baseline, но не влияет на высоту строки // ниже baseline. if ( LineAscent < NumberingItem.Height ) LineAscent = NumberingItem.Height; switch ( NumJc ) { case align_Right: { NumberingItem.WidthVisible = 0; break; } case align_Center: { NumberingItem.WidthVisible = NumberingItem.WidthNum / 2; X += NumberingItem.WidthNum / 2; break; } case align_Left: default: { NumberingItem.WidthVisible = NumberingItem.WidthNum; X += NumberingItem.WidthNum; break; } } switch( NumSuff ) { case numbering_suff_Nothing: { // Ничего не делаем break; } case numbering_suff_Space: { var OldTextPr = g_oTextMeasurer.GetTextPr(); g_oTextMeasurer.SetTextPr( NumTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII ); NumberingItem.WidthSuff = g_oTextMeasurer.Measure( " " ).Width; g_oTextMeasurer.SetTextPr( OldTextPr ); break; } case numbering_suff_Tab: { var NewX = null; var PageStart = this.Parent.Get_PageContentStartPos( this.PageNum + CurPage ); // Если у данного параграфа есть табы, тогда ищем среди них var TabsCount = ParaPr.Tabs.Get_Count(); // Добавим в качестве таба левую границу var TabsPos = new Array(); var bCheckLeft = true; for ( var Index = 0; Index < TabsCount; Index++ ) { var Tab = ParaPr.Tabs.Get(Index); var TabPos = Tab.Pos + PageStart.X; if ( true === bCheckLeft && TabPos > PageStart.X + ParaPr.Ind.Left ) { TabsPos.push( PageStart.X + ParaPr.Ind.Left ); bCheckLeft = false; } if ( tab_Clear != Tab.Value ) TabsPos.push( TabPos ); } if ( true === bCheckLeft ) TabsPos.push( PageStart.X + ParaPr.Ind.Left ); TabsCount++; for ( var Index = 0; Index < TabsCount; Index++ ) { var TabPos = TabsPos[Index]; if ( X < TabPos ) { NewX = TabPos; break; } } // Если табов нет, либо их позиции левее текущей позиции ставим таб по умолчанию if ( null === NewX ) { if ( X < PageStart.X + ParaPr.Ind.Left ) NewX = PageStart.X + ParaPr.Ind.Left; else { NewX = this.X; while ( X >= NewX ) NewX += Default_Tab_Stop; } } NumberingItem.WidthSuff = NewX - X; break; } } NumberingItem.Width = NumberingItem.WidthNum; NumberingItem.WidthVisible += NumberingItem.WidthSuff; X += NumberingItem.WidthSuff; this.Numbering.Pos = Pos; } } else if ( para_PresentationNumbering === NumberingType ) { var Bullet = this.PresentationPr.Bullet; if ( numbering_presentationnumfrmt_None != Bullet.Get_Type() ) { if ( ParaPr.Ind.FirstLine < 0 ) NumberingItem.WidthVisible = Math.max( NumberingItem.Width, this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine - X, this.X + ParaPr.Ind.Left - X ); else NumberingItem.WidthVisible = Math.max( this.X + ParaPr.Ind.Left + NumberingItem.Width - X, this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine - X, this.X + ParaPr.Ind.Left - X ); } X += NumberingItem.WidthVisible; this.Numbering.Pos = Pos; } bAddNumbering = false; } } switch( Item.Type ) { case para_Text: { bStartWord = true; // При проверке, убирается ли слово, мы должны учитывать ширину // предшевствующих пробелов. if ( LineTextAscent < TextAscent ) LineTextAscent = TextAscent; if ( LineTextAscent2 < TextAscent2 ) LineTextAscent2 = TextAscent2; if ( LineTextDescent < TextDescent ) LineTextDescent = TextDescent; if ( linerule_Exact === ParaPr.Spacing.LineRule ) { // Смещение не учитывается в метриках строки, когда расстояние между строк точное if ( LineAscent < TextAscent ) LineAscent = TextAscent; if ( LineDescent < TextDescent ) LineDescent = TextDescent; } else { if ( LineAscent < TextAscent + Item.YOffset ) LineAscent = TextAscent + Item.YOffset; if ( LineDescent < TextDescent - Item.YOffset ) LineDescent = TextDescent - Item.YOffset; } if ( !bWord ) { // Слово только началось. Делаем следующее: // 1) Если до него на строке ничего не было и данная строка не // имеет разрывов, тогда не надо проверять убирается ли слово в строке. // 2) В противном случае, проверяем убирается ли слово в промежутке. // Если слово только началось, и до него на строке ничего не было, и в строке нет разрывов, тогда не надо проверять убирается ли оно на строке. var LetterLen = Item.Width; if ( !bFirstItemOnLine || false === this.Internal_Check_Ranges(CurLine, CurRange) ) { if ( X + nSpaceLen + LetterLen > XEnd ) { if ( RangesCount == CurRange ) { bNewLine = true; Pos--; } else { bNewRange = true; Pos--; } } } if ( !bNewLine && !bNewRange ) { nWordStartPos = Pos; nWordLen = Item.Width; bWord = true; //this.Lines[CurLine].Words++; //if ( !bNewRange ) // this.Lines[CurLine].Ranges[CurRange].Words++; } } else { var LetterLen = Item.Width; if ( X + nSpaceLen + nWordLen + LetterLen > XEnd ) { if ( bFirstItemOnLine ) { // Слово оказалось единственным элементом в промежутке, и, все равно, // не умещается целиком. Делаем следующее: // // 1) Если у нас строка без вырезов, тогда ставим перенос строки на // текущей позиции. // 2) Если у нас строка с вырезом, и данный вырез не последний, тогда // ставим перенос внутри строки в начале слова. // 3) Если у нас строка с вырезом и вырез последний, тогда ставим перенос // строки в начале слова. if ( false === this.Internal_Check_Ranges(CurLine, CurRange) ) { Pos = nWordStartPos - 1; if ( RangesCount != CurRange ) bNewRange = true; else bNewLine = true; } else { bEmptyLine = false; X += nWordLen; Pos--; if ( RangesCount != CurRange ) bNewRange = true; else bNewLine = true; } } else { // Слово не убирается в промежутке. Делаем следующее: // 1) Если у нас строка без вырезов или текущей вырез последний, // тогда ставим перенос строки в начале слова. // 2) Если строка с вырезами и вырез не последний, ставим // перенос внутри строки в начале слова. Pos = nWordStartPos; if ( RangesCount == CurRange ) { Pos--; bNewLine = true; //this.Lines[CurLine].Words--; //this.Lines[CurLine].Ranges[CurRange].Words--; } else // if ( 0 != RangesCount && RangesCount != CurRange ) { Pos--; bNewRange = true; //this.Lines[CurLine].Ranges[CurRange].Words--; } } } if ( !bNewLine && !bNewRange ) { nWordLen += LetterLen; // Если текущий символ, например, дефис, тогда на нем заканчивается слово if ( true === Item.SpaceAfter ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; // Пробелы перед первым словом в строке не считаем //if ( this.Lines[CurLine].Words > 1 ) // this.Lines[CurLine].Spaces += nSpacesCount; //if ( this.Lines[CurLine].Ranges[CurRange].Words > 1 ) // this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; bWord = false; bFirstItemOnLine = false; bEmptyLine = false; nSpaceLen = 0; nWordLen = 0; nSpacesCount = 0; } } } break; } case para_Space: { bFirstItemOnLine = false; var SpaceLen = Item.Width; if ( bWord ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; // Пробелы перед первым словом в строке не считаем //if ( this.Lines[CurLine].Words > 1 ) // this.Lines[CurLine].Spaces += nSpacesCount; //if ( this.Lines[CurLine].Ranges[CurRange].Words > 1 ) // this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; bWord = false; bEmptyLine = false; nSpaceLen = 0; nWordLen = 0; nSpacesCount = 1; } else nSpacesCount++; // На пробеле не делаем перенос. Перенос строки или внутристрочный // перенос делаем при добавлении любого непробельного символа nSpaceLen += SpaceLen; break; } case para_Drawing: { if ( true === Item.Is_Inline() || true === this.Parent.Is_DrawingShape() ) { if ( true != Item.Is_Inline() ) Item.Set_DrawingType( drawing_Inline ); if ( true === bStartWord ) bFirstItemOnLine = false; // Если до этого было слово, тогда не надо проверять убирается ли оно, но если стояли пробелы, // тогда мы их учитываем при проверке убирается ли данный элемент, и добавляем только если // данный элемент убирается if ( bWord || nWordLen > 0 ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; // Пробелы перед первым словом в строке не считаем //if ( this.Lines[CurLine].Words > 1 ) // this.Lines[CurLine].Spaces += nSpacesCount; //if ( this.Lines[CurLine].Ranges[CurRange].Words > 1 ) // this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; bWord = false; nSpaceLen = 0; nSpacesCount = 0; nWordLen = 0; } if ( X + nSpaceLen + Item.Width > XEnd && ( false === bFirstItemOnLine || false === this.Internal_Check_Ranges( CurLine, CurRange ) ) ) { if ( RangesCount == CurRange ) { bNewLine = true; Pos--; } else { bNewRange = true; Pos--; } } else { // Добавляем длину пробелов до слова X += nSpaceLen; if ( linerule_Exact === ParaPr.Spacing.LineRule ) { if ( LineAscent < Item.Height ) LineAscent = Item.Height; if ( Item.Height > this.Lines[CurLine].Metrics.Ascent ) this.Lines[CurLine].Metrics.Ascent = Item.Height; } else { if ( LineAscent < Item.Height + Item.YOffset ) LineAscent = Item.Height + Item.YOffset; if ( Item.Height + Item.YOffset > this.Lines[CurLine].Metrics.Ascent ) this.Lines[CurLine].Metrics.Ascent = Item.Height + Item.YOffset; if ( -Item.YOffset > this.Lines[CurLine].Metrics.Descent ) this.Lines[CurLine].Metrics.Descent = -Item.YOffset; } X += Item.Width; bFirstItemOnLine = false; bEmptyLine = false; //this.Lines[CurLine].Words++; //this.Lines[CurLine].Ranges[CurRange].Words++; // Пробелы перед первым словом в строке не считаем //if ( this.Lines[CurLine].Words > 1 ) // this.Lines[CurLine].Spaces += nSpacesCount; //if ( this.Lines[CurLine].Ranges[CurRange].Words > 1 ) // this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; } nSpaceLen = 0; nSpacesCount = 0; } else { // Основная обработка происходит в Internal_Recalculate_2. Здесь обрабатывается единственный случай, // когда после второго пересчета с уже добавленной картинкой оказывается, что место в параграфе, где // идет картинка ушло на следующую страницу. В этом случае мы ставим перенос страницы перед картинкой. var LogicDocument = this.Parent; var LDRecalcInfo = LogicDocument.RecalcInfo; var DrawingObjects = LogicDocument.DrawingObjects; if ( true === LDRecalcInfo.Check_FlowObject(Item) && true === LDRecalcInfo.Is_PageBreakBefore() ) { LDRecalcInfo.Reset(); // Добавляем разрыв страницы. Если это первая страница, тогда ставим разрыв страницы в начале параграфа, // если нет, тогда в начале текущей строки. if ( null != this.Get_DocumentPrev() && true != this.Parent.Is_TableCellContent() && 0 === CurPage ) { // Мы должны из соответствующих FlowObjects удалить все Flow-объекты, идущие до этого места в параграфе for ( var TempPos = StartPos; TempPos < Pos; TempPos++ ) { var TempItem = this.Content[TempPos]; if ( para_Drawing === TempItem.Type && drawing_Anchor === TempItem.DrawingType && true === TempItem.Use_TextWrap() ) { DrawingObjects.removeById( TempItem.PageNum, TempItem.Get_Id() ); } } this.Internal_Content_Add( StartPos, new ParaPageBreakRenderer() ); this.Pages[CurPage].Set_EndLine( -1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } RecalcResult = recalcresult_NextPage; return; } else { if ( CurLine != this.Pages[CurPage].FirstLine ) { this.Internal_Content_Add( LineStart_Pos, new ParaPageBreakRenderer() ); this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } RecalcResult = recalcresult_NextPage; bBreak = true; break; } else { Pos--; bNewLine = true; bForceNewPage = true; } } // Если до этого было слово, тогда не надо проверять убирается ли оно if ( bWord || nWordLen > 0 ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; bWord = false; nSpaceLen = 0; nSpacesCount = 0; nWordLen = 0; } } } break; } case para_PageNum: { // Если до этого было слово, тогда не надо проверять убирается ли оно, но если стояли пробелы, // тогда мы их учитываем при проверке убирается ли данный элемент, и добавляем только если // данный элемент убирается if ( bWord || nWordLen > 0 ) { // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; bWord = false; nSpaceLen = 0; nSpacesCount = 0; nWordLen = 0; } if ( true === bStartWord ) bFirstItemOnLine = false; if ( LineTextAscent < TextAscent ) LineTextAscent = TextAscent; if ( LineTextAscent2 < TextAscent2 ) LineTextAscent2 = TextAscent2; if ( LineTextDescent < TextDescent ) LineTextDescent = TextDescent; if ( linerule_Exact === ParaPr.Spacing.LineRule ) { if ( LineAscent < TextAscent ) LineAscent = TextAscent; if ( LineDescent < TextDescent ) LineDescent = TextDescent; } else { if ( LineAscent < TextAscent + Item.YOffset ) LineAscent = TextAscent + Item.YOffset; if ( LineDescent < TextDescent - Item.YOffset ) LineDescent = TextDescent - Item.YOffset; } if ( X + nSpaceLen + Item.Width > XEnd && ( false === bFirstItemOnLine || RangesCount > 0 ) ) { if ( RangesCount == CurRange ) { bNewLine = true; Pos--; } else { bNewRange = true; Pos--; } } else { // Добавляем длину пробелов до слова X += nSpaceLen; X += Item.Width; bFirstItemOnLine = false; bEmptyLine = false; } nSpaceLen = 0; nSpacesCount = 0; break; } case para_Tab: { if ( -1 != pLastTab.Value ) { var TempTabX = X; if ( bWord || nWordLen > 0 ) TempTabX += nSpaceLen + nWordLen; var TabItem = pLastTab.Item; var TabStartX = pLastTab.X; var TabRangeW = TempTabX - TabStartX; var TabValue = pLastTab.Value; var TabPos = pLastTab.TabPos; var TabCalcW = 0; if ( tab_Right === TabValue ) TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW), 0 ); else if ( tab_Center === TabValue ) TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW / 2), 0 ); if ( X + TabCalcW > XEnd ) TabCalcW = XEnd - X; TabItem.Width = TabCalcW; TabItem.WidthVisible = TabCalcW; pLastTab.Value = -1; X += TabCalcW; } // Добавляем длину пробелов до слова X += nSpaceLen; // Не надо проверять убирается ли слово, мы это проверяем при добавленнии букв X += nWordLen; bWord = false; nSpaceLen = 0; nWordLen = 0; nSpacesCount = 0; this.Lines[CurLine].Ranges[CurRange].Spaces = 0; this.Lines[CurLine].Ranges[CurRange].TabPos = Pos; var PageStart = this.Parent.Get_PageContentStartPos( this.PageNum + CurPage ); if ( undefined != this.Get_FramePr() ) PageStart.X = 0; // Если у данного параграфа есть табы, тогда ищем среди них var TabsCount = ParaPr.Tabs.Get_Count(); // Добавим в качестве таба левую границу var TabsPos = new Array(); var bCheckLeft = true; for ( var Index = 0; Index < TabsCount; Index++ ) { var Tab = ParaPr.Tabs.Get(Index); var TabPos = Tab.Pos + PageStart.X; if ( true === bCheckLeft && TabPos > PageStart.X + ParaPr.Ind.Left ) { TabsPos.push( PageStart.X + ParaPr.Ind.Left ); bCheckLeft = false; } if ( tab_Clear != Tab.Value ) TabsPos.push( Tab ); } if ( true === bCheckLeft ) TabsPos.push( PageStart.X + ParaPr.Ind.Left ); TabsCount = TabsPos.length; var Tab = null; for ( var Index = 0; Index < TabsCount; Index++ ) { var TempTab = TabsPos[Index]; if ( X < TempTab.Pos + PageStart.X ) { Tab = TempTab; break; } } var NewX = null; // Если табов нет, либо их позиции левее текущей позиции ставим таб по умолчанию if ( null === Tab ) { if ( X < PageStart.X + ParaPr.Ind.Left ) NewX = PageStart.X + ParaPr.Ind.Left; else { NewX = this.X; while ( X >= NewX - 0.001 ) NewX += Default_Tab_Stop; } } else { // Если таб левый, тогда мы сразу смещаемся к нему if ( tab_Left === Tab.Value ) { NewX = Tab.Pos + PageStart.X; } else { pLastTab.TabPos = Tab.Pos + PageStart.X; pLastTab.Value = Tab.Value; pLastTab.X = X; pLastTab.Item = Item; Item.Width = 0; Item.WidthVisible = 0; } } if ( null != NewX ) { if ( NewX > XEnd && ( false === bFirstItemOnLine || RangesCount > 0 ) ) { nWordLen = NewX - X; if ( RangesCount == CurRange ) { bNewLine = true; Pos--; } else { bNewRange = true; Pos--; } } else { Item.Width = NewX - X; Item.WidthVisible = NewX - X; X = NewX; } } // Если перенос идет по строке, а не из-за обтекания, тогда разрываем перед табом, а если // из-за обтекания, тогда разрываем перед последним словом, идущим перед табом if ( RangesCount === CurRange ) { if ( true === bStartWord ) { bFirstItemOnLine = false; bEmptyLine = false; } nWordStartPos = Pos; } nSpacesCount = 0; bStartWord = true; bWord = true; nWordStartPos = Pos; break; } case para_TextPr: { break; } case para_NewLine: { if ( break_Page === Item.BreakType ) { // PageBreak вне самого верхнего документа не надо учитывать, поэтому мы его с радостью удаляем if ( !(this.Parent instanceof CDocument) ) { this.Internal_Content_Remove( Pos ); Pos--; break; } bNewPage = true; bNewLine = true; bBreakPageLine = true; } else { if ( RangesCount === CurRange ) { bNewLine = true; } else // if ( 0 != RangesCount && RangesCount != CurRange ) { bNewRange = true; } bEmptyLine = false; } X += nWordLen; if ( bWord && this.Lines[CurLine].Words > 1 ) this.Lines[CurLine].Spaces += nSpacesCount; if ( bWord && this.Lines[CurLine].Ranges[CurRange].Words > 1 ) this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; if ( bWord ) { bEmptyLine = false; bWord = false; X += nSpaceLen; nSpaceLen = 0; } break; } case para_End: { if ( true === bWord ) { bFirstItemOnLine = false; bEmptyLine = false; } // false === bExtendBoundToBottom, потому что это уже делалось для PageBreak if ( false === bExtendBoundToBottom ) { X += nWordLen; if ( bWord ) { this.Lines[CurLine].Spaces += nSpacesCount; this.Lines[CurLine].Ranges[CurRange].Spaces += nSpacesCount; } if ( bWord ) { X += nSpaceLen; nSpaceLen = 0; } if ( -1 != pLastTab.Value ) { var TabItem = pLastTab.Item; var TabStartX = pLastTab.X; var TabRangeW = X - TabStartX; var TabValue = pLastTab.Value; var TabPos = pLastTab.TabPos; var TabCalcW = 0; if ( tab_Right === TabValue ) TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW), 0 ); else if ( tab_Center === TabValue ) TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW / 2), 0 ); if ( X + TabCalcW > XEnd ) TabCalcW = XEnd - X; TabItem.Width = TabCalcW; TabItem.WidthVisible = TabCalcW; pLastTab.Value = -1; X += TabCalcW; } } bNewLine = true; bEnd = true; break; } } if ( bBreak ) { break; } } // Переносим строку if ( bNewLine ) { pLastTab.Value = -1; nSpaceLen = 0; // Строка пустая, у нее надо выставить ненулевую высоту. Делаем как Word, выставляем высоту по размеру // текста, на котором закончилась данная строка. if ( true === bEmptyLine || LineAscent < 0.001 ) { if ( true === bEnd ) { TextAscent = Item.TextAscent; TextDescent = Item.TextDescent; TextAscent2 = Item.TextAscent2; } if ( LineTextAscent < TextAscent ) LineTextAscent = TextAscent; if ( LineTextAscent2 < TextAscent2 ) LineTextAscent2 = TextAscent2; if ( LineTextDescent < TextDescent ) LineTextDescent = TextDescent; if ( LineAscent < TextAscent ) LineAscent = TextAscent; if ( LineDescent < TextDescent ) LineDescent = TextDescent; } // Рассчитаем метрики строки this.Lines[CurLine].Metrics.Update( LineTextAscent, LineTextAscent2, LineTextDescent, LineAscent, LineDescent, ParaPr ); bFirstItemOnLine = true; bStartWord = false; bNewLine = false; bNewRange = false; // Перед тем как перейти к новой строке мы должны убедиться, что вся высота строки // убирается в промежутках. var TempDy = this.Lines[this.Pages[CurPage].FirstLine].Metrics.Ascent; if ( 0 === this.Pages[CurPage].FirstLine && ( 0 === CurPage || true === this.Parent.Is_TableCellContent() || true === ParaPr.PageBreakBefore ) ) TempDy += ParaPr.Spacing.Before; if ( 0 === this.Pages[CurPage].FirstLine ) { if ( ( true === ParaPr.Brd.First || 1 === CurPage ) && border_Single === ParaPr.Brd.Top.Value ) TempDy += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; else if ( false === ParaPr.Brd.First && border_Single === ParaPr.Brd.Between.Value ) TempDy += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; } var Top, Bottom; var Top2, Bottom2; // верх и низ без Pr.Spacing var LastPage_Bottom = this.Pages[CurPage].Bounds.Bottom; if ( true === this.Lines[CurLine].RangeY ) { Top = Y; Top2 = Y; this.Lines[CurLine].Top = Top - this.Pages[CurPage].Y; if ( 0 === CurLine ) { if ( 0 === CurPage || true === this.Parent.Is_TableCellContent() ) { Top2 = Top + ParaPr.Spacing.Before; Bottom2 = Top + ParaPr.Spacing.Before + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent; Bottom = Top + ParaPr.Spacing.Before + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent + this.Lines[0].Metrics.LineGap; if ( true === ParaPr.Brd.First && border_Single === ParaPr.Brd.Top.Value ) { Top2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; } else if ( false === ParaPr.Brd.First && border_Single === ParaPr.Brd.Between.Value ) { Top2 += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; Bottom2 += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; Bottom += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; } } else { // Параграф начинается с новой страницы Bottom2 = Top + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent; Bottom = Top + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent + this.Lines[0].Metrics.LineGap; if ( border_Single === ParaPr.Brd.Top.Value ) { Top2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; } } } else { Bottom2 = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent; Bottom = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; } if ( bEnd ) { Bottom += ParaPr.Spacing.After; // Если нижняя граница Between, тогда она учитывается в следующем параграфе if ( true === ParaPr.Brd.Last ) { if ( border_Single === ParaPr.Brd.Bottom.Value ) Bottom += ParaPr.Brd.Bottom.Size + ParaPr.Brd.Bottom.Space; } else { if ( border_Single === ParaPr.Brd.Between.Value ) Bottom += ParaPr.Brd.Between.Space; } if ( false === this.Parent.Is_TableCellContent() && Bottom > this.YLimit && Bottom - this.YLimit <= ParaPr.Spacing.After ) Bottom = this.YLimit; } this.Lines[CurLine].Bottom = Bottom - this.Pages[CurPage].Y; this.Bounds.Bottom = Bottom; this.Pages[CurPage].Bounds.Bottom = Bottom; } else { if ( 0 != CurLine ) { if ( CurLine != this.Pages[CurPage].FirstLine ) { Top = Y + TempDy + this.Lines[CurLine - 1].Metrics.Descent + this.Lines[CurLine - 1].Metrics.LineGap; Bottom = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; Top2 = Top; Bottom2 = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent; this.Lines[CurLine].Top = Top - this.Pages[CurPage].Y; if ( bEnd ) { Bottom += ParaPr.Spacing.After; // Если нижняя граница Between, тогда она учитывается в следующем параграфе if ( true === ParaPr.Brd.Last ) { if ( border_Single === ParaPr.Brd.Bottom.Value ) Bottom += ParaPr.Brd.Bottom.Size + ParaPr.Brd.Bottom.Space; } else { if ( border_Single === ParaPr.Brd.Between.Value ) Bottom += ParaPr.Brd.Between.Space; } if ( false === this.Parent.Is_TableCellContent() && Bottom > this.YLimit && Bottom - this.YLimit <= ParaPr.Spacing.After ) Bottom = this.YLimit; } this.Lines[CurLine].Bottom = Bottom - this.Pages[CurPage].Y; this.Bounds.Bottom = Bottom; this.Pages[CurPage].Bounds.Bottom = Bottom; } else { Top = this.Pages[CurPage].Y; Bottom = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; Top2 = Top; Bottom2 = Top + this.Lines[CurLine].Metrics.Ascent + this.Lines[CurLine].Metrics.Descent; this.Lines[CurLine].Top = 0; if ( bEnd ) { Bottom += ParaPr.Spacing.After; // Если нижняя граница Between, тогда она учитывается в следующем параграфе if ( true === ParaPr.Brd.Last ) { if ( border_Single === ParaPr.Brd.Bottom.Value ) Bottom += ParaPr.Brd.Bottom.Size + ParaPr.Brd.Bottom.Space; } else { if ( border_Single === ParaPr.Brd.Between.Value ) Bottom += ParaPr.Brd.Between.Space; } if ( false === this.Parent.Is_TableCellContent() && Bottom > this.YLimit && Bottom - this.YLimit <= ParaPr.Spacing.After ) Bottom = this.YLimit; } this.Lines[CurLine].Bottom = Bottom - this.Pages[CurPage].Y; this.Bounds.Bottom = Bottom; this.Pages[CurPage].Bounds.Bottom = Bottom; } } else { Top = Y; Top2 = Y; if ( 0 === CurPage || true === this.Parent.Is_TableCellContent() || true === ParaPr.PageBreakBefore ) { Top2 = Top + ParaPr.Spacing.Before; Bottom = Top + ParaPr.Spacing.Before + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent + this.Lines[0].Metrics.LineGap; Bottom2 = Top + ParaPr.Spacing.Before + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent; if ( true === ParaPr.Brd.First && border_Single === ParaPr.Brd.Top.Value ) { Top2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; } else if ( false === ParaPr.Brd.First && border_Single === ParaPr.Brd.Between.Value ) { Top2 += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; Bottom2 += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; Bottom += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; } } else { // Параграф начинается с новой страницы Bottom = Top + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent + this.Lines[0].Metrics.LineGap; Bottom2 = Top + this.Lines[0].Metrics.Ascent + this.Lines[0].Metrics.Descent; if ( border_Single === ParaPr.Brd.Top.Value ) { Top2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom2 += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; Bottom += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; } } if ( bEnd ) { Bottom += ParaPr.Spacing.After; // Если нижняя граница Between, тогда она учитывается в следующем параграфе if ( true === ParaPr.Brd.Last ) { if ( border_Single === ParaPr.Brd.Bottom.Value ) Bottom += ParaPr.Brd.Bottom.Size + ParaPr.Brd.Bottom.Space; } else { if ( border_Single === ParaPr.Brd.Between.Value ) Bottom += ParaPr.Brd.Between.Space; } if ( false === this.Parent.Is_TableCellContent() && Bottom > this.YLimit && Bottom - this.YLimit <= ParaPr.Spacing.After ) Bottom = this.YLimit; } this.Lines[0].Top = Top - this.Pages[CurPage].Y; this.Lines[0].Bottom = Bottom - this.Pages[CurPage].Y; this.Bounds.Top = Top; this.Bounds.Bottom = Bottom; this.Pages[CurPage].Bounds.Top = Top; this.Pages[CurPage].Bounds.Bottom = Bottom; } } // Переносим строку по BreakPage, выясним есть ли в строке что-нибудь кроме BreakPage. Если нет, // тогда нам не надо проверять высоту строки и обтекание. var bBreakPageLineEmpty = false; if ( true === bBreakPageLine ) { bBreakPageLineEmpty = true; for ( var _Pos = Pos - 1; _Pos >= LineStart_Pos; _Pos-- ) { var _Item = this.Content[_Pos]; var _Type = _Item.Type; if ( para_Drawing === _Type || para_End === _Type || (para_NewLine === _Type && break_Line === _Item.BreakType) || para_PageNum === _Type || para_Space === _Type || para_Tab === _Type || para_Text === _Type ) { bBreakPageLineEmpty = false; break; } } } // Сначала проверяем не нужно ли сделать перенос страницы в данном месте // Перенос не делаем, если это первая строка на новой странице if ( true === this.Use_YLimit() && (Top > this.YLimit || Bottom2 > this.YLimit ) && ( CurLine != this.Pages[CurPage].FirstLine || ( 0 === CurPage && ( null != this.Get_DocumentPrev() || true === this.Parent.Is_TableCellContent() ) ) ) && false === bBreakPageLineEmpty ) { // Проверим висячую строку if ( this.Parent instanceof CDocument && true === this.Parent.RecalcInfo.Can_RecalcObject() && true === ParaPr.WidowControl && CurLine - this.Pages[CurPage].StartLine <= 1 && CurLine >= 1 && true != bBreakPageLine && ( 0 === CurPage && null != this.Get_DocumentPrev() ) ) { this.Parent.RecalcInfo.Set_WidowControl(this, CurLine - 1); RecalcResult = recalcresult_CurPage; break; } else { // Неразрывные абзацы не учитываются в таблицах if ( true === ParaPr.KeepLines && null != this.Get_DocumentPrev() && true != this.Parent.Is_TableCellContent() && 0 === CurPage ) { CurLine = 0; LineStart_Pos = 0; } // Восстанавливаем позицию нижней границы предыдущей страницы this.Pages[CurPage].Bounds.Bottom = LastPage_Bottom; this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } // Добавляем разрыв страницы RecalcResult = recalcresult_NextPage; break; } } bBreakPageLine = false; var Left = ( 0 != CurLine ? this.X + ParaPr.Ind.Left : this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine ); var Right = this.XLimit - ParaPr.Ind.Right; var PageFields = this.Parent.Get_PageFields( this.PageNum + CurPage ); var Ranges2; if ( true === this.Use_Wrap() ) Ranges2 = this.Parent.CheckRange( Left, Top, Right, Bottom, Top2, Bottom2, PageFields.X, PageFields.XLimit, this.PageNum + CurPage, true ); else Ranges2 = new Array(); // Проверяем совпали ли промежутки. Если совпали, тогда данная строчка рассчитана верно, // и мы переходим к следующей, если нет, тогда заново рассчитываем данную строчку, но // с новыми промежутками. // Заметим, что тут возможен случай, когда Ranges2 меньше, чем Ranges, такое может случится // при повторном обсчете строки. (После первого расчета мы выяснили что Ranges < Ranges2, // при повторном обсчете строки, т.к. она стала меньше, то у нее и рассчитанная высота могла // уменьшиться, а значит Ranges2 могло оказаться меньше чем Ranges). В таком случае не надо // делать повторный пересчет, иначе будет зависание. if ( -1 == FlowObjects_CompareRanges( Ranges, Ranges2 ) && true === FlowObjects_CheckInjection( Ranges, Ranges2 ) && false === bBreakPageLineEmpty ) { bEnd = false; Ranges = Ranges2; Pos = LineStart_Pos - 1; if ( 0 == CurLine ) X = this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else X = this.X + ParaPr.Ind.Left; this.Lines[CurLine].Reset(); //this.Lines[CurLine].Metrics.Update( TextAscent, TextAscent2, TextDescent, TextAscent, TextDescent, ParaPr ); LineTextAscent = 0; LineTextAscent2 = 0; LineTextDescent = 0; LineAscent = 0; LineDescent = 0; TextAscent = 0; TextDescent = 0; TextAscent2 = 0; RangesCount = Ranges.length; // Выставляем начальные сдвиги для промежутков. Начало промежутка = конец вырезаемого промежутка this.Lines[CurLine].Add_Range( ( 0 == CurLine ? this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine : this.X + ParaPr.Ind.Left ), (RangesCount == 0 ? XLimit : Ranges[0].X0) ); this.Lines[CurLine].Set_RangeStartPos( 0, Pos + 1 ); for ( var Index = 1; Index < Ranges.length + 1; Index++ ) { this.Lines[CurLine].Add_Range( Ranges[Index - 1].X1, (RangesCount == Index ? XLimit : Ranges[Index].X0) ); } CurRange = 0; XEnd = 0; if ( RangesCount == 0 ) XEnd = XLimit; else XEnd = Ranges[0].X0; bStartWord = false; bWord = false; bNewPage = false; bForceNewPage = false; bExtendBoundToBottom = false; nWordLen = 0; nSpacesCount = 0; bAddNumbering = this.Internal_CheckAddNumbering( CurPage, CurLine, CurRange ); } else { if ( 0 != CurLine ) this.Lines[CurLine].W = X - this.X - ParaPr.Ind.Left; else this.Lines[CurLine].W = X - this.X - ParaPr.Ind.Left - ParaPr.Ind.FirstLine; if ( 0 == CurRange ) { if ( 0 != CurLine ) this.Lines[CurLine].Ranges[CurRange].W = X - this.X - ParaPr.Ind.Left; else this.Lines[CurLine].Ranges[CurRange].W = X - this.X - ParaPr.Ind.Left - ParaPr.Ind.FirstLine; } else { if ( true === this.Lines[CurLine].Ranges[CurRange].FirstRange ) { if ( ParaPr.Ind.FirstLine < 0 ) Ranges[CurRange - 1].X1 += ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else Ranges[CurRange - 1].X1 += ParaPr.Ind.FirstLine; } this.Lines[CurLine].Ranges[CurRange].W = X - Ranges[CurRange - 1].X1; } if ( true === bNewPage ) { bNewPage = false; // Если это последний элемент параграфа, тогда нам не надо переносить текущий параграф // на новую страницу. Нам надо выставить границы так, чтобы следующий параграф начинался // с новой страницы. // TODO: заменить на функцию проверки var ____Pos = Pos + 1; var Next = this.Internal_FindForward( ____Pos, [ para_End, para_NewLine, para_Space, para_Text, para_Drawing, para_Tab, para_PageNum ] ); while ( true === Next.Found && para_Drawing === Next.Type && drawing_Anchor === this.Content[Next.LetterPos].Get_DrawingType() ) Next = this.Internal_FindForward( ++____Pos, [ para_End, para_NewLine, para_Space, para_Text, para_Drawing, para_Tab, para_PageNum ] ); if ( true === Next.Found && para_End === Next.Type ) { Item.Flags.NewLine = false; bExtendBoundToBottom = true; continue; } if ( true === this.Lines[CurLine].RangeY ) { this.Lines[CurLine].Y = Y - this.Pages[CurPage].Y; } else { if ( CurLine > 0 ) { // Первая линия на странице не должна двигаться if ( CurLine != this.Pages[CurPage].FirstLine ) Y += this.Lines[CurLine - 1].Metrics.Descent + this.Lines[CurLine - 1].Metrics.LineGap + this.Lines[CurLine].Metrics.Ascent; this.Lines[CurLine].Y = Y - this.Pages[CurPage].Y; } } this.Pages[CurPage].Set_EndLine( CurLine ); this.Lines[CurLine].Set_EndPos( Pos, this ); RecalcResult = recalcresult_NextPage; break; } else { if ( true === this.Lines[CurLine].RangeY ) { this.Lines[CurLine].Y = Y - this.Pages[CurPage].Y; } else { if ( CurLine > 0 ) { // Первая линия на странице не должна двигаться if ( CurLine != this.Pages[CurPage].FirstLine ) Y += this.Lines[CurLine - 1].Metrics.Descent + this.Lines[CurLine - 1].Metrics.LineGap + this.Lines[CurLine].Metrics.Ascent; this.Lines[CurLine].Y = Y - this.Pages[CurPage].Y; } } if ( ( true === bEmptyLine && RangesCount > 0 && LineStart_Pos < 0 ) || Pos < 0 ) X = this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else X = this.X + ParaPr.Ind.Left; } if ( !bEnd ) { // Если строка пустая в следствии того, что у нас было обтекание, тогда мы не // добавляем новую строку, а просто текущую смещаем ниже. if ( true === bEmptyLine && RangesCount > 0 ) { Pos = LineStart_Pos - 1; var RangesY = Ranges[0].Y1; for ( var Index = 1; Index < Ranges.length; Index++ ) { if ( RangesY > Ranges[Index].Y1 ) RangesY = Ranges[Index].Y1; } if ( Math.abs(RangesY - Y) < 0.01 ) Y = RangesY + 1; // смещаемся по 1мм else Y = RangesY + 0.001; if ( 0 === CurLine ) X = this.X + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else X = this.X + ParaPr.Ind.Left; } else { this.Lines[CurLine].Set_EndPos( Pos, this ); CurLine++; if ( this.Parent instanceof CDocument && true === this.Parent.RecalcInfo.Check_WidowControl(this, CurLine) ) { this.Parent.RecalcInfo.Reset_WidowControl(); this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine( 0 ); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } RecalcResult = recalcresult_NextPage; break; } } this.Lines[CurLine] = new CParaLine(Pos + 1); //this.Lines[CurLine].Metrics.Update( TextAscent, TextAscent2, TextDescent, TextAscent, TextDescent, ParaPr ); LineTextAscent = 0; LineTextDescent = 0; LineTextAscent2 = 0; LineAscent = 0; LineDescent = 0; TextAscent = 0; TextDescent = 0; TextAscent2 = 0; // Верх следующей строки var TempY; if ( true === bEmptyLine && RangesCount > 0 ) { TempY = Y; this.Lines[CurLine].RangeY = true; } else { if ( CurLine > 0 ) { if ( CurLine != this.Pages[CurPage].FirstLine ) TempY = TempDy + Y + this.Lines[CurLine - 1].Metrics.Descent + this.Lines[CurLine - 1].Metrics.LineGap; else TempY = this.Pages[CurPage].Y; } else TempY = this.Y; } // Получаем промежутки обтекания, т.е. промежутки, которые нам нельзя использовать Ranges = [];//this.Parent.CheckRange( X, TempY, XLimit, TempY, TempY, TempY, this.PageNum + CurPage, true ); RangesCount = Ranges.length; // Выставляем начальные сдвиги для промежутков. Началао промежутка = конец вырезаемого промежутка this.Lines[CurLine].Add_Range( X, (RangesCount == 0 ? XLimit : Ranges[0].X0) ); this.Lines[CurLine].Set_RangeStartPos( 0, Pos + 1 ); for ( var Index = 1; Index < Ranges.length + 1; Index++ ) { this.Lines[CurLine].Add_Range( Ranges[Index - 1].X1, (RangesCount == Index ? XLimit : Ranges[Index].X0) ); } CurRange = 0; XEnd = 0; if ( RangesCount == 0 ) XEnd = XLimit; else XEnd = Ranges[0].X0; bWord = false; nWordLen = 0; nSpacesCount = 0; LineStart_Pos = Pos + 1; if ( true === bForceNewPage ) { this.Pages[CurPage].Set_EndLine( CurLine - 1 ); if ( 0 === CurLine ) { this.Lines[-1] = new CParaLine( 0 ); this.Lines[-1].Set_EndPos( LineStart_Pos - 1, this ); } RecalcResult = recalcresult_NextPage; break; } bAddNumbering = this.Internal_CheckAddNumbering( CurPage, CurLine, CurRange ); } else { for ( var TempRange = CurRange + 1; TempRange <= RangesCount; TempRange++ ) this.Lines[CurLine].Set_RangeStartPos( TempRange, Pos + 1 ); this.Lines[CurLine].Set_EndPos( Pos, this ); // Проверим висячую строку if ( true === ParaPr.WidowControl && CurLine === this.Pages[CurPage].StartLine && CurLine >= 1 ) { // Проверим не встречается ли в предыдущей строке BreakPage, если да, тогда не учитываем WidowControl var bBreakPagePrevLine = false; var StartPos = (CurLine == 2 ? this.Lines[CurLine - 2].StartPos : this.Lines[CurLine - 1].StartPos ); var EndPos = this.Lines[CurLine - 1].EndPos; for ( var TempPos = StartPos; TempPos <= EndPos; TempPos++ ) { var TempItem = this.Content[TempPos]; if ( para_NewLine === TempItem.Type && break_Page === TempItem.BreakType ) { bBreakPagePrevLine = true; break; } } if ( this.Parent instanceof CDocument && true === this.Parent.RecalcInfo.Can_RecalcObject() && false === bBreakPagePrevLine && ( 1 === CurPage && null != this.Get_DocumentPrev() ) ) { this.Parent.RecalcInfo.Set_WidowControl(this, ( CurLine > 2 ? CurLine - 1 : 0 ) ); // Если у нас в параграфе 3 строки, тогда сразу начинаем параграф с новой строки RecalcResult = recalcresult_PrevPage; break; } } if ( true === bEnd && true === bExtendBoundToBottom ) { // Специальный случай с PageBreak, когда после самого PageBreak ничего нет // в параграфе this.Pages[CurPage].Bounds.Bottom = this.Pages[CurPage].YLimit; this.Bounds.Bottom = this.Pages[CurPage].YLimit; this.Lines[CurLine].Set_EndPos( Pos, this ); this.Pages[CurPage].Set_EndLine( CurLine ); for ( var TempRange = CurRange + 1; TempRange <= RangesCount; TempRange++ ) this.Lines[CurLine].Set_RangeStartPos( TempRange, Pos ); // Если у нас нумерация относится к знаку конца параграфа, тогда в такой // ситуации не рисуем нумерацию у такого параграфа. if ( Pos === this.Numbering.Pos ) this.Numbering.Pos = -1; } else { this.Lines[CurLine].Set_EndPos( Pos, this ); this.Pages[CurPage].Set_EndLine( CurLine ); for ( var TempRange = CurRange + 1; TempRange <= RangesCount; TempRange++ ) this.Lines[CurLine].Set_RangeStartPos( TempRange, Pos + 1 ); } } } bEmptyLine = true; } else if ( bNewRange ) { pLastTab.Value = -1; this.Lines[CurLine].Set_RangeStartPos( CurRange + 1, Pos + 1 ); nSpaceLen = 0; bNewRange = false; bFirstItemOnLine = true; bStartWord = false; if ( 0 == CurRange ) { if ( 0 != CurLine ) this.Lines[CurLine].Ranges[CurRange].W = X - this.X - ParaPr.Ind.Left; else this.Lines[CurLine].Ranges[CurRange].W = X - this.X - ParaPr.Ind.Left - ParaPr.Ind.FirstLine; } else { if ( true === this.Lines[CurLine].Ranges[CurRange].FirstRange ) { if ( ParaPr.Ind.FirstLine < 0 ) Ranges[CurRange - 1].X1 += ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else Ranges[CurRange - 1].X1 += ParaPr.Ind.FirstLine; } this.Lines[CurLine].Ranges[CurRange].W = X - Ranges[CurRange - 1].X1; } CurRange++; if ( 0 === CurLine && true === bEmptyLine ) { if ( ParaPr.Ind.FirstLine < 0 ) this.Lines[CurLine].Ranges[CurRange].X += ParaPr.Ind.Left + ParaPr.Ind.FirstLine; else this.Lines[CurLine].Ranges[CurRange].X += ParaPr.Ind.FirstLine; this.Lines[CurLine].Ranges[CurRange].FirstRange = true; } X = this.Lines[CurLine].Ranges[CurRange].X; if ( CurRange == RangesCount ) XEnd = XLimit; else XEnd = Ranges[CurRange].X0; bWord = false; nWordLen = 0; nSpacesCount = 0; bAddNumbering = this.Internal_CheckAddNumbering( CurPage, CurLine, CurRange ); } } // TODO: пока таким образом мы делаем, this.Y - был верхним краем параграфа // Потом надо будет переделать. var StartLine = this.Pages[CurPage].FirstLine; var EndLine = this.Lines.length - 1; var TempDy = this.Lines[this.Pages[CurPage].FirstLine].Metrics.Ascent; if ( 0 === StartLine && ( 0 === CurPage || true === this.Parent.Is_TableCellContent() || true === ParaPr.PageBreakBefore ) ) TempDy += ParaPr.Spacing.Before; if ( 0 === StartLine ) { if ( ( true === ParaPr.Brd.First || 1 === CurPage ) && border_Single === ParaPr.Brd.Top.Value ) TempDy += ParaPr.Brd.Top.Size + ParaPr.Brd.Top.Space; else if ( false === ParaPr.Brd.First && border_Single === ParaPr.Brd.Between.Value ) TempDy += ParaPr.Brd.Between.Size + ParaPr.Brd.Between.Space; } for ( var Index = StartLine; Index <= EndLine; Index++ ) { this.Lines[Index].Y += TempDy; if ( this.Lines[Index].Metrics.LineGap < 0 ) this.Lines[Index].Y += this.Lines[Index].Metrics.LineGap; } return RecalcResult; }, // Пересчитываем сдвиги элементов внутри параграфа, в зависимости от align. // Пересчитываем текущую позицию курсора, и видимые ширины пробелов. Internal_Recalculate_2_ : function(StartPos, _CurPage, _CurLine) { // Здесь мы пересчитываем ширину пробелов (и в особенных случаях дополнительное // расстояние между символами) с учетом прилегания параграфа. // 1. Если align = left, тогда внутри каждого промежутка текста выравниваем его // к левой границе промежутка. // 2. Если align = right, тогда внутри каждого промежутка текста выравниваем его // к правой границе промежутка. // 3. Если align = center, тогда внутри каждого промежутка текста выравниваем его // по центру промежутка. // 4. Если align = justify, тогда // 4.1 Если внутри промежутка ровно 1 слово. // 4.1.1 Если промежуток в строке 1 и слово занимает почти всю строку, // добавляем в слове к каждой букве дополнительное расстояние между // символами, чтобы ширина слова совпала с шириной строки. // 4.1.2 Если промежуток первый, тогда слово приставляем к левой границе // промежутка // 4.1.3 Если промежуток последний, тогда приставляем слово к правой // границе промежутка // 4.1.4 Если промежуток ни первый, ни последний, тогда ставим слово по // середине промежутка // 4.2 Если слов больше 1, тогда, исходя из количества пробелов между словами в // промежутке, увеличиваем их на столько, чтобы правая граница последнего // слова совпала с правой границей промежутка var Pr = this.Get_CompiledPr2(false); var ParaPr = Pr.ParaPr; var CurRange = 0; var CurLine = _CurLine; var CurPage = _CurPage; // Если параграф переносится на новую страницу с первой строки if ( this.Pages[CurPage].EndLine < 0 ) return recalcresult_NextPage; var EndPos = this.Lines[this.Pages[CurPage].EndLine].EndPos; var JustifyWord = 0; var JustifySpace = 0; var Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; var bFirstLineItem = true; var Range = this.Lines[CurLine].Ranges[CurRange]; var RangesCount = this.Lines[CurLine].Ranges.length; var RangeWidth = Range.XEnd - Range.X; var X = 0; switch (ParaPr.Jc) { case align_Left : X = Range.X; break; case align_Right : X = Math.max(Range.X + RangeWidth - Range.W, Range.X ); break; case align_Center : X = Math.max(Range.X + (RangeWidth - Range.W) / 2, Range.X); break case align_Justify: { X = Range.X; if ( 1 == Range.Words ) { if ( 1 == RangesCount && this.Lines.length > 1 ) { // Подсчитаем количество букв в слове var LettersCount = 0; var TempPos = StartPos; var LastW = 0; var __CurLine = CurLine; var __CurRange = CurRange; while ( this.Content[TempPos].Type != para_End ) { var __Item = this.Content[TempPos]; if ( undefined != __Item.CurPage ) { if ( __CurLine != __Item.CurLine || __CurRange != __Item.Range ) break; } if ( para_Text == this.Content[TempPos].Type ) { LettersCount++; LastW = this.Content[TempPos].Width; } TempPos++; } // Либо слово целиком занимает строку, либо не целиком, но разница очень мала if ( RangeWidth - Range.W <= 0.05 * RangeWidth && LettersCount > 1 ) JustifyWord = (RangeWidth - Range.W) / (LettersCount - 1); } else if ( 0 == CurRange || ( CurLine == this.Lines.length - 1 && CurRange == this.Lines[CurLine].Ranges.length - 1 ) ) { // Ничего не делаем (выравниваем текст по левой границе) } else if ( CurRange == this.Lines[CurLine].Ranges.length - 1 ) { X = Range.X + RangeWidth - Range.W; } else { X = Range.X + (RangeWidth - Range.W) / 2; } } else { // Последний промежуток последней строки не надо растягивать по ширине. if ( Range.Spaces > 0 && ( CurLine != this.Lines.length - 1 || CurRange != this.Lines[CurLine].Ranges.length - 1 ) ) JustifySpace = (RangeWidth - Range.W) / Range.Spaces; else JustifySpace = 0; } break; } default : X = Range.X; break; } var SpacesCounter = this.Lines[CurLine].Ranges[CurRange].Spaces; this.Lines[CurLine].Ranges[CurRange].XVisible = X; this.Lines[CurLine].X = X - this.X; var LastW = 0; // параметр нужен для позиционирования Flow-объектов for ( var ItemNum = StartPos; ItemNum <= EndPos; ItemNum++ ) { var Item = this.Content[ItemNum]; if ( undefined != Item.CurPage ) { if ( CurLine < Item.CurLine ) { CurLine = Item.CurLine; CurRange = Item.CurRange; JustifyWord = 0; JustifySpace = 0; Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; bFirstLineItem = true; Range = this.Lines[CurLine].Ranges[CurRange]; RangesCount = this.Lines[CurLine].Ranges.length; RangeWidth = Range.XEnd - Range.X; switch (ParaPr.Jc) { case align_Left : X = Range.X; break; case align_Right : X = Math.max(Range.X + RangeWidth - Range.W, Range.X); break; case align_Center : X = Math.max(Range.X + (RangeWidth - Range.W) / 2, Range.X); break case align_Justify: { X = Range.X; if ( 1 == Range.Words ) { if ( 1 == RangesCount && this.Lines.length > 1 ) { // Подсчитаем количество букв в слове var LettersCount = 0; var TempPos = ItemNum + 1; var LastW = 0; var __CurLine = CurLine; var __CurRange = CurRange; while ( this.Content[TempPos].Type != para_End ) { var __Item = this.Content[TempPos]; if ( undefined != __Item.CurPage ) { if ( __CurLine != __Item.CurLine || __CurRange != __Item.Range ) break; } if ( para_Text == this.Content[TempPos].Type ) { LettersCount++; LastW = this.Content[TempPos].Width; } TempPos++; } // Либо слово целиком занимает строку, либо не целиком, но разница очень мала if ( RangeWidth - Range.W <= 0.05 * RangeWidth && LettersCount > 1 ) JustifyWord = (RangeWidth - Range.W) / (LettersCount - 1); } else if ( 0 == CurRange || ( CurLine == this.Lines.length - 1 && CurRange == this.Lines[CurLine].Ranges.length - 1 ) ) { // Ничего не делаем (выравниваем текст по левой границе) } else if ( CurRange == this.Lines[CurLine].Ranges.length - 1 ) { X = Range.X + RangeWidth - Range.W; } else { X = Range.X + (RangeWidth - Range.W) / 2; } } else { // Последний промежуток последней строки не надо растягивать по ширине. if ( Range.Spaces > 0 && ( CurLine != this.Lines.length - 1 || CurRange != this.Lines[CurLine].Ranges.length - 1 ) ) JustifySpace = (RangeWidth - Range.W) / Range.Spaces; else JustifySpace = 0; } break; } default : X = Range.X; break; } SpacesCounter = this.Lines[CurLine].Ranges[CurRange].Spaces; this.Lines[CurLine].Ranges[CurRange].XVisible = X; this.Lines[CurLine].X = X - this.X; } else if ( CurRange < Item.CurRange ) { CurRange = Item.CurRange; Range = this.Lines[CurLine].Ranges[CurRange]; RangeWidth = Range.XEnd - Range.X; switch (ParaPr.Jc) { case align_Left : X = Range.X; break; case align_Right : X = Math.max(Range.X + RangeWidth - Range.W, Range.X); break; case align_Center : X = Math.max(Range.X + (RangeWidth - Range.W) / 2, Range.X); break case align_Justify: { X = Range.X; if ( 1 == Range.Words ) { if ( 1 == RangesCount && this.Lines.length > 1 ) { // Подсчитаем количество букв в слове var LettersCount = 0; var TempPos = ItemNum + 1; var LastW = 0; var __CurLine = CurLine; var __CurRange = CurRange; while ( this.Content[TempPos].Type != para_End ) { var __Item = this.Content[TempPos]; if ( undefined != __Item.CurPage ) { if ( __CurLine != __Item.CurLine || __CurRange != __Item.Range ) break; } if ( para_Text == this.Content[TempPos].Type ) { LettersCount++; LastW = this.Content[TempPos].Width; } TempPos++; } // Либо слово целиком занимает строку, либо не целиком, но разница очень мала if ( RangeWidth - Range.W <= 0.05 * RangeWidth && LettersCount > 1 ) JustifyWord = (RangeWidth - Range.W) / (LettersCount - 1); } else if ( 0 == CurRange || ( CurLine == this.Lines.length - 1 && CurRange == this.Lines[CurLine].Ranges.length - 1 ) ) { // Ничего не делаем (выравниваем текст по левой границе) } else if ( CurRange == this.Lines[CurLine].Ranges.length - 1 ) { X = Range.X + RangeWidth - Range.W; } else { X = Range.X + (RangeWidth - Range.W) / 2; } } else { // Последний промежуток последней строки не надо растягивать по ширине. if ( Range.Spaces > 0 && ( CurLine != this.Lines.length - 1 || CurRange != this.Lines[CurLine].Ranges.length - 1 ) ) JustifySpace = (RangeWidth - Range.W) / Range.Spaces; else JustifySpace = 0; } break; } default : X = Range.X; break; } SpacesCounter = this.Lines[CurLine].Ranges[CurRange].Spaces; this.Lines[CurLine].Ranges[CurRange].XVisible = X; } } if ( ItemNum == this.CurPos.ContentPos ) { this.CurPos.X = X; this.CurPos.Y = Y; this.CurPos.PagesPos = CurPage; } if ( ItemNum == this.Numbering.Pos ) X += this.Numbering.WidthVisible; switch( Item.Type ) { case para_Text: { bFirstLineItem = false; if ( CurLine != this.Lines.length - 1 && JustifyWord > 0 ) Item.WidthVisible = Item.Width + JustifyWord; else Item.WidthVisible = Item.Width; X += Item.WidthVisible; LastW = Item.WidthVisible; break; } case para_Space: { if ( !bFirstLineItem && CurLine != this.Lines.length - 1 && SpacesCounter > 0 && (ItemNum > this.Lines[CurLine].Ranges[CurRange].SpacePos) ) { Item.WidthVisible = Item.Width + JustifySpace; SpacesCounter--; } else Item.WidthVisible = Item.Width; X += Item.WidthVisible; LastW = Item.WidthVisible; break; } case para_Drawing: { var DrawingObjects = this.Parent.DrawingObjects; var PageLimits = this.Parent.Get_PageLimits(this.PageNum + CurPage); var PageFields = this.Parent.Get_PageFields(this.PageNum + CurPage); var ColumnStartX = (0 === CurPage ? this.X_ColumnStart : this.Pages[CurPage].X); var ColumnEndX = (0 === CurPage ? this.X_ColumnEnd : this.Pages[CurPage].XLimit); var Top_Margin = Y_Top_Margin; var Bottom_Margin = Y_Bottom_Margin; var Page_H = Page_Height; if ( true === this.Parent.Is_TableCellContent() && true == Item.Use_TextWrap() ) { Top_Margin = 0; Bottom_Margin = 0; Page_H = 0; } if ( true != Item.Use_TextWrap() ) { PageFields.X = X_Left_Field; PageFields.Y = Y_Top_Field; PageFields.XLimit = X_Right_Field; PageFields.YLimit = Y_Bottom_Field; PageLimits.X = 0; PageLimits.Y = 0; PageLimits.XLimit = Page_Width; PageLimits.YLimit = Page_Height; } if ( true === Item.Is_Inline() || true === this.Parent.Is_DrawingShape() ) { Item.Update_Position( X, Y , this.Get_StartPage_Absolute() + CurPage, LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent, this.Pages[CurPage].Y, PageLimits ); bFirstLineItem = false; X += Item.WidthVisible; LastW = Item.WidthVisible; } else { // У нас Flow-объект. Если он с обтеканием, тогда мы останавливаем пересчет и // запоминаем текущий объект. В функции Internal_Recalculate_2 пересчитываем // его позицию и сообщаем ее внешнему классу. if ( true === Item.Use_TextWrap() ) { var LogicDocument = this.Parent; var LDRecalcInfo = this.Parent.RecalcInfo; var Page_abs = this.Get_StartPage_Absolute() + CurPage; if ( true === LDRecalcInfo.Can_RecalcObject() ) { // Обновляем позицию объекта Item.Update_Position( X, Y , this.Get_StartPage_Absolute() + CurPage, LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent, this.Pages[CurPage].Y, PageLimits); LDRecalcInfo.Set_FlowObject( Item, 0, recalcresult_NextElement ); return recalcresult_CurPage; } else if ( true === LDRecalcInfo.Check_FlowObject(Item) ) { // Если мы находимся с таблице, тогда делаем как Word, не пересчитываем предыдущую страницу, // даже если это необходимо. Такое поведение нужно для точного определения рассчиталась ли // данная страница окончательно или нет. Если у нас будет ветка с переходом на предыдущую страницу, // тогда не рассчитав следующую страницу мы о конечном рассчете текущей страницы не узнаем. // Если данный объект нашли, значит он уже был рассчитан и нам надо проверить номер страницы if ( Item.PageNum === Page_abs ) { // Все нормально, можно продолжить пересчет LDRecalcInfo.Reset(); } else if ( true === this.Parent.Is_TableCellContent() ) { // Картинка не на нужной странице, но так как это таблица // мы не персчитываем заново текущую страницу, а не предыдущую // Обновляем позицию объекта Item.Update_Position( X, Y , this.Get_StartPage_Absolute() + CurPage, LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent, this.Pages[CurPage].Y, PageLimits); LDRecalcInfo.Set_FlowObject( Item, 0, recalcresult_NextElement ); LDRecalcInfo.Set_PageBreakBefore( false ); return recalcresult_CurPage; } else { LDRecalcInfo.Set_PageBreakBefore( true ); DrawingObjects.removeById( Item.PageNum, Item.Get_Id() ); return recalcresult_PrevPage; } } else { // Либо данный элемент уже обработан, либо будет обработан в будущем } continue; } else { // Картинка ложится на или под текст, в данном случае пересчет можно спокойно продолжать Item.Update_Position( X, Y , this.Get_StartPage_Absolute() + CurPage, LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent, this.Pages[CurPage].Y, PageLimits); continue; } } break; } case para_PageNum: { bFirstLineItem = false; X += Item.WidthVisible; LastW = Item.WidthVisible; break; } case para_Tab: { X += Item.WidthVisible; break; } case para_TextPr: { break; } case para_End: { X += Item.Width; break; } case para_NewLine: { X += Item.WidthVisible; break; } case para_CommentStart: { var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var CommentId = Item.Id; var CommentY = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var CommentH = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; DocumentComments.Set_StartInfo( CommentId, this.Get_StartPage_Absolute() + CurPage, X, CommentY, CommentH, this.Id ); break; } case para_CommentEnd: { var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var CommentId = Item.Id; var CommentY = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var CommentH = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; DocumentComments.Set_EndInfo( CommentId, this.Get_StartPage_Absolute() + CurPage, X, CommentY, CommentH, this.Id ); break; } } } return recalcresult_NextElement; }, // Пересчитываем заданную позицию элемента или текущую позицию курсора. Internal_Recalculate_CurPos : function(Pos, UpdateCurPos, UpdateTarget, ReturnTarget) { if ( this.Lines.length <= 0 ) return { X : 0, Y : 0, Height : 0, Internal : { Line : 0, Page : 0, Range : 0 } }; var LinePos = this.Internal_Get_ParaPos_By_Pos( Pos ); var CurLine = LinePos.Line; var CurRange = LinePos.Range; var CurPage = LinePos.Page; if ( Pos === this.CurPos.ContentPos && -1 != this.CurPos.Line ) CurLine = this.CurPos.Line; var X = this.Lines[CurLine].Ranges[CurRange].XVisible; var Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; if ( Pos < this.Lines[CurLine].Ranges[CurRange].StartPos ) { if ( true === ReturnTarget ) return { X : X, Y : TargetY, Height : 0, Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; else return { X : X, Y : Y, PageNum : CurPage + this.Get_StartPage_Absolute(), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; } for ( var ItemNum = this.Lines[CurLine].Ranges[CurRange].StartPos; ItemNum < this.Content.length; ItemNum++ ) { var Item = this.Content[ItemNum]; if ( ItemNum === this.Numbering.Pos ) X += this.Numbering.WidthVisible; if ( Pos === ItemNum ) { // Если так случилось, что у нас заданная позиция идет до позиции с нумерацией, к которой привязана нумерация, // тогда добавляем ширину нумерации. var _X = X; if ( ItemNum < this.Numbering.Pos ) _X += this.Numbering.WidthVisible; if ( true === UpdateCurPos) { this.CurPos.X = _X; this.CurPos.Y = Y; this.CurPos.PagesPos = CurPage; if ( true === UpdateTarget ) { var CurTextPr = this.Internal_CalculateTextPr(ItemNum); g_oTextMeasurer.SetTextPr( CurTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII, CurTextPr.Get_FontKoef() ); var Height = g_oTextMeasurer.GetHeight(); var Descender = Math.abs( g_oTextMeasurer.GetDescender() ); var Ascender = Height - Descender; this.DrawingDocument.SetTargetSize( Height ); this.DrawingDocument.SetTargetColor( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b ); var TargetY = Y - Ascender - CurTextPr.Position; switch( CurTextPr.VertAlign ) { case vertalign_SubScript: { TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Sub; break; } case vertalign_SuperScript: { TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Super; break; } } var Page_Abs = this.Get_StartPage_Absolute() + CurPage; this.DrawingDocument.UpdateTarget( _X, TargetY, Page_Abs ); // TODO: Тут делаем, чтобы курсор не выходил за границы буквицы. На самом деле, надо делать, чтобы // курсор не выходил за границы строки, но для этого надо делать обрезку по строкам, а без нее // такой вариант будет смотреться плохо. if ( undefined != this.Get_FramePr() ) { var __Y0 = TargetY, __Y1 = TargetY + Height; var ___Y0 = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var ___Y1 = this.Pages[CurPage].Y + this.Lines[CurLine].Bottom; var __Y0 = Math.max( __Y0, ___Y0 ); var __Y1 = Math.min( __Y1, ___Y1 ); this.DrawingDocument.SetTargetSize( __Y1 - __Y0 ); this.DrawingDocument.UpdateTarget( _X, __Y0, Page_Abs ); } } } if ( true === ReturnTarget ) { var CurTextPr = this.Internal_CalculateTextPr(ItemNum); g_oTextMeasurer.SetTextPr( CurTextPr ); g_oTextMeasurer.SetFontSlot( fontslot_ASCII, CurTextPr.Get_FontKoef() ); var Height = g_oTextMeasurer.GetHeight(); var Descender = Math.abs( g_oTextMeasurer.GetDescender() ); var Ascender = Height - Descender; var TargetY = Y - Ascender - CurTextPr.Position; switch( CurTextPr.VertAlign ) { case vertalign_SubScript: { TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Sub; break; } case vertalign_SuperScript: { TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Super; break; } } return { X : _X, Y : TargetY, Height : Height, Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; } else return { X : _X, Y : Y, PageNum : CurPage + this.Get_StartPage_Absolute(), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; } switch( Item.Type ) { case para_Text: case para_Space: case para_PageNum: case para_Tab: case para_TextPr: case para_End: case para_NewLine: { X += Item.WidthVisible; break; } case para_Drawing: { if ( drawing_Inline != Item.DrawingType ) break; X += Item.WidthVisible; break; } } } if ( true === ReturnTarget ) return { X : X, Y : TargetY, Height : Height, Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; else return { X : X, Y : Y, PageNum : CurPage + this.Get_StartPage_Absolute(), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } }; }, // Нужно ли добавлять нумерацию в начале данной строки Internal_CheckAddNumbering : function(CurPage, CurLine, CurRange) { var StartLine = this.Pages[CurPage].StartLine; var bRes = false; if ( CurLine != StartLine ) bRes = false; else { if ( CurPage > 1 ) bRes = false; else { var StartPos = this.Lines[CurLine].Ranges[CurRange].StartPos; bRes = true; // Проверим, есть ли какие-нибудь реальные элементы (к которым можно было бы // дорисовать нумерацию) до стартовой позиции текущей страницы for ( var Pos = 0; Pos < StartPos; Pos++ ) { var Item = this.Content[Pos]; if ( true === Item.Can_AddNumbering() ) { bRes = false; break; } } } } if ( true === bRes ) this.Numbering.Pos = -1; return bRes; }, // Можно ли объединить границы двух параграфов с заданными настройками Pr1, Pr2 Internal_CompareBrd : function(Pr1, Pr2) { // Сначала сравним правую и левую границы параграфов var Left_1 = Math.min( Pr1.Ind.Left, Pr1.Ind.Left + Pr1.Ind.FirstLine ); var Right_1 = Pr1.Ind.Right; var Left_2 = Math.min( Pr2.Ind.Left, Pr2.Ind.Left + Pr2.Ind.FirstLine ); var Right_2 = Pr2.Ind.Right; if ( Math.abs( Left_1 - Left_2 ) > 0.001 || Math.abs( Right_1 - Right_2 ) > 0.001 ) return false; if ( false === Pr1.Brd.Top.Compare( Pr2.Brd.Top ) || false === Pr1.Brd.Bottom.Compare( Pr2.Brd.Bottom ) || false === Pr1.Brd.Left.Compare( Pr2.Brd.Left ) || false === Pr1.Brd.Right.Compare( Pr2.Brd.Right ) || false === Pr1.Brd.Between.Compare( Pr2.Brd.Between ) ) return false; return true; }, // Проверяем не пустые ли границы Internal_Is_NullBorders : function (Borders) { if ( border_None != Borders.Top.Value || border_None != Borders.Bottom.Value || border_None != Borders.Left.Value || border_None != Borders.Right.Value || border_None != Borders.Between.Value ) return false; return true; }, Internal_Check_Ranges : function(CurLine, CurRange) { var Ranges = this.Lines[CurLine].Ranges; var RangesCount = Ranges.length; if ( RangesCount <= 1 ) return true; else if ( 2 === RangesCount ) { var Range0 = Ranges[0]; var Range1 = Ranges[1]; if ( Range0.XEnd - Range0.X < 0.001 && 1 === CurRange && Range1.XEnd - Range1.X >= 0.001 ) return true; else if ( Range1.XEnd - Range1.X < 0.001 && 0 === CurRange && Range0.XEnd - Range0.X >= 0.001 ) return true; else return false } else if ( 3 === RangesCount && 1 === CurRange ) { var Range0 = Ranges[0]; var Range2 = Ranges[2]; if ( Range0.XEnd - Range0.X < 0.001 && Range2.XEnd - Range2.X < 0.001 ) return true; else return false; } else return false; }, Internal_Get_NumberingTextPr : function() { var Pr = this.Get_CompiledPr(); var ParaPr = Pr.ParaPr; var NumPr = ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) return new CTextPr(); var Numbering = this.Parent.Get_Numbering(); var NumLvl = Numbering.Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl]; var NumTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); NumTextPr.Merge( this.TextPr.Value ); NumTextPr.Merge( NumLvl.TextPr ); NumTextPr.FontFamily.Name = NumTextPr.RFonts.Ascii.Name; return NumTextPr; }, Internal_Get_ClearPos : function(Pos) { // TODO: Переделать. Надо ускорить. При пересчете параграфа запоминать // все позиции элементов para_NewLineRendered, para_InlineBreak, para_PageBreakRendered, // para_FlowObjectAnchor, para_CollaborativeChangesEnd, para_CollaborativeChangesStart var Counter = 0; for ( var Index = 0; Index < Math.min(Pos, this.Content.length - 1); Index++ ) { if ( false === this.Content[Index].Is_RealContent() || para_Numbering === this.Content[Index].Type ) Counter++; } return Pos - Counter; }, Internal_Get_RealPos : function(Pos) { // TODO: Переделать. Надо ускорить. При пересчете параграфа запоминать // все позиции элементов para_NewLineRendered, para_InlineBreak, para_PageBreakRendered, // para_FlowObjectAnchor, para_CollaborativeChangesEnd, para_CollaborativeChangesStart var Counter = Pos; for ( var Index = 0; Index <= Math.min(Counter, this.Content.length - 1); Index++ ) { if ( false === this.Content[Index].Is_RealContent() || para_Numbering === this.Content[Index].Type ) Counter++; } return Counter; }, Internal_Get_ClearContentLength : function() { var Len = this.Content.length; var ClearLen = Len; for ( var Index = 0; Index < Len; Index++ ) { var Item = this.Content[Index]; if ( false === Item.Is_RealContent() ) ClearLen--; } return ClearLen; }, Recalculate_Fast : function() { }, Start_FromNewPage : function() { this.Pages.length = 1; // Добавляем разрыв страницы this.Pages[0].Set_EndLine( - 1 ); this.Lines[-1] = new CParaLine(0); this.Lines[-1].Set_EndPos( - 1, this ); }, Reset_RecalculateCache : function() { }, Recalculate_Page : function(_PageIndex) { // Во время пересчета сбрасываем привязку курсора к строке. this.CurPos.Line = -1; var PageIndex = _PageIndex - this.PageNum; var CurPage, StartPos, CurLine; if ( 0 === PageIndex ) { CurPage = 0; StartPos = 0; CurLine = 0; } else { CurPage = PageIndex; if ( CurPage > 0 ) CurLine = this.Pages[CurPage - 1].EndLine + 1; else CurLine = 0; if ( CurLine > 0 ) StartPos = this.Lines[CurLine - 1].EndPos + 1; else StartPos = 0; } // Если параграф начинается с новой страницы, и у самого параграфа нет настройки начать с новой страницы if ( 1 === CurPage && this.Pages[0].EndLine < 0 && this.Parent instanceof CDocument && false === this.Get_CompiledPr2(false).ParaPr.PageBreakBefore ) { // Если у предыдущего параграфа стоит настройка "не отрывать от следующего". // И сам параграф не разбит на несколько страниц и не начинается с новой страницы, // тогда мы должны пересчитать предыдущую страницу, с учетом того, что предыдущий параграф // надо начать с новой страницы. var Curr = this.Get_DocumentPrev(); while ( null != Curr && type_Paragraph === Curr.GetType() ) { var CurrKeepNext = Curr.Get_CompiledPr2(false).ParaPr.KeepNext; if ( (true === CurrKeepNext && Curr.Pages.length > 1) || false === CurrKeepNext ) { break; } else { var Prev = Curr.Get_DocumentPrev(); if ( null === Prev || type_Paragraph != Prev.GetType() ) break; var PrevKeepNext = Prev.Get_CompiledPr2(false).ParaPr.KeepNext; if ( false === PrevKeepNext ) { if ( true === this.Parent.RecalcInfo.Can_RecalcObject() ) { this.Parent.RecalcInfo.Set_KeepNext(Curr); return recalcresult_PrevPage; } else break; } else Curr = Prev; } } } // Пересчет параграфа: // 1. Сначала рассчитаем новые переносы строк, при этом подсчитав количество // слов и пробелов между словами. // 2. Далее, в зависимости от прилегания(align) параграфа, проставим начальные // позиции строк и проставим видимые размеры пробелов. this.FontMap.NeedRecalc = true; this.Internal_Recalculate_0(); this.Internal_CheckSpelling(); var RecalcResult_1 = this.Internal_Recalculate_1_(StartPos, CurPage, CurLine); var RecalcResult_2 = this.Internal_Recalculate_2_(StartPos, CurPage, CurLine); if ( true === this.Parent.RecalcInfo.WidowControlReset ) this.Parent.RecalcInfo.Reset(); var RecalcResult = ( recalcresult_NextElement != RecalcResult_2 ? RecalcResult_2 : RecalcResult_1 ); return RecalcResult; }, RecalculateCurPos : function() { this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, true, false ); }, Recalculate_MinMaxContentWidth : function() { // Пересчитаем ширины всех элементов this.Internal_Recalculate_0(); var bWord = false; var nWordLen = 0; var nSpaceLen = 0; var nMinWidth = 0; var nMaxWidth = 0; var nCurMaxWidth = 0; var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; // TODO: Продумать здесь учет нумерации switch( Item.Type ) { case para_Text : { if ( false === bWord ) { bWord = true; nWordLen = Item.Width; } else { nWordLen += Item.Width; if ( true === Item.SpaceAfter ) { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; } } if ( nSpaceLen > 0 ) { nCurMaxWidth += nSpaceLen; nSpaceLen = 0; } nCurMaxWidth += Item.Width; break; } case para_Space: { if ( true === bWord ) { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; } // Мы сразу не добавляем ширину пробелов к максимальной ширине, потому что // пробелы, идущие в конце параграфа или перед переносом строки(явным), не // должны учитываться. nSpaceLen += Item.Width; break; } case para_Drawing: { if ( true === bWord ) { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; } if ( ( true === Item.Is_Inline() || true === this.Parent.Is_DrawingShape() ) && Item.Width > nMinWidth ) nMinWidth = Item.Width; if ( nSpaceLen > 0 ) { nCurMaxWidth += nSpaceLen; nSpaceLen = 0; } nCurMaxWidth += Item.Width; break; } case para_PageNum: { if ( true === bWord ) { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; } if ( Item.Width > nMinWidth ) nMinWidth = Item.Width; if ( nSpaceLen > 0 ) { nCurMaxWidth += nSpaceLen; nSpaceLen = 0; } nCurMaxWidth += Item.Width; break; } case para_Tab: { nWordLen += Item.Width; if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; if ( nSpaceLen > 0 ) { nCurMaxWidth += nSpaceLen; nSpaceLen = 0; } nCurMaxWidth += Item.Width; break; } case para_NewLine: { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; bWord = false; nWordLen = 0; nSpaceLen = 0; if ( nCurMaxWidth > nMaxWidth ) nMaxWidth = nCurMaxWidth; nCurMaxWidth = 0; break; } case para_End: { if ( nMinWidth < nWordLen ) nMinWidth = nWordLen; if ( nCurMaxWidth > nMaxWidth ) nMaxWidth = nCurMaxWidth; break; } } } // добавляем 0.001, чтобы избавиться от погрешностей return { Min : ( nMinWidth > 0 ? nMinWidth + 0.001 : 0 ), Max : ( nMaxWidth > 0 ? nMaxWidth + 0.001 : 0 ) }; }, Draw : function(PageNum, pGraphics) { var CurPage = PageNum - this.PageNum; // Параграф начинается с новой страницы if ( this.Pages[CurPage].EndLine < 0 ) return; var Pr = this.Get_CompiledPr(); // Задаем обрезку, если данный параграф является рамкой var FramePr = this.Get_FramePr(); if ( undefined != FramePr && this.Parent instanceof CDocument ) { var PixelError = editor.WordControl.m_oLogicDocument.DrawingDocument.GetMMPerDot(1); var BoundsL = this.CalculatedFrame.L2 - PixelError; var BoundsT = this.CalculatedFrame.T2 - PixelError; var BoundsH = this.CalculatedFrame.H2 + 2 * PixelError; var BoundsW = this.CalculatedFrame.W2 + 2 * PixelError; /* var Brd = Pr.ParaPr.Brd; var BorderBottom = Brd.Bottom; if ( undefined != Brd.Bottom ) BoundsH += BorderBottom.Size + BorderBottom.Space; var BorderLeft = Brd.Left; if ( undefined != Brd.Left ) { BoundsL -= BorderLeft.Size + BorderLeft.Space; BoundsW += BorderLeft.Size + BorderLeft.Space; } var BorderRight = Brd.Right; if ( undefined != Brd.Right ) BoundsW += BorderRight.Size + BorderRight.Space; */ pGraphics.SaveGrState(); pGraphics.AddClipRect( BoundsL, BoundsT, BoundsW, BoundsH ); } // 1 часть отрисовки : // Рисуем слева от параграфа знак, если данный параграф зажат другим пользователем this.Internal_Draw_1( CurPage, pGraphics, Pr ); // 2 часть отрисовки : // Добавляем специальный символ слева от параграфа, для параграфов, у которых стоит хотя бы // одна из настроек: не разрывать абзац(KeepLines), не отрывать от следующего(KeepNext), // начать с новой страницы(PageBreakBefore) this.Internal_Draw_2( CurPage, pGraphics, Pr ); // 3 часть отрисовки : // Рисуем заливку параграфа и различные выделения текста (highlight, поиск, совместное редактирование). // Кроме этого рисуем боковые линии обводки параграфа. this.Internal_Draw_3( CurPage, pGraphics, Pr ); // 4 часть отрисовки : // Рисуем сами элементы параграфа this.Internal_Draw_4( CurPage, pGraphics, Pr ); // 5 часть отрисовки : // Рисуем различные подчеркивания и зачеркивания. this.Internal_Draw_5( CurPage, pGraphics, Pr ); // 6 часть отрисовки : // Рисуем верхнюю, нижнюю и промежуточную границы this.Internal_Draw_6( CurPage, pGraphics, Pr ); // Убираем обрезку if ( undefined != FramePr ) { pGraphics.RestoreGrState(); } }, Internal_Draw_1 : function(CurPage, pGraphics, Pr) { // Если данный параграф зажат другим пользователем, рисуем соответствующий знак if ( locktype_None != this.Lock.Get_Type() ) { if ( ( CurPage > 0 || false === this.Is_StartFromNewPage() || null === this.Get_DocumentPrev() ) ) { var X_min = -1 + Math.min( this.Pages[CurPage].X, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var Y_top = this.Pages[CurPage].Bounds.Top; var Y_bottom = this.Pages[CurPage].Bounds.Bottom; if ( true === editor.isCoMarksDraw || locktype_Mine != this.Lock.Get_Type() ) pGraphics.DrawLockParagraph(this.Lock.Get_Type(), X_min, Y_top, Y_bottom); } } }, Internal_Draw_2 : function(CurPage, pGraphics, Pr) { if ( true === editor.ShowParaMarks && ( ( 0 === CurPage && ( this.Pages.length <= 1 || this.Pages[1].FirstLine > 0 ) ) || ( 1 === CurPage && this.Pages.length > 1 && this.Pages[1].FirstLine === 0 ) ) && ( true === Pr.ParaPr.KeepNext || true === Pr.ParaPr.KeepLines || true === Pr.ParaPr.PageBreakBefore ) ) { var SpecFont = { FontFamily: { Name : "Arial", Index : -1 }, FontSize : 12, Italic : false, Bold : false }; var SpecSym = String.fromCharCode( 0x25AA ); pGraphics.SetFont( SpecFont ); pGraphics.b_color1( 0, 0, 0, 255 ); var CurLine = this.Pages[CurPage].FirstLine; var CurRange = 0; var X = this.Lines[CurLine].Ranges[CurRange].XVisible; var Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; var SpecW = 2.5; // 2.5 mm var SpecX = Math.min( X, this.X ) - SpecW; pGraphics.FillText( SpecX, Y, SpecSym ); } }, Internal_Draw_3 : function(CurPage, pGraphics, Pr) { var _Page = this.Pages[CurPage]; var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var bDrawComments = DocumentComments.Is_Use(); var CommentsFlag = DocumentComments.Check_CurrentDraw(); var CollaborativeChanges = 0; var StartPagePos = this.Lines[_Page.StartLine].StartPos; var DrawSearch = editor.WordControl.m_oLogicDocument.SearchEngine.Selection; // в PDF не рисуем метки совместного редактирования if ( undefined === pGraphics.RENDERER_PDF_FLAG ) { var Pos = 0; while ( Pos < StartPagePos ) { Item = this.Content[Pos]; if ( para_CollaborativeChangesEnd == Item.Type ) CollaborativeChanges--; else if ( para_CollaborativeChangesStart == Item.Type ) CollaborativeChanges++; Pos++; } } var CurTextPr = _Page.TextPr; var StartLine = _Page.StartLine; var EndLine = _Page.EndLine; var aHigh = new CParaDrawingRangeLines(); var aColl = new CParaDrawingRangeLines(); var aFind = new CParaDrawingRangeLines(); var aComm = new CParaDrawingRangeLines(); for ( var CurLine = StartLine; CurLine <= EndLine; CurLine++ ) { var _Line = this.Lines[CurLine]; var _LineMetrics = _Line.Metrics; var EndLinePos = _Line.EndPos; var Y0 = (_Page.Y + _Line.Y - _LineMetrics.Ascent); var Y1 = (_Page.Y + _Line.Y + _LineMetrics.Descent); if ( _LineMetrics.LineGap < 0 ) Y1 += _LineMetrics.LineGap; var RangesCount = _Line.Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var _Range = _Line.Ranges[CurRange]; aHigh.Clear(); aColl.Clear(); aFind.Clear(); aComm.Clear(); // Сначала проанализируем данную строку: в массивы aHigh, aColl, aFind // сохраним позиции начала и конца продолжительных одинаковых настроек // выделения, совместного редатирования и поиска соответственно. var X = _Range.XVisible; var StartPos = _Range.StartPos; var EndPos = ( CurRange === RangesCount - 1 ? EndLinePos : _Line.Ranges[CurRange + 1].StartPos - 1 ); for ( var Pos = StartPos; Pos <= EndPos; Pos++ ) { var Item = this.Content[Pos]; var bSearchResult = false; if ( true === DrawSearch ) { for ( var SId in this.SearchResults ) { var SResult = this.SearchResults[SId]; if ( Pos >= SResult.StartPos && Pos < SResult.EndPos ) { bSearchResult = true; break; } } } if ( Pos === this.Numbering.Pos ) { var NumberingType = this.Numbering.Type; var NumberingItem = this.Numbering; if ( para_Numbering === NumberingType ) { var NumPr = Pr.ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) break; var Numbering = this.Parent.Get_Numbering(); var NumLvl = Numbering.Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl]; var NumJc = NumLvl.Jc; var NumTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); NumTextPr.Merge( this.TextPr.Value ); NumTextPr.Merge( NumLvl.TextPr ); var X_start = X; if ( align_Right === NumJc ) X_start = X - NumberingItem.WidthNum; else if ( align_Center === NumJc ) X_start = X - NumberingItem.WidthNum / 2; // Если есть выделение текста, рисуем его сначала if ( highlight_None != NumTextPr.HighLight ) aHigh.Add( Y0, Y1, X_start, X_start + NumberingItem.WidthNum + NumberingItem.WidthSuff, 0, NumTextPr.HighLight.r, NumTextPr.HighLight.g, NumTextPr.HighLight.b ); if ( CollaborativeChanges > 0 ) aColl.Add( Y0, Y1, X_start, X_start + NumberingItem.WidthNum + NumberingItem.WidthSuff, 0, 0, 0, 0 ); X += NumberingItem.WidthVisible; } else if ( para_PresentationNumbering === NumberingType ) { X += NumberingItem.WidthVisible; } } switch( Item.Type ) { case para_PageNum: case para_Drawing: case para_Tab: case para_Text: { if ( para_Drawing === Item.Type && drawing_Anchor === Item.DrawingType ) break; if ( CommentsFlag != comments_NoComment && true === bDrawComments ) aComm.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0, { Active : CommentsFlag === comments_ActiveComment ? true : false } ); else if ( highlight_None != CurTextPr.HighLight ) aHigh.Add( Y0, Y1, X, X + Item.WidthVisible, 0, CurTextPr.HighLight.r, CurTextPr.HighLight.g, CurTextPr.HighLight.b ); if ( true === bSearchResult ) aFind.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); else if ( CollaborativeChanges > 0 ) aColl.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); if ( para_Drawing != Item.Type || drawing_Anchor != Item.DrawingType ) X += Item.WidthVisible; break; } case para_Space: { // Пробелы в конце строки (и строку состоящую из пробелов) не подчеркиваем, не зачеркиваем и не выделяем if ( Pos >= _Range.StartPos2 && Pos <= _Range.EndPos2 ) { if ( CommentsFlag != comments_NoComment && bDrawComments ) aComm.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0, { Active : CommentsFlag === comments_ActiveComment ? true : false } ); else if ( highlight_None != CurTextPr.HighLight ) aHigh.Add( Y0, Y1, X, X + Item.WidthVisible, 0, CurTextPr.HighLight.r, CurTextPr.HighLight.g, CurTextPr.HighLight.b ); } if ( true === bSearchResult ) aFind.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); else if ( CollaborativeChanges > 0 ) aColl.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); X += Item.WidthVisible; break; } case para_TextPr: { CurTextPr = Item.CalcValue; break; } case para_End: { if ( CollaborativeChanges > 0 ) aColl.Add( Y0, Y1, X, X + Item.WidthVisible, 0, 0, 0, 0 ); X += Item.Width; break; } case para_NewLine: { X += Item.WidthVisible; break; } case para_CollaborativeChangesStart: { CollaborativeChanges++; break; } case para_CollaborativeChangesEnd: { CollaborativeChanges--; break; } case para_CommentStart: { if ( undefined === pGraphics.RENDERER_PDF_FLAG ) { var CommentId = Item.Id; var CommentY = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var CommentH = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; DocumentComments.Set_StartInfo( CommentId, this.Get_StartPage_Absolute() + CurPage, X, CommentY, CommentH, this.Id ); DocumentComments.Add_CurrentDraw( CommentId ); CommentsFlag = DocumentComments.Check_CurrentDraw(); } break; } case para_CommentEnd: { if ( undefined === pGraphics.RENDERER_PDF_FLAG ) { var CommentId = Item.Id; var CommentY = this.Pages[CurPage].Y + this.Lines[CurLine].Top; var CommentH = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; DocumentComments.Set_EndInfo( CommentId, this.Get_StartPage_Absolute() + CurPage, X, CommentY, CommentH, this.Id ); DocumentComments.Remove_CurrentDraw( CommentId ); CommentsFlag = DocumentComments.Check_CurrentDraw(); } break; } } } //---------------------------------------------------------------------------------------------------------- // Заливка параграфа //---------------------------------------------------------------------------------------------------------- if ( (_Range.W > 0.001 || true === this.IsEmpty() ) && ( ( this.Pages.length - 1 === CurPage ) || ( CurLine < this.Pages[CurPage + 1].FirstLine ) ) && shd_Clear === Pr.ParaPr.Shd.Value ) { var TempX0 = this.Lines[CurLine].Ranges[CurRange].X; if ( 0 === CurRange ) TempX0 = Math.min( TempX0, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var TempX1 = this.Lines[CurLine].Ranges[CurRange].XEnd; var TempTop = this.Lines[CurLine].Top; var TempBottom = this.Lines[CurLine].Bottom; if ( 0 === CurLine ) { // Закрашиваем фон до параграфа, только если данный параграф не является первым // на странице, предыдущий параграф тоже имеет не пустой фон и у текущего и предыдущего // параграфов совпадают правая и левая границы фонов. var PrevEl = this.Get_DocumentPrev(); var PrevPr = null; var PrevLeft = 0; var PrevRight = 0; var CurLeft = Math.min( Pr.ParaPr.Ind.Left, Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var CurRight = Pr.ParaPr.Ind.Right; if ( null != PrevEl && type_Paragraph === PrevEl.GetType() ) { PrevPr = PrevEl.Get_CompiledPr2(); PrevLeft = Math.min( PrevPr.ParaPr.Ind.Left, PrevPr.ParaPr.Ind.Left + PrevPr.ParaPr.Ind.FirstLine ); PrevRight = PrevPr.ParaPr.Ind.Right; } // Если данный параграф находится в группе параграфов с одинаковыми границами(с хотябы одной // непустой), и он не первый, тогда закрашиваем вместе с расстоянием до параграфа if ( true === Pr.ParaPr.Brd.First ) { // Если следующий элемент таблица, тогда PrevPr = null if ( null === PrevEl || true === this.Is_StartFromNewPage() || null === PrevPr || shd_Nil === PrevPr.ParaPr.Shd.Value || PrevLeft != CurLeft || CurRight != PrevRight || false === this.Internal_Is_NullBorders(PrevPr.ParaPr.Brd) || false === this.Internal_Is_NullBorders(Pr.ParaPr.Brd) ) { if ( false === this.Is_StartFromNewPage() || null === PrevEl ) TempTop += Pr.ParaPr.Spacing.Before; } } } if ( this.Lines.length - 1 === CurLine ) { // Закрашиваем фон после параграфа, только если данный параграф не является последним, // на странице, следующий параграф тоже имеет не пустой фон и у текущего и следующего // параграфов совпадают правая и левая границы фонов. var NextEl = this.Get_DocumentNext(); var NextPr = null; var NextLeft = 0; var NextRight = 0; var CurLeft = Math.min( Pr.ParaPr.Ind.Left, Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var CurRight = Pr.ParaPr.Ind.Right; if ( null != NextEl && type_Paragraph === NextEl.GetType() ) { NextPr = NextEl.Get_CompiledPr2(); NextLeft = Math.min( NextPr.ParaPr.Ind.Left, NextPr.ParaPr.Ind.Left + NextPr.ParaPr.Ind.FirstLine ); NextRight = NextPr.ParaPr.Ind.Right; } if ( null != NextEl && type_Paragraph === NextEl.GetType() && true === NextEl.Is_StartFromNewPage() ) { TempBottom = this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; } // Если данный параграф находится в группе параграфов с одинаковыми границами(с хотябы одной // непустой), и он не последний, тогда закрашиваем вместе с расстоянием после параграфа else if ( true === Pr.ParaPr.Brd.Last ) { // Если следующий элемент таблица, тогда NextPr = null if ( null === NextEl || true === NextEl.Is_StartFromNewPage() || null === NextPr || shd_Nil === NextPr.ParaPr.Shd.Value || NextLeft != CurLeft || CurRight != NextRight || false === this.Internal_Is_NullBorders(NextPr.ParaPr.Brd) || false === this.Internal_Is_NullBorders(Pr.ParaPr.Brd) ) TempBottom -= Pr.ParaPr.Spacing.After; } } if ( 0 === CurRange ) { if ( Pr.ParaPr.Brd.Left.Value === border_Single ) TempX0 -= 1 + Pr.ParaPr.Brd.Left.Size + Pr.ParaPr.Brd.Left.Space; else TempX0 -= 1; } if ( this.Lines[CurLine].Ranges.length - 1 === CurRange ) { if ( Pr.ParaPr.Brd.Right.Value === border_Single ) TempX1 += 1 + Pr.ParaPr.Brd.Right.Size + Pr.ParaPr.Brd.Right.Space; else TempX1 += 1; } pGraphics.b_color1( Pr.ParaPr.Shd.Color.r, Pr.ParaPr.Shd.Color.g, Pr.ParaPr.Shd.Color.b, 255 ); pGraphics.rect(TempX0, this.Pages[CurPage].Y + TempTop, TempX1 - TempX0, TempBottom - TempTop); pGraphics.df(); } //---------------------------------------------------------------------------------------------------------- // Рисуем выделение текста //---------------------------------------------------------------------------------------------------------- var Element = aHigh.Get_Next(); while ( null != Element ) { pGraphics.b_color1( Element.r, Element.g, Element.b, 255 ); pGraphics.rect( Element.x0, Element.y0, Element.x1 - Element.x0, Element.y1 - Element.y0 ); pGraphics.df(); Element = aHigh.Get_Next(); } //---------------------------------------------------------------------------------------------------------- // Рисуем комментарии //---------------------------------------------------------------------------------------------------------- Element = aComm.Get_Next(); while ( null != Element ) { if ( Element.Additional.Active === true ) pGraphics.b_color1( 240, 200, 120, 255 ); else pGraphics.b_color1( 248, 231, 195, 255 ); pGraphics.rect( Element.x0, Element.y0, Element.x1 - Element.x0, Element.y1 - Element.y0 ); pGraphics.df(); Element = aComm.Get_Next(); } //---------------------------------------------------------------------------------------------------------- // Рисуем выделение совместного редактирования //---------------------------------------------------------------------------------------------------------- Element = aColl.Get_Next(); while ( null != Element ) { pGraphics.drawCollaborativeChanges( Element.x0, Element.y0, Element.x1 - Element.x0, Element.y1 - Element.y0 ); Element = aColl.Get_Next(); } //---------------------------------------------------------------------------------------------------------- // Рисуем выделение поиска //---------------------------------------------------------------------------------------------------------- Element = aFind.Get_Next(); while ( null != Element ) { pGraphics.drawSearchResult( Element.x0, Element.y0, Element.x1 - Element.x0, Element.y1 - Element.y0 ); Element = aFind.Get_Next(); } } //---------------------------------------------------------------------------------------------------------- // Рисуем боковые линии границы параграфа //---------------------------------------------------------------------------------------------------------- if ( ( this.Pages.length - 1 === CurPage ) || ( CurLine < this.Pages[CurPage + 1].FirstLine ) ) { var TempX0 = Math.min( this.Lines[CurLine].Ranges[0].X, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine); var TempX1 = this.Lines[CurLine].Ranges[this.Lines[CurLine].Ranges.length - 1].XEnd; if ( true === this.Is_LineDropCap() ) { TempX1 = TempX0 + this.Get_LineDropCapWidth(); } var TempTop = this.Lines[CurLine].Top; var TempBottom = this.Lines[CurLine].Bottom; if ( 0 === CurLine ) { if ( true === Pr.ParaPr.Brd.First && ( Pr.ParaPr.Brd.Top.Value === border_Single || shd_Clear === Pr.ParaPr.Shd.Value ) ) { if ( false === this.Is_StartFromNewPage() || null === this.Get_DocumentPrev() ) TempTop += Pr.ParaPr.Spacing.Before; } } if ( this.Lines.length - 1 === CurLine ) { var NextEl = this.Get_DocumentNext(); if ( null != NextEl && type_Paragraph === NextEl.GetType() && true === NextEl.Is_StartFromNewPage() ) TempBottom = this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; else if ( true === Pr.ParaPr.Brd.Last && ( Pr.ParaPr.Brd.Bottom.Value === border_Single || shd_Clear === Pr.ParaPr.Shd.Value ) ) TempBottom -= Pr.ParaPr.Spacing.After; } if ( Pr.ParaPr.Brd.Right.Value === border_Single ) { pGraphics.p_color( Pr.ParaPr.Brd.Right.Color.r, Pr.ParaPr.Brd.Right.Color.g, Pr.ParaPr.Brd.Right.Color.b, 255 ); pGraphics.drawVerLine( c_oAscLineDrawingRule.Right, TempX1 + 1 + Pr.ParaPr.Brd.Right.Size + Pr.ParaPr.Brd.Right.Space, this.Pages[CurPage].Y + TempTop, this.Pages[CurPage].Y + TempBottom, Pr.ParaPr.Brd.Right.Size ); } if ( Pr.ParaPr.Brd.Left.Value === border_Single ) { pGraphics.p_color( Pr.ParaPr.Brd.Left.Color.r, Pr.ParaPr.Brd.Left.Color.g, Pr.ParaPr.Brd.Left.Color.b, 255 ); pGraphics.drawVerLine( c_oAscLineDrawingRule.Left, TempX0 - 1 - Pr.ParaPr.Brd.Left.Size - Pr.ParaPr.Brd.Left.Space, this.Pages[CurPage].Y + TempTop, this.Pages[CurPage].Y + TempBottom, Pr.ParaPr.Brd.Left.Size ); } } } }, Internal_Draw_4 : function(CurPage, pGraphics, Pr) { var StartPagePos = this.Lines[this.Pages[CurPage].StartLine].StartPos; var HyperPos = this.Internal_FindBackward( StartPagePos, [para_HyperlinkStart, para_HyperlinkEnd] ); var bVisitedHyperlink = false; if ( true === HyperPos.Found && para_HyperlinkStart === HyperPos.Type ) bVisitedHyperlink = this.Content[HyperPos.LetterPos].Get_Visited(); var CurTextPr = this.Pages[CurPage].TextPr; // Выставляем шрифт и заливку текста pGraphics.SetTextPr( CurTextPr ); if ( true === bVisitedHyperlink ) pGraphics.b_color1( 128, 0, 151, 255 ); else pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); var StartLine = this.Pages[CurPage].StartLine; var EndLine = this.Pages[CurPage].EndLine; for ( var CurLine = StartLine; CurLine <= EndLine; CurLine++ ) { var StartPos = this.Lines[CurLine].StartPos; var EndPos = this.Lines[CurLine].EndPos; var bFirstLineItem = true; var CurRange = 0; var Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y; var X = this.Lines[CurLine].Ranges[CurRange].XVisible; var bEnd = false; for ( var Pos = StartPos; Pos <= EndPos; Pos++ ) { var Item = this.Content[Pos]; // Отслеживаем изменение позиции (отрезок) // Изменении страницы и строки не отслеживаем if ( undefined != Item.CurRange ) { if ( Item.CurRange > CurRange ) { CurRange = Item.CurRange; X = this.Lines[CurLine].Ranges[CurRange].XVisible; } } var TempY = Y; switch( CurTextPr.VertAlign ) { case vertalign_SubScript: { Y -= vertalign_Koef_Sub * CurTextPr.FontSize * g_dKoef_pt_to_mm; break; } case vertalign_SuperScript: { Y -= vertalign_Koef_Super * CurTextPr.FontSize * g_dKoef_pt_to_mm; break; } } if ( Pos === this.Numbering.Pos ) { var NumberingItem = this.Numbering; if ( para_Numbering === this.Numbering.Type ) { var NumPr = Pr.ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) break; var Numbering = this.Parent.Get_Numbering(); var NumLvl = Numbering.Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl]; var NumSuff = NumLvl.Suff; var NumJc = NumLvl.Jc; var NumTextPr = this.Get_CompiledPr2(false).TextPr.Copy(); // Word не рисует подчеркивание у символа списка, если оно пришло из настроек для // символа параграфа. var TextPr_temp = this.TextPr.Value.Copy(); TextPr_temp.Underline = undefined; NumTextPr.Merge( TextPr_temp ); NumTextPr.Merge( NumLvl.TextPr ); var X_start = X; if ( align_Right === NumJc ) X_start = X - NumberingItem.WidthNum; else if ( align_Center === NumJc ) X_start = X - NumberingItem.WidthNum / 2; pGraphics.b_color1( NumTextPr.Color.r, NumTextPr.Color.g, NumTextPr.Color.b, 255 ); // Рисуется только сам символ нумерации switch ( NumJc ) { case align_Right: NumberingItem.Draw( X - NumberingItem.WidthNum, Y, pGraphics, Numbering, NumTextPr, NumPr ); break; case align_Center: NumberingItem.Draw( X - NumberingItem.WidthNum / 2, Y, pGraphics, Numbering, NumTextPr, NumPr ); break; case align_Left: default: NumberingItem.Draw( X, Y, pGraphics, Numbering, NumTextPr, NumPr ); break; } if ( true === editor.ShowParaMarks && numbering_suff_Tab === NumSuff ) { var TempWidth = NumberingItem.WidthSuff; var TempRealWidth = 3.143; // ширина символа "стрелка влево" в шрифте Wingding3,10 var X1 = X; switch ( NumJc ) { case align_Right: break; case align_Center: X1 += NumberingItem.WidthNum / 2; break; case align_Left: default: X1 += NumberingItem.WidthNum; break; } var X0 = TempWidth / 2 - TempRealWidth / 2; pGraphics.SetFont( {FontFamily: { Name : "Wingdings 3", Index : -1 }, FontSize: 10, Italic: false, Bold : false} ); if ( X0 > 0 ) pGraphics.FillText2( X1 + X0, Y, String.fromCharCode( tab_Symbol ), 0, TempWidth ); else pGraphics.FillText2( X1, Y, String.fromCharCode( tab_Symbol ), TempRealWidth - TempWidth, TempWidth ); } if ( true === NumTextPr.Strikeout || true === NumTextPr.Underline ) pGraphics.p_color( NumTextPr.Color.r, NumTextPr.Color.g, NumTextPr.Color.b, 255 ); if ( true === NumTextPr.Strikeout ) pGraphics.drawHorLine(0, (Y - NumTextPr.FontSize * g_dKoef_pt_to_mm * 0.27), X_start, X_start + NumberingItem.WidthNum, (NumTextPr.FontSize / 18) * g_dKoef_pt_to_mm); if ( true === NumTextPr.Underline ) pGraphics.drawHorLine( 0, (Y + this.Lines[CurLine].Metrics.TextDescent * 0.4), X_start, X_start + NumberingItem.WidthNum, (NumTextPr.FontSize / 18) * g_dKoef_pt_to_mm); X += NumberingItem.WidthVisible; // Восстановим настройки pGraphics.SetTextPr( CurTextPr ); if ( true === bVisitedHyperlink ) pGraphics.b_color1( 128, 0, 151, 255 ); else pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); } else if ( para_PresentationNumbering === this.Numbering.Type ) { if ( true != this.IsEmpty() ) { // Найдем настройки для первого текстового элемента var FirstTextPr = this.Internal_CalculateTextPr( this.Internal_GetStartPos() ); if ( Pr.ParaPr.Ind.FirstLine < 0 ) NumberingItem.Draw( X, Y, pGraphics, FirstTextPr ); else NumberingItem.Draw( this.X + Pr.ParaPr.Ind.Left, Y, pGraphics, FirstTextPr ); } X += NumberingItem.WidthVisible; } } switch( Item.Type ) { case para_PageNum: case para_Drawing: case para_Tab: case para_Text: { if ( para_Drawing != Item.Type || drawing_Anchor != Item.DrawingType ) { bFirstLineItem = false; if ( para_PageNum != Item.Type ) Item.Draw( X, Y - Item.YOffset, pGraphics ); else Item.Draw( X, Y - Item.YOffset, pGraphics, this.Get_StartPage_Absolute() + CurPage, Pr.ParaPr.Jc ); X += Item.WidthVisible; } // Внутри отрисовки инлайн-автофигур могут изменится цвета и шрифт, поэтому восстанавливаем настройки if ( para_Drawing === Item.Type && drawing_Inline === Item.DrawingType ) { pGraphics.SetTextPr( CurTextPr ); pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); pGraphics.p_color( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); } break; } case para_Space: { Item.Draw( X, Y - Item.YOffset, pGraphics ); X += Item.WidthVisible; break; } case para_TextPr: { CurTextPr = Item.CalcValue;//this.Internal_CalculateTextPr( Pos ); pGraphics.SetTextPr( CurTextPr ); if ( true === bVisitedHyperlink ) pGraphics.b_color1( 128, 0, 151, 255 ); else pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } case para_End: { // Выставляем настройки для символа параграфа var EndTextPr = Item.TextPr; pGraphics.SetTextPr( EndTextPr ); pGraphics.b_color1( EndTextPr.Color.r, EndTextPr.Color.g, EndTextPr.Color.b, 255); bEnd = true; var bEndCell = false; if ( null === this.Get_DocumentNext() && true === this.Parent.Is_TableCellContent() ) bEndCell = true; Item.Draw( X, Y - Item.YOffset, pGraphics, bEndCell ); X += Item.Width; break; } case para_NewLine: { Item.Draw( X, Y - Item.YOffset, pGraphics ); X += Item.WidthVisible; break; } case para_HyperlinkStart: { bVisitedHyperlink = Item.Get_Visited(); if ( true === bVisitedHyperlink ) pGraphics.b_color1( 128, 0, 151, 255 ); else pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } case para_HyperlinkEnd: { bVisitedHyperlink = false; pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } } Y = TempY; } } }, Internal_Draw_5 : function(CurPage, pGraphics, Pr) { var _Page = this.Pages[CurPage]; var StartPagePos = this.Lines[_Page.StartLine].StartPos; var HyperPos = this.Internal_FindBackward( StartPagePos, [para_HyperlinkStart, para_HyperlinkEnd] ); var bVisitedHyperlink = false; if ( true === HyperPos.Found && para_HyperlinkStart === HyperPos.Type ) bVisitedHyperlink = this.Content[HyperPos.LetterPos].Get_Visited(); var CurTextPr = _Page.TextPr; // Выставляем цвет обводки var CurColor; if ( true === bVisitedHyperlink ) CurColor = new CDocumentColor( 128, 0, 151 ); else CurColor = new CDocumentColor( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b ); var StartLine = _Page.StartLine; var EndLine = _Page.EndLine; var CheckSpelling = this.SpellChecker.Get_DrawingInfo(); var aStrikeout = new CParaDrawingRangeLines(); var aDStrikeout = new CParaDrawingRangeLines(); var aUnderline = new CParaDrawingRangeLines(); var aSpelling = new CParaDrawingRangeLines(); for ( var CurLine = StartLine; CurLine <= EndLine; CurLine++ ) { var _Line = this.Lines[CurLine]; var EndLinePos = _Line.EndPos; var LineY = _Page.Y + _Line.Y; var Y = LineY; var LineM = _Line.Metrics; var LineM_D_04 = LineM.TextDescent * 0.4; var RangesCount = _Line.Ranges.length; aStrikeout.Clear(); aDStrikeout.Clear(); aUnderline.Clear(); aSpelling.Clear(); for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var _Range = _Line.Ranges[CurRange]; // Сначала проанализируем данную строку: в массивы aStrikeout, aDStrikeout, aUnderline // aSpelling сохраним позиции начала и конца продолжительных одинаковых настроек зачеркивания, // двойного зачеркивания, подчеркивания и подчеркивания орфографии. var X = _Range.XVisible; var StartPos = _Range.StartPos; var EndPos = ( CurRange === RangesCount - 1 ? EndLinePos : _Line.Ranges[CurRange + 1].StartPos - 1 ); for ( var Pos = StartPos; Pos <= EndPos; Pos++ ) { var Item = this.Content[Pos]; // Нумерацию подчеркиваем и зачеркиваем в Internal_Draw_4 if ( Pos === this.Numbering.Pos ) X += this.Numbering.WidthVisible; switch( Item.Type ) { case para_End: case para_NewLine: { X += Item.WidthVisible; break; } case para_PageNum: case para_Drawing: case para_Tab: case para_Text: { if ( para_Drawing != Item.Type || drawing_Anchor != Item.DrawingType ) { if ( true === CurTextPr.DStrikeout ) aDStrikeout.Add( Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); else if ( true === CurTextPr.Strikeout ) aStrikeout.Add( Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); if ( true === CurTextPr.Underline ) aUnderline.Add( Y + this.Lines[CurLine].Metrics.TextDescent * 0.4, Y + this.Lines[CurLine].Metrics.TextDescent * 0.4, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); if ( true === CheckSpelling[Pos] ) aSpelling.Add( Y + LineM_D_04, Y + LineM_D_04, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, 0, 0, 0 ); X += Item.WidthVisible; } break; } case para_Space: { // Пробелы в конце строки (и строку состоящую из пробелов) не подчеркиваем, не зачеркиваем и не выделяем if ( Pos >= _Range.StartPos2 && Pos <= _Range.EndPos2 ) { if ( true === CurTextPr.DStrikeout ) aDStrikeout.Add( Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); else if ( true === CurTextPr.Strikeout ) aStrikeout.Add( Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, Y - CurTextPr.FontSize * g_dKoef_pt_to_mm * 0.27, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); if ( true === CurTextPr.Underline ) aUnderline.Add( Y + LineM_D_04, Y + LineM_D_04, X, X + Item.WidthVisible, (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm, CurColor.r, CurColor.g, CurColor.b ); } X += Item.WidthVisible; break; } case para_TextPr: { CurTextPr = Item.CalcValue; // Выставляем цвет обводки if ( true === bVisitedHyperlink ) CurColor.Set( 128, 0, 151, 255 ); else CurColor.Set( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); switch( CurTextPr.VertAlign ) { case vertalign_SubScript: { Y = LineY - vertalign_Koef_Sub * CurTextPr.FontSize * g_dKoef_pt_to_mm; break; } case vertalign_SuperScript: { Y = LineY - vertalign_Koef_Super * CurTextPr.FontSize * g_dKoef_pt_to_mm; break; } default : { Y = LineY; break; } } break; } case para_HyperlinkStart: { bVisitedHyperlink = Item.Get_Visited(); // Выставляем цвет обводки if ( true === bVisitedHyperlink ) CurColor.Set( 128, 0, 151, 255 ); else CurColor.Set( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } case para_HyperlinkEnd: { bVisitedHyperlink = false; CurColor.Set( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255); break; } } } } // Рисуем зачеркивание var Element = aStrikeout.Get_Next(); while ( null != Element ) { pGraphics.p_color( Element.r, Element.g, Element.b, 255 ); pGraphics.drawHorLine(c_oAscLineDrawingRule.Top, Element.y0, Element.x0, Element.x1, Element.w ); Element = aStrikeout.Get_Next(); } // Рисуем двойное зачеркивание Element = aDStrikeout.Get_Next(); while ( null != Element ) { pGraphics.p_color( Element.r, Element.g, Element.b, 255 ); pGraphics.drawHorLine2(c_oAscLineDrawingRule.Top, Element.y0, Element.x0, Element.x1, Element.w ); Element = aDStrikeout.Get_Next(); } // Рисуем подчеркивание aUnderline.Correct_w_ForUnderline(); Element = aUnderline.Get_Next(); while ( null != Element ) { pGraphics.p_color( Element.r, Element.g, Element.b, 255 ); pGraphics.drawHorLine(0, Element.y0, Element.x0, Element.x1, Element.w ); Element = aUnderline.Get_Next(); } // Рисуем подчеркивание орфографии pGraphics.p_color( 255, 0, 0, 255 ); var SpellingW = editor.WordControl.m_oDrawingDocument.GetMMPerDot(1); Element = aSpelling.Get_Next(); while ( null != Element ) { pGraphics.DrawSpellingLine(Element.y0, Element.x0, Element.x1, SpellingW); Element = aSpelling.Get_Next(); } } }, Internal_Draw_6 : function(CurPage, pGraphics, Pr) { var bEmpty = this.IsEmpty(); var X_left = Math.min( this.Pages[CurPage].X + Pr.ParaPr.Ind.Left, this.Pages[CurPage].X + Pr.ParaPr.Ind.Left + Pr.ParaPr.Ind.FirstLine ); var X_right = this.Pages[CurPage].XLimit - Pr.ParaPr.Ind.Right; if ( true === this.Is_LineDropCap() ) X_right = X_left + this.Get_LineDropCapWidth(); if ( Pr.ParaPr.Brd.Left.Value === border_Single ) X_left -= 1 + Pr.ParaPr.Brd.Left.Space; else X_left -= 1; if ( Pr.ParaPr.Brd.Right.Value === border_Single ) X_right += 1 + Pr.ParaPr.Brd.Right.Space; else X_right += 1; var LeftMW = -( border_Single === Pr.ParaPr.Brd.Left.Value ? Pr.ParaPr.Brd.Left.Size : 0 ); var RightMW = ( border_Single === Pr.ParaPr.Brd.Right.Value ? Pr.ParaPr.Brd.Right.Size : 0 ); // Рисуем линию до параграфа if ( true === Pr.ParaPr.Brd.First && border_Single === Pr.ParaPr.Brd.Top.Value && ( ( 0 === CurPage && ( false === this.Is_StartFromNewPage() || null === this.Get_DocumentPrev() ) ) || ( 1 === CurPage && true === this.Is_StartFromNewPage() ) ) ) { var Y_top = this.Pages[CurPage].Y; if ( 0 === CurPage ) Y_top += Pr.ParaPr.Spacing.Before; pGraphics.p_color( Pr.ParaPr.Brd.Top.Color.r, Pr.ParaPr.Brd.Top.Color.g, Pr.ParaPr.Brd.Top.Color.b, 255 ); // Учтем разрывы из-за обтекания var StartLine = this.Pages[CurPage].StartLine; var RangesCount = this.Lines[StartLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var X0 = ( 0 === CurRange ? X_left : this.Lines[StartLine].Ranges[CurRange].X ); var X1 = ( RangesCount - 1 === CurRange ? X_right : this.Lines[StartLine].Ranges[CurRange].XEnd ); if ( this.Lines[StartLine].Ranges[CurRange].W > 0.001 || ( true === bEmpty && 1 === RangesCount ) ) pGraphics.drawHorLineExt( c_oAscLineDrawingRule.Top, Y_top, X0, X1, Pr.ParaPr.Brd.Top.Size, LeftMW, RightMW ); } } else if ( false === Pr.ParaPr.Brd.First ) { var bDraw = false; var Size = 0; var Y = 0; if ( 1 === CurPage && true === this.Is_StartFromNewPage() && border_Single === Pr.ParaPr.Brd.Top.Value ) { pGraphics.p_color( Pr.ParaPr.Brd.Top.Color.r, Pr.ParaPr.Brd.Top.Color.g, Pr.ParaPr.Brd.Top.Color.b, 255 ); Size = Pr.ParaPr.Brd.Top.Size; Y = this.Pages[CurPage].Y + this.Lines[this.Pages[CurPage].FirstLine].Top; bDraw = true; } else if ( 0 === CurPage && false === this.Is_StartFromNewPage() && border_Single === Pr.ParaPr.Brd.Between.Value ) { pGraphics.p_color( Pr.ParaPr.Brd.Between.Color.r, Pr.ParaPr.Brd.Between.Color.g, Pr.ParaPr.Brd.Between.Color.b, 255 ); Size = Pr.ParaPr.Brd.Between.Size; Y = this.Pages[CurPage].Y; bDraw = true; } if ( true === bDraw ) { // Учтем разрывы из-за обтекания var StartLine = this.Pages[CurPage].StartLine; var RangesCount = this.Lines[StartLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var X0 = ( 0 === CurRange ? X_left : this.Lines[StartLine].Ranges[CurRange].X ); var X1 = ( RangesCount - 1 === CurRange ? X_right : this.Lines[StartLine].Ranges[CurRange].XEnd ); if ( this.Lines[StartLine].Ranges[CurRange].W > 0.001 || ( true === bEmpty && 1 === RangesCount ) ) pGraphics.drawHorLineExt( c_oAscLineDrawingRule.Top, Y, X0, X1, Size, LeftMW, RightMW ); } } } var CurLine = this.Pages[CurPage].EndLine; var bEnd = ( this.Content.length - 2 <= this.Lines[CurLine].EndPos ? true : false ); // Рисуем линию после параграфа if ( true === bEnd && true === Pr.ParaPr.Brd.Last && border_Single === Pr.ParaPr.Brd.Bottom.Value ) { var TempY = this.Pages[CurPage].Y; var NextEl = this.Get_DocumentNext(); var DrawLineRule = c_oAscLineDrawingRule.Bottom; if ( null != NextEl && type_Paragraph === NextEl.GetType() && true === NextEl.Is_StartFromNewPage() ) { TempY = this.Pages[CurPage].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; DrawLineRule = c_oAscLineDrawingRule.Top; } else { TempY = this.Pages[CurPage].Y + this.Lines[CurLine].Bottom - Pr.ParaPr.Spacing.After; DrawLineRule = c_oAscLineDrawingRule.Bottom; } pGraphics.p_color( Pr.ParaPr.Brd.Bottom.Color.r, Pr.ParaPr.Brd.Bottom.Color.g, Pr.ParaPr.Brd.Bottom.Color.b, 255 ); // Учтем разрывы из-за обтекания var EndLine = this.Pages[CurPage].EndLine; var RangesCount = this.Lines[EndLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var X0 = ( 0 === CurRange ? X_left : this.Lines[EndLine].Ranges[CurRange].X ); var X1 = ( RangesCount - 1 === CurRange ? X_right : this.Lines[EndLine].Ranges[CurRange].XEnd ); if ( this.Lines[EndLine].Ranges[CurRange].W > 0.001 || ( true === bEmpty && 1 === RangesCount ) ) pGraphics.drawHorLineExt( DrawLineRule, TempY, X0, X1, Pr.ParaPr.Brd.Bottom.Size, LeftMW, RightMW ); } } else if ( true === bEnd && false === Pr.ParaPr.Brd.Last && border_Single === Pr.ParaPr.Brd.Bottom.Value ) { var NextEl = this.Get_DocumentNext(); if ( null != NextEl && type_Paragraph === NextEl.GetType() && true === NextEl.Is_StartFromNewPage() ) { pGraphics.p_color( Pr.ParaPr.Brd.Bottom.Color.r, Pr.ParaPr.Brd.Bottom.Color.g, Pr.ParaPr.Brd.Bottom.Color.b, 255 ); // Учтем разрывы из-за обтекания var EndLine = this.Pages[CurPage].EndLine; var RangesCount = this.Lines[EndLine].Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var X0 = ( 0 === CurRange ? X_left : this.Lines[EndLine].Ranges[CurRange].X ); var X1 = ( RangesCount - 1 === CurRange ? X_right : this.Lines[EndLine].Ranges[CurRange].XEnd ); if ( this.Lines[EndLine].Ranges[CurRange].W > 0.001 || ( true === bEmpty && 1 === RangesCount ) ) pGraphics.drawHorLineExt( c_oAscLineDrawingRule.Top, this.Pages[CurPage].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap, X0, X1, Pr.ParaPr.Brd.Bottom.Size, LeftMW, RightMW ); } } } }, ReDraw : function() { this.Parent.OnContentReDraw( this.Get_StartPage_Absolute(), this.Get_StartPage_Absolute() + this.Pages.length - 1 ); }, Shift : function(PageIndex, Dx, Dy) { if ( 0 === PageIndex ) { this.X += Dx; this.Y += Dy; this.XLimit += Dx; this.YLimit += Dy; } var Page_abs = PageIndex + this.Get_StartPage_Absolute(); this.Pages[PageIndex].Shift( Dx, Dy ); var StartLine = this.Pages[PageIndex].FirstLine; var EndLine = ( PageIndex >= this.Pages.length - 1 ? this.Lines.length - 1 : this.Pages[PageIndex + 1].FirstLine - 1 ); for ( var CurLine = StartLine; CurLine <= EndLine; CurLine++ ) this.Lines[CurLine].Shift( Dx, Dy ); // Пробегаемся по всем картинкам на данной странице и обновляем координаты var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type && Item.PageNum === Page_abs ) { Item.Shift( Dx, Dy ); } } }, Internal_Remove_CollaborativeMarks : function() { for ( var Pos = 0; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; if ( para_CollaborativeChangesEnd === Item.Type || para_CollaborativeChangesStart === Item.Type ) { this.Internal_Content_Remove(Pos); Pos--; } } }, // Удаляем элементы параграфа // nCount - количество удаляемых элементов, > 0 удаляем элементы после курсора // < 0 удаляем элементы до курсора // bOnlyText - true: удаляем только текст и пробелы, false - Удаляем любые элементы Remove : function(nCount, bOnlyText) { this.Internal_Remove_CollaborativeMarks(); this.RecalcInfo.Set_Type_0(pararecalc_0_All); // Сначала проверим имеется ли у нас селект if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( EndPos >= this.Content.length - 1 ) { for ( var Index = StartPos; Index < this.Content.length - 2; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type ) { var ObjId = Item.Get_Id(); this.Parent.DrawingObjects.Remove_ById( ObjId ); } } var Hyper_start = null; if ( StartPos < EndPos ) Hyper_start = this.Check_Hyperlink2( StartPos ); // Удаляем внутреннюю часть селекта (без знака параграфа) this.Internal_Content_Remove2( StartPos, this.Content.length - 2 - StartPos ); // После удаления позиции могли измениться StartPos = this.Selection.StartPos; EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Set_ContentPos( StartPos, true, -1 ); if ( null != Hyper_start ) { this.Internal_Content_Add( StartPos, new ParaTextPr() ); this.Internal_Content_Add( StartPos, new ParaHyperlinkEnd() ); } // Данный параграф надо объединить со следующим return false; } else { var Hyper_start = this.Check_Hyperlink2( StartPos ); var Hyper_end = this.Check_Hyperlink2( EndPos ); // Если встречалось какое-либо изменение настроек, сохраним его последние изменение var LastTextPr = null; for ( var Index = StartPos; Index < EndPos; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type ) { var ObjId = Item.Get_Id(); this.Parent.DrawingObjects.Remove_ById( ObjId ); } else if ( para_TextPr === Item.Type ) LastTextPr = Item; } this.Internal_Content_Remove2( StartPos, EndPos - StartPos ); // После удаления позиции могли измениться StartPos = this.Selection.StartPos; EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( null != LastTextPr ) this.Internal_Content_Add( StartPos, new ParaTextPr( LastTextPr.Value ) ); this.Set_ContentPos( StartPos, true, -1 ); if ( Hyper_start != Hyper_end ) { if ( null != Hyper_end ) { this.Internal_Content_Add( StartPos, Hyper_end ); this.Set_ContentPos( this.CurPos.ContentPos + 1 ); } if ( null != Hyper_start ) { this.Internal_Content_Add( StartPos, new ParaHyperlinkEnd() ); this.Set_ContentPos( this.CurPos.ContentPos + 1 ); } } else { // TODO: Пока селект реализован так, что тут начало гиперссылки не попадает в выделение, а конец попадает. // Поэтому добавляем конец гиперссылки, и потом проверяем пустая ли она. this.Internal_Content_Add( StartPos, new ParaHyperlinkEnd() ); this.Internal_Check_EmptyHyperlink( StartPos ); } } return; } if ( 0 == nCount ) return; var absCount = ( nCount < 0 ? -nCount : nCount ); for ( var Index = 0; Index < absCount; Index++ ) { var OldPos = this.CurPos.ContentPos; if ( nCount < 0 ) { if ( false === this.Internal_RemoveBackward(bOnlyText) ) return false; } else { if ( false === this.Internal_RemoveForward(bOnlyText) ) return false; } this.Internal_Check_EmptyHyperlink( OldPos ); } return true; }, Internal_RemoveBackward : function(bOnlyText) { var Line = this.Content; var CurPos = this.CurPos.ContentPos; if ( !bOnlyText ) { if ( CurPos == 0 ) return false; else { // Просто удаляем элемент предстоящий текущей позиции и уменьшаем текущую позицию this.Internal_Content_Remove( CurPos - 1 ); } } else { var LetterPos = CurPos - 1; var oPos = this.Internal_FindBackward( LetterPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( oPos.Found ) { if ( para_Drawing === oPos.Type ) { this.Parent.Select_DrawingObject( this.Content[oPos.LetterPos].Get_Id() ); } else { // Удаляем элемент в найденной позиции и уменьшаем текущую позицию this.Internal_Content_Remove( oPos.LetterPos ); this.Set_ContentPos( oPos.LetterPos, true, -1 ); } } else { // Мы стоим в начале параграфа и пытаемся удалить элемент влево. Действуем следующим образом: // 1. Если у нас параграф с нумерацией, тогда удаляем нумерацию, но при этом сохраняем // значения отступов так как это делается в Word. (аналогично работаем с нумерацией в презентациях) // 2. Если у нас отступ первой строки ненулевой, тогда: // 2.1 Если он положительный делаем его нулевым. // 2.2 Если он отрицательный сдвигаем левый отступ на значение отступа первой строки, // а сам отступ первой строки делаем нулевым. // 3. Если у нас ненулевой левый отступ, делаем его нулевым // 4. Если ничего из предыдущего не случается, тогда говорим родительскому классу, что удаление // не было выполнено. var Pr = this.Get_CompiledPr2(false).ParaPr; if ( undefined != this.Numbering_Get() ) { this.Numbering_Remove(); this.Set_Ind( { FirstLine : 0, Left : Math.max( Pr.Ind.Left, Pr.Ind.Left + Pr.Ind.FirstLine ) }, false ); } else if ( numbering_presentationnumfrmt_None != this.PresentationPr.Bullet.Get_Type() ) { this.Remove_PresentationNumbering(); } else if ( align_Right === Pr.Jc ) { this.Set_Align( align_Center ); } else if ( align_Center === Pr.Jc ) { this.Set_Align( align_Left ); } else if ( Math.abs(Pr.Ind.FirstLine) > 0.001 ) { if ( Pr.Ind.FirstLine > 0 ) this.Set_Ind( { FirstLine : 0 }, false ); else this.Set_Ind( { Left : Pr.Ind.Left + Pr.Ind.FirstLine, FirstLine : 0 }, false ); } else if ( Math.abs(Pr.Ind.Left) > 0.001 ) { this.Set_Ind( { Left : 0 }, false ); } else return false; } } return true; }, Internal_RemoveForward : function(bOnlyText) { var Line = this.Content; var CurPos = this.CurPos.ContentPos; if ( !bOnlyText ) { if ( CurPos == Line.length - 1 ) { return false; } else { // Просто удаляем элемент после текущей позиции this.Internal_Content_Remove( CurPos + 1 ); } } else { var LetterPos = CurPos; var oPos = this.Internal_FindForward( LetterPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( oPos.Found ) { if ( para_Drawing === oPos.Type ) { this.Parent.Select_DrawingObject( this.Content[oPos.LetterPos].Get_Id() ); } else { // Удаляем элемент в найденной позиции и меняем текущую позицию this.Internal_Content_Remove( oPos.LetterPos ); this.Set_ContentPos( oPos.LetterPos, true, -1 ); } } else { return false; } } return true; }, // Ищем первый элемент, при промотке вперед Internal_FindForward : function(CurPos, arrId) { var LetterPos = CurPos; var bFound = false; var Type = para_Unknown; if ( CurPos < 0 || CurPos >= this.Content.length ) return { Found : false }; while ( !bFound ) { Type = this.Content[LetterPos].Type; for ( var Id = 0; Id < arrId.length; Id++ ) { if ( arrId[Id] == Type ) { bFound = true; break; } } if ( bFound ) break; LetterPos++; if ( LetterPos > this.Content.length - 1 ) break; } return { LetterPos : LetterPos, Found : bFound, Type : Type }; }, // Ищем первый элемент, при промотке назад Internal_FindBackward : function(CurPos, arrId) { var LetterPos = CurPos; var bFound = false; var Type = para_Unknown; if ( CurPos < 0 || CurPos >= this.Content.length ) return { Found : false }; while ( !bFound ) { Type = this.Content[LetterPos].Type; for ( var Id = 0; Id < arrId.length; Id++ ) { if ( arrId[Id] == Type ) { bFound = true; break; } } if ( bFound ) break; LetterPos--; if ( LetterPos < 0 ) break; } return { LetterPos : LetterPos, Found : bFound, Type : Type }; }, Internal_CalculateTextPr : function (LetterPos, StartPr) { var Pr; if ( "undefined" != typeof(StartPr) ) { Pr = this.Get_CompiledPr(); StartPr.ParaPr = Pr.ParaPr; StartPr.TextPr = Pr.TextPr; } else { Pr = this.Get_CompiledPr2(false); } // Выствляем начальные настройки текста у данного параграфа var TextPr = Pr.TextPr.Copy(); // Ищем ближайший TextPr if ( LetterPos < 0 ) return TextPr; // Ищем предыдущие записи с изменением текстовых свойств var Pos = this.Internal_FindBackward( LetterPos, [para_TextPr] ); if ( true === Pos.Found ) { var CurTextPr = this.Content[Pos.LetterPos].Value; // Копируем настройки из символьного стиля if ( undefined != CurTextPr.RStyle ) { var Styles = this.Parent.Get_Styles(); var StyleTextPr = Styles.Get_Pr( CurTextPr.RStyle, styletype_Character).TextPr; TextPr.Merge( StyleTextPr ); } // Копируем прямые настройки TextPr.Merge( CurTextPr ); } TextPr.FontFamily.Name = TextPr.RFonts.Ascii.Name; TextPr.FontFamily.Index = TextPr.RFonts.Ascii.Index; return TextPr; }, Internal_GetLang : function(LetterPos) { var Lang = this.Get_CompiledPr2(false).TextPr.Lang.Copy(); // Ищем ближайший TextPr if ( LetterPos < 0 ) return Lang; // Ищем предыдущие записи с изменением текстовых свойств var Pos = this.Internal_FindBackward( LetterPos, [para_TextPr] ); if ( true === Pos.Found ) { var CurTextPr = this.Content[Pos.LetterPos].Value; // Копируем настройки из символьного стиля if ( undefined != CurTextPr.RStyle ) { var Styles = this.Parent.Get_Styles(); var StyleTextPr = Styles.Get_Pr( CurTextPr.RStyle, styletype_Character).TextPr; Lang.Merge( StyleTextPr.Lang ); } // Копируем прямые настройки Lang.Merge( CurTextPr.Lang ); } return Lang; }, Internal_GetTextPr : function(LetterPos) { var TextPr = new CTextPr(); // Ищем ближайший TextPr if ( LetterPos < 0 ) return TextPr; // Ищем предыдущие записи с изменением текстовых свойств var Pos = this.Internal_FindBackward( LetterPos, [para_TextPr] ); if ( true === Pos.Found ) { var CurTextPr = this.Content[Pos.LetterPos].Value; TextPr.Merge( CurTextPr ); } // Если ничего не нашли, то TextPr будет пустым, что тоже нормально return TextPr; }, // Добавляем новый элемент к содержимому параграфа (на текущую позицию) Add : function(Item) { var CurPos = this.CurPos.ContentPos; if ( "undefined" != typeof(Item.Parent) ) Item.Parent = this; switch (Item.Type) { case para_Text: { this.Internal_Content_Add( CurPos, Item ); break; } case para_Space: { this.Internal_Content_Add( CurPos, Item ); break; } case para_TextPr: { this.Internal_AddTextPr( Item.Value ); break; } case para_HyperlinkStart: { this.Internal_AddHyperlink( Item ); break; } case para_PageNum: case para_Tab: case para_Drawing: default: { this.Internal_Content_Add( CurPos, Item ); break; } } if ( para_TextPr != Item.Type ) this.DeleteCollaborativeMarks = true; this.RecalcInfo.Set_Type_0(pararecalc_0_All); }, // Данная функция вызывается, когда уже точно известно, что у нас либо выделение начинается с начала параграфа, либо мы стоим курсором в начале параграфа Add_Tab : function(bShift) { var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { if ( true != this.Selection.Use ) { var NumId = NumPr.NumId; var Lvl = NumPr.Lvl; var NumInfo = this.Parent.Internal_GetNumInfo( this.Id, NumPr ); if ( 0 === Lvl && NumInfo[Lvl] <= 1 ) { var Numbering = this.Parent.Get_Numbering(); var AbstractNum = Numbering.Get_AbstractNum(NumId); var NumLvl = AbstractNum.Lvl[Lvl]; var NumParaPr = NumLvl.ParaPr; var ParaPr = this.Get_CompiledPr2(false).ParaPr; if ( undefined != NumParaPr.Ind && undefined != NumParaPr.Ind.Left ) { var NewX = ParaPr.Ind.Left; if ( true != bShift ) NewX += Default_Tab_Stop; else { NewX -= Default_Tab_Stop; if ( NewX < 0 ) NewX = 0; if ( ParaPr.Ind.FirstLine < 0 && NewX + ParaPr.Ind.FirstLine < 0 ) NewX = -ParaPr.Ind.FirstLine; } AbstractNum.Change_LeftInd( NewX ); History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : undefined } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : undefined } ); // При добавлении списка в параграф, удаляем все собственные сдвиги this.Pr.Ind.FirstLine = undefined; this.Pr.Ind.Left = undefined; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } } else this.Numbering_IndDec_Level( !bShift ); } else this.Numbering_IndDec_Level( !bShift ); } else if ( true === this.Is_SelectionUse() ) { this.IncDec_Indent( !bShift ); } else { var ParaPr = this.Get_CompiledPr2(false).ParaPr; if ( true != bShift ) { if ( ParaPr.Ind.FirstLine < 0 ) { this.Set_Ind( { FirstLine : 0 }, false ); this.CompiledPr.NeedRecalc = true; } else if ( ParaPr.Ind.FirstLine < 12.5 ) { this.Set_Ind( { FirstLine : 12.5 }, false ); this.CompiledPr.NeedRecalc = true; } else if ( X_Right_Field - X_Left_Margin > ParaPr.Ind.Left + 25 ) { this.Set_Ind( { Left : ParaPr.Ind.Left + 12.5 }, false ); this.CompiledPr.NeedRecalc = true; } } else { if ( ParaPr.Ind.FirstLine > 0 ) { if ( ParaPr.Ind.FirstLine > 12.5 ) this.Set_Ind( { FirstLine : ParaPr.Ind.FirstLine - 12.5 }, false ); else this.Set_Ind( { FirstLine : 0 }, false ); this.CompiledPr.NeedRecalc = true; } else { var Left = ParaPr.Ind.Left + ParaPr.Ind.FirstLine; if ( Left < 0 ) { this.Set_Ind( { Left : -ParaPr.Ind.FirstLine }, false ); this.CompiledPr.NeedRecalc = true; } else { if ( Left > 12.5 ) this.Set_Ind( { Left : ParaPr.Ind.Left - 12.5 }, false ); else this.Set_Ind( { Left : -ParaPr.Ind.FirstLine }, false ); this.CompiledPr.NeedRecalc = true; } } } } }, // Расширяем параграф до позиции X Extend_ToPos : function(_X) { var Page = this.Pages[this.Pages.length - 1]; var X0 = Page.X; var X1 = Page.XLimit - X0; var X = _X - X0; if ( true === this.IsEmpty() ) { if ( Math.abs(X - X1 / 2) < 12.5 ) return this.Set_Align( align_Center ); else if ( X > X1 - 12.5 ) return this.Set_Align( align_Right ); else if ( X < 12.5 ) return this.Set_Ind( { FirstLine : 12.5 }, false ); } var Tabs = this.Get_CompiledPr2(false).ParaPr.Tabs.Copy(); var CurPos = this.Internal_GetEndPos(); if ( Math.abs(X - X1 / 2) < 12.5 ) Tabs.Add( new CParaTab( tab_Center, X1 / 2 ) ); else if ( X > X1 - 12.5 ) Tabs.Add( new CParaTab( tab_Right, X1 - 0.001 ) ); else Tabs.Add( new CParaTab( tab_Left, X ) ); this.Set_Tabs( Tabs ); this.Internal_Content_Add( CurPos, new ParaTab() ); }, Internal_IncDecFontSize : function(bIncrease, Value) { // Закон изменения размеров : // 1. Если значение меньше 8, тогда мы увеличиваем/уменьшаем по 1 (от 1 до 8) // 2. Если значение больше 72, тогда мы увеличиваем/уменьшаем по 10 (от 80 до бесконечности // 3. Если значение в отрезке [8,72], тогда мы переходим по следующим числам 8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72 var Sizes = [8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72]; var NewValue = Value; if ( true === bIncrease ) { if ( Value < Sizes[0] ) { if ( Value >= Sizes[0] - 1 ) NewValue = Sizes[0]; else NewValue = Math.floor(Value + 1); } else if ( Value >= Sizes[Sizes.length - 1] ) { NewValue = Math.min( 300, Math.floor( Value / 10 + 1 ) * 10 ); } else { for ( var Index = 0; Index < Sizes.length; Index++ ) { if ( Value < Sizes[Index] ) { NewValue = Sizes[Index]; break; } } } } else { if ( Value <= Sizes[0] ) { NewValue = Math.max( Math.floor( Value - 1 ), 1 ); } else if ( Value > Sizes[Sizes.length - 1] ) { if ( Value <= Math.floor( Sizes[Sizes.length - 1] / 10 + 1 ) * 10 ) NewValue = Sizes[Sizes.length - 1]; else NewValue = Math.floor( Math.ceil(Value / 10) - 1 ) * 10; } else { for ( var Index = Sizes.length - 1; Index >= 0; Index-- ) { if ( Value > Sizes[Index] ) { NewValue = Sizes[Index]; break; } } } } return NewValue; }, IncDec_FontSize : function(bIncrease) { this.RecalcInfo.Set_Type_0(pararecalc_0_All); var StartTextPr = this.Get_CompiledPr().TextPr; if ( true === this.ApplyToAll ) { var StartFontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( 0, new ParaTextPr( { FontSize : StartFontSize } ) ); for ( var Index = 1; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { if ( undefined != Item.Value.FontSize ) Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, Item.Value.FontSize ) ); else Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); } } // Выставляем настройки для символа параграфа if ( undefined != this.TextPr.Value.FontSize ) this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, this.TextPr.Value.FontSize ) ); else this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); return true; } // найдем текущую позицию var Line = this.Content; var CurPos = this.CurPos.ContentPos; if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } // Если селект продолжается до конца параграфа, не ставим отметку в конце var LastPos = this.Internal_GetEndPos(); var bEnd = false; if ( EndPos > LastPos ) { EndPos = LastPos; bEnd = true; } // Рассчитываем настройки, которые используются после селекта var TextPr_end = this.Internal_GetTextPr( EndPos ); var TextPr_start = this.Internal_GetTextPr( StartPos ); if ( undefined != TextPr_start.FontSize ) TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, TextPr_start.FontSize ); else TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( StartPos, new ParaTextPr( TextPr_start ) ); if ( false === bEnd ) this.Internal_Content_Add( EndPos + 1, new ParaTextPr( TextPr_end ) ); else { // Выставляем настройки для символа параграфа if ( undefined != this.TextPr.Value.FontSize ) this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, this.TextPr.Value.FontSize ) ); else this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); } for ( var Pos = StartPos + 1; Pos < EndPos; Pos++ ) { Item = this.Content[Pos]; if ( para_TextPr === Item.Type ) { if ( undefined != typeof(Item.Value.FontSize) ) Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, Item.Value.FontSize ) ); else Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); } } return true; } // 1. Если мы в конце параграфа, тогда добавляем запись о шрифте (применимо к знаку конца параграфа) // 2. Если справа или слева стоит пробел (начало параграфа или перенос строки(командный)), тогда ставим метку со шрифтом и фокусим канву. // 3. Если мы посередине слова, тогда меняем шрифт для данного слова var oEnd = this.Internal_FindForward ( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_End, para_NewLine] ); var oStart = this.Internal_FindBackward( CurPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); var CurType = this.Content[CurPos].Type; if ( !oEnd.Found ) return false; if ( para_End == oEnd.Type ) { // Вставляем запись о новых настройках перед концом параграфа, а текущую позицию выставляем на конец параграфа var Pos = oEnd.LetterPos; var TextPr_start = this.Internal_GetTextPr( Pos ); if ( undefined != TextPr_start.FontSize ) TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, TextPr_start.FontSize ); else TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_start ) ); this.Set_ContentPos( Pos + 1, true, -1 ); // Выставляем настройки для символа параграфа if ( undefined != typeof(this.TextPr.Value.FontSize) ) this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, this.TextPr.Value.FontSize ) ); else this.TextPr.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); return true; } else if ( para_PageNum === CurType || para_Drawing === CurType || para_Tab == CurType || para_Space == CurType || para_NewLine == CurType || !oStart.Found || para_NewLine == oEnd.Type || para_Space == oEnd.Type || para_NewLine == oStart.Type || para_Space == oStart.Type || para_Tab == oEnd.Type || para_Tab == oStart.Type || para_Drawing == oEnd.Type || para_Drawing == oStart.Type || para_PageNum == oEnd.Type || para_PageNum == oStart.Type ) { var TextPr_old = this.Internal_GetTextPr( CurPos ); var TextPr_new = TextPr_old.Copy(); if ( undefined != TextPr_new.FontSize ) TextPr_new.FontSize = this.Internal_IncDecFontSize( bIncrease, TextPr_new.FontSize ); else TextPr_new.FontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_old ) ); this.Internal_Content_Add( CurPos, new ParaEmpty(true) ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_new ) ); this.Set_ContentPos( CurPos + 1, true, -1 ); this.RecalculateCurPos(); return false; } else { // Мы находимся посередине слова. В начале слова ставим запись о новом размере шрифта, // а в конце слова старый размер шрифта. Кроме этого, надо заменить все записи о размерах шрифте внутри слова. // Найдем начало слова var oWordStart = this.Internal_FindBackward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_NewLine] ); if ( !oWordStart.Found ) oWordStart = this.Internal_FindForward( 0, [para_Text] ); else oWordStart.LetterPos++; var oWordEnd = this.Internal_FindForward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_End, para_NewLine] ); if ( !oWordStart.Found || !oWordEnd.Found ) return; // Рассчитываем настройки, которые используются после слова var TextPr_end = this.Internal_GetTextPr( oWordEnd.LetterPos ); var TextPr_start = this.Internal_GetTextPr( oWordStart.LetterPos ); if ( undefined != TextPr_start.FontSize ) TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, TextPr_start.FontSize ); else TextPr_start.FontSize = this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ); this.Internal_Content_Add( oWordStart.LetterPos, new ParaTextPr( TextPr_start ) ); this.Internal_Content_Add( oWordEnd.LetterPos + 1 /* из-за предыдущего Internal_Content_Add */, new ParaTextPr( TextPr_end ) ); this.Set_ContentPos( CurPos + 1, true, -1 ); // Если внутри слова были изменения размера шрифта, тогда заменяем их. for ( var Pos = oWordStart.LetterPos + 1; Pos < oWordEnd.LetterPos; Pos++ ) { Item = this.Content[Pos]; if ( para_TextPr === Item.Type ) { if ( undefined != Item.Value.FontSize ) Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, Item.Value.FontSize ) ); else Item.Set_FontSize( this.Internal_IncDecFontSize( bIncrease, StartTextPr.FontSize ) ); } } return true; } }, IncDec_Indent : function(bIncrease) { var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { this.Numbering_IndDec_Level( bIncrease ); } else { var ParaPr = this.Get_CompiledPr2(false).ParaPr; var LeftMargin = ParaPr.Ind.Left; if ( UnknownValue === LeftMargin ) LeftMargin = 0; else if ( LeftMargin < 0 ) { this.Set_Ind( { Left : 0 }, false ); return; } var LeftMargin_new = 0; if ( true === bIncrease ) { if ( LeftMargin >= 0 ) { LeftMargin = 12.5 * parseInt(10 * LeftMargin / 125); LeftMargin_new = ( (LeftMargin - (10 * LeftMargin) % 125 / 10) / 12.5 + 1) * 12.5; } if ( LeftMargin_new < 0 ) LeftMargin_new = 12.5; } else { var TempValue = (125 - (10 * LeftMargin) % 125); TempValue = ( 125 === TempValue ? 0 : TempValue ); LeftMargin_new = Math.max( ( (LeftMargin + TempValue / 10) / 12.5 - 1 ) * 12.5, 0 ); } this.Set_Ind( { Left : LeftMargin_new }, false ); } var NewPresLvl = ( true === bIncrease ? Math.min( 8, this.PresentationPr.Level + 1 ) : Math.max( 0, this.PresentationPr.Level - 1 ) ); this.Set_PresentationLevel( NewPresLvl ); }, Cursor_GetPos : function() { return { X : this.CurPos.RealX, Y : this.CurPos.RealY }; }, Cursor_MoveLeft : function(Count, AddToSelect, Word) { if ( this.CurPos.ContentPos < 0 ) return false; if ( 0 == Count || !Count ) return; var absCount = ( Count < 0 ? -Count : Count ); for ( var Index = 0; Index < absCount; Index++ ) { if ( false === this.Internal_MoveCursorBackward(AddToSelect, Word) ) return false; } this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; return true; }, Cursor_MoveRight : function(Count, AddToSelect, Word) { if ( this.CurPos.ContentPos < 0 ) return false; if ( 0 == Count || !Count ) return; var absCount = ( Count < 0 ? -Count : Count ); for ( var Index = 0; Index < absCount; Index++ ) { if ( false === this.Internal_MoveCursorForward(AddToSelect, Word) ) return false; } this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; return true; }, Cursor_MoveUp : function(Count, AddToSelect) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( this.CurPos.ContentPos < 0 ) return false; if ( !Count || 0 == Count ) return; var absCount = ( Count < 0 ? -Count : Count ); // Пока сделаем для Count = 1 var CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; var Result = true; if ( true === this.Selection.Use ) { if ( true === AddToSelect ) { this.Set_ContentPos( this.Selection.EndPos, true, -1 ); // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.RecalculateCurPos(); this.CurPos.RealY = this.CurPos.Y; if ( 0 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; this.Selection.EndPos = this.Internal_GetStartPos(); } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine - 1, true, true ); this.CurPos.RealY = this.CurPos.Y; this.Selection.EndPos = this.CurPos.ContentPos; } if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return Result; } } else { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Set_ContentPos( StartPos, true, -1 ); this.Selection_Remove(); // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; if ( 0 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine - 1, true, true ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } } } else if ( true === AddToSelect ) { this.Selection.Use = true; this.Selection.StartPos = this.CurPos.ContentPos; // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.RecalculateCurPos(); this.CurPos.RealY = this.CurPos.Y; if ( 0 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; this.Selection.EndPos = this.Internal_GetStartPos(); } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine - 1, true, true ); this.CurPos.RealY = this.CurPos.Y; this.Selection.EndPos = this.CurPos.ContentPos; } if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return Result; } } else { if ( 0 == CurLine ) { // Возвращяем значение false, это означает, что надо перейти в // предыдущий элемент контента документа. return false; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine - 1, true, true ); this.CurPos.RealY = this.CurPos.Y; } } return Result; }, Cursor_MoveDown : function(Count, AddToSelect) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( this.CurPos.ContentPos < 0 ) return false; if ( !Count || 0 == Count ) return; var absCount = ( Count < 0 ? -Count : Count ); // Пока сделаем для Count = 1 var CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; var Result = true; if ( true === this.Selection.Use ) { if ( true === AddToSelect ) { this.Set_ContentPos( this.Selection.EndPos, true, -1 ); // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.RecalculateCurPos(); this.CurPos.RealY = this.CurPos.Y; if ( this.Lines.length - 1 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; this.Selection.EndPos = this.Content.length - 1; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine + 1, true, true ); this.CurPos.RealY = this.CurPos.Y; this.Selection.EndPos = this.CurPos.ContentPos; } if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return Result; } } else { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Set_ContentPos( Math.max( CursorPos_min, Math.min( EndPos, CursorPos_max ) ), true, -1 ); this.Selection_Remove(); // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; if ( this.Lines.length - 1 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine + 1, true, true ); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } } } else if ( AddToSelect ) { this.Selection.Use = true; this.Selection.StartPos = this.CurPos.ContentPos; // Пока сделаем для Count = 1 CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; this.RecalculateCurPos(); this.CurPos.RealY = this.CurPos.Y; if ( this.Lines.length - 1 == CurLine ) { // Переходим в предыдущий элеменет документа Result = false; this.Selection.EndPos = this.Content.length - 1; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine + 1, true, true ); this.CurPos.RealY = this.CurPos.Y; this.Selection.EndPos = this.CurPos.ContentPos; } if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return Result; } } else { if ( this.Lines.length - 1 == CurLine ) { // Возвращяем значение false, это означает, что надо перейти в // предыдущий элемент контента документа. return false; } else { this.Cursor_MoveAt( this.CurPos.RealX, CurLine + 1, true, true ); this.CurPos.RealY = this.CurPos.Y; } } return Result; }, Cursor_MoveEndOfLine : function(AddToSelect) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( this.CurPos.ContentPos < 0 ) return false; if ( true === this.Selection.Use ) { if ( true === AddToSelect ) this.Set_ContentPos( this.Selection.EndPos, true, -1 ); else { this.Set_ContentPos( Math.max( CursorPos_min, Math.min( CursorPos_max, ( this.Selection.EndPos >= this.Selection.StartPos ? this.Selection.EndPos : this.Selection.StartPos ) ) ), true, -1 ); this.Selection_Remove(); } } var CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; var LineEndPos = ( CurLine >= this.Lines.length - 1 ? this.Internal_GetEndPos() : this.Lines[CurLine + 1].StartPos - 1 ); if ( true === this.Selection.Use && true === AddToSelect ) { this.Selection.EndPos = LineEndPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } } else if ( AddToSelect ) { this.Selection.StartPos = this.CurPos.ContentPos; this.Selection.Use = true; this.Selection.EndPos = LineEndPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } } else { this.Set_ContentPos( LineEndPos, true, -1 ); this.RecalculateCurPos(); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } }, Cursor_MoveStartOfLine : function(AddToSelect) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( this.CurPos.ContentPos < 0 ) return false; if ( true === this.Selection.Use ) { if ( true === AddToSelect ) this.Set_ContentPos( this.Selection.EndPos, true, -1 ); else { this.Set_ContentPos( ( this.Selection.StartPos <= this.Selection.EndPos ? this.Selection.StartPos : this.Selection.EndPos ), true, -1 ); this.Selection_Remove(); } } var CurLine = this.Internal_Get_ParaPos_By_Pos( this.CurPos.ContentPos).Line; var LineStartPos = this.Lines[CurLine].StartPos; if ( true === this.Selection.Use && true === AddToSelect ) { this.Selection.EndPos = LineStartPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } } else if ( AddToSelect ) { this.Selection.EndPos = LineStartPos; this.Selection.StartPos = this.CurPos.ContentPos; this.Selection.Use = true; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } } else { this.Set_ContentPos( LineStartPos, true, -1 ); this.RecalculateCurPos(); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } }, Cursor_MoveToStartPos : function() { this.Selection.Use = false; this.Set_ContentPos( this.Internal_GetStartPos(), true, -1 ); }, Cursor_MoveToEndPos : function() { this.Selection.Use = false; this.Set_ContentPos( this.Internal_GetEndPos(), true, -1 ); }, Cursor_MoveUp_To_LastRow : function(X, Y, AddToSelect) { this.CurPos.RealX = X; this.CurPos.RealY = Y; // Перемещаем курсор в последнюю строку, с позицией, самой близкой по X this.Cursor_MoveAt( X, this.Lines.length - 1, true, true, this.PageNum ); if ( true === AddToSelect ) { if ( false === this.Selection.Use ) { this.Selection.Use = true; this.Selection.StartPos = this.Content.length - 1; } this.Selection.EndPos = this.CurPos.ContentPos; } }, Cursor_MoveDown_To_FirstRow : function(X, Y, AddToSelect) { this.CurPos.RealX = X; this.CurPos.RealY = Y; // Перемещаем курсор в последнюю строку, с позицией, самой близкой по X this.Cursor_MoveAt( X, 0, true, true, this.PageNum ); if ( true === AddToSelect ) { if ( false === this.Selection.Use ) { this.Selection.Use = true; this.Selection.StartPos = this.Internal_GetStartPos(); } this.Selection.EndPos = this.CurPos.ContentPos; } }, Cursor_MoveTo_Drawing : function(Id) { // Ставим курсор перед автофигурой с заданным Id var Pos = -1; var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type && Id === Item.Get_Id() ) Pos = Index; } if ( -1 === Pos ) return; this.Set_ContentPos( Pos, true, -1 ); this.RecalculateCurPos(); this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; }, Set_ContentPos : function(Pos, bCorrectPos, Line) { this.CurPos.ContentPos = Pos; this.CurPos.Line = ( undefined === Line ? -1 : Line ); if ( false != bCorrectPos ) this.Internal_Correct_ContentPos(); }, Internal_Correct_ContentPos : function() { // 1. Ищем ближайший справа элемент // Это делается для того, чтобы если мы находимся в конце гиперссылки выйти из нее. var Count = this.Content.length; var CurPos = this.CurPos.ContentPos; while ( CurPos < Count - 1 ) { var Item = this.Content[CurPos]; var ItemType = Item.Type; if ( para_Text === ItemType || para_Space === ItemType || para_End === ItemType || para_Tab === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType || para_NewLine === ItemType || para_HyperlinkStart === ItemType ) break; CurPos++; } // 2. Ищем ближайший слева (текcт, пробел, картинку, нумерацию и т.д.) // Смещаемся к концу ближайшего левого элемента, чтобы продолжался набор с // настройками левого ближайшего элемента. while ( CurPos > 0 ) { CurPos--; var Item = this.Content[CurPos]; var ItemType = Item.Type; if ( para_Text === ItemType || para_Space === ItemType || para_End === ItemType || para_Tab === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType || para_NewLine === ItemType ) { this.CurPos.ContentPos = CurPos + 1; return; } else if ( para_HyperlinkEnd === ItemType ) { while ( CurPos < Count - 1 && para_TextPr === this.Content[CurPos + 1].Type ) CurPos++; this.CurPos.ContentPos = CurPos + 1; return; } } // 3. Если мы попали в начало параграфа, тогда пропускаем все TextPr if ( CurPos <= 0 ) { CurPos = 0; while ( para_TextPr === this.Content[CurPos].Type || para_CollaborativeChangesEnd === this.Content[CurPos].Type || para_CollaborativeChangesStart === this.Content[CurPos].Type ) CurPos++; this.CurPos.ContentPos = CurPos; } }, Get_CurPosXY : function() { return { X : this.CurPos.RealX, Y : this.CurPos.RealY }; }, Is_SelectionUse : function() { return this.Selection.Use; }, // Функция определяет начальную позицию курсора в параграфе Internal_GetStartPos : function() { var oPos = this.Internal_FindForward( 0, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End] ); if ( true === oPos.Found ) return oPos.LetterPos; return 0; }, // Функция определяет конечную позицию в параграфе Internal_GetEndPos : function() { var Res = this.Internal_FindBackward( this.Content.length - 1, [para_End] ); if ( true === Res.Found ) return Res.LetterPos; return 0; }, Internal_MoveCursorBackward : function (AddToSelect, Word) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( true === this.Selection.Use ) { if ( true === AddToSelect ) { this.Set_ContentPos( this.Selection.EndPos, true, -1 ); } else { // В случае селекта, убираем селект и перемещаем курсор в начало селекта var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Selection_Remove(); this.Set_ContentPos( StartPos, true, -1 ); return; } } if ( true === this.Selection.Use ) // Добавляем к селекту { var oPos; if ( true != Word ) oPos = this.Internal_FindBackward( this.CurPos.ContentPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End] ); else oPos = this.Internal_FindWordStart( this.CurPos.ContentPos - 1, CursorPos_min ); if ( oPos.Found ) { this.Selection.EndPos = oPos.LetterPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return true; } return true; } else { // TODO: Надо перейти в предыдущий элемент документа return false; } } else if ( true == AddToSelect ) { var oPos; if ( true != Word ) oPos = this.Internal_FindBackward( this.CurPos.ContentPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End] ); else oPos = this.Internal_FindWordStart( this.CurPos.ContentPos - 1, CursorPos_min ); // Селекта еще нет, добавляем с текущей позиции this.Selection.StartPos = this.CurPos.ContentPos; this.Selection.Use = true; if ( oPos.Found ) { this.Selection.EndPos = oPos.LetterPos; return true; } else { this.Selection.Use = false; // TODO: Надо перейти в предыдущий элемент документа return false; } } else { var oPos; if ( true != Word ) oPos = this.Internal_FindBackward( this.CurPos.ContentPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); else oPos = this.Internal_FindWordStart( this.CurPos.ContentPos - 1, CursorPos_min ); if ( oPos.Found ) { this.Set_ContentPos( oPos.LetterPos, true, -1 ); return true; } else { // Надо перейти в предыдущий элемент документа return false; } } }, Internal_FindWordStart : function(Pos, Pos_min) { var LetterPos = Pos; if ( Pos < Pos_min || Pos >= this.Content.length ) return { Found : false }; // На первом этапе ищем первый непробельный ( и не таб ) элемент while ( true ) { var Item = this.Content[LetterPos]; var Type = Item.Type; var bSpace = false; if ( para_TextPr === Type || para_Space === Type || para_HyperlinkStart === Type || para_HyperlinkEnd === Type || para_Tab === Type || para_Empty === Type || para_CommentStart === Type || para_CommentEnd === Type || para_CollaborativeChangesEnd === Type || para_CollaborativeChangesStart === Type || ( para_Text === Type && true === Item.Is_NBSP() ) ) bSpace = true; if ( true === bSpace ) { LetterPos--; if ( LetterPos < 0 ) break; } else break; } if ( LetterPos <= Pos_min ) return { LetterPos : Pos_min, Found : true, Type : this.Content[Pos_min].Type }; // На втором этапе мы смотрим на каком элементе мы встали: если это не текст, тогда // останавливаемся здесь. В противном случае сдвигаемся назад, пока не попали на первый // не текстовый элемент. if ( para_Text != this.Content[LetterPos].Type ) return { LetterPos : LetterPos, Found : true, Type : this.Content[LetterPos].Type }; else { var bPunctuation = this.Content[LetterPos].Is_Punctuation(); var TempPos = LetterPos; while ( TempPos > Pos_min ) { TempPos--; var Item = this.Content[TempPos] var TempType = Item.Type; if ( !( true != Item.Is_RealContent() || para_TextPr === TempType || ( para_Text === TempType && true != Item.Is_NBSP() && ( ( true === bPunctuation && true === Item.Is_Punctuation() ) || ( false === bPunctuation && false === Item.Is_Punctuation() ) ) ) || para_CommentStart === TempType || para_CommentEnd === TempType || para_HyperlinkEnd === TempType || para_HyperlinkEnd === TempType ) ) break; else LetterPos = TempPos; } return { LetterPos : LetterPos, Found : true, Type : this.Content[LetterPos].Type } } return { Found : false }; }, Internal_FindWordEnd : function(Pos, Pos_max) { var LetterPos = Pos; if ( Pos > Pos_max || Pos >= this.Content.length ) return { Found : false }; var bFirst = true; var bFirstPunctuation = false; // является ли первый найденный символ знаком препинания // На первом этапе ищем первый нетекстовый ( и не таб ) элемент while ( true ) { var Item = this.Content[LetterPos]; var Type = Item.Type; var bText = false; if ( para_TextPr === Type || para_HyperlinkStart === Type || para_HyperlinkEnd === Type || para_Empty === Type || ( para_Text === Type && true != Item.Is_NBSP() && ( true === bFirst || ( bFirstPunctuation === Item.Is_Punctuation() ) ) ) || para_CommentStart === Type || para_CommentEnd === Type || para_CollaborativeChangesEnd === Type || para_CollaborativeChangesStart === Type ) bText = true; if ( true === bText ) { if ( true === bFirst && para_Text === Type ) { bFirst = false; bFirstPunctuation = Item.Is_Punctuation(); } LetterPos++; if ( LetterPos > Pos_max || LetterPos >= this.Content.length ) break; } else break; } // Первый найденный элемент не текстовый, смещаемся вперед if ( true === bFirst ) LetterPos++; if ( LetterPos > Pos_max ) return { Found : false }; // На втором этапе мы смотрим на каком элементе мы встали: если это не пробел, тогда // останавливаемся здесь. В противном случае сдвигаемся вперед, пока не попали на первый // не пробельный элемент. if ( !(para_Space === this.Content[LetterPos].Type || ( para_Text === this.Content[LetterPos].Type && true === this.Content[LetterPos].Is_NBSP() ) ) ) return { LetterPos : LetterPos, Found : true, Type : this.Content[LetterPos].Type }; else { var TempPos = LetterPos; while ( TempPos < Pos_max ) { TempPos++; var Item = this.Content[TempPos] var TempType = Item.Type; if ( !( true != Item.Is_RealContent() || para_TextPr === TempType || para_Space === this.Content[LetterPos].Type || ( para_Text === this.Content[LetterPos].Type && true === this.Content[LetterPos].Is_NBSP() ) || para_CommentStart === TempType || para_CommentEnd === TempType || para_HyperlinkEnd === TempType || para_HyperlinkEnd === TempType ) ) break; else LetterPos = TempPos; } return { LetterPos : LetterPos, Found : true, Type : this.Content[LetterPos].Type } } return { Found : false }; }, Internal_MoveCursorForward : function (AddToSelect, Word) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( true === this.Selection.Use ) { if ( true === AddToSelect ) { this.Set_ContentPos( this.Selection.EndPos, false, -1 ); } else { // В случае селекта, убираем селект и перемещаем курсор в конец селекта var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } this.Selection_Remove(); this.Set_ContentPos( Math.max( CursorPos_min, Math.min( EndPos, CursorPos_max ) ), true, -1 ); return true; } } if ( true == this.Selection.Use && true == AddToSelect ) { var oPos; if ( true != Word ) oPos = this.Internal_FindForward( this.CurPos.ContentPos + 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End, para_Empty] ); else oPos = this.Internal_FindWordEnd( this.CurPos.ContentPos, CursorPos_max + 1 ); if ( oPos.Found ) { this.Selection.EndPos = oPos.LetterPos; if ( this.Selection.StartPos == this.Selection.EndPos ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Math.max( CursorPos_min, Math.min( this.Selection.EndPos, CursorPos_max ) ), true, -1 ); this.RecalculateCurPos(); return; } return true; } else { // TODO: Надо перейти в предыдущий элемент документа return false; } } else if ( true == AddToSelect ) { var oPos; if ( true != Word ) oPos = this.Internal_FindForward( this.CurPos.ContentPos + 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End, para_Empty] ); else oPos = this.Internal_FindWordEnd( this.CurPos.ContentPos, CursorPos_max + 1 ); // Селекта еще нет, добавляем с текущей позиции this.Selection.StartPos = this.CurPos.ContentPos; this.Selection.Use = true; if ( oPos.Found ) { this.Selection.EndPos = oPos.LetterPos; return true; } else { this.Selection.Use = false; // TODO: Надо перейти в предыдущий элемент документа return false; } } else { var oPos; if ( true != Word ) { oPos = this.Internal_FindForward( this.CurPos.ContentPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( oPos.Found ) oPos.LetterPos++; } else oPos = this.Internal_FindWordEnd( this.CurPos.ContentPos, CursorPos_max ); if ( oPos.Found ) { this.Set_ContentPos( oPos.LetterPos, true, -1 ); return true; } else { // TODO: Надо перейти в следующий элемент документа return false; } } }, Internal_Clear_EmptyTextPr : function() { var Count = this.Content.length; for ( var Pos = 0; Pos < Count - 1; Pos++ ) { if ( para_TextPr === this.Content[Pos].Type && para_TextPr === this.Content[Pos + 1].Type ) { this.Internal_Content_Remove( Pos ); Pos--; Count--; } } }, Internal_AddTextPr : function(TextPr) { this.Internal_Clear_EmptyTextPr(); if ( undefined != TextPr.FontFamily ) { var FName = TextPr.FontFamily.Name; var FIndex = TextPr.FontFamily.Index; TextPr.RFonts = new CRFonts(); TextPr.RFonts.Ascii = { Name : FName, Index : FIndex }; TextPr.RFonts.EastAsia = { Name : FName, Index : FIndex }; TextPr.RFonts.HAnsi = { Name : FName, Index : FIndex }; TextPr.RFonts.CS = { Name : FName, Index : FIndex }; } if ( true === this.ApplyToAll ) { this.Internal_Content_Add( 0, new ParaTextPr( TextPr ) ); // Внутри каждого TextPr меняем те настройки, которые пришли в TextPr. Например, // у нас изменен только размер шрифта, то изменяем запись о размере шрифта. for ( var Pos = 0; Pos < this.Content.length; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) this.Content[Pos].Apply_TextPr( TextPr ); } // Выставляем настройки для символа параграфа this.TextPr.Apply_TextPr( TextPr ); return; } // найдем текущую позицию var Line = this.Content; var CurPos = this.CurPos.ContentPos; if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } // Если селект продолжается до конца параграфа, не ставим отметку в конце var LastPos = this.Internal_GetEndPos(); var bEnd = false; if ( EndPos > LastPos ) { EndPos = LastPos; bEnd = true; } // Рассчитываем шрифт, который используется после слова var TextPr_end = this.Internal_GetTextPr( EndPos ); var TextPr_start = this.Internal_GetTextPr( StartPos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( StartPos, new ParaTextPr( TextPr_start ) ); if ( false === bEnd ) this.Internal_Content_Add( EndPos + 1, new ParaTextPr( TextPr_end ) ); else { // Выставляем настройки для символа параграфа this.TextPr.Apply_TextPr( TextPr ); } // Если внутри слова были изменения текстовых настроек, тогда удаляем только те записи, которые // меняются сейчас. Например, у нас изменен только размер шрифта, то удаляем запись о размере шрифта. for ( var Pos = StartPos + 1; Pos < EndPos; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) { this.Content[Pos].Apply_TextPr( TextPr ); } } return; } // При изменении шрифта ведем себе следующим образом: // 1. Если мы в конце параграфа, тогда добавляем запись о шрифте (применимо к знаку конца параграфа) // 2. Если справа или слева стоит пробел (начало параграфа или перенос строки(командный)), тогда ставим метку со шрифтом и фокусим канву. // 3. Если мы посередине слова, тогда меняем шрифт для данного слова var oEnd = this.Internal_FindForward ( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_End, para_NewLine] ); var oStart = this.Internal_FindBackward( CurPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); var CurType = this.Content[CurPos].Type; if ( !oEnd.Found ) return; if ( para_End == oEnd.Type ) { // Вставляем запись о новых настройках перед концом параграфа, а текущую позицию выставляем на конец параграфа var Pos = oEnd.LetterPos; var TextPr_start = this.Internal_GetTextPr( Pos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_start ) ); this.Set_ContentPos( Pos + 1, false, -1 ); if ( true === this.IsEmpty() && undefined === this.Numbering_Get() ) { // Выставляем настройки для символа параграфа this.TextPr.Apply_TextPr( TextPr ); } } else if ( para_PageNum === CurType || para_Drawing === CurType || para_Tab == CurType || para_Space == CurType || para_NewLine == CurType || !oStart.Found || para_NewLine == oEnd.Type || para_Space == oEnd.Type || para_NewLine == oStart.Type || para_Space == oStart.Type || para_Tab == oEnd.Type || para_Tab == oStart.Type || para_Drawing == oEnd.Type || para_Drawing == oStart.Type || para_PageNum == oEnd.Type || para_PageNum == oStart.Type ) { var TextPr_old = this.Internal_GetTextPr( CurPos ); var TextPr_new = TextPr_old.Copy(); TextPr_new.Merge( TextPr ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_old ) ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_new ) ); this.Set_ContentPos( CurPos + 1, false, -1 ); this.RecalculateCurPos(); } else { // Мы находимся посередине слова. В начале слова ставим запись о новом шрифте, // а в конце слова старый шрифт. Кроме этого, надо удалить все записи о шрифте внутри слова. // Найдем начало слова var oWordStart = this.Internal_FindBackward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_NewLine] ); if ( !oWordStart.Found ) oWordStart = this.Internal_FindForward( 0, [para_Text] ); else oWordStart.LetterPos++; var oWordEnd = this.Internal_FindForward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_End, para_NewLine] ); if ( !oWordStart.Found || !oWordEnd.Found ) return; // Рассчитываем настройки, которые используются после слова var TextPr_end = this.Internal_GetTextPr( oWordEnd.LetterPos ); var TextPr_start = this.Internal_GetTextPr( oWordStart.LetterPos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( oWordStart.LetterPos, new ParaTextPr( TextPr_start ) ); this.Internal_Content_Add( oWordEnd.LetterPos + 1 /* из-за предыдущего Internal_Content_Add */, new ParaTextPr( TextPr_end ) ); this.Set_ContentPos( CurPos + 1, false, -1 ); // Если внутри слова были изменения текстовых настроек, тогда удаляем только те записи, которые // меняются сейчас. Например, у нас изменен только размер шрифта, то удаляем запись о размере шрифта. for ( var Pos = oWordStart.LetterPos + 1; Pos < oWordEnd.LetterPos; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) this.Content[Pos].Apply_TextPr( TextPr ); } } }, Internal_AddHyperlink : function(Hyperlink_start) { // Создаем текстовую настройку для гиперссылки var Hyperlink_end = new ParaHyperlinkEnd(); var RStyle = editor.WordControl.m_oLogicDocument.Get_Styles().Get_Default_Hyperlink(); if ( true === this.ApplyToAll ) { // TODO: Надо выяснить, нужно ли в данном случае делать гиперссылку return; } var CurPos = this.CurPos.ContentPos; if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } // Если селект продолжается до конца параграфа, не ставим отметку в конце var LastPos = this.Internal_GetEndPos(); if ( EndPos > LastPos ) EndPos = LastPos; var TextPr_end = this.Internal_GetTextPr( EndPos ); var TextPr_start = this.Internal_GetTextPr( StartPos ); TextPr_start.RStyle = RStyle; TextPr_start.Underline = undefined; TextPr_start.Color = undefined; this.Internal_Content_Add( EndPos, new ParaTextPr( TextPr_end ) ); this.Internal_Content_Add( EndPos, Hyperlink_end ); this.Internal_Content_Add( StartPos, new ParaTextPr( TextPr_start ) ); this.Internal_Content_Add( StartPos, Hyperlink_start ); // Если внутри выделения были изменения текстовых настроек, тогда удаляем только те записи, которые // меняются сейчас. Например, у нас изменен только размер шрифта, то удаляем запись о размере шрифта. for ( var Pos = StartPos + 2; Pos < EndPos + 1; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) { var Item = this.Content[Pos]; Item.Set_RStyle( RStyle ); Item.Set_Underline( undefined ); Item.Set_Color( undefined ); } } return; } return; // При изменении шрифта ведем себе следующим образом: // 1. Если мы в конце параграфа, тогда добавляем запись о шрифте (применимо к знаку конца параграфа) // 2. Если справа или слева стоит пробел (начало параграфа или перенос строки(командный)), тогда ставим метку со шрифтом и фокусим канву. // 3. Если мы посередине слова, тогда меняем шрифт для данного слова var oEnd = this.Internal_FindForward ( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_End, para_NewLine] ); var oStart = this.Internal_FindBackward( CurPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); var CurType = this.Content[CurPos].Type; if ( !oEnd.Found ) return; if ( para_End == oEnd.Type ) { // Вставляем запись о новых настройках перед концом параграфа, а текущую позицию выставляем на конец параграфа var Pos = oEnd.LetterPos; var TextPr_start = this.Internal_GetTextPr( Pos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_start ) ); this.Set_ContentPos( Pos + 1, false, -1 ); } else if ( para_PageNum === CurType || para_Drawing === CurType || para_Tab == CurType || para_Space == CurType || para_NewLine == CurType || !oStart.Found || para_NewLine == oEnd.Type || para_Space == oEnd.Type || para_NewLine == oStart.Type || para_Space == oStart.Type || para_Tab == oEnd.Type || para_Tab == oStart.Type || para_Drawing == oEnd.Type || para_Drawing == oStart.Type || para_PageNum == oEnd.Type || para_PageNum == oStart.Type ) { var TextPr_old = this.Internal_GetTextPr( CurPos ); var TextPr_new = TextPr_old.Copy(); TextPr_new.Merge( TextPr ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_old ) ); this.Internal_Content_Add( CurPos, new ParaTextPr( TextPr_new ) ); this.Set_ContentPos( CurPos + 1, false, -1 ); this.RecalculateCurPos(); } else { // Мы находимся посередине слова. В начале слова ставим запись о новом шрифте, // а в конце слова старый шрифт. Кроме этого, надо удалить все записи о шрифте внутри слова. // Найдем начало слова var oWordStart = this.Internal_FindBackward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_NewLine] ); if ( !oWordStart.Found ) oWordStart = this.Internal_FindForward( 0, [para_Text] ); else oWordStart.LetterPos++; var oWordEnd = this.Internal_FindForward( CurPos, [para_PageNum, para_Drawing, para_Tab, para_Space, para_End, para_NewLine] ); if ( !oWordStart.Found || !oWordEnd.Found ) return; // Рассчитываем настройки, которые используются после слова var TextPr_end = this.Internal_GetTextPr( oWordEnd.LetterPos ); var TextPr_start = this.Internal_GetTextPr( oWordStart.LetterPos ); TextPr_start.Merge( TextPr ); this.Internal_Content_Add( oWordStart.LetterPos, new ParaTextPr( TextPr_start ) ); this.Internal_Content_Add( oWordEnd.LetterPos + 1 /* из-за предыдущего Internal_Content_Add */, new ParaTextPr( TextPr_end ) ); this.Set_ContentPos( CurPos + 1, false, -1 ); // Если внутри слова были изменения текстовых настроек, тогда удаляем только те записи, которые // меняются сейчас. Например, у нас изменен только размер шрифта, то удаляем запись о размере шрифта. for ( var Pos = oWordStart.LetterPos + 1; Pos < oWordEnd.LetterPos; Pos++ ) { if ( this.Content[Pos].Type == para_TextPr ) this.Content[Pos].Apply_TextPr( TextPr ); } } }, Internal_GetContentPosByXY : function(X,Y, bLine, PageNum, bCheckNumbering) { if ( this.Lines.length <= 0 ) return {Pos : 0, End:false, InText : false}; // Сначала определим на какую строку мы попали var PNum = 0; if ( "number" == typeof(PageNum) ) { PNum = PageNum - this.PageNum; } else PNum = 0; if ( PNum >= this.Pages.length ) { PNum = this.Pages.length - 1; bLine = true; Y = this.Lines.length - 1; } else if ( PNum < 0 ) { PNum = 0; bLine = true; Y = 0; } var bFindY = false; var CurLine = this.Pages[PNum].FirstLine; var CurLineY = this.Pages[PNum].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; var LastLine = ( PNum >= this.Pages.length - 1 ? this.Lines.length - 1 : this.Pages[PNum + 1].FirstLine - 1 ); if ( true === bLine ) CurLine = Y; else { while ( !bFindY ) { if ( Y < CurLineY ) break; if ( CurLine >= LastLine ) break; CurLine++; CurLineY = this.Lines[CurLine].Y + this.Pages[PNum].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap; } } // Ищем позицию в строке var CurRange = 0; var CurX = this.Lines[CurLine].Ranges[CurRange].XVisible; var DiffX = 1000000;//this.XLimit; // километра для ограничения должно хватить var NumberingDiffX = 1000000;//this.XLimit; var DiffPos = -1; var bEnd = false; var bInText = false; var Result = { Pos : 0, End : false }; var StartPos = this.Lines[CurLine].StartPos; var ResultLine = -1; for ( var ItemNum = StartPos; ItemNum < this.Content.length; ItemNum++ ) { var Item = this.Content[ItemNum]; if ( undefined != Item.CurLine ) { if ( CurLine != Item.CurLine ) break; if ( CurRange != Item.CurRange ) { CurRange = Item.CurRange; CurX = this.Lines[CurLine].Ranges[CurRange].XVisible; } } var TempDx = 0; var bCheck = false; if ( ItemNum === this.Numbering.Pos ) { if ( para_Numbering === this.Numbering.Type ) { var NumberingItem = this.Numbering; var NumPr = this.Numbering_Get(); var NumJc = this.Parent.Get_Numbering().Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl].Jc; var NumX0 = CurX; var NumX1 = CurX; switch( NumJc ) { case align_Right: { NumX0 -= NumberingItem.WidthNum; break; } case align_Center: { NumX0 -= NumberingItem.WidthNum / 2; NumX1 += NumberingItem.WidthNum / 2; break; } case align_Left: default: { NumX1 += NumberingItem.WidthNum; break; } } if ( X >= NumX0 && X <= NumX1 ) NumberingDiffX = 0; } CurX += this.Numbering.WidthVisible; if ( -1 != DiffPos ) { DiffX = Math.abs( X - CurX ); DiffPos = ItemNum; } } switch( Item.Type ) { case para_Drawing: { if ( Item.DrawingType != drawing_Inline ) { bCheck = false; TempDx = 0; } else { TempDx = Item.WidthVisible; bCheck = true; } break; } case para_PageNum: case para_Text: TempDx = Item.WidthVisible; bCheck = true; break; case para_Space: TempDx = Item.WidthVisible; bCheck = true; break; case para_Tab: TempDx = Item.WidthVisible; bCheck = true; break; case para_NewLine: bCheck = true; TempDx = Item.WidthVisible; break; case para_End: bEnd = true; bCheck = true; TempDx = Item.WidthVisible; break; case para_TextPr: case para_CommentEnd: case para_CommentStart: case para_CollaborativeChangesEnd: case para_CollaborativeChangesStart: case para_HyperlinkEnd: case para_HyperlinkStart: bCheck = true; TempDx = 0; break; } if ( bCheck ) { if ( Math.abs( X - CurX ) < DiffX + 0.001 ) { DiffX = Math.abs( X - CurX ); DiffPos = ItemNum; } if ( true != bEnd && ItemNum === this.Lines[CurLine].EndPos && X > CurX + TempDx && para_NewLine != Item.Type ) { ResultLine = CurLine; DiffPos = ItemNum + 1; } // Заглушка для знака параграфа if ( bEnd ) { CurX += TempDx; if ( Math.abs( X - CurX ) < DiffX ) { Result.End = true; } break; } } if ( X >= CurX - 0.001 && X <= CurX + TempDx + 0.001 ) bInText = true; CurX += TempDx; } // По Х попали в какой-то элемент, проверяем по Y if ( true === bInText && Y >= this.Pages[PNum].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent - 0.01 && Y <= this.Pages[PNum].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent + this.Lines[CurLine].Metrics.LineGap + 0.01 ) Result.InText = true; else Result.InText = false; if ( NumberingDiffX <= DiffX ) Result.Numbering = true; else Result.Numbering = false; Result.Pos = DiffPos; Result.Line = ResultLine; return Result; }, Internal_GetXYByContentPos : function(Pos) { return this.Internal_Recalculate_CurPos(Pos, false, false, false); }, Internal_Selection_CheckHyperlink : function() { // Если у нас начало селекта находится внутри гиперссылки, а конец // нет (или наоборот), тогда выделяем всю гиперссылку. var Direction = 1; var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; Direction = -1; } var Hyperlink_start = this.Check_Hyperlink2( StartPos ); var Hyperlink_end = this.Check_Hyperlink2( EndPos ); if ( null != Hyperlink_start && Hyperlink_end != Hyperlink_start ) StartPos = this.Internal_FindBackward( StartPos, [para_HyperlinkStart]).LetterPos; if ( null != Hyperlink_end && Hyperlink_end != Hyperlink_start ) EndPos = this.Internal_FindForward( EndPos, [para_HyperlinkEnd]).LetterPos + 1; if ( Direction > 0 ) { this.Selection.StartPos = StartPos; this.Selection.EndPos = EndPos; } else { this.Selection.StartPos = EndPos; this.Selection.EndPos = StartPos; } }, Check_Hyperlink : function(X, Y, PageNum) { var Result = this.Internal_GetContentPosByXY( X, Y, false, PageNum, false); if ( -1 != Result.Pos && true === Result.InText ) { var Find = this.Internal_FindBackward( Result.Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkStart === Find.Type ) return this.Content[Find.LetterPos]; } return null; }, Check_Hyperlink2 : function(Pos, bCheckEnd, bNoSelectCheck) { if ( undefined === bNoSelectCheck ) bNoSelectCheck = false; if ( undefined === bCheckEnd ) bCheckEnd = true; // TODO : Специальная заглушка, для конца селекта. Неплохо бы переделать. if ( true === bCheckEnd && Pos > 0 ) { while ( this.Content[Pos - 1].Type === para_TextPr || this.Content[Pos - 1].Type === para_HyperlinkEnd || this.Content[Pos - 1].Type === para_CollaborativeChangesStart || this.Content[Pos - 1].Type === para_CollaborativeChangesEnd ) { Pos--; if ( Pos <= 0 ) return null; } } // TODO: специальная заглушка, для случая, когда курсор стоит перед гиперссылкой, чтобы мы определяли данную ситуацию как попадание в гиперссылку if ( true === bNoSelectCheck ) { Pos = this.Internal_Correct_HyperlinkPos(Pos); } var Find = this.Internal_FindBackward( Pos - 1, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkStart === Find.Type ) return this.Content[Find.LetterPos]; return null; }, Internal_Correct_HyperlinkPos : function(_Pos) { var Pos = _Pos; var Count = this.Content.length; while ( Pos < Count ) { var TempType = this.Content[Pos].Type; if ( para_HyperlinkStart === TempType || para_TextPr === TempType || para_CollaborativeChangesEnd === TempType || para_CollaborativeChangesStart === TempType ) Pos++; else break; } return Pos; }, Hyperlink_Add : function(HyperProps) { var Hyperlink = new ParaHyperlinkStart(); Hyperlink.Set_Value( HyperProps.Value ); if ( "undefined" != typeof(HyperProps.ToolTip) && null != HyperProps.ToolTip ) Hyperlink.Set_ToolTip( HyperProps.ToolTip ); if ( true === this.Selection.Use ) { this.Add( Hyperlink ); } else if ( null != HyperProps.Text && "" != HyperProps.Text ) // добавлять ссылку, без селекта и с пустым текстом нельзя { var TextPr_hyper = this.Internal_GetTextPr(this.CurPos.ContentPos); var Styles = editor.WordControl.m_oLogicDocument.Get_Styles(); TextPr_hyper.RStyle = Styles.Get_Default_Hyperlink(); TextPr_hyper.Color = undefined; TextPr_hyper.Underline = undefined; var TextPr_old = this.Internal_GetTextPr(this.CurPos.ContentPos); var Pos = this.CurPos.ContentPos; this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_old ) ); this.Internal_Content_Add( Pos, new ParaHyperlinkEnd() ); this.Internal_Content_Add( Pos, new ParaTextPr( TextPr_hyper ) ); this.Internal_Content_Add( Pos, Hyperlink ); for ( var NewPos = 0; NewPos < HyperProps.Text.length; NewPos++ ) { var Char = HyperProps.Text.charAt( NewPos ); if ( " " == Char ) this.Internal_Content_Add( Pos + 2 + NewPos, new ParaSpace() ); else this.Internal_Content_Add( Pos + 2 + NewPos, new ParaText(Char) ); } this.Set_ContentPos( Pos + 2, false, -1 ); // чтобы курсор встал после TextPr } }, Hyperlink_Modify : function(HyperProps) { var Hyperlink = null; var Pos = -1; if ( true === this.Selection.Use ) { var Hyper_start = this.Check_Hyperlink2( this.Selection.StartPos ); var Hyper_end = this.Check_Hyperlink2( this.Selection.EndPos ); if ( null != Hyper_start && Hyper_start === Hyper_end ) { Hyperlink = Hyper_start; Pos = this.Selection.StartPos; } } else { Hyperlink = this.Check_Hyperlink2( this.CurPos.ContentPos, false, true ); Pos = this.Internal_Correct_HyperlinkPos(this.CurPos.ContentPos); } if ( null != Hyperlink ) { if ( "undefined" != typeof( HyperProps.Value) && null != HyperProps.Value ) Hyperlink.Set_Value( HyperProps.Value ); if ( "undefined" != typeof( HyperProps.ToolTip) && null != HyperProps.ToolTip ) Hyperlink.Set_ToolTip( HyperProps.ToolTip ); if ( null != HyperProps.Text ) { var Find = this.Internal_FindBackward( Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true != Find.Found || para_HyperlinkStart != Find.Type ) return false; var Start = Find.LetterPos; var Find = this.Internal_FindForward( Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true != Find.Found || para_HyperlinkEnd != Find.Type ) return false; var End = Find.LetterPos; var TextPr = this.Internal_GetTextPr(End); TextPr.RStyle = editor.WordControl.m_oLogicDocument.Get_Styles().Get_Default_Hyperlink(); TextPr.Color = undefined; TextPr.Underline = undefined; // TODO: тут не должно быть картинок, но все-таки если будет такая ситуация, // тогда надо будет убрать записи о картинках. this.Internal_Content_Remove2( Start + 1, End - Start - 1 ); this.Internal_Content_Add( Start + 1, new ParaTextPr( TextPr ) ); for ( var NewPos = 0; NewPos < HyperProps.Text.length; NewPos++ ) { var Char = HyperProps.Text.charAt( NewPos ); if ( " " == Char ) this.Internal_Content_Add( Start + 2 + NewPos, new ParaSpace() ); else this.Internal_Content_Add( Start + 2 + NewPos, new ParaText(Char) ); } if ( true === this.Selection.Use ) { this.Selection.StartPos = Start + 1; this.Selection.EndPos = Start + 2 + HyperProps.Text.length; this.Set_ContentPos( this.Selection.EndPos ); } else this.Set_ContentPos( Start + 2, false ); // чтобы курсор встал после TextPr return true; } return false; } return false; }, Hyperlink_Remove : function() { var Pos = -1; if ( true === this.Selection.Use ) { var Hyper_start = this.Check_Hyperlink2( this.Selection.StartPos ); var Hyper_end = this.Check_Hyperlink2( this.Selection.EndPos ); if ( null != Hyper_start && Hyper_start === Hyper_end ) Pos = ( this.Selection.StartPos <= this.Selection.EndPos ? this.Selection.StartPos : this.Selection.EndPos ); } else { var Hyper_cur = this.Check_Hyperlink2( this.CurPos.ContentPos, false, true ); if ( null != Hyper_cur ) Pos = this.Internal_Correct_HyperlinkPos( this.CurPos.ContentPos ); } if ( -1 != Pos ) { var Find = this.Internal_FindForward( Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkEnd === Find.Type ) this.Internal_Content_Remove( Find.LetterPos ); var EndPos = Find.LetterPos - 2; Find = this.Internal_FindBackward( Pos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkStart === Find.Type ) this.Internal_Content_Remove( Find.LetterPos ); var StartPos = Find.LetterPos; var RStyle = editor.WordControl.m_oLogicDocument.Get_Styles().Get_Default_Hyperlink(); // TODO: когда появятся стили текста, тут надо будет переделать for ( var Index = StartPos; Index <= EndPos; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type && Item.Value.RStyle === RStyle ) { Item.Set_RStyle( undefined ); } } // Пересчитаем TextPr this.RecalcInfo.Set_Type_0( pararecalc_0_All ); this.Internal_Recalculate_0(); // Запускаем перерисовку this.ReDraw(); return true; } return false; }, Hyperlink_CanAdd : function(bCheckInHyperlink) { if ( true === bCheckInHyperlink ) { if ( true === this.Selection.Use ) { // Если у нас в выделение попадает начало или конец гиперссылки, или конец параграфа, или // у нас все выделение находится внутри гиперссылки, тогда мы не можем добавить новую. Во // всех остальных случаях разрешаем добавить. var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( EndPos < StartPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } // Проверяем не находимся ли мы внутри гиперссылки var Find = this.Internal_FindBackward( StartPos, [para_HyperlinkStart, para_HyperlinkEnd] ); if ( true === Find.Found && para_HyperlinkStart === Find.Type ) return false; for ( var Pos = StartPos; Pos < EndPos; Pos++ ) { var Item = this.Content[Pos]; switch ( Item.Type ) { case para_HyperlinkStart: case para_HyperlinkEnd: case para_End: return false; } } return true; } else { // Внутри гиперссылки мы не можем задать ниперссылку var Hyper_cur = this.Check_Hyperlink2( this.CurPos.ContentPos ); if ( null != Hyper_cur ) return false; else return true; } } else { if ( true === this.Selection.Use ) { // Если у нас в выделение попадает несколько гиперссылок или конец параграфа, тогда // возвращаем false, во всех остальных случаях true var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( EndPos < StartPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } var bHyper = false; for ( var Pos = StartPos; Pos < EndPos; Pos++ ) { var Item = this.Content[Pos]; switch ( Item.Type ) { case para_HyperlinkStart: { if ( true === bHyper ) return false; bHyper = true; break; } case para_HyperlinkEnd: { bHyper = true; break; } case para_End: return false; } } return true; } else { return true; } } }, Hyperlink_Check : function(bCheckEnd) { if ( true === this.Selection.Use ) { var Hyper_start = this.Check_Hyperlink2( this.Selection.StartPos ); var Hyper_end = this.Check_Hyperlink2( this.Selection.EndPos ); if ( Hyper_start === Hyper_end && null != Hyper_start ) return Hyper_start } else { var Hyper_cur = this.Check_Hyperlink2( this.CurPos.ContentPos, bCheckEnd ); if ( null != Hyper_cur ) return Hyper_cur; } return null; }, Cursor_MoveAt : function(X,Y, bLine, bDontChangeRealPos, PageNum) { var TempPos = this.Internal_GetContentPosByXY( X, Y, bLine, PageNum ); var Pos = TempPos.Pos; var Line = TempPos.Line; if ( -1 != Pos ) { this.Set_ContentPos( Pos, true, Line ); } this.Internal_Recalculate_CurPos(Pos, false, false, false ); if ( bDontChangeRealPos != true ) { this.CurPos.RealX = this.CurPos.X; this.CurPos.RealY = this.CurPos.Y; } if ( true != bLine ) { this.CurPos.RealX = X; this.CurPos.RealY = Y; } }, Selection_SetStart : function(X,Y,PageNum, bTableBorder) { var Pos = this.Internal_GetContentPosByXY( X, Y, false, PageNum ); if ( -1 != Pos.Pos ) { if ( true === Pos.End ) this.Selection.StartPos = Pos.Pos + 1; else this.Selection.StartPos = Pos.Pos; this.Set_ContentPos( Pos.Pos, true , Pos.Line ); this.Selection.Use = true; this.Selection.Start = true; this.Selection.Flag = selectionflag_Common; } }, // Данная функция может использоваться как при движении, так и при окончательном выставлении селекта. // Если bEnd = true, тогда это конец селекта. Selection_SetEnd : function(X,Y,PageNum, MouseEvent, bTableBorder) { var PagesCount = this.Pages.length; if ( false === editor.isViewMode && null === this.Parent.Is_HdrFtr(true) && null == this.Get_DocumentNext() && PageNum - this.PageNum >= PagesCount - 1 && Y > this.Pages[PagesCount - 1].Bounds.Bottom && MouseEvent.ClickCount >= 2 ) return this.Parent.Extend_ToPos( X, Y ); this.CurPos.RealX = X; this.CurPos.RealY = Y; var Temp = this.Internal_GetContentPosByXY( X, Y, false, PageNum ); var Pos = Temp.Pos; if ( -1 != Pos ) { this.Set_ContentPos( Pos, true, Temp.Line ); if ( true === Temp.End ) { if ( PageNum - this.PageNum >= PagesCount - 1 && X > this.Lines[this.Lines.length - 1].Ranges[this.Lines[this.Lines.length - 1].Ranges.length - 1].W && MouseEvent.ClickCount >= 2 && Y <= this.Pages[PagesCount - 1].Bounds.Bottom ) { if ( false === editor.isViewMode && false === editor.WordControl.m_oLogicDocument.Document_Is_SelectionLocked(changestype_None, { Type : changestype_2_Element_and_Type, Element : this, CheckType : changestype_Paragraph_Content } ) ) { History.Create_NewPoint(); History.Set_Additional_ExtendDocumentToPos(); this.Extend_ToPos( X ); this.Cursor_MoveToEndPos(); this.Document_SetThisElementCurrent(); editor.WordControl.m_oLogicDocument.Recalculate(); return; } } this.Selection.EndPos = Pos + 1; } else this.Selection.EndPos = Pos; if ( this.Selection.EndPos == this.Selection.StartPos && g_mouse_event_type_up === MouseEvent.Type ) { var NumPr = this.Numbering_Get(); if ( true === Temp.Numbering && undefined != NumPr ) { // Ставим именно 0, а не this.Internal_GetStartPos(), чтобы при нажатии на клавишу "направо" // мы оказывались в начале параграфа. this.Set_ContentPos( 0, true, -1 ); this.Parent.Document_SelectNumbering( NumPr ); } else { var Temp2 = MouseEvent.ClickCount % 2; if ( 1 >= MouseEvent.ClickCount ) { this.Selection_Remove(); this.Selection.Use = false; this.Set_ContentPos( Pos, true, Temp.Line ); this.RecalculateCurPos(); return; } else if ( 0 == Temp2 ) { var oStart; if ( this.Content[Pos].Type == para_Space ) { oStart = this.Internal_FindBackward( Pos, [ para_Text, para_NewLine ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); else if ( oStart.Type == para_NewLine ) { oStart.LetterPos++; // смещаемся на начало следующей строки } else { oStart = this.Internal_FindBackward( oStart.LetterPos, [ para_Tab, para_Space, para_NewLine ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); else { oStart = this.Internal_FindForward( oStart.LetterPos, [ para_Text ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); } } } else { oStart = this.Internal_FindBackward( Pos, [ para_Tab, para_Space, para_NewLine ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); else { oStart = this.Internal_FindForward( oStart.LetterPos, [ para_Text, para_NewLine ] ); if ( !oStart.Found ) oStart.LetterPos = this.Internal_GetStartPos(); } } var oEnd = this.Internal_FindForward( Pos, [ para_Tab, para_Space, para_NewLine ] ); if ( !oEnd.Found ) oEnd.LetterPos = this.Content.length - 1; else if ( oEnd.Type != para_NewLine ) // при переносе строки селектим все до переноса строки { oEnd = this.Internal_FindForward( oEnd.LetterPos, [ para_Text ] ); if ( !oEnd.Found ) oEnd.LetterPos = this.Content.length - 1; } this.Selection.StartPos = oStart.LetterPos; this.Selection.EndPos = oEnd.LetterPos; this.Selection.Use = true; } else // ( 1 == Temp2 % 3 ) { // Селектим параграф целиком this.Selection.StartPos = this.Internal_GetStartPos(); this.Selection.EndPos = this.Content.length - 1; this.Selection.Use = true; } } } } if ( -1 === this.Selection.EndPos ) { //Temp = this.Internal_GetContentPosByXY( X, Y, false, PageNum ); return; } }, Selection_Stop : function(X,Y,PageNum, MouseEvent) { this.Selection.Start = false; }, Selection_Remove : function() { this.Selection.Use = false; this.Selection.Flag = selectionflag_Common; this.Selection_Clear(); }, Selection_Clear : function() { }, Selection_Draw_Page : function(Page_abs) { if ( true != this.Selection.Use ) return; var CurPage = Page_abs - this.Get_StartPage_Absolute(); if ( CurPage < 0 || CurPage >= this.Pages.length ) return; if ( 0 === CurPage && this.Pages[0].EndLine < 0 ) return; switch ( this.Selection.Flag ) { case selectionflag_Common: { // Делаем подсветку var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } var _StartLine = this.Pages[CurPage].StartLine; var _EndLine = this.Pages[CurPage].EndLine; if ( StartPos > this.Lines[_EndLine].EndPos + 1 || EndPos < this.Lines[_StartLine].StartPos ) return; else { StartPos = Math.max( StartPos, this.Lines[_StartLine].StartPos ); EndPos = Math.min( EndPos, ( _EndLine != this.Lines.length - 1 ? this.Lines[_EndLine].EndPos + 1 : this.Content.length - 1 ) ); } // Найдем линию, с которой начинается селект var StartParaPos = this.Internal_Get_ParaPos_By_Pos( StartPos ); var CurLine = StartParaPos.Line; var CurRange = StartParaPos.Range; var PNum = StartParaPos.Page; // Найдем начальный сдвиг в данном отрезке var StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; var Pos, Item; if ( this.Numbering.Pos >= this.Lines[CurLine].Ranges[CurRange].StartPos ) StartX += this.Numbering.WidthVisible; for ( Pos = this.Lines[CurLine].Ranges[CurRange].StartPos; Pos <= StartPos - 1; Pos++ ) { Item = this.Content[Pos]; if ( undefined != Item.WidthVisible && ( para_Drawing != Item.Type || drawing_Inline === Item.DrawingType ) ) StartX += Item.WidthVisible; } if ( this.Pages[PNum].StartLine > CurLine ) { CurLine = this.Pages[PNum].StartLine; CurRange = 0; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; StartPos = this.Lines[this.Pages[PNum].StartLine].StartPos; } var StartY = this.Pages[PNum].Y + this.Lines[CurLine].Top; var H = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; var W = 0; for ( Pos = StartPos; Pos < EndPos; Pos++ ) { Item = this.Content[Pos]; if ( undefined != Item.CurPage ) { if ( CurLine < Item.CurLine ) { this.DrawingDocument.AddPageSelection(Page_abs, StartX, StartY, W, H); CurLine = Item.CurLine; CurRange = Item.CurRange; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; StartY = this.Pages[PNum].Y + this.Lines[CurLine].Top; H = this.Lines[CurLine].Bottom - this.Lines[CurLine].Top; W = 0; } else if ( CurRange < Item.CurRange ) { this.DrawingDocument.AddPageSelection(Page_abs, StartX, StartY, W, H); CurRange = Item.CurRange; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; W = 0; } } if ( undefined != Item.WidthVisible ) { if ( para_Drawing != Item.Type || drawing_Inline === Item.DrawingType ) W += Item.WidthVisible; else Item.Draw_Selection(); } if ( Pos == EndPos - 1 ) { this.DrawingDocument.AddPageSelection(Page_abs, StartX, StartY, W, H); } } break; } case selectionflag_Numbering: { var ParaNum = this.Numbering; var NumberingPos = this.Numbering.Pos; if ( -1 === NumberingPos ) break; var ParaNumPos = this.Internal_Get_ParaPos_By_Pos(NumberingPos); if ( ParaNumPos.Page != CurPage ) break; var CurRange = ParaNumPos.Range; var CurLine = ParaNumPos.Line; var NumPr = this.Numbering_Get(); var SelectX = this.Lines[CurLine].Ranges[CurRange].XVisible; var SelectW = ParaNum.WidthVisible; var NumJc = this.Parent.Get_Numbering().Get_AbstractNum( NumPr.NumId ).Lvl[NumPr.Lvl].Jc; switch ( NumJc ) { case align_Center: SelectX = this.Lines[CurLine].Ranges[CurRange].XVisible - ParaNum.WidthNum / 2; SelectW = ParaNum.WidthVisible + ParaNum.WidthNum / 2; break; case align_Right: SelectX = this.Lines[CurLine].Ranges[CurRange].XVisible - ParaNum.WidthNum; SelectW = ParaNum.WidthVisible + ParaNum.WidthNum; break; case align_Left: default: SelectX = this.Lines[CurLine].Ranges[CurRange].XVisible; SelectW = ParaNum.WidthVisible; break; } this.DrawingDocument.AddPageSelection(Page_abs, SelectX, this.Lines[CurLine].Top + this.Pages[CurPage].Y, SelectW, this.Lines[CurLine].Bottom - this.Lines[CurLine].Top); break; } } }, Selection_Check : function(X, Y, Page_Abs) { var PageIndex = Page_Abs - this.Get_StartPage_Absolute(); if ( PageIndex < 0 || PageIndex >= this.Pages.length || true != this.Selection.Use ) return false; var Start = this.Selection.StartPos; var End = this.Selection.EndPos; if ( Start > End ) { Start = this.Selection.EndPos; End = this.Selection.StartPos; } var ContentPos = this.Internal_GetContentPosByXY( X, Y, false, PageIndex + this.PageNum, false ); if ( -1 != ContentPos.Pos && Start <= ContentPos.Pos && End >= ContentPos.Pos ) return true; return false; }, Selection_CalculateTextPr : function() { if ( true === this.Selection.Use || true === this.ApplyToAll ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( true === this.ApplyToAll ) { StartPos = 0; EndPos = this.Content.length - 1; } if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( EndPos >= this.Content.length ) EndPos = this.Content.length - 1; if ( StartPos < 0 ) StartPos = 0; if ( StartPos == EndPos ) return this.Internal_CalculateTextPr( StartPos ); while ( this.Content[StartPos].Type == para_TextPr ) StartPos++; var oEnd = this.Internal_FindBackward( EndPos - 1, [ para_Text, para_Space ] ); if ( oEnd.Found ) EndPos = oEnd.LetterPos; else { while ( this.Content[EndPos].Type == para_TextPr ) EndPos--; } // Рассчитаем стиль в начале селекта var TextPr_start = this.Internal_CalculateTextPr( StartPos ); var TextPr_vis = TextPr_start; for ( var Pos = StartPos + 1; Pos < EndPos; Pos++ ) { var Item = this.Content[Pos]; if ( para_TextPr == Item.Type && Pos < this.Content.length - 1 && para_TextPr != this.Content[Pos + 1].Type ) { // Рассчитываем настройки в данной позиции var TextPr_cur = this.Internal_CalculateTextPr( Pos ); TextPr_vis = TextPr_vis.Compare( TextPr_cur ); } } return TextPr_vis; } else return new CTextPr(); }, Selection_SelectNumbering : function() { if ( undefined != this.Numbering_Get() ) { this.Selection.Use = true; this.Selection.Flag = selectionflag_Numbering; } }, Select_All : function() { this.Selection.Use = true; this.Selection.StartPos = this.Internal_GetStartPos(); this.Selection.EndPos = this.Content.length - 1; }, // Возвращаем выделенный текст Get_SelectedText : function(bClearText) { if ( true === this.ApplyToAll ) { var Str = ""; var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; switch ( Item.Type ) { case para_Drawing: case para_End: case para_Numbering: case para_PresentationNumbering: case para_PageNum: { if ( true === bClearText ) return null; break; } case para_Text : Str += Item.Value; break; case para_Space: case para_Tab : Str += " "; break; } } return Str; } if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( EndPos < StartPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } var Str = ""; for ( var Pos = StartPos; Pos < EndPos; Pos++ ) { var Item = this.Content[Pos]; switch ( Item.Type ) { case para_Drawing: case para_End: case para_Numbering: case para_PresentationNumbering: case para_PageNum: { if ( true === bClearText ) return null; break; } case para_Text : Str += Item.Value; break; case para_Space: case para_Tab : Str += " "; break; } } return Str; } return ""; }, Get_SelectedElementsInfo : function(Info) { Info.Set_Paragraph( this ); }, // Проверяем пустой ли параграф IsEmpty : function() { var Pos = this.Internal_FindForward( 0, [para_Tab, para_Drawing, para_PageNum, para_Text, para_Space, para_NewLine] ); return ( Pos.Found === true ? false : true ); }, // Проверяем, попали ли мы в текст Is_InText : function(X, Y, PageNum_Abs) { var PNum = PageNum_Abs - this.Get_StartPage_Absolute(); if ( PNum < 0 || PNum >= this.Pages.length ) return null; var Result = this.Internal_GetContentPosByXY( X, Y, false, PNum + this.PageNum, false); if ( true === Result.InText ) return this; return null; }, Is_UseInDocument : function() { if ( null != this.Parent ) return this.Parent.Is_UseInDocument(this.Get_Id()); return false; }, // Проверяем пустой ли селект Selection_IsEmpty : function(bCheckHidden) { if ( undefined === bCheckHidden ) bCheckHidden = true; // TODO: при добавлении новых элементов в параграф, добавить их сюда if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } var CheckArray = [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine]; if ( true === bCheckHidden ) CheckArray.push( para_End ); var Pos = this.Internal_FindForward( StartPos, CheckArray ); if ( true != Pos.Found ) return true; if ( Pos.LetterPos >= EndPos ) return true; return false; } return true; }, //----------------------------------------------------------------------------------- // Функции для работы с нумерацией параграфов в документах //----------------------------------------------------------------------------------- // Добавляем нумерацию к данному параграфу Numbering_Add : function(NumId, Lvl) { var ParaPr = this.Get_CompiledPr2(false).ParaPr; var NumPr_old = this.Numbering_Get(); this.Numbering_Remove(); var SelectionUse = this.Is_SelectionUse(); var SelectedOneElement = this.Parent.Selection_Is_OneElement(); // Рассчитаем количество табов, идущих в начале параграфа var Count = this.Content.length; var TabsCount = 0; var TabsPos = new Array(); for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; var ItemType = Item.Type; if ( para_Tab === ItemType ) { TabsCount++; TabsPos.push( Pos ); } else if ( para_Text === ItemType || para_Space === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType ) break; } // Рассчитаем левую границу и сдвиг первой строки с учетом начальных табов var X = ParaPr.Ind.Left + ParaPr.Ind.FirstLine; var LeftX = X; if ( TabsCount > 0 && ParaPr.Ind.FirstLine < 0 ) { X = ParaPr.Ind.Left; LeftX = X; TabsCount--; } var ParaTabsCount = ParaPr.Tabs.Get_Count(); while ( TabsCount ) { // Ищем ближайший таб var TabFound = false; for ( var TabIndex = 0; TabIndex < ParaTabsCount; TabIndex++ ) { var Tab = ParaPr.Tabs.Get(TabIndex); if ( Tab.Pos > X ) { X = Tab.Pos; TabFound = true; break; } } // Ищем по дефолтовому сдвигу if ( false === TabFound ) { var NewX = 0; while ( X >= NewX ) NewX += Default_Tab_Stop; X = NewX; } TabsCount--; } var Numbering = this.Parent.Get_Numbering(); var AbstractNum = Numbering.Get_AbstractNum(NumId); // Если у параграфа не было никакой нумерации изначально if ( undefined === NumPr_old ) { if ( true === SelectedOneElement || false === SelectionUse ) { // Проверим сначала предыдущий элемент, если у него точно такая же нумерация, тогда копируем его сдвиги var Prev = this.Get_DocumentPrev(); var PrevNumbering = ( null != Prev ? (type_Paragraph === Prev.GetType() ? Prev.Numbering_Get() : undefined) : undefined ); if ( undefined != PrevNumbering && NumId === PrevNumbering.NumId && Lvl === PrevNumbering.Lvl ) { var NewFirstLine = Prev.Pr.Ind.FirstLine; var NewLeft = Prev.Pr.Ind.Left; History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : NewFirstLine } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : NewLeft } ); // При добавлении списка в параграф, удаляем все собственные сдвиги this.Pr.Ind.FirstLine = NewFirstLine; this.Pr.Ind.Left = NewLeft; } else { // Выставляем заданную нумерацию и сдвиги Ind.Left = X + NumPr.ParaPr.Ind.Left var NumLvl = AbstractNum.Lvl[Lvl]; var NumParaPr = NumLvl.ParaPr; if ( undefined != NumParaPr.Ind && undefined != NumParaPr.Ind.Left ) { AbstractNum.Change_LeftInd( X + NumParaPr.Ind.Left ); History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : undefined } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : undefined } ); // При добавлении списка в параграф, удаляем все собственные сдвиги this.Pr.Ind.FirstLine = undefined; this.Pr.Ind.Left = undefined; } } this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, Lvl ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr_old, New : this.Pr.NumPr } ); } else { // Если выделено несколько параграфов, тогда уже по сдвигу X определяем уровень данной нумерации var LvlFound = -1; var LvlsCount = AbstractNum.Lvl.length; for ( var LvlIndex = 0; LvlIndex < LvlsCount; LvlIndex++ ) { var NumLvl = AbstractNum.Lvl[LvlIndex]; var NumParaPr = NumLvl.ParaPr; if ( undefined != NumParaPr.Ind && undefined != NumParaPr.Ind.Left && X <= NumParaPr.Ind.Left ) { LvlFound = LvlIndex; break; } } if ( -1 === LvlFound ) LvlFound = LvlsCount - 1; if ( undefined != this.Pr.Ind && undefined != NumParaPr.Ind && undefined != NumParaPr.Ind.Left ) { History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : undefined } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : undefined } ); // При добавлении списка в параграф, удаляем все собственные сдвиги this.Pr.Ind.FirstLine = undefined; this.Pr.Ind.Left = undefined; } this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, LvlFound ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr_old, New : this.Pr.NumPr } ); } // Удалим все табы идущие в начале параграфа TabsCount = TabsPos.length; while ( TabsCount ) { var Pos = TabsPos[TabsCount - 1]; this.Internal_Content_Remove( Pos ); TabsCount--; } } else { // просто меняем список, так чтобы он не двигался this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, Lvl ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr_old, New : this.Pr.NumPr } ); var Left = ParaPr.Ind.Left; var FirstLine = ParaPr.Ind.FirstLine; History.Add( this, { Type : historyitem_Paragraph_Ind_First, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ), New : Left } ); History.Add( this, { Type : historyitem_Paragraph_Ind_Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ), New : FirstLine } ); this.Pr.Ind.FirstLine = FirstLine; this.Pr.Ind.Left = Left; } // Если у параграфа выставлен стиль, тогда не меняем его, если нет, тогда выставляем стандартный // стиль для параграфа с нумерацией. if ( undefined === this.Style_Get() ) { this.Style_Add( this.Parent.Get_Styles().Get_Default_ParaList() ); } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Добавляем нумерацию к данному параграфу, не делая никаких дополнительных действий Numbering_Set : function(NumId, Lvl) { var NumPr_old = this.Pr.NumPr; this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, Lvl ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr_old, New : this.Pr.NumPr } ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Изменяем уровень нумерации Numbering_IndDec_Level : function(bIncrease) { var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { var NewLvl; if ( true === bIncrease ) NewLvl = Math.min( 8, NumPr.Lvl + 1 ); else NewLvl = Math.max( 0, NumPr.Lvl - 1 ); this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumPr.NumId, NewLvl ); History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : NumPr, New : this.Pr.NumPr } ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, // Добавление нумерации в параграф при открытии и копировании Numbering_Add_Open : function(NumId, Lvl) { this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Set( NumId, Lvl ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Numbering_Get : function() { var NumPr = this.Get_CompiledPr2(false).ParaPr.NumPr; if ( undefined != NumPr && 0 != NumPr.NumId ) return NumPr.Copy(); return undefined; }, // Удаляем нумерацию Numbering_Remove : function() { // Если у нас была задана нумерации в стиле, тогда чтобы ее отменить(не удаляя нумерацию в стиле) // мы проставляем NumPr с NumId undefined var OldNumPr = this.Numbering_Get(); var NewNumPr = undefined; if ( undefined != this.CompiledPr.Pr.ParaPr.StyleNumPr ) { NewNumPr = new CNumPr(); NewNumPr.Set( 0, 0 ); } History.Add( this, { Type : historyitem_Paragraph_Numbering, Old : undefined != this.Pr.NumPr ? this.Pr.NumPr : undefined, New : NewNumPr } ); this.Pr.NumPr = NewNumPr; if ( undefined != this.Pr.Ind && undefined != OldNumPr ) { // При удалении нумерации из параграфа, если отступ первой строки > 0, тогда // увеличиваем левый отступ параграфа, а первую сторку делаем 0, а если отступ // первой строки < 0, тогда просто делаем оступ первой строки 0. if ( undefined === this.Pr.Ind.FirstLine || Math.abs( this.Pr.Ind.FirstLine ) < 0.001 ) { if ( undefined != OldNumPr && undefined != OldNumPr.NumId ) { var Lvl = this.Parent.Get_Numbering().Get_AbstractNum(OldNumPr.NumId).Lvl[OldNumPr.Lvl]; if ( undefined != Lvl && undefined != Lvl.ParaPr.Ind && undefined != Lvl.ParaPr.Ind.Left ) { var CurParaPr = this.Get_CompiledPr2(false).ParaPr; var Left = CurParaPr.Ind.Left + CurParaPr.Ind.FirstLine; History.Add( this, { Type : historyitem_Paragraph_Ind_Left, New : Left, Old : this.Pr.Ind.Left } ); History.Add( this, { Type : historyitem_Paragraph_Ind_First, New : 0, Old : this.Pr.Ind.FirstLine } ); this.Pr.Ind.Left = Left; this.Pr.Ind.FirstLine = 0; } } } else if ( this.Pr.Ind.FirstLine < 0 ) { History.Add( this, { Type : historyitem_Paragraph_Ind_First, New : 0, Old : this.Pr.Ind.FirstLine } ); this.Pr.Ind.FirstLine = 0; } else if ( undefined != this.Pr.Ind.Left && this.Pr.Ind.FirstLine > 0 ) { History.Add( this, { Type : historyitem_Paragraph_Ind_Left, New : this.Pr.Ind.Left + this.Pr.Ind.FirstLine, Old : this.Pr.Ind.Left } ); History.Add( this, { Type : historyitem_Paragraph_Ind_First, New : 0, Old : this.Pr.Ind.FirstLine } ); this.Pr.Ind.Left += this.Pr.Ind.FirstLine; this.Pr.Ind.FirstLine = 0; } } // При удалении проверяем стиль. Если данный стиль является стилем по умолчанию // для параграфов с нумерацией, тогда удаляем запись и о стиле. var StyleId = this.Style_Get(); var NumStyleId = this.Parent.Get_Styles().Get_Default_ParaList(); if ( StyleId === NumStyleId ) this.Style_Remove(); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Используется ли заданная нумерация в параграфе Numbering_IsUse: function(NumId, Lvl) { var bLvl = (undefined === Lvl ? false : true); var NumPr = this.Numbering_Get(); if ( undefined != NumPr && NumId === NumPr.NumId && ( false === bLvl || Lvl === NumPr.Lvl ) ) return true; return false; }, //----------------------------------------------------------------------------------- // Функции для работы с нумерацией параграфов в презентациях //----------------------------------------------------------------------------------- // Добавляем нумерацию к данному параграфу Add_PresentationNumbering : function(_Bullet) { var Bullet = _Bullet.Copy(); History.Add( this, { Type : historyitem_Paragraph_PresentationPr_Bullet, New : Bullet, Old : this.PresentationPr.Bullet } ); var OldType = this.PresentationPr.Bullet.Get_Type(); var NewType = Bullet.Get_Type(); this.PresentationPr.Bullet = Bullet; if ( OldType != NewType ) { var ParaPr = this.Get_CompiledPr2(false).ParaPr; var LeftInd = Math.min( ParaPr.Ind.Left, ParaPr.Ind.Left + ParaPr.Ind.FirstLine ); if ( numbering_presentationnumfrmt_None === NewType ) { this.Set_Ind( { FirstLine : 0, Left : LeftInd } ); } else if ( numbering_presentationnumfrmt_RomanLcPeriod === NewType || numbering_presentationnumfrmt_RomanUcPeriod === NewType ) { this.Set_Ind( { Left : LeftInd + 15.9, FirstLine : -15.9 } ); } else { this.Set_Ind( { Left : LeftInd + 14.3, FirstLine : -14.3 } ); } } }, Get_PresentationNumbering : function() { return this.PresentationPr.Bullet; }, // Удаляем нумерацию Remove_PresentationNumbering : function() { this.Add_PresentationNumbering( new CPresentationBullet() ); }, Set_PresentationLevel : function(Level) { if ( this.PresentationPr.Level != Level ) { History.Add( this, { Type : historyitem_Paragraph_PresentationPr_Level, Old : this.PresentationPr.Level, New : Level } ); this.PresentationPr.Level = Level; } }, //----------------------------------------------------------------------------------- // Формируем конечные свойства параграфа на основе стиля, возможной нумерации и прямых настроек. // Также учитываем настройки предыдущего и последующего параграфов. Get_CompiledPr : function() { var Pr = this.Get_CompiledPr2(); // При формировании конечных настроек параграфа, нужно учитывать предыдущий и последующий // параграфы. Например, для формирования интервала между параграфами. // max(Prev.After, Cur.Before) - реальное значение расстояния между параграфами. // Поэтому Prev.After = Prev.After (значение не меняем), а вот Cur.Before = max(Prev.After, Cur.Before) - Prev.After var StyleId = this.Style_Get(); var PrevEl = this.Get_DocumentPrev(); var NextEl = this.Get_DocumentNext(); var NumPr = this.Numbering_Get(); if ( null != PrevEl && type_Paragraph === PrevEl.GetType() ) { var PrevStyle = PrevEl.Style_Get(); var Prev_Pr = PrevEl.Get_CompiledPr2(false).ParaPr; var Prev_After = Prev_Pr.Spacing.After; var Prev_AfterAuto = Prev_Pr.Spacing.AfterAutoSpacing; var Cur_Before = Pr.ParaPr.Spacing.Before; var Cur_BeforeAuto = Pr.ParaPr.Spacing.BeforeAutoSpacing; var Prev_NumPr = PrevEl.Numbering_Get(); if ( PrevStyle === StyleId && true === Pr.ParaPr.ContextualSpacing ) { Pr.ParaPr.Spacing.Before = 0; } else { if ( true === Cur_BeforeAuto && PrevStyle === StyleId && undefined != Prev_NumPr && undefined != NumPr && Prev_NumPr.NumId === NumPr.NumId ) Pr.ParaPr.Spacing.Before = 0; else { Cur_Before = this.Internal_CalculateAutoSpacing( Cur_Before, Cur_BeforeAuto, this ); Prev_After = this.Internal_CalculateAutoSpacing( Prev_After, Prev_AfterAuto, this ); if ( true === Prev_Pr.ContextualSpacing && PrevStyle === StyleId ) Prev_After = 0; Pr.ParaPr.Spacing.Before = Math.max( Prev_After, Cur_Before ) - Prev_After; } } if ( false === this.Internal_Is_NullBorders(Pr.ParaPr.Brd) && true === this.Internal_CompareBrd( Prev_Pr, Pr.ParaPr ) ) Pr.ParaPr.Brd.First = false; else Pr.ParaPr.Brd.First = true; } else if ( null === PrevEl ) { if ( true === Pr.ParaPr.Spacing.BeforeAutoSpacing ) { Pr.ParaPr.Spacing.Before = 0; } } else if ( type_Table === PrevEl.GetType() ) { if ( true === Pr.ParaPr.Spacing.BeforeAutoSpacing ) { Pr.ParaPr.Spacing.Before = 14 * g_dKoef_pt_to_mm; } } if ( null != NextEl ) { if ( type_Paragraph === NextEl.GetType() ) { var NextStyle = NextEl.Style_Get(); var Next_Pr = NextEl.Get_CompiledPr2(false).ParaPr; var Next_Before = Next_Pr.Spacing.Before; var Next_BeforeAuto = Next_Pr.Spacing.BeforeAutoSpacing; var Cur_After = Pr.ParaPr.Spacing.After; var Cur_AfterAuto = Pr.ParaPr.Spacing.AfterAutoSpacing; var Next_NumPr = NextEl.Numbering_Get(); if ( NextStyle === StyleId && true === Pr.ParaPr.ContextualSpacing ) { Pr.ParaPr.Spacing.After = 0; } else { if ( true === Cur_AfterAuto && NextStyle === StyleId && undefined != Next_NumPr && undefined != NumPr && Next_NumPr.NumId === NumPr.NumId ) Pr.ParaPr.Spacing.After = 0; else { Pr.ParaPr.Spacing.After = this.Internal_CalculateAutoSpacing( Cur_After, Cur_AfterAuto, this ); } } if ( false === this.Internal_Is_NullBorders(Pr.ParaPr.Brd) && true === this.Internal_CompareBrd( Next_Pr, Pr.ParaPr ) ) Pr.ParaPr.Brd.Last = false; else Pr.ParaPr.Brd.Last = true; } else if ( type_Table === NextEl.GetType() ) { var TableFirstParagraph = NextEl.Get_FirstParagraph(); if ( null != TableFirstParagraph && undefined != TableFirstParagraph ) { var NextStyle = TableFirstParagraph.Style_Get(); var Next_Before = TableFirstParagraph.Get_CompiledPr2(false).ParaPr.Spacing.Before; var Next_BeforeAuto = TableFirstParagraph.Get_CompiledPr2(false).ParaPr.Spacing.BeforeAutoSpacing; var Cur_After = Pr.ParaPr.Spacing.After; var Cur_AfterAuto = Pr.ParaPr.Spacing.AfterAutoSpacing; if ( NextStyle === StyleId && true === Pr.ParaPr.ContextualSpacing ) { Cur_After = this.Internal_CalculateAutoSpacing( Cur_After, Cur_AfterAuto, this ); Next_Before = this.Internal_CalculateAutoSpacing( Next_Before, Next_BeforeAuto, this ); Pr.ParaPr.Spacing.After = Math.max( Next_Before, Cur_After ) - Cur_After; } else { Pr.ParaPr.Spacing.After = this.Internal_CalculateAutoSpacing( Pr.ParaPr.Spacing.After, Cur_AfterAuto, this ); } } } } else { Pr.ParaPr.Spacing.After = this.Internal_CalculateAutoSpacing( Pr.ParaPr.Spacing.After, Pr.ParaPr.Spacing.AfterAutoSpacing, this ); } return Pr; }, Recalc_CompiledPr : function() { this.CompiledPr.NeedRecalc = true; }, // Формируем конечные свойства параграфа на основе стиля, возможной нумерации и прямых настроек. // Без пересчета расстояния между параграфами. Get_CompiledPr2 : function(bCopy) { if ( true === this.CompiledPr.NeedRecalc ) { this.CompiledPr.Pr = this.Internal_CompileParaPr(); this.CompiledPr.NeedRecalc = false; } if ( false === bCopy ) return this.CompiledPr.Pr; else { // Отдаем копию объекта, чтобы никто не поменял извне настройки скомпилированного стиля var Pr = {}; Pr.TextPr = this.CompiledPr.Pr.TextPr.Copy(); Pr.ParaPr = this.CompiledPr.Pr.ParaPr.Copy(); return Pr; } }, // Формируем конечные свойства параграфа на основе стиля, возможной нумерации и прямых настроек. Internal_CompileParaPr : function() { var Styles = this.Parent.Get_Styles(); var Numbering = this.Parent.Get_Numbering(); var TableStyle = this.Parent.Get_TableStyleForPara(); var StyleId = this.Style_Get(); // Считываем свойства для текущего стиля var Pr = Styles.Get_Pr( StyleId, styletype_Paragraph, TableStyle ); // Если в стиле была задана нумерация сохраним это в специальном поле if ( undefined != Pr.ParaPr.NumPr ) Pr.ParaPr.StyleNumPr = Pr.ParaPr.NumPr.Copy(); var Lvl = -1; if ( undefined != this.Pr.NumPr ) { if ( undefined != this.Pr.NumPr.NumId && 0 != this.Pr.NumPr.NumId ) { Pr.ParaPr.Merge( Numbering.Get_ParaPr( this.Pr.NumPr.NumId, this.Pr.NumPr.Lvl ) ); Lvl = this.Pr.NumPr.Lvl; } } else if ( undefined != Pr.ParaPr.NumPr ) { if ( undefined != Pr.ParaPr.NumPr.NumId && 0 != Pr.ParaPr.NumPr.NumId ) { var AbstractNum = Numbering.Get_AbstractNum( Pr.ParaPr.NumPr.NumId ); Lvl = AbstractNum.Get_LvlByStyle( StyleId ); if ( -1 != Lvl ) {} else Pr.ParaPr.NumPr = undefined; } } Pr.ParaPr.StyleTabs = ( undefined != Pr.ParaPr.Tabs ? Pr.ParaPr.Tabs.Copy() : new CParaTabs() ); // Копируем прямые настройки параграфа. Pr.ParaPr.Merge( this.Pr ); if ( -1 != Lvl && undefined != Pr.ParaPr.NumPr ) Pr.ParaPr.NumPr.Lvl = Lvl; // Настройки рамки не наследуются if ( undefined === this.Pr.FramePr ) Pr.ParaPr.FramePr = undefined; else Pr.ParaPr.FramePr = this.Pr.FramePr.Copy(); return Pr; }, // Сообщаем параграфу, что ему надо будет пересчитать скомпилированный стиль // (Такое может случится, если у данного параграфа есть нумерация или задан стиль, // которые меняются каким-то внешним образом) Recalc_CompileParaPr : function() { this.CompiledPr.NeedRecalc = true; }, Internal_CalculateAutoSpacing : function(Value, UseAuto, Para) { var Result = Value; if ( true === UseAuto ) { if ( true === Para.Parent.Is_TableCellContent() ) Result = 0; else Result = 14 * g_dKoef_pt_to_mm; } return Result; }, Get_Paragraph_ParaPr_Copy : function() { var ParaPr = this.Pr.Copy(); return ParaPr; }, Paragraph_Format_Paste : function(TextPr, ParaPr, ApplyPara) { // Применяем текстовые настройки всегда if ( null != TextPr ) this.Add( new ParaTextPr( TextPr ) ); var _ApplyPara = ApplyPara; if ( false === _ApplyPara ) { if ( true === this.Selection.Use ) { _ApplyPara = true; var Start = this.Selection.StartPos; var End = this.Selection.EndPos; if ( Start > End ) { Start = this.Selection.EndPos; End = this.Selection.StartPos; } if ( true === this.Internal_FindForward( End, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End]).Found ) _ApplyPara = false; else if ( true === this.Internal_FindBackward( Start - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine, para_End]).Found ) _ApplyPara = false; } else _ApplyPara = true; } // Применяем настройки параграфа if ( true === _ApplyPara && null != ParaPr ) { // Ind if ( undefined != ParaPr.Ind ) this.Set_Ind( ParaPr.Ind, false ); // Jc if ( undefined != ParaPr.Jc ) this.Set_Align( ParaPr.Jc ); // Spacing if ( undefined != ParaPr.Spacing ) this.Set_Spacing( ParaPr.Spacing, false ); // PageBreakBefore if ( undefined != ParaPr.PageBreakBefore ) this.Set_PageBreakBefore( ParaPr.PageBreakBefore ); // KeepLines if ( undefined != ParaPr.KeepLines ) this.Set_KeepLines( ParaPr.KeepLines ); // ContextualSpacing if ( undefined != ParaPr.ContextualSpacing ) this.Set_ContextualSpacing( ParaPr.ContextualSpacing ); // Shd if ( undefined != ParaPr.Shd ) this.Set_Shd( ParaPr.Shd, false ); // NumPr if ( undefined != ParaPr.NumPr ) this.Numbering_Set( ParaPr.NumPr.NumId, ParaPr.NumPr.Lvl ); else this.Numbering_Remove(); // StyleId if ( undefined != ParaPr.PStyle ) this.Style_Add( ParaPr.PStyle, true ); else this.Style_Remove(); // Brd if ( undefined != ParaPr.Brd ) this.Set_Borders( ParaPr.Brd ); } }, Style_Get : function() { if ( undefined != this.Pr.PStyle ) return this.Pr.PStyle; return undefined; }, Style_Add : function(Id, bDoNotDeleteProps) { this.RecalcInfo.Set_Type_0(pararecalc_0_All); var Id_old = this.Pr.PStyle; if ( undefined === this.Pr.PStyle ) Id_old = null; else this.Style_Remove(); if ( null === Id ) return; // Если стиль является стилем по умолчанию для параграфа, тогда не надо его записывать. if ( Id != this.Parent.Get_Styles().Get_Default_Paragraph() ) { History.Add( this, { Type : historyitem_Paragraph_PStyle, Old : Id_old, New : Id } ); this.Pr.PStyle = Id; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; if ( true === bDoNotDeleteProps ) return; // TODO: По мере добавления элементов в стили параграфа и текста добавить их обработку здесь. // Не удаляем форматирование, при добавлении списка к данному параграфу var DefNumId = this.Parent.Get_Styles().Get_Default_ParaList(); if ( Id != DefNumId && ( Id_old != DefNumId || Id != this.Parent.Get_Styles().Get_Default_Paragraph() ) ) { this.Set_ContextualSpacing( undefined ); this.Set_Ind( new CParaInd(), true ); this.Set_Align( undefined ); this.Set_KeepLines( undefined ); this.Set_KeepNext( undefined ); this.Set_PageBreakBefore( undefined ); this.Set_Spacing( new CParaSpacing(), true ); this.Set_Shd( undefined, true ); this.Set_WidowControl( undefined ); this.Set_Tabs( new CParaTabs() ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Between ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Bottom ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Left ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Right ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Top ); // При изменении стиля убираются только те текстовые настроки внутри параграфа, // которые присутствуют в стиле. Пока мы удалим вообще все настроки. // TODO : переделать for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { this.Internal_Content_Remove( Index ); Index--; } } } }, // Добавление стиля в параграф при открытии и копировании Style_Add_Open : function(Id) { this.Pr.PStyle = Id; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Style_Remove : function() { if ( undefined != this.Pr.PStyle ) { History.Add( this, { Type : historyitem_Paragraph_PStyle, Old : this.Pr.PStyle, New : undefined } ); this.Pr.PStyle = undefined; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Проверяем находится ли курсор в конце параграфа Cursor_IsEnd : function(ContentPos) { if ( undefined === ContentPos ) ContentPos = this.CurPos.ContentPos; var oPos = this.Internal_FindForward( ContentPos, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( true === oPos.Found ) return false; else return true; }, // Проверяем находится ли курсор в начале параграфа Cursor_IsStart : function(ContentPos) { if ( undefined === ContentPos ) ContentPos = this.CurPos.ContentPos; var oPos = this.Internal_FindBackward( ContentPos - 1, [para_PageNum, para_Drawing, para_Tab, para_Text, para_Space, para_NewLine] ); if ( true === oPos.Found ) return false; else return true; }, // Проверим, начинается ли выделение с начала параграфа Selection_IsFromStart : function() { if ( true === this.Is_SelectionUse() ) { var StartPos = ( this.Selection.StartPos > this.Selection.EndPos ? this.Selection.EndPos : this.Selection.StartPos ); if ( true != this.Cursor_IsStart( StartPos ) ) return false; return true; } return false; }, // Очищение форматирования параграфа Clear_Formatting : function() { this.Style_Remove(); this.Numbering_Remove(); this.Set_ContextualSpacing(undefined); this.Set_Ind( new CParaInd(), true ); this.Set_Align( undefined, false ); this.Set_KeepLines( undefined ); this.Set_KeepNext( undefined ); this.Set_PageBreakBefore( undefined ); this.Set_Spacing( new CParaSpacing(), true ); this.Set_Shd( new CDocumentShd(), true ); this.Set_WidowControl( undefined ); this.Set_Tabs( new CParaTabs() ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Between ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Bottom ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Left ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Right ); this.Set_Border( undefined, historyitem_Paragraph_Borders_Top ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Clear_TextFormatting : function() { var Styles = this.Parent.Get_Styles(); var DefHyper = Styles.Get_Default_Hyperlink(); // TODO: Сделать, чтобы данная функция работала по выделению for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { Item.Set_Bold( undefined ); Item.Set_Italic( undefined ); Item.Set_Strikeout( undefined ); Item.Set_Underline( undefined ); Item.Set_FontFamily( undefined ); Item.Set_FontSize( undefined ); Item.Set_Color( undefined ); Item.Set_VertAlign( undefined ); Item.Set_HighLight( undefined ); Item.Set_Spacing( undefined ); Item.Set_DStrikeout( undefined ); Item.Set_Caps( undefined ); Item.Set_SmallCaps( undefined ); Item.Set_Position( undefined ); Item.Set_RFonts2( undefined ); Item.Set_Lang( undefined ); if ( undefined === Item.Value.RStyle || Item.Value.RStyle != DefHyper ) { Item.Set_RStyle( undefined ); } } } }, Set_Ind : function(Ind, bDeleteUndefined) { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); if ( ( undefined != Ind.FirstLine || true === bDeleteUndefined ) && this.Pr.Ind.FirstLine !== Ind.FirstLine ) { History.Add( this, { Type : historyitem_Paragraph_Ind_First, New : Ind.FirstLine, Old : ( undefined != this.Pr.Ind.FirstLine ? this.Pr.Ind.FirstLine : undefined ) } ); this.Pr.Ind.FirstLine = Ind.FirstLine; } if ( ( undefined != Ind.Left || true === bDeleteUndefined ) && this.Pr.Ind.Left !== Ind.Left ) { History.Add( this, { Type : historyitem_Paragraph_Ind_Left, New : Ind.Left, Old : ( undefined != this.Pr.Ind.Left ? this.Pr.Ind.Left : undefined ) } ); this.Pr.Ind.Left = Ind.Left; } if ( ( undefined != Ind.Right || true === bDeleteUndefined ) && this.Pr.Ind.Right !== Ind.Right ) { History.Add( this, { Type : historyitem_Paragraph_Ind_Right, New : Ind.Right, Old : ( undefined != this.Pr.Ind.Right ? this.Pr.Ind.Right : undefined ) } ); this.Pr.Ind.Right = Ind.Right; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_Spacing : function(Spacing, bDeleteUndefined) { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( ( undefined != Spacing.Line || true === bDeleteUndefined ) && this.Pr.Spacing.Line !== Spacing.Line ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_Line, New : Spacing.Line, Old : ( undefined != this.Pr.Spacing.Line ? this.Pr.Spacing.Line : undefined ) } ); this.Pr.Spacing.Line = Spacing.Line; } if ( ( undefined != Spacing.LineRule || true === bDeleteUndefined ) && this.Pr.Spacing.LineRule !== Spacing.LineRule ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_LineRule, New : Spacing.LineRule, Old : ( undefined != this.Pr.Spacing.LineRule ? this.Pr.Spacing.LineRule : undefined ) } ); this.Pr.Spacing.LineRule = Spacing.LineRule; } if ( ( undefined != Spacing.Before || true === bDeleteUndefined ) && this.Pr.Spacing.Before !== Spacing.Before ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_Before, New : Spacing.Before, Old : ( undefined != this.Pr.Spacing.Before ? this.Pr.Spacing.Before : undefined ) } ); this.Pr.Spacing.Before = Spacing.Before; } if ( ( undefined != Spacing.After || true === bDeleteUndefined ) && this.Pr.Spacing.After !== Spacing.After ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_After, New : Spacing.After, Old : ( undefined != this.Pr.Spacing.After ? this.Pr.Spacing.After : undefined ) } ); this.Pr.Spacing.After = Spacing.After; } if ( ( undefined != Spacing.AfterAutoSpacing || true === bDeleteUndefined ) && this.Pr.Spacing.AfterAutoSpacing !== Spacing.AfterAutoSpacing ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_AfterAutoSpacing, New : Spacing.AfterAutoSpacing, Old : ( undefined != this.Pr.Spacing.AfterAutoSpacing ? this.Pr.Spacing.AfterAutoSpacing : undefined ) } ); this.Pr.Spacing.AfterAutoSpacing = Spacing.AfterAutoSpacing; } if ( ( undefined != Spacing.BeforeAutoSpacing || true === bDeleteUndefined ) && this.Pr.Spacing.BeforeAutoSpacing !== Spacing.BeforeAutoSpacing ) { History.Add( this, { Type : historyitem_Paragraph_Spacing_BeforeAutoSpacing, New : Spacing.BeforeAutoSpacing, Old : ( undefined != this.Pr.Spacing.BeforeAutoSpacing ? this.Pr.Spacing.BeforeAutoSpacing : undefined ) } ); this.Pr.Spacing.BeforeAutoSpacing = Spacing.BeforeAutoSpacing; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_Align : function(Align) { if ( this.Pr.Jc != Align ) { History.Add( this, { Type : historyitem_Paragraph_Align, New : Align, Old : ( undefined != this.Pr.Jc ? this.Pr.Jc : undefined ) } ); this.Pr.Jc = Align; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_Shd : function(_Shd, bDeleteUndefined) { if ( undefined === _Shd ) { if ( undefined != this.Pr.Shd ) { History.Add( this, { Type : historyitem_Paragraph_Shd, New : undefined, Old : this.Pr.Shd } ); this.Pr.Shd = undefined; } } else { var Shd = new CDocumentShd(); Shd.Set_FromObject( _Shd ); if ( undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( ( undefined != Shd.Value || true === bDeleteUndefined ) && this.Pr.Shd.Value !== Shd.Value ) { History.Add( this, { Type : historyitem_Paragraph_Shd_Value, New : Shd.Value, Old : ( undefined != this.Pr.Shd.Value ? this.Pr.Shd.Value : undefined ) } ); this.Pr.Shd.Value = Shd.Value; } if ( undefined != Shd.Color || true === bDeleteUndefined ) { History.Add( this, { Type : historyitem_Paragraph_Shd_Color, New : Shd.Color, Old : ( undefined != this.Pr.Shd.Color ? this.Pr.Shd.Color : undefined ) } ); this.Pr.Shd.Color = Shd.Color; } } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_Tabs : function(Tabs) { var _Tabs = new CParaTabs(); var StyleTabs = this.Get_CompiledPr2(false).ParaPr.StyleTabs; // 1. Ищем табы, которые уже есть в стиле (такие добавлять не надо) for ( var Index = 0; Index < Tabs.Tabs.length; Index++ ) { var Value = StyleTabs.Get_Value( Tabs.Tabs[Index].Pos ); if ( -1 === Value ) _Tabs.Add( Tabs.Tabs[Index] ); } // 2. Ищем табы в стиле, которые нужно отменить for ( var Index = 0; Index < StyleTabs.Tabs.length; Index++ ) { var Value = _Tabs.Get_Value( StyleTabs.Tabs[Index].Pos ); if ( tab_Clear != StyleTabs.Tabs[Index] && -1 === Value ) _Tabs.Add( new CParaTab(tab_Clear, StyleTabs.Tabs[Index].Pos ) ); } History.Add( this, { Type : historyitem_Paragraph_Tabs, New : _Tabs, Old : this.Pr.Tabs } ); this.Pr.Tabs = _Tabs; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_ContextualSpacing : function(Value) { if ( Value != this.Pr.ContextualSpacing ) { History.Add( this, { Type : historyitem_Paragraph_ContextualSpacing, New : Value, Old : ( undefined != this.Pr.ContextualSpacing ? this.Pr.ContextualSpacing : undefined ) } ); this.Pr.ContextualSpacing = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_PageBreakBefore : function(Value) { if ( Value != this.Pr.PageBreakBefore ) { History.Add( this, { Type : historyitem_Paragraph_PageBreakBefore, New : Value, Old : ( undefined != this.Pr.PageBreakBefore ? this.Pr.PageBreakBefore : undefined ) } ); this.Pr.PageBreakBefore = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_KeepLines : function(Value) { if ( Value != this.Pr.KeepLines ) { History.Add( this, { Type : historyitem_Paragraph_KeepLines, New : Value, Old : ( undefined != this.Pr.KeepLines ? this.Pr.KeepLines : undefined ) } ); this.Pr.KeepLines = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_KeepNext : function(Value) { if ( Value != this.Pr.KeepNext ) { History.Add( this, { Type : historyitem_Paragraph_KeepNext, New : Value, Old : ( undefined != this.Pr.KeepNext ? this.Pr.KeepNext : undefined ) } ); this.Pr.KeepNext = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_WidowControl : function(Value) { if ( Value != this.Pr.WidowControl ) { History.Add( this, { Type : historyitem_Paragraph_WidowControl, New : Value, Old : ( undefined != this.Pr.WidowControl ? this.Pr.WidowControl : undefined ) } ); this.Pr.WidowControl = Value; // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; } }, Set_Borders : function(Borders) { if ( undefined === Borders ) return; var OldBorders = this.Get_CompiledPr2(false).ParaPr.Brd; if ( undefined != Borders.Between ) { var NewBorder = undefined; if ( undefined != Borders.Between.Value /*&& border_Single === Borders.Between.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Between.Color ? new CDocumentColor( Borders.Between.Color.r, Borders.Between.Color.g, Borders.Between.Color.b ) : new CDocumentColor( OldBorders.Between.Color.r, OldBorders.Between.Color.g, OldBorders.Between.Color.b ) ); NewBorder.Space = ( undefined != Borders.Between.Space ? Borders.Between.Space : OldBorders.Between.Space ); NewBorder.Size = ( undefined != Borders.Between.Size ? Borders.Between.Size : OldBorders.Between.Size ); NewBorder.Value = ( undefined != Borders.Between.Value ? Borders.Between.Value : OldBorders.Between.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Between, New : NewBorder, Old : this.Pr.Brd.Between } ); this.Pr.Brd.Between = NewBorder; } if ( undefined != Borders.Top ) { var NewBorder = undefined; if ( undefined != Borders.Top.Value /*&& border_Single === Borders.Top.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Top.Color ? new CDocumentColor( Borders.Top.Color.r, Borders.Top.Color.g, Borders.Top.Color.b ) : new CDocumentColor( OldBorders.Top.Color.r, OldBorders.Top.Color.g, OldBorders.Top.Color.b ) ); NewBorder.Space = ( undefined != Borders.Top.Space ? Borders.Top.Space : OldBorders.Top.Space ); NewBorder.Size = ( undefined != Borders.Top.Size ? Borders.Top.Size : OldBorders.Top.Size ); NewBorder.Value = ( undefined != Borders.Top.Value ? Borders.Top.Value : OldBorders.Top.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Top, New : NewBorder, Old : this.Pr.Brd.Top } ); this.Pr.Brd.Top = NewBorder; } if ( undefined != Borders.Right ) { var NewBorder = undefined; if ( undefined != Borders.Right.Value /*&& border_Single === Borders.Right.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Right.Color ? new CDocumentColor( Borders.Right.Color.r, Borders.Right.Color.g, Borders.Right.Color.b ) : new CDocumentColor( OldBorders.Right.Color.r, OldBorders.Right.Color.g, OldBorders.Right.Color.b ) ); NewBorder.Space = ( undefined != Borders.Right.Space ? Borders.Right.Space : OldBorders.Right.Space ); NewBorder.Size = ( undefined != Borders.Right.Size ? Borders.Right.Size : OldBorders.Right.Size ); NewBorder.Value = ( undefined != Borders.Right.Value ? Borders.Right.Value : OldBorders.Right.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Right, New : NewBorder, Old : this.Pr.Brd.Right } ); this.Pr.Brd.Right = NewBorder; } if ( undefined != Borders.Bottom ) { var NewBorder = undefined; if ( undefined != Borders.Bottom.Value /*&& border_Single === Borders.Bottom.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Bottom.Color ? new CDocumentColor( Borders.Bottom.Color.r, Borders.Bottom.Color.g, Borders.Bottom.Color.b ) : new CDocumentColor( OldBorders.Bottom.Color.r, OldBorders.Bottom.Color.g, OldBorders.Bottom.Color.b ) ); NewBorder.Space = ( undefined != Borders.Bottom.Space ? Borders.Bottom.Space : OldBorders.Bottom.Space ); NewBorder.Size = ( undefined != Borders.Bottom.Size ? Borders.Bottom.Size : OldBorders.Bottom.Size ); NewBorder.Value = ( undefined != Borders.Bottom.Value ? Borders.Bottom.Value : OldBorders.Bottom.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Bottom, New : NewBorder, Old : this.Pr.Brd.Bottom } ); this.Pr.Brd.Bottom = NewBorder; } if ( undefined != Borders.Left ) { var NewBorder = undefined; if ( undefined != Borders.Left.Value /*&& border_Single === Borders.Left.Value*/ ) { NewBorder = new CDocumentBorder(); NewBorder.Color = ( undefined != Borders.Left.Color ? new CDocumentColor( Borders.Left.Color.r, Borders.Left.Color.g, Borders.Left.Color.b ) : new CDocumentColor( OldBorders.Left.Color.r, OldBorders.Left.Color.g, OldBorders.Left.Color.b ) ); NewBorder.Space = ( undefined != Borders.Left.Space ? Borders.Left.Space : OldBorders.Left.Space ); NewBorder.Size = ( undefined != Borders.Left.Size ? Borders.Left.Size : OldBorders.Left.Size ); NewBorder.Value = ( undefined != Borders.Left.Value ? Borders.Left.Value : OldBorders.Left.Value ); } History.Add( this, { Type : historyitem_Paragraph_Borders_Left, New : NewBorder, Old : this.Pr.Brd.Left } ); this.Pr.Brd.Left = NewBorder; } // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, Set_Border : function(Border, HistoryType) { var OldValue; switch( HistoryType ) { case historyitem_Paragraph_Borders_Between: OldValue = this.Pr.Brd.Between; this.Pr.Brd.Between = Border; break; case historyitem_Paragraph_Borders_Bottom: OldValue = this.Pr.Brd.Bottom; this.Pr.Brd.Bottom = Border; break; case historyitem_Paragraph_Borders_Left: OldValue = this.Pr.Brd.Left; this.Pr.Brd.Left = Border; break; case historyitem_Paragraph_Borders_Right: OldValue = this.Pr.Brd.Right; this.Pr.Brd.Right = Border; break; case historyitem_Paragraph_Borders_Top: OldValue = this.Pr.Brd.Top; this.Pr.Brd.Top = Border; break; } History.Add( this, { Type : HistoryType, New : Border, Old : OldValue } ); // Надо пересчитать конечный стиль this.CompiledPr.NeedRecalc = true; }, // Проверяем начинается ли текущий параграф с новой страницы. Is_StartFromNewPage : function() { // TODO: пока здесь стоит простая проверка. В будущем надо будет данную проверку улучшить. // Например, сейчас не учитывается случай, когда в начале параграфа стоит PageBreak. if ( ( this.Pages.length > 1 && 0 === this.Pages[1].FirstLine ) || ( null === this.Get_DocumentPrev() ) ) return true; return false; }, Internal_GetPage : function(Pos) { if ( undefined === Pos ) Pos = this.CurPos.ContentPos; return this.Internal_Get_ParaPos_By_Pos( Pos).Page; }, // Ищем графический объект по Id и удаляем запись он нем в параграфе Remove_DrawingObject : function(Id) { for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type && Id === Item.Get_Id() ) { var HdrFtr = this.Parent.Is_HdrFtr(true); if ( null != HdrFtr && true != Item.Is_Inline() ) HdrFtr.RecalcInfo.NeedRecalc = true; this.Internal_Content_Remove( Index ); return Index; } } return -1; }, Internal_CorrectAnchorPos : function(Result, Drawing, PageNum) { // Поправляем позицию var RelH = Drawing.PositionH.RelativeFrom; var RelV = Drawing.PositionV.RelativeFrom; var ContentPos = 0; if ( c_oAscRelativeFromH.Character != RelH || c_oAscRelativeFromV.Line != RelV ) { var CurLine = Result.Internal.Line; if ( c_oAscRelativeFromV.Line != RelV ) { var CurPage = Result.Internal.Page; CurLine = this.Pages[CurPage].StartLine; } var StartLinesPos = this.Lines[CurLine].StartPos; var EndLinesPos = this.Lines[CurLine].EndPos; var CurRange = this.Internal_Get_ParaPos_By_Pos( StartLinesPos).Range; Result.X = this.Lines[CurLine].Ranges[CurRange].X - 3.8; ContentPos = Math.min( StartLinesPos + 1, EndLinesPos ); } if ( c_oAscRelativeFromV.Line != RelV ) { var CurPage = Result.Internal.Page; var CurLine = this.Pages[CurPage].StartLine; Result.Y = this.Pages[CurPage].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent; } if ( c_oAscRelativeFromH.Character === RelH ) { // Ничего не делаем } else if ( c_oAscRelativeFromV.Line === RelV ) { var CurLine = this.Internal_Get_ParaPos_By_Pos( Result.ContentPos).Line; Result.ContentPos = this.Lines[CurLine].StartPos; } else { Result.ContentPos = ContentPos; } }, // Получем ближающую возможную позицию курсора Get_NearestPos : function(PageNum, X, Y, bAnchor, Drawing) { var ContentPos = this.Internal_GetContentPosByXY( X, Y, false, PageNum ).Pos; var Result = this.Internal_Recalculate_CurPos( ContentPos, false, false, true ); // Сохраняем параграф и найденное место в параграфе Result.ContentPos = ContentPos; Result.Paragraph = this; if ( true === bAnchor && undefined != Drawing && null != Drawing ) this.Internal_CorrectAnchorPos( Result, Drawing, PageNum - this.PageNum ); return Result; }, Get_AnchorPos : function(Drawing) { // Ищем, где находится наш объект var ContentPos = -1; var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type && Item.Get_Id() === Drawing.Get_Id() ) { ContentPos = Index; break; } } var CurPage = this.Internal_Get_ParaPos_By_Pos( ContentPos).Page; if ( -1 === ContentPos ) return { X : 0, Y : 0, Height : 0 }; var Result = this.Internal_Recalculate_CurPos( ContentPos, false, false, true ); Result.Paragraph = this; Result.ContentPos = ContentPos; this.Internal_CorrectAnchorPos( Result, Drawing, CurPage ); return Result; }, Set_DocumentNext : function(Object) { History.Add( this, { Type : historyitem_Paragraph_DocNext, New : Object, Old : this.Next } ); this.Next = Object; }, Set_DocumentPrev : function(Object) { History.Add( this, { Type : historyitem_Paragraph_DocPrev, New : Object, Old : this.Prev } ); this.Prev = Object; }, Get_DocumentNext : function() { return this.Next; }, Get_DocumentPrev : function() { return this.Prev; }, Set_DocumentIndex : function(Index) { this.Index = Index; }, Set_Parent : function(ParentObject) { History.Add( this, { Type : historyitem_Paragraph_Parent, New : ParentObject, Old : this.Parent } ); this.Parent = ParentObject; }, Get_Parent : function() { return this.Parent; }, Is_ContentOnFirstPage : function() { // Если параграф сразу переносится на новую страницу, тогда это значение обычно -1 if ( this.Pages[0].EndLine < 0 ) return false; return true; }, Get_CurrentPage_Absolute : function() { // Обновляем позицию this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); return (this.Get_StartPage_Absolute() + this.CurPos.PagesPos); }, Get_CurrentPage_Relative : function() { // Обновляем позицию this.Internal_Recalculate_CurPos( this.CurPos.ContentPos, true, false, false ); return (this.PageNum + this.CurPos.PagesPos); }, // на вход подается строка с как минимум 1 символом (поэтому тут это не проверяем) DocumentSearch : function(Str, ElementType) { var Pr = this.Get_CompiledPr(); var StartPage = this.Get_StartPage_Absolute(); var SearchResults = new Array(); // Сначала найдем элементы поиска в данном параграфе for ( var Pos = 0; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; if ( para_Numbering === Item.Type || para_PresentationNumbering === Item.Type || para_TextPr === Item.Type ) continue; if ( (" " === Str[0] && para_Space === Item.Type) || ( para_Text === Item.Type && (Item.Value).toLowerCase() === Str[0].toLowerCase() ) ) { if ( 1 === Str.length ) SearchResults.push( { StartPos : Pos, EndPos : Pos + 1 } ); else { var bFind = true; var Pos2 = Pos + 1; // Проверяем for ( var Index = 1; Index < Str.length; Index++ ) { // Пропускаем записи TextPr while ( Pos2 < this.Content.length && ( para_TextPr === this.Content[Pos2].Type ) ) Pos2++; if ( ( Pos2 >= this.Content.length ) || (" " === Str[Index] && para_Space != this.Content[Pos2].Type) || ( " " != Str[Index] && ( ( para_Text != this.Content[Pos2].Type ) || ( para_Text === this.Content[Pos2].Type && this.Content[Pos2].Value.toLowerCase() != Str[Index].toLowerCase() ) ) ) ) { bFind = false; break; } Pos2++; } if ( true === bFind ) { SearchResults.push( { StartPos : Pos, EndPos : Pos2 } ); } } } } var MaxShowValue = 100; for ( var FoundIndex = 0; FoundIndex < SearchResults.length; FoundIndex++ ) { var Rects = new Array(); // Делаем подсветку var StartPos = SearchResults[FoundIndex].StartPos; var EndPos = SearchResults[FoundIndex].EndPos; // Найдем линию, с которой начинается селект var StartParaPos = this.Internal_Get_ParaPos_By_Pos( StartPos ); var CurLine = StartParaPos.Line; var CurRange = StartParaPos.Range; var PNum = StartParaPos.Page; // Найдем начальный сдвиг в данном отрезке var StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; var Pos, Item; for ( Pos = this.Lines[CurLine].Ranges[CurRange].StartPos; Pos <= StartPos - 1; Pos++ ) { Item = this.Content[Pos]; if ( Pos === this.Numbering.Pos ) StartX += this.Numbering.WidthVisible; if ( undefined != Item.WidthVisible && ( para_Drawing != Item.Type || drawing_Inline === Item.DrawingType ) ) StartX += Item.WidthVisible; } if ( this.Pages[PNum].StartLine > CurLine ) { CurLine = this.Pages[PNum].StartLine; CurRange = 0; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; StartPos = this.Lines[this.Pages[PNum].StartLine].StartPos; } var StartY = (this.Pages[PNum].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent); var EndY = (this.Pages[PNum].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent); if ( this.Lines[CurLine].Metrics.LineGap < 0 ) EndY += this.Lines[CurLine].Metrics.LineGap; var W = 0; for ( Pos = StartPos; Pos < EndPos; Pos++ ) { Item = this.Content[Pos]; if ( undefined != Item.CurPage ) { if ( Item.CurPage > PNum ) PNum = Item.CurPage; if ( CurLine < Item.CurLine ) { Rects.push( { PageNum : StartPage + PNum, X : StartX, Y : StartY, W : W, H : EndY - StartY } ); CurLine = Item.CurLine; CurRange = Item.CurRange; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; StartY = (this.Pages[PNum].Y + this.Lines[CurLine].Y - this.Lines[CurLine].Metrics.Ascent); EndY = (this.Pages[PNum].Y + this.Lines[CurLine].Y + this.Lines[CurLine].Metrics.Descent); if ( this.Lines[CurLine].Metrics.LineGap < 0 ) EndY += this.Lines[CurLine].Metrics.LineGap; W = 0; } else if ( CurRange < Item.CurRange ) { Rects.push( { PageNum : StartPage + PNum, X : StartX, Y : StartY, W : W, H : EndY - StartY } ); CurRange = Item.CurRange; StartX = this.Lines[CurLine].Ranges[CurRange].XVisible; W = 0; } } if ( undefined != Item.WidthVisible ) W += Item.WidthVisible; if ( Pos == EndPos - 1 ) Rects.push( { PageNum : StartPage + PNum, X : StartX, Y : StartY, W : W, H : EndY - StartY } ); } var ResultStr = new String(); var _Str = ""; for ( var Pos = StartPos; Pos < EndPos; Pos++ ) { Item = this.Content[Pos]; if ( para_Text === Item.Type ) _Str += Item.Value; else if ( para_Space === Item.Type ) _Str += " "; } // Теперь мы должны сформировать строку if ( _Str.length >= MaxShowValue ) { ResultStr = "\<b\>"; for ( var Index = 0; Index < MaxShowValue - 1; Index++ ) ResultStr += _Str[Index]; ResultStr += "\</b\>..."; } else { ResultStr = "\<b\>" + _Str + "\</b\>"; var Pos_before = StartPos - 1; var Pos_after = EndPos; var LeaveCount = MaxShowValue - _Str.length; var bAfter = true; while ( LeaveCount > 0 && ( Pos_before >= 0 || Pos_after < this.Content.length ) ) { var TempPos = ( true === bAfter ? Pos_after : Pos_before ); var Flag = 0; while ( ( ( TempPos >= 0 && false === bAfter ) || ( TempPos < this.Content.length && true === bAfter ) ) && para_Text != this.Content[TempPos].Type && para_Space != this.Content[TempPos].Type ) { if ( true === bAfter ) { TempPos++; if ( TempPos >= this.Content.length ) { TempPos = Pos_before; bAfter = false; Flag++; } } else { TempPos--; if ( TempPos < 0 ) { TempPos = Pos_after; bAfter = true; Flag++; } } // Дошли до обоих концов параграфа if ( Flag >= 2 ) break; } if ( Flag >= 2 || !( ( TempPos >= 0 && false === bAfter ) || ( TempPos < this.Content.length && true === bAfter ) ) ) break; if ( true === bAfter ) { ResultStr += (para_Space === this.Content[TempPos].Type ? " " : this.Content[TempPos].Value); Pos_after = TempPos + 1; LeaveCount--; if ( Pos_before >= 0 ) bAfter = false; if ( Pos_after >= this.Content.length ) bAfter = false; } else { ResultStr = (para_Space === this.Content[TempPos].Type ? " " : this.Content[TempPos].Value) + ResultStr; Pos_before = TempPos - 1; LeaveCount--; if ( Pos_after < this.Content.length ) bAfter = true; if ( Pos_before < 0 ) bAfter = true; } } } this.DrawingDocument.AddPageSearch( ResultStr, Rects, ElementType ); } }, DocumentStatistics : function(Stats) { var bEmptyParagraph = true; var bWord = false; for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; var bSymbol = false; var bSpace = false; var bNewWord = false; if ( (para_Text === Item.Type && false === Item.Is_NBSP()) || (para_PageNum === Item.Type) ) { if ( false === bWord ) bNewWord = true; bWord = true; bSymbol = true; bSpace = false; bEmptyParagraph = false; } else if ( ( para_Text === Item.Type && true === Item.Is_NBSP() ) || para_Space === Item.Type || para_Tab === Item.Type ) { bWord = false; bSymbol = true; bSpace = true; } if ( true === bSymbol ) Stats.Add_Symbol( bSpace ); if ( true === bNewWord ) Stats.Add_Word(); } var NumPr = this.Numbering_Get(); if ( undefined != NumPr ) { bEmptyParagraph = false; this.Parent.Get_Numbering().Get_AbstractNum( NumPr.NumId).DocumentStatistics( NumPr.Lvl, Stats ); } if ( false === bEmptyParagraph ) Stats.Add_Paragraph(); }, TurnOff_RecalcEvent : function() { this.TurnOffRecalcEvent = true; }, TurnOn_RecalcEvent : function() { this.TurnOffRecalcEvent = false; }, Set_ApplyToAll : function(bValue) { this.ApplyToAll = bValue; }, Get_ApplyToAll : function() { return this.ApplyToAll; }, Update_CursorType : function(X, Y, PageIndex) { var text_transform = null; var cur_parent = this.Parent; if(this.Parent.Is_TableCellContent()) { while(isRealObject(cur_parent) && cur_parent.Is_TableCellContent()) { cur_parent = cur_parent.Parent.Row.Table.Parent; } } if(cur_parent.Parent instanceof WordShape) { if(isRealObject(cur_parent.Parent.transformText)) { text_transform = cur_parent.Parent.transformText; } } var MMData = new CMouseMoveData(); var Coords = this.DrawingDocument.ConvertCoordsToCursorWR( X, Y, this.Get_StartPage_Absolute() + ( PageIndex - this.PageNum ), text_transform ); MMData.X_abs = Coords.X; MMData.Y_abs = Coords.Y; var Hyperlink = this.Check_Hyperlink( X, Y, PageIndex ); var PNum = PageIndex - this.PageNum; if ( null != Hyperlink && ( PNum >= 0 && PNum < this.Pages.length && Y <= this.Pages[PNum].Bounds.Bottom && Y >= this.Pages[PNum].Bounds.Top ) ) { MMData.Type = c_oAscMouseMoveDataTypes.Hyperlink; MMData.Hyperlink = new CHyperlinkProperty( Hyperlink ); } else MMData.Type = c_oAscMouseMoveDataTypes.Common; if ( null != Hyperlink && true === global_keyboardEvent.CtrlKey ) this.DrawingDocument.SetCursorType( "pointer", MMData ); else this.DrawingDocument.SetCursorType( "default", MMData ); var PNum = Math.max( 0, Math.min( PageIndex - this.PageNum, this.Pages.length - 1 ) ); var Bounds = this.Pages[PNum].Bounds; if ( true === this.Lock.Is_Locked() && X < Bounds.Right && X > Bounds.Left && Y > Bounds.Top && Y < Bounds.Bottom ) { var _X = this.Pages[PNum].X; var _Y = this.Pages[PNum].Y; var MMData = new CMouseMoveData(); var Coords = this.DrawingDocument.ConvertCoordsToCursorWR( _X, _Y, this.Get_StartPage_Absolute() + ( PageIndex - this.PageNum ), text_transform ); MMData.X_abs = Coords.X - 5; MMData.Y_abs = Coords.Y; MMData.Type = c_oAscMouseMoveDataTypes.LockedObject; MMData.UserId = this.Lock.Get_UserId(); MMData.HaveChanges = this.Lock.Have_Changes(); MMData.LockedObjectType = c_oAscMouseMoveLockedObjectType.Common; editor.sync_MouseMoveCallback( MMData ); } }, Document_CreateFontMap : function(FontMap) { if ( true === this.FontMap.NeedRecalc ) { this.FontMap.Map = new Object(); if ( true === this.CompiledPr.NeedRecalc ) { this.CompiledPr.Pr = this.Internal_CompileParaPr(); this.CompiledPr.NeedRecalc = false; } var CurTextPr = this.CompiledPr.Pr.TextPr.Copy(); CurTextPr.Document_CreateFontMap( this.FontMap.Map ); CurTextPr.Merge( this.TextPr.Value ); CurTextPr.Document_CreateFontMap( this.FontMap.Map ); for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { // Выствляем начальные настройки текста у данного параграфа CurTextPr = this.CompiledPr.Pr.TextPr.Copy(); var _CurTextPr = Item.Value; // Копируем настройки из символьного стиля if ( undefined != _CurTextPr.RStyle ) { var Styles = this.Parent.Get_Styles(); var StyleTextPr = Styles.Get_Pr( _CurTextPr.RStyle, styletype_Character).TextPr; CurTextPr.Merge( StyleTextPr ); } // Копируем прямые настройки CurTextPr.Merge( _CurTextPr ); CurTextPr.Document_CreateFontMap( this.FontMap.Map ); } } this.FontMap.NeedRecalc = false; } for ( Key in this.FontMap.Map ) { FontMap[Key] = this.FontMap.Map[Key]; } }, Document_CreateFontCharMap : function(FontCharMap) { if ( true === this.CompiledPr.NeedRecalc ) { this.CompiledPr.Pr = this.Internal_CompileParaPr(); this.CompiledPr.NeedRecalc = false; } var CurTextPr = this.CompiledPr.Pr.TextPr.Copy(); FontCharMap.StartFont( CurTextPr.FontFamily.Name, CurTextPr.Bold, CurTextPr.Italic, CurTextPr.FontSize ); for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { // Выставляем начальные настройки текста у данного параграфа CurTextPr = this.CompiledPr.Pr.TextPr.Copy(); var _CurTextPr = Item.Value; // Копируем настройки из символьного стиля if ( undefined != _CurTextPr.RStyle ) { var Styles = this.Parent.Get_Styles(); var StyleTextPr = Styles.Get_Pr( _CurTextPr.RStyle, styletype_Character).TextPr; CurTextPr.Merge( StyleTextPr ); } // Копируем прямые настройки CurTextPr.Merge( _CurTextPr ); FontCharMap.StartFont( CurTextPr.FontFamily.Name, CurTextPr.Bold, CurTextPr.Italic, CurTextPr.FontSize ); } else if ( para_Text === Item.Type ) { FontCharMap.AddChar( Item.Value ); } else if ( para_Space === Item.Type ) { FontCharMap.AddChar( ' ' ); } else if ( para_Numbering === Item.Type ) { var ParaPr = this.CompiledPr.Pr.ParaPr; var NumPr = ParaPr.NumPr; if ( undefined === NumPr || undefined === NumPr.NumId || 0 === NumPr.NumId ) continue; var Numbering = this.Parent.Get_Numbering(); var NumInfo = this.Parent.Internal_GetNumInfo( this.Id, NumPr ); var NumTextPr = this.CompiledPr.Pr.TextPr.Copy(); NumTextPr.Merge( this.TextPr.Value ); NumTextPr.Merge( NumLvl.TextPr ); Numbering.Document_CreateFontCharMap( FontCharMap, NumTextPr, NumPr, NumInfo ); FontCharMap.StartFont( CurTextPr.FontFamily.Name, CurTextPr.Bold, CurTextPr.Italic, CurTextPr.FontSize ); } else if ( para_PageNum === Item.Type ) { Item.Document_CreateFontCharMap( FontCharMap ); } } CurTextPr.Merge( this.TextPr.Value ); }, Document_Get_AllFontNames : function(AllFonts) { // Смотрим на знак конца параграфа this.TextPr.Value.Document_Get_AllFontNames( AllFonts ); var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_TextPr === Item.Type ) { Item.Value.Document_Get_AllFontNames( AllFonts ); } else if ( para_Drawing === Item.Type ) { Item.documentGetAllFontNames( AllFonts ); } } }, // Обновляем линейку Document_UpdateRulersState : function() { var FramePr = this.Get_FramePr(); if ( undefined === FramePr ) this.Parent.DrawingDocument.Set_RulerState_Paragraph( null ); else { var Frame = this.CalculatedFrame; this.Parent.DrawingDocument.Set_RulerState_Paragraph( { L : Frame.L, T : Frame.T, R : Frame.L + Frame.W, B : Frame.T + Frame.H, PageIndex : Frame.PageIndex, Frame : this } ); } }, // Пока мы здесь проверяем только, находимся ли мы внутри гиперссылки Document_UpdateInterfaceState : function() { if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } var Hyper_start = this.Check_Hyperlink2( this.Selection.StartPos ); var Hyper_end = this.Check_Hyperlink2( this.Selection.EndPos ); if ( Hyper_start === Hyper_end && null != Hyper_start ) { // Вычислим строку var Find = this.Internal_FindBackward( this.Selection.StartPos, [para_HyperlinkStart] ); if ( true != Find.Found ) return; var Str = ""; for ( var Pos = Find.LetterPos + 1; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; var bBreak = false; switch ( Item.Type ) { case para_Drawing: case para_End: case para_Numbering: case para_PresentationNumbering: case para_PageNum: { Str = null; bBreak = true; break; } case para_Text : Str += Item.Value; break; case para_Space: case para_Tab : Str += " "; break; case para_HyperlinkEnd: { bBreak = true; break; } case para_HyperlinkStart: return; } if ( true === bBreak ) break; } var HyperProps = new CHyperlinkProperty( Hyper_start ); HyperProps.put_Text( Str ); editor.sync_HyperlinkPropCallback( HyperProps ); } this.SpellChecker.Document_UpdateInterfaceState( StartPos, EndPos ); } else { var Hyper_cur = this.Check_Hyperlink2( this.CurPos.ContentPos, false, true ); if ( null != Hyper_cur ) { // Вычислим строку var Find = this.Internal_FindBackward( this.CurPos.ContentPos, [para_HyperlinkStart] ); if ( true != Find.Found ) return; var Str = ""; for ( var Pos = Find.LetterPos + 1; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; var bBreak = false; switch ( Item.Type ) { case para_Drawing: case para_End: case para_Numbering: case para_PresentationNumbering: case para_PageNum: { Str = null; bBreak = true; break; } case para_Text : Str += Item.Value; break; case para_Space: case para_Tab : Str += " "; break; case para_HyperlinkEnd: { bBreak = true; break; } case para_HyperlinkStart: return; } if ( true === bBreak ) break; } var HyperProps = new CHyperlinkProperty( Hyper_cur ); HyperProps.put_Text( Str ); editor.sync_HyperlinkPropCallback( HyperProps ); } this.SpellChecker.Document_UpdateInterfaceState( this.CurPos.ContentPos, this.CurPos.ContentPos ); } }, // Функция, которую нужно вызвать перед удалением данного элемента PreDelete : function() { // Поскольку данный элемент удаляется, поэтому надо удалить все записи о // inline объектах в родительском классе, используемых в данном параграфе. // Кроме этого, если тут начинались или заканчивались комметарии, то их тоже // удаляем. this.Internal_Remove_CollaborativeMarks(); for ( var Index = 0; Index < this.Content.length; Index++ ) { var Item = this.Content[Index]; if ( para_CommentEnd === Item.Type || para_CommentStart === Item.Type ) { editor.WordControl.m_oLogicDocument.Remove_Comment( Item.Id, true ); } } }, //----------------------------------------------------------------------------------- // Функции для работы с номерами страниц //----------------------------------------------------------------------------------- Get_StartPage_Absolute : function() { return this.Parent.Get_StartPage_Absolute() + this.Get_StartPage_Relative(); }, Get_StartPage_Relative : function() { return this.PageNum; }, //----------------------------------------------------------------------------------- // Дополнительные функции //----------------------------------------------------------------------------------- Document_SetThisElementCurrent : function() { this.Parent.Set_CurrentElement( this.Index ); }, Is_ThisElementCurrent : function() { var Parent = this.Parent; if ( docpostype_Content === Parent.CurPos.Type && false === Parent.Selection.Use && this.Index === Parent.CurPos.ContentPos ) return this.Parent.Is_ThisElementCurrent(); return false; }, Is_Inline : function() { if ( undefined != this.Pr.FramePr ) return false; return true; }, Get_FramePr : function() { return this.Pr.FramePr; }, Set_FramePr : function(FramePr, bDelete) { var FramePr_old = this.Pr.FramePr; if ( undefined === bDelete ) bDelete = false; if ( true === bDelete ) { this.Pr.FramePr = undefined; History.Add( this, { Type : historyitem_Paragraph_FramePr, Old : FramePr_old, New : undefined } ); this.CompiledPr.NeedRecalc = true; return; } var FrameParas = this.Internal_Get_FrameParagraphs(); // Тут FramePr- объект класса из api.js CParagraphFrame if ( true === FramePr.FromDropCapMenu && 1 === FrameParas.length ) { // Здесь мы смотрим только на количество строк, шрифт, тип и горизонтальный отступ от текста var NewFramePr = FramePr_old.Copy(); if ( undefined != FramePr.DropCap ) { var OldLines = NewFramePr.Lines; NewFramePr.Init_Default_DropCap( FramePr.DropCap === c_oAscDropCap.Drop ? true : false ); NewFramePr.Lines = OldLines; } if ( undefined != FramePr.Lines ) { var AnchorPara = this.Get_FrameAnchorPara(); if ( null === AnchorPara || AnchorPara.Lines.length <= 0 ) return; var LineH = AnchorPara.Lines[0].Bottom - AnchorPara.Lines[0].Top; var LineTA = AnchorPara.Lines[0].Metrics.TextAscent2; var LineTD = AnchorPara.Lines[0].Metrics.TextDescent + AnchorPara.Lines[0].Metrics.LineGap; this.Set_Spacing( { LineRule : linerule_Exact, Line : FramePr.Lines * LineH }, false ); this.Update_DropCapByLines( this.Internal_CalculateTextPr( this.Internal_GetStartPos() ), FramePr.Lines, LineH, LineTA, LineTD ); } if ( undefined != FramePr.FontFamily ) { var FF = new ParaTextPr( { RFonts : { Ascii : { Name : FramePr.FontFamily.Name, Index : -1 } } } ); this.Select_All(); this.Add( FF ); this.Selection_Remove(); } if ( undefined != FramePr.HSpace ) NewFramePr.HSpace = FramePr.HSpace; this.Pr.FramePr = NewFramePr; } else { var NewFramePr = FramePr_old.Copy(); if ( undefined != FramePr.H ) NewFramePr.H = FramePr.H; if ( undefined != FramePr.HAnchor ) NewFramePr.HAnchor = FramePr.HAnchor; if ( undefined != FramePr.HRule ) NewFramePr.HRule = FramePr.HRule; if ( undefined != FramePr.HSpace ) NewFramePr.HSpace = FramePr.HSpace; if ( undefined != FramePr.Lines ) NewFramePr.Lines = FramePr.Lines; if ( undefined != FramePr.VAnchor ) NewFramePr.VAnchor = FramePr.VAnchor; if ( undefined != FramePr.VSpace ) NewFramePr.VSpace = FramePr.VSpace; // Потому что undefined - нормальное значение (и W всегда заполняется в интерфейсе) NewFramePr.W = FramePr.W; if ( undefined != FramePr.Wrap ) NewFramePr.Wrap = FramePr.Wrap; if ( undefined != FramePr.X ) NewFramePr.X = FramePr.X; if ( undefined != FramePr.XAlign ) NewFramePr.XAlign = FramePr.XAlign; if ( undefined != FramePr.Y ) NewFramePr.Y = FramePr.Y; if ( undefined != FramePr.YAlign ) NewFramePr.YAlign = FramePr.YAlign; this.Pr.FramePr = NewFramePr; } if ( undefined != FramePr.Brd ) { var Count = FrameParas.length; for ( var Index = 0; Index < Count; Index++ ) { FrameParas[Index].Set_Borders( FramePr.Brd ); } } if ( undefined != FramePr.Shd ) { var Count = FrameParas.length; for ( var Index = 0; Index < Count; Index++ ) { FrameParas[Index].Set_Shd( FramePr.Shd ); } } History.Add( this, { Type : historyitem_Paragraph_FramePr, Old : FramePr_old, New : this.Pr.FramePr } ); this.CompiledPr.NeedRecalc = true; }, Set_FramePr2 : function(FramePr) { History.Add( this, { Type : historyitem_Paragraph_FramePr, Old : this.Pr.FramePr, New : FramePr } ); this.Pr.FramePr = FramePr; this.CompiledPr.NeedRecalc = true; }, Set_FrameParaPr : function(Para) { Para.CopyPr( this ); this.Set_Spacing( { After : 0 }, false ); this.Numbering_Remove(); }, Get_FrameBounds : function(FrameX, FrameY, FrameW, FrameH) { var X0 = FrameX, Y0 = FrameY, X1 = FrameX + FrameW, Y1 = FrameY + FrameH; var Paras = this.Internal_Get_FrameParagraphs(); var Count = Paras.length; var FramePr = this.Get_FramePr(); if ( 0 >= Count ) return { X : X0, Y : Y0, W : X1 - X0, H : Y1 - Y0 }; for ( var Index = 0; Index < Count; Index++ ) { var Para = Paras[Index]; var ParaPr = Para.Get_CompiledPr2(false).ParaPr; var Brd = ParaPr.Brd; var _X0 = X0 + ParaPr.Ind.Left + ParaPr.Ind.FirstLine; if ( undefined != Brd.Left && border_None != Brd.Left.Value ) _X0 -= Brd.Left.Size + Brd.Left.Space + 1; if ( _X0 < X0 ) X0 = _X0 var _X1 = X1 - ParaPr.Ind.Right; if ( undefined != Brd.Right && border_None != Brd.Right.Value ) _X1 += Brd.Right.Size + Brd.Right.Space + 1; if ( _X1 > X1 ) X1 = _X1; } var _Y1 = Y1; var BottomBorder = Paras[Count - 1].Get_CompiledPr2(false).ParaPr.Brd.Bottom; if ( undefined != BottomBorder && border_None != BottomBorder.Value ) _Y1 += BottomBorder.Size + BottomBorder.Space; if ( _Y1 > Y1 && ( heightrule_Auto === FramePr.HRule || ( heightrule_AtLeast === FramePr.HRule && FrameH >= FramePr.H ) ) ) Y1 = _Y1; return { X : X0, Y : Y0, W : X1 - X0, H : Y1 - Y0 }; }, Set_CalculatedFrame : function(L, T, W, H, L2, T2, W2, H2, PageIndex) { this.CalculatedFrame.T = T; this.CalculatedFrame.L = L; this.CalculatedFrame.W = W; this.CalculatedFrame.H = H; this.CalculatedFrame.T2 = T2; this.CalculatedFrame.L2 = L2; this.CalculatedFrame.W2 = W2; this.CalculatedFrame.H2 = H2; this.CalculatedFrame.PageIndex = PageIndex; }, Internal_Get_FrameParagraphs : function() { var FrameParas = new Array(); var FramePr = this.Get_FramePr(); if ( undefined === FramePr ) return FrameParas; FrameParas.push( this ); var Prev = this.Get_DocumentPrev(); while ( null != Prev ) { if ( type_Paragraph === Prev.GetType() ) { var PrevFramePr = Prev.Get_FramePr(); if ( undefined != PrevFramePr && true === FramePr.Compare( PrevFramePr ) ) { FrameParas.push( Prev ); Prev = Prev.Get_DocumentPrev(); } else break; } else break; } var Next = this.Get_DocumentNext(); while ( null != Next ) { if ( type_Paragraph === Next.GetType() ) { var NextFramePr = Next.Get_FramePr(); if ( undefined != NextFramePr && true === FramePr.Compare( NextFramePr ) ) { FrameParas.push( Next ); Next = Next.Get_DocumentNext(); } else break; } else break; } return FrameParas; }, Is_LineDropCap : function() { var FrameParas = this.Internal_Get_FrameParagraphs(); if ( 1 !== FrameParas.length || 1 !== this.Lines.length ) return false; return true; }, Get_LineDropCapWidth : function() { var W = this.Lines[0].Ranges[0].W; var ParaPr = this.Get_CompiledPr2(false).ParaPr; W += ParaPr.Ind.Left + ParaPr.Ind.FirstLine; return W; }, Change_Frame : function(X, Y, W, H, PageIndex) { var LogicDocument = editor.WordControl.m_oLogicDocument; var FramePr = this.Get_FramePr(); if ( undefined === FramePr || ( Math.abs( Y - this.CalculatedFrame.T ) < 0.001 && Math.abs( X - this.CalculatedFrame.L ) < 0.001 && Math.abs( W - this.CalculatedFrame.W ) < 0.001 && Math.abs( H - this.CalculatedFrame.H ) < 0.001 && PageIndex === this.CalculatedFrame.PageIndex ) ) return; var FrameParas = this.Internal_Get_FrameParagraphs(); if ( false === LogicDocument.Document_Is_SelectionLocked( changestype_None, { Type : changestype_2_ElementsArray_and_Type, Elements : FrameParas, CheckType : changestype_Paragraph_Content } ) ) { History.Create_NewPoint(); var NewFramePr = FramePr.Copy(); if ( Math.abs( X - this.CalculatedFrame.L ) > 0.001 ) { NewFramePr.X = X; NewFramePr.XAlign = undefined; NewFramePr.HAnchor = c_oAscHAnchor.Page; } if ( Math.abs( Y - this.CalculatedFrame.T ) > 0.001 ) { NewFramePr.Y = Y; NewFramePr.YAlign = undefined; NewFramePr.VAnchor = c_oAscVAnchor.Page; } if ( Math.abs( W - this.CalculatedFrame.W ) > 0.001 ) NewFramePr.W = W; if ( Math.abs( H - this.CalculatedFrame.H ) > 0.001 ) { if ( undefined != FramePr.DropCap && dropcap_None != FramePr.DropCap && 1 === FrameParas.length ) { var _H = Math.min( H, Page_Height ); NewFramePr.Lines = this.Update_DropCapByHeight( _H ); NewFramePr.HRule = linerule_Auto; } else { if ( H <= this.CalculatedFrame.H ) NewFramePr.HRule = linerule_Exact; else NewFramePr.HRule = linerule_AtLeast; NewFramePr.H = H; } } var Count = FrameParas.length; for ( var Index = 0; Index < Count; Index++ ) { var Para = FrameParas[Index]; Para.Set_FramePr( NewFramePr, false ); } LogicDocument.Recalculate(); LogicDocument.Document_UpdateInterfaceState(); } }, Supplement_FramePr : function(FramePr) { if ( undefined != FramePr.DropCap && dropcap_None != FramePr.DropCap ) { var _FramePr = this.Get_FramePr(); var FirstFramePara = this; var Prev = FirstFramePara.Get_DocumentPrev(); while ( null != Prev ) { if ( type_Paragraph === Prev.GetType() ) { var PrevFramePr = Prev.Get_FramePr(); if ( undefined != PrevFramePr && true === _FramePr.Compare( PrevFramePr ) ) { FirstFramePara = Prev; Prev = Prev.Get_DocumentPrev(); } else break; } else break; } var TextPr = FirstFramePara.Internal_CalculateTextPr(0); FramePr.FontFamily = { Name : TextPr.RFonts.Ascii.Name, Index : TextPr.RFonts.Ascii.Index }; } var FrameParas = this.Internal_Get_FrameParagraphs(); var Count = FrameParas.length; var ParaPr = FrameParas[0].Get_CompiledPr2(false).ParaPr.Copy(); for ( var Index = 1; Index < Count; Index++ ) { var TempPr= FrameParas[Index].Get_CompiledPr2(false).ParaPr; ParaPr = ParaPr.Compare(TempPr); } FramePr.Brd = ParaPr.Brd; FramePr.Shd = ParaPr.Shd; }, Can_AddDropCap : function() { var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { if ( para_Text === this.Content[Pos].Type ) return true; } return false; }, Split_DropCap : function(NewParagraph) { // Если есть выделение, тогда мы проверяем элементы, идущие до конца выделения, если есть что-то кроме текста // тогда мы добавляем в буквицу только первый текстовый элемент, иначе добавляем все от начала параграфа и до // конца выделения, кроме этого в буквицу добавляем все табы идущие в начале. var Count = this.Content.length; var EndPos = this.Selection.StartPos > this.Selection.EndPos ? this.Selection.StartPos : this.Selection.EndPos; var bSelection = false; var LastTextPr = null; if ( true === this.Selection.Use ) { var EndPos = Math.min( this.Selection.StartPos > this.Selection.EndPos ? this.Selection.StartPos : this.Selection.EndPos, this.Content.length ); bSelection = true; for (var Pos = 0; Pos < EndPos; Pos++ ) { var Type = this.Content[Pos].Type; if ( para_Text != Type && para_TextPr != Type && para_Tab != Type ) { bSelection = false; break; } else if ( para_TextPr === Type ) LastTextPr = this.Content[Pos]; } } if ( false === bSelection ) { var Pos = 0; for (; Pos < Count; Pos++ ) { var Type = this.Content[Pos].Type; if ( para_Text === Type ) break; else if ( para_TextPr === Type ) LastTextPr = this.Content[Pos]; } EndPos = Pos + 1; } for ( var Pos = 0; Pos < EndPos; Pos++ ) { NewParagraph.Internal_Content_Add(Pos, this.Content[Pos]); } var TextPr = this.Internal_CalculateTextPr(EndPos); this.Internal_Content_Remove2( 0, EndPos ); if ( null != LastTextPr ) this.Internal_Content_Add( 0, new ParaTextPr(LastTextPr.Value) ); return TextPr; }, Update_DropCapByLines : function(TextPr, Count, LineH, LineTA, LineTD) { // Мы должны сделать так, чтобы высота данного параграфа была точно Count * LineH this.Set_Spacing( { Before : 0, After : 0, LineRule : linerule_Exact, Line : Count * LineH - 0.001 }, false ); var FontSize = 72; TextPr.FontSize = FontSize; g_oTextMeasurer.SetTextPr(TextPr); g_oTextMeasurer.SetFontSlot(fontslot_ASCII, 1); var TDescent = null; var TAscent = null; var TempCount = this.Content.length; for ( var Index = 0; Index < TempCount; Index++ ) { var Item = this.Content[Index]; if ( para_Text === Item.Type ) { var Temp = g_oTextMeasurer.Measure2( Item.Value ); if ( null === TAscent || TAscent < Temp.Ascent ) TAscent = Temp.Ascent; if ( null === TDescent || TDescent > Temp.Ascent - Temp.Height ) TDescent = Temp.Ascent - Temp.Height; } } var THeight = 0; if ( null === TAscent || null === TDescent ) THeight = g_oTextMeasurer.GetHeight(); else THeight = -TDescent + TAscent; var EmHeight = THeight; var NewEmHeight = (Count - 1) * LineH + LineTA; var Koef = NewEmHeight / EmHeight; var NewFontSize = TextPr.FontSize * Koef; TextPr.FontSize = parseInt(NewFontSize * 2) / 2; g_oTextMeasurer.SetTextPr(TextPr); g_oTextMeasurer.SetFontSlot(fontslot_ASCII, 1); var TNewDescent = null; var TNewAscent = null; var TempCount = this.Content.length; for ( var Index = 0; Index < TempCount; Index++ ) { var Item = this.Content[Index]; if ( para_Text === Item.Type ) { var Temp = g_oTextMeasurer.Measure2( Item.Value ); if ( null === TNewAscent || TNewAscent < Temp.Ascent ) TNewAscent = Temp.Ascent; if ( null === TNewDescent || TNewDescent > Temp.Ascent - Temp.Height ) TNewDescent = Temp.Ascent - Temp.Height; } } var TNewHeight = 0; if ( null === TNewAscent || null === TNewDescent ) TNewHeight = g_oTextMeasurer.GetHeight(); else TNewHeight = -TNewDescent + TNewAscent; var Descent = g_oTextMeasurer.GetDescender(); var Ascent = g_oTextMeasurer.GetAscender(); var Dy = Descent * (LineH * Count) / ( Ascent - Descent ) + TNewHeight - TNewAscent + LineTD; var PTextPr = new ParaTextPr( { RFonts : { Ascii : { Name : TextPr.RFonts.Ascii.Name, Index : -1 } }, FontSize : TextPr.FontSize, Position : Dy } ); this.Select_All(); this.Add( PTextPr ); this.Selection_Remove(); }, Update_DropCapByHeight : function(Height) { // Ищем следующий параграф, к которому относится буквица var AnchorPara = this.Get_FrameAnchorPara(); if ( null === AnchorPara || AnchorPara.Lines.length <= 0 ) return 1; this.Set_Spacing( { LineRule : linerule_Exact, Line : Height }, false ); var LineH = AnchorPara.Lines[0].Bottom - AnchorPara.Lines[0].Top; var LineTA = AnchorPara.Lines[0].Metrics.TextAscent2; var LineTD = AnchorPara.Lines[0].Metrics.TextDescent + AnchorPara.Lines[0].Metrics.LineGap; // Посчитаем количество строк var LinesCount = Math.ceil( Height / LineH ); var TextPr = this.Internal_CalculateTextPr(this.Internal_GetStartPos()); g_oTextMeasurer.SetTextPr(TextPr); g_oTextMeasurer.SetFontSlot(fontslot_ASCII, 1); var TDescent = null; var TAscent = null; var TempCount = this.Content.length; for ( var Index = 0; Index < TempCount; Index++ ) { var Item = this.Content[Index]; if ( para_Text === Item.Type ) { var Temp = g_oTextMeasurer.Measure2( Item.Value ); if ( null === TAscent || TAscent < Temp.Ascent ) TAscent = Temp.Ascent; if ( null === TDescent || TDescent > Temp.Ascent - Temp.Height ) TDescent = Temp.Ascent - Temp.Height; } } var THeight = 0; if ( null === TAscent || null === TDescent ) THeight = g_oTextMeasurer.GetHeight(); else THeight = -TDescent + TAscent; var Koef = (Height - LineTD) / THeight; var NewFontSize = TextPr.FontSize * Koef; TextPr.FontSize = parseInt(NewFontSize * 2) / 2; g_oTextMeasurer.SetTextPr(TextPr); g_oTextMeasurer.SetFontSlot(fontslot_ASCII, 1); var TNewDescent = null; var TNewAscent = null; var TempCount = this.Content.length; for ( var Index = 0; Index < TempCount; Index++ ) { var Item = this.Content[Index]; if ( para_Text === Item.Type ) { var Temp = g_oTextMeasurer.Measure2( Item.Value ); if ( null === TNewAscent || TNewAscent < Temp.Ascent ) TNewAscent = Temp.Ascent; if ( null === TNewDescent || TNewDescent > Temp.Ascent - Temp.Height ) TNewDescent = Temp.Ascent - Temp.Height; } } var TNewHeight = 0; if ( null === TNewAscent || null === TNewDescent ) TNewHeight = g_oTextMeasurer.GetHeight(); else TNewHeight = -TNewDescent + TNewAscent; var Descent = g_oTextMeasurer.GetDescender(); var Ascent = g_oTextMeasurer.GetAscender(); var Dy = Descent * (Height) / ( Ascent - Descent ) + TNewHeight - TNewAscent + LineTD; var PTextPr = new ParaTextPr( { RFonts : { Ascii : { Name : TextPr.RFonts.Ascii.Name, Index : -1 } }, FontSize : TextPr.FontSize, Position : Dy } ); this.Select_All(); this.Add( PTextPr ); this.Selection_Remove(); return LinesCount; }, Get_FrameAnchorPara : function() { var FramePr = this.Get_FramePr(); if ( undefined === FramePr ) return null; var Next = this.Get_DocumentNext(); while ( null != Next ) { if ( type_Paragraph === Next.GetType() ) { var NextFramePr = Next.Get_FramePr(); if ( undefined === NextFramePr || false === FramePr.Compare( NextFramePr ) ) return Next; } Next = Next.Get_DocumentNext(); } return Next; }, // Разделяем данный параграф Split : function(NewParagraph, Pos) { if ( "undefined" === typeof(Pos) || null === Pos ) Pos = this.CurPos.ContentPos; // Копируем контент, начиная с текущей позиции в параграфе до конца параграфа, // в новый параграф (первым элементом выставляем настройки текста, рассчитанные // для текущей позиции). Проверим, находится ли данная позиция внутри гиперссылки, // если да, тогда в текущем параграфе закрываем гиперссылку, а в новом создаем ее копию. var Hyperlink = this.Check_Hyperlink2( Pos, false ); var TextPr = this.Internal_CalculateTextPr( Pos ); NewParagraph.DeleteCommentOnRemove = false; NewParagraph.Internal_Content_Remove2(0, NewParagraph.Content.length); NewParagraph.Internal_Content_Concat( this.Content.slice( Pos ) ); NewParagraph.Internal_Content_Add( 0, new ParaTextPr( TextPr ) ); NewParagraph.Set_ContentPos( 0 ); NewParagraph.DeleteCommentOnRemove = true; NewParagraph.TextPr.Value = this.TextPr.Value.Copy(); if ( null != Hyperlink ) NewParagraph.Internal_Content_Add( 1, Hyperlink.Copy() ); // Удаляем все элементы после текущей позиции и добавляем признак окончания параграфа. this.DeleteCommentOnRemove = false; this.Internal_Remove_CollaborativeMarks(); this.Internal_Content_Remove2( Pos, this.Content.length - Pos ); this.DeleteCommentOnRemove = true; if ( null != Hyperlink ) { // Добавляем конец гиперссылки и пустые текстовые настройки this.Internal_Content_Add( this.Content.length, new ParaHyperlinkEnd() ); this.Internal_Content_Add( this.Content.length, new ParaTextPr() ); } this.Internal_Content_Add( this.Content.length, new ParaEnd() ); this.Internal_Content_Add( this.Content.length, new ParaEmpty() ); // Копируем все настройки в новый параграф. Делаем это после того как определили контент параграфов. this.CopyPr( NewParagraph ); this.RecalcInfo.Set_Type_0(pararecalc_0_All); NewParagraph.RecalcInfo.Set_Type_0(pararecalc_0_All); }, // Присоединяем контент параграфа Para к текущему параграфу Concat : function(Para) { this.DeleteCommentOnRemove = false; this.Internal_Content_Remove2( this.Content.length - 2, 2 ); this.DeleteCommentOnRemove = true; // Убираем нумерацию, если она была у следующего параграфа Para.Numbering_Remove(); Para.Remove_PresentationNumbering(); this.Internal_Content_Concat( Para.Content ); this.RecalcInfo.Set_Type_0(pararecalc_0_All); }, // Копируем настройки параграфа и последние текстовые настройки в новый параграф Continue : function(NewParagraph) { // Копируем настройки параграфа this.CopyPr( NewParagraph ); // Копируем последние настройки текста var TextPr = this.Internal_CalculateTextPr( this.Internal_GetEndPos() ); NewParagraph.Internal_Content_Add( 0, new ParaTextPr( TextPr ) ); NewParagraph.TextPr.Value = this.TextPr.Value.Copy(); }, //----------------------------------------------------------------------------------- // Undo/Redo функции //----------------------------------------------------------------------------------- Undo : function(Data) { var Type = Data.Type; switch ( Type ) { case historyitem_Paragraph_AddItem: { var StartPos = this.Internal_Get_RealPos( Data.Pos ); var EndPos = this.Internal_Get_RealPos( Data.EndPos ); this.Content.splice( StartPos, EndPos - StartPos + 1 ); break; } case historyitem_Paragraph_RemoveItem: { var Pos = this.Internal_Get_RealPos( Data.Pos ); var Array_start = this.Content.slice( 0, Pos ); var Array_end = this.Content.slice( Pos ); this.Content = Array_start.concat( Data.Items, Array_end ); break; } case historyitem_Paragraph_Numbering: { var Old = Data.Old; if ( undefined != Old ) this.Pr.NumPr = Old; else this.Pr.NumPr = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Align: { this.Pr.Jc = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_First: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaSpacing(); this.Pr.Ind.FirstLine = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Left: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaSpacing(); this.Pr.Ind.Left = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Right: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaSpacing(); this.Pr.Ind.Right = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_ContextualSpacing: { this.Pr.ContextualSpacing = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepLines: { this.Pr.KeepLines = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepNext: { this.Pr.KeepNext = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PageBreakBefore: { this.Pr.PageBreakBefore = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Line: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.Line = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_LineRule: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.LineRule = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Before: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.Before = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_After: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.After = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_AfterAutoSpacing: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.AfterAutoSpacing = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_BeforeAutoSpacing: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.BeforeAutoSpacing = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Value: { if ( undefined != Data.Old && undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( undefined != Data.Old ) this.Pr.Shd.Value = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Color: { if ( undefined != Data.Old && undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( undefined != Data.Old ) this.Pr.Shd.Color = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd: { this.Pr.Shd = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_WidowControl: { this.Pr.WidowControl = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Tabs: { this.Pr.Tabs = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PStyle: { var Old = Data.Old; if ( undefined != Old ) this.Pr.PStyle = Old; else this.Pr.PStyle = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_DocNext: { this.Next = Data.Old; break; } case historyitem_Paragraph_DocPrev: { this.Prev = Data.Old; break; } case historyitem_Paragraph_Parent: { this.Parent = Data.Old; break; } case historyitem_Paragraph_Borders_Between: { this.Pr.Brd.Between = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Bottom: { this.Pr.Brd.Bottom = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Left: { this.Pr.Brd.Left = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Right: { this.Pr.Brd.Right = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Top: { this.Pr.Brd.Top = Data.Old; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Pr: { var Old = Data.Old; if ( undefined != Old ) this.Pr = Old; else this.Pr = new CParaPr(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PresentationPr_Bullet: { this.PresentationPr.Bullet = Data.Old; break; } case historyitem_Paragraph_PresentationPr_Level: { this.PresentationPr.Level = Data.Old; break; } case historyitem_Paragraph_FramePr: { this.Pr.FramePr = Data.Old; this.CompiledPr.NeedRecalc = true; break; } } this.RecalcInfo.Set_Type_0(pararecalc_0_All); this.RecalcInfo.Set_Type_0_Spell(pararecalc_0_Spell_All); }, Redo : function(Data) { var Type = Data.Type; switch ( Type ) { case historyitem_Paragraph_AddItem: { var Pos = this.Internal_Get_RealPos( Data.Pos ); var Array_start = this.Content.slice( 0, Pos ); var Array_end = this.Content.slice( Pos ); this.Content = Array_start.concat( Data.Items, Array_end ); break; } case historyitem_Paragraph_RemoveItem: { var StartPos = this.Internal_Get_RealPos( Data.Pos ); var EndPos = this.Internal_Get_RealPos( Data.EndPos ); this.Content.splice( StartPos, EndPos - StartPos + 1 ); break; } case historyitem_Paragraph_Numbering: { var New = Data.New; if ( undefined != New ) this.Pr.NumPr = New; else this.Pr.NumPr = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Align: { this.Pr.Jc = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_First: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); this.Pr.Ind.FirstLine = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Left: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); this.Pr.Ind.Left = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Right: { if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); this.Pr.Ind.Right = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_ContextualSpacing: { this.Pr.ContextualSpacing = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepLines: { this.Pr.KeepLines = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepNext: { this.Pr.KeepNext = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PageBreakBefore: { this.Pr.PageBreakBefore = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Line: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.Line = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_LineRule: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.LineRule = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Before: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.Before = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_After: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.After = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_AfterAutoSpacing: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.AfterAutoSpacing = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_BeforeAutoSpacing: { if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); this.Pr.Spacing.BeforeAutoSpacing = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Value: { if ( undefined != Data.New && undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( undefined != Data.New ) this.Pr.Shd.Value = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Color: { if ( undefined != Data.New && undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); if ( undefined != Data.New ) this.Pr.Shd.Color = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd: { this.Pr.Shd = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_WidowControl: { this.Pr.WidowControl = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Tabs: { this.Pr.Tabs = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PStyle: { var New = Data.New; if ( undefined != New ) this.Pr.PStyle = New; else this.Pr.PStyle = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_DocNext: { this.Next = Data.New; break; } case historyitem_Paragraph_DocPrev: { this.Prev = Data.New; break; } case historyitem_Paragraph_Parent: { this.Parent = Data.New; break; } case historyitem_Paragraph_Borders_Between: { this.Pr.Brd.Between = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Bottom: { this.Pr.Brd.Bottom = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Left: { this.Pr.Brd.Left = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Right: { this.Pr.Brd.Right = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Top: { this.Pr.Brd.Top = Data.New; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Pr: { var New = Data.New; if ( undefined != New ) this.Pr = New; else this.Pr = new CParaPr(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PresentationPr_Bullet: { this.PresentationPr.Bullet = Data.New; break; } case historyitem_Paragraph_PresentationPr_Level: { this.PresentationPr.Level = Data.New; break; } case historyitem_Paragraph_FramePr: { this.Pr.FramePr = Data.New; this.CompiledPr.NeedRecalc = true; break; } } this.RecalcInfo.Set_Type_0(pararecalc_0_All); this.RecalcInfo.Set_Type_0_Spell(pararecalc_0_Spell_All); }, Get_SelectionState : function() { var ParaState = new Object(); ParaState.CurPos = { X : this.CurPos.X, Y : this.CurPos.Y, Line : this.CurPos.Line, ContentPos : this.Internal_Get_ClearPos(this.CurPos.ContentPos), RealX : this.CurPos.RealX, RealY : this.CurPos.RealY, PagesPos : this.CurPos.PagesPos }; ParaState.Selection = { Start : this.Selection.Start, Use : this.Selection.Use, StartPos : this.Internal_Get_ClearPos(this.Selection.StartPos), EndPos : this.Internal_Get_ClearPos(this.Selection.EndPos), Flag : this.Selection.Flag }; return [ ParaState ]; }, Set_SelectionState : function(State, StateIndex) { if ( State.length <= 0 ) return; var ParaState = State[StateIndex]; this.CurPos = { X : ParaState.CurPos.X, Y : ParaState.CurPos.Y, Line : ParaState.CurPos.Line, ContentPos : this.Internal_Get_RealPos(ParaState.CurPos.ContentPos), RealX : ParaState.CurPos.RealX, RealY : ParaState.CurPos.RealY, PagesPos : ParaState.CurPos.PagesPos }; this.Selection = { Start : ParaState.Selection.Start, Use : ParaState.Selection.Use, StartPos : this.Internal_Get_RealPos(ParaState.Selection.StartPos), EndPos : this.Internal_Get_RealPos(ParaState.Selection.EndPos), Flag : ParaState.Selection.Flag }; var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); this.Set_ContentPos( Math.max( CursorPos_min, Math.min( CursorPos_max, this.CurPos.ContentPos ) ) ); this.Selection.StartPos = Math.max( CursorPos_min, Math.min( CursorPos_max, this.Selection.StartPos ) ); this.Selection.EndPos = Math.max( CursorPos_min, Math.min( CursorPos_max, this.Selection.EndPos ) ); }, Get_ParentObject_or_DocumentPos : function() { return this.Parent.Get_ParentObject_or_DocumentPos(this.Index); }, Refresh_RecalcData : function(Data) { var Type = Data.Type; var bNeedRecalc = false; var CurPage = 0; switch ( Type ) { case historyitem_Paragraph_AddItem: case historyitem_Paragraph_RemoveItem: { for ( CurPage = this.Pages.length - 1; CurPage > 0; CurPage-- ) { if ( Data.Pos > this.Lines[this.Pages[CurPage].StartLine].StartPos ) break; } this.RecalcInfo.Set_Type_0(pararecalc_0_All); bNeedRecalc = true; break; } case historyitem_Paragraph_Numbering: case historyitem_Paragraph_PStyle: case historyitem_Paragraph_Pr: case historyitem_Paragraph_PresentationPr_Bullet: case historyitem_Paragraph_PresentationPr_Level: { this.RecalcInfo.Set_Type_0(pararecalc_0_All); bNeedRecalc = true; break; } case historyitem_Paragraph_Align: case historyitem_Paragraph_Ind_First: case historyitem_Paragraph_Ind_Left: case historyitem_Paragraph_Ind_Right: case historyitem_Paragraph_ContextualSpacing: case historyitem_Paragraph_KeepLines: case historyitem_Paragraph_KeepNext: case historyitem_Paragraph_PageBreakBefore: case historyitem_Paragraph_Spacing_Line: case historyitem_Paragraph_Spacing_LineRule: case historyitem_Paragraph_Spacing_Before: case historyitem_Paragraph_Spacing_After: case historyitem_Paragraph_Spacing_AfterAutoSpacing: case historyitem_Paragraph_Spacing_BeforeAutoSpacing: case historyitem_Paragraph_WidowControl: case historyitem_Paragraph_Tabs: case historyitem_Paragraph_Parent: case historyitem_Paragraph_Borders_Between: case historyitem_Paragraph_Borders_Bottom: case historyitem_Paragraph_Borders_Left: case historyitem_Paragraph_Borders_Right: case historyitem_Paragraph_Borders_Top: case historyitem_Paragraph_FramePr: { bNeedRecalc = true; break; } case historyitem_Paragraph_Shd_Value: case historyitem_Paragraph_Shd_Color: case historyitem_Paragraph_Shd: case historyitem_Paragraph_DocNext: case historyitem_Paragraph_DocPrev: { // Пересчитывать этот элемент не надо при таких изменениях break; } } if ( true === bNeedRecalc ) { // Сообщаем родительскому классу, что изменения произошли в элементе с номером this.Index и на странице this.PageNum return this.Refresh_RecalcData2(CurPage); } }, Refresh_RecalcData2 : function(CurPage) { if ( undefined === CurPage ) CurPage = 0; // Если Index < 0, значит данный элемент еще не был добавлен в родительский класс if ( this.Index >= 0 ) this.Parent.Refresh_RecalcData2( this.Index, this.PageNum + CurPage ); }, Check_HistoryUninon : function(Data1, Data2) { var Type1 = Data1.Type; var Type2 = Data2.Type; if ( historyitem_Paragraph_AddItem === Type1 && historyitem_Paragraph_AddItem === Type2 ) { if ( 1 === Data1.Items.length && 1 === Data2.Items.length && Data1.Pos === Data2.Pos - 1 && para_Text === Data1.Items[0].Type && para_Text === Data2.Items[0].Type ) return true; } return false; }, //----------------------------------------------------------------------------------- // Функции для совместного редактирования //----------------------------------------------------------------------------------- Document_Is_SelectionLocked : function(CheckType) { switch ( CheckType ) { case changestype_Paragraph_Content: case changestype_Paragraph_Properties: case changestype_Document_Content: case changestype_Document_Content_Add: case changestype_Image_Properties: { this.Lock.Check( this.Get_Id() ); break; } case changestype_Remove: { // Если у нас нет выделения, и курсор стоит в начале, мы должны проверить в том же порядке, в каком // идут проверки при удалении в команде Internal_Remove_Backward. if ( true != this.Selection.Use && true == this.Cursor_IsStart() ) { var Pr = this.Get_CompiledPr2(false).ParaPr; if ( undefined != this.Numbering_Get() || Math.abs(Pr.Ind.FirstLine) > 0.001 || Math.abs(Pr.Ind.Left) > 0.001 ) { // Надо проверить только текущий параграф, а это будет сделано далее } else { var Prev = this.Get_DocumentPrev(); if ( null != Prev && type_Paragraph === Prev.GetType() ) Prev.Lock.Check( Prev.Get_Id() ); } } // Если есть выделение, и знак параграфа попал в выделение ( и параграф выделен не целиком ) else if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( EndPos >= this.Content.length - 1 && StartPos > this.Internal_GetStartPos() ) { var Next = this.Get_DocumentNext(); if ( null != Next && type_Paragraph === Next.GetType() ) Next.Lock.Check( Next.Get_Id() ); } } this.Lock.Check( this.Get_Id() ); break; } case changestype_Delete: { // Если у нас нет выделения, и курсор стоит в конце, мы должны проверить следующий элемент if ( true != this.Selection.Use && true === this.Cursor_IsEnd() ) { var Next = this.Get_DocumentNext(); if ( null != Next && type_Paragraph === Next.GetType() ) Next.Lock.Check( Next.Get_Id() ); } // Если есть выделение, и знак параграфа попал в выделение и параграф выделен не целиком else if ( true === this.Selection.Use ) { var StartPos = this.Selection.StartPos; var EndPos = this.Selection.EndPos; if ( StartPos > EndPos ) { var Temp = EndPos; EndPos = StartPos; StartPos = Temp; } if ( EndPos >= this.Content.length - 1 && StartPos > this.Internal_GetStartPos() ) { var Next = this.Get_DocumentNext(); if ( null != Next && type_Paragraph === Next.GetType() ) Next.Lock.Check( Next.Get_Id() ); } } this.Lock.Check( this.Get_Id() ); break; } case changestype_Document_SectPr: case changestype_Table_Properties: case changestype_Table_RemoveCells: case changestype_HdrFtr: { CollaborativeEditing.Add_CheckLock(true); break; } } }, Save_Changes : function(Data, Writer) { // Сохраняем изменения из тех, которые используются для Undo/Redo в бинарный файл. // Long : тип класса // Long : тип изменений Writer.WriteLong( historyitem_type_Paragraph ); var Type = Data.Type; // Пишем тип Writer.WriteLong( Type ); switch ( Type ) { case historyitem_Paragraph_AddItem: { // Long : Количество элементов // Array of : // { // Long : Позиция // Variable : Элемент // } var bArray = Data.UseArray; var Count = Data.Items.length; Writer.WriteLong( Count ); for ( var Index = 0; Index < Count; Index++ ) { if ( true === bArray ) Writer.WriteLong( Data.PosArray[Index] ); else Writer.WriteLong( Data.Pos + Index ); Data.Items[Index].Write_ToBinary(Writer); } break; } case historyitem_Paragraph_RemoveItem: { // Long : Количество удаляемых элементов // Array of Long : позиции удаляемых элементов var bArray = Data.UseArray; var Count = Data.Items.length; var StartPos = Writer.GetCurPosition(); Writer.Skip(4); var RealCount = Count; for ( var Index = 0; Index < Count; Index++ ) { if ( true === bArray ) { if ( false === Data.PosArray[Index] ) RealCount--; else Writer.WriteLong( Data.PosArray[Index] ); } else Writer.WriteLong( Data.Pos ); } var EndPos = Writer.GetCurPosition(); Writer.Seek( StartPos ); Writer.WriteLong( RealCount ); Writer.Seek( EndPos ); break; } case historyitem_Paragraph_Numbering: { // Bool : IsUndefined // Если false // Variable : NumPr (CNumPr) if ( undefined === Data.New ) Writer.WriteBool( true ); else { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } break; } case historyitem_Paragraph_Ind_First: case historyitem_Paragraph_Ind_Left: case historyitem_Paragraph_Ind_Right: case historyitem_Paragraph_Spacing_Line: case historyitem_Paragraph_Spacing_Before: case historyitem_Paragraph_Spacing_After: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === Data.New ) { Writer.WriteBool( true ); } else { Writer.WriteBool( false ); Writer.WriteDouble( Data.New ); } break; } case historyitem_Paragraph_Align: case historyitem_Paragraph_Spacing_LineRule: { // Bool : IsUndefined // Если false // Long : Value if ( undefined === Data.New ) { Writer.WriteBool( true ); } else { Writer.WriteBool( false ); Writer.WriteLong( Data.New ); } break; } case historyitem_Paragraph_ContextualSpacing: case historyitem_Paragraph_KeepLines: case historyitem_Paragraph_KeepNext: case historyitem_Paragraph_PageBreakBefore: case historyitem_Paragraph_Spacing_AfterAutoSpacing: case historyitem_Paragraph_Spacing_BeforeAutoSpacing: case historyitem_Paragraph_WidowControl: { // Bool : IsUndefined // Если false // Bool : Value if ( undefined === Data.New ) { Writer.WriteBool( true ); } else { Writer.WriteBool( false ); Writer.WriteBool( Data.New ); } break; } case historyitem_Paragraph_Shd_Value: { // Bool : IsUndefined // Если false // Byte : Value var New = Data.New; if ( undefined != New ) { Writer.WriteBool( false ); Writer.WriteByte( Data.New ); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_Shd_Color: { // Bool : IsUndefined // Если false // Variable : Color (CDocumentColor) var New = Data.New; if ( undefined != New ) { Writer.WriteBool( false ); Data.New.Write_ToBinary(Writer); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_Shd: { // Bool : IsUndefined // Если false // Variable : Shd (CDocumentShd) var New = Data.New; if ( undefined != New ) { Writer.WriteBool( false ); Data.New.Write_ToBinary(Writer); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_Tabs: { // Bool : IsUndefined // Есди false // Variable : CParaTabs if ( undefined != Data.New ) { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } else Writer.WriteBool(true); break; } case historyitem_Paragraph_PStyle: { // Bool : Удаляем ли // Если false // String : StyleId if ( undefined != Data.New ) { Writer.WriteBool( false ); Writer.WriteString2( Data.New ); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_DocNext: case historyitem_Paragraph_DocPrev: case historyitem_Paragraph_Parent: { // String : Id элемента if ( null != Data.New ) Writer.WriteString2( Data.New.Get_Id() ); else Writer.WriteString2( "" ); break; } case historyitem_Paragraph_Borders_Between: case historyitem_Paragraph_Borders_Bottom: case historyitem_Paragraph_Borders_Left: case historyitem_Paragraph_Borders_Right: case historyitem_Paragraph_Borders_Top: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( undefined != Data.New ) { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } else Writer.WriteBool( true ); break; } case historyitem_Paragraph_Pr: { // Bool : удаляем ли if ( undefined === Data.New ) Writer.WriteBool( true ); else { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } break; } case historyitem_Paragraph_PresentationPr_Bullet: { // Variable : Bullet Data.New.Write_ToBinary( Writer ); break; } case historyitem_Paragraph_PresentationPr_Level: { // Long : Level Writer.WriteLong( Data.New ); break; } case historyitem_Paragraph_FramePr: { // Bool : IsUndefined // false -> // Variable : CFramePr if ( undefined === Data.New ) Writer.WriteBool( true ); else { Writer.WriteBool( false ); Data.New.Write_ToBinary( Writer ); } break; } } return Writer; }, Load_Changes : function(Reader) { // Сохраняем изменения из тех, которые используются для Undo/Redo в бинарный файл. // Long : тип класса // Long : тип изменений var ClassType = Reader.GetLong(); if ( historyitem_type_Paragraph != ClassType ) return; var Type = Reader.GetLong(); switch ( Type ) { case historyitem_Paragraph_AddItem: { // Long : Количество элементов // Array of : // { // Long : Позиция // Variable : Элемент // } var Count = Reader.GetLong(); for ( var Index = 0; Index < Count; Index++ ) { var Pos = this.Internal_Get_RealPos( this.m_oContentChanges.Check( contentchanges_Add, Reader.GetLong() ) ); var Element = ParagraphContent_Read_FromBinary(Reader); if ( null != Element ) { if ( Element instanceof ParaCommentStart ) { var Comment = g_oTableId.Get_ById( Element.Id ); if ( null != Comment ) Comment.Set_StartInfo( 0, 0, 0, 0, this.Get_Id() ); } else if ( Element instanceof ParaCommentEnd ) { var Comment = g_oTableId.Get_ById( Element.Id ); if ( null != Comment ) Comment.Set_EndInfo( 0, 0, 0, 0, this.Get_Id() ); } // TODO: Подумать над тем как по минимуму вставлять отметки совместного редактирования this.Content.splice( Pos, 0, new ParaCollaborativeChangesEnd() ); this.Content.splice( Pos, 0, Element ); this.Content.splice( Pos, 0, new ParaCollaborativeChangesStart() ); CollaborativeEditing.Add_ChangedClass(this); } } this.DeleteCollaborativeMarks = false; break; } case historyitem_Paragraph_RemoveItem: { // Long : Количество удаляемых элементов // Array of Long : позиции удаляемых элементов var Count = Reader.GetLong(); for ( var Index = 0; Index < Count; Index++ ) { var ChangesPos = this.m_oContentChanges.Check( contentchanges_Remove, Reader.GetLong() ); // действие совпало, не делаем его if ( false === ChangesPos ) continue; var Pos = this.Internal_Get_RealPos( ChangesPos ); this.Content.splice( Pos, 1 ); } break; } case historyitem_Paragraph_Numbering: { // Bool : IsUndefined // Если false // Variable : NumPr (CNumPr) if ( true === Reader.GetBool() ) this.Pr.NumPr = undefined; else { this.Pr.NumPr = new CNumPr(); this.Pr.NumPr.Read_FromBinary(Reader); } this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Align: { // Bool : IsUndefined // Если false // Long : Value if ( true === Reader.GetBool() ) this.Pr.Jc = undefined; else this.Pr.Jc = Reader.GetLong(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_First: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); if ( true === Reader.GetBool() ) this.Pr.Ind.FirstLine = undefined; else this.Pr.Ind.FirstLine = Reader.GetDouble(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Left: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); if ( true === Reader.GetBool() ) this.Pr.Ind.Left = undefined; else this.Pr.Ind.Left = Reader.GetDouble(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Ind_Right: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Ind ) this.Pr.Ind = new CParaInd(); if ( true === Reader.GetBool() ) this.Pr.Ind.Right = undefined; else this.Pr.Ind.Right = Reader.GetDouble(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_ContextualSpacing: { // Bool : IsUndefined // Если false // Bool : Value if ( true === Reader.GetBool() ) this.Pr.ContextualSpacing = undefined; else this.Pr.ContextualSpacing = Reader.GetBool(); this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepLines: { // Bool : IsUndefined // Если false // Bool : Value if ( false === Reader.GetBool() ) this.Pr.KeepLines = Reader.GetBool(); else this.Pr.KeepLines = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_KeepNext: { // Bool : IsUndefined // Если false // Bool : Value if ( false === Reader.GetBool() ) this.Pr.KeepNext = Reader.GetLong(); else this.Pr.KeepNext = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PageBreakBefore: { // Bool : IsUndefined // Если false // Bool : Value if ( false === Reader.GetBool() ) this.Pr.PageBreakBefore = Reader.GetBool(); else this.Pr.PageBreakBefore = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Line: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.Line = Reader.GetDouble(); else this.Pr.Spacing.Line = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_LineRule: { // Bool : IsUndefined // Если false // Long : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.LineRule = Reader.GetLong(); else this.Pr.Spacing.LineRule = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_Before: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.Before = Reader.GetDouble(); else this.Pr.Spacing.Before = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_After: { // Bool : IsUndefined // Если false // Double : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.After = Reader.GetDouble(); else this.Pr.Spacing.After = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_AfterAutoSpacing: { // Bool : IsUndefined // Если false // Bool : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.AfterAutoSpacing = Reader.GetBool(); else this.Pr.Spacing.AfterAutoSpacing = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Spacing_BeforeAutoSpacing: { // Bool : IsUndefined // Если false // Bool : Value if ( undefined === this.Pr.Spacing ) this.Pr.Spacing = new CParaSpacing(); if ( false === Reader.GetBool() ) this.Pr.Spacing.AfterAutoSpacing = Reader.GetBool(); else this.Pr.Spacing.BeforeAutoSpacing = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Value: { // Bool : IsUndefined // Если false // Byte : Value if ( false === Reader.GetBool() ) { if ( undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); this.Pr.Shd.Value = Reader.GetByte(); } else if ( undefined != this.Pr.Shd ) this.Pr.Shd.Value = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd_Color: { // Bool : IsUndefined // Если false // Variable : Color (CDocumentColor) if ( false === Reader.GetBool() ) { if ( undefined === this.Pr.Shd ) this.Pr.Shd = new CDocumentShd(); this.Pr.Shd.Color = new CDocumentColor(0,0,0); this.Pr.Shd.Color.Read_FromBinary(Reader); } else if ( undefined != this.Pr.Shd ) this.Pr.Shd.Color = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Shd: { // Bool : IsUndefined // Если false // Byte : Value if ( false === Reader.GetBool() ) { this.Pr.Shd = new CDocumentShd(); this.Pr.Shd.Read_FromBinary( Reader ); } else this.Pr.Shd = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_WidowControl: { // Bool : IsUndefined // Если false // Bool : Value if ( false === Reader.GetBool() ) this.Pr.WidowControl = Reader.GetBool(); else this.Pr.WidowControl = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Tabs: { // Bool : IsUndefined // Есди false // Variable : CParaTabs if ( false === Reader.GetBool() ) { this.Pr.Tabs = new CParaTabs(); this.Pr.Tabs.Read_FromBinary( Reader ); } else this.Pr.Tabs = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PStyle: { // Bool : Удаляем ли // Если false // String : StyleId if ( false === Reader.GetBool() ) this.Pr.PStyle = Reader.GetString2(); else this.Pr.PStyle = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_DocNext: { // String : Id элемента //this.Next = g_oTableId.Get_ById( Reader.GetString2() ); break; } case historyitem_Paragraph_DocPrev: { // String : Id элемента //this.Prev = g_oTableId.Get_ById( Reader.GetString2() ); break; } case historyitem_Paragraph_Parent: { // String : Id элемента this.Parent = g_oTableId.Get_ById( Reader.GetString2() ); break; } case historyitem_Paragraph_Borders_Between: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Between = new CDocumentBorder(); this.Pr.Brd.Between.Read_FromBinary( Reader ); } else this.Pr.Brd.Between = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Bottom: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Bottom = new CDocumentBorder(); this.Pr.Brd.Bottom.Read_FromBinary( Reader ); } else this.Pr.Brd.Bottom = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Left: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Left = new CDocumentBorder(); this.Pr.Brd.Left.Read_FromBinary( Reader ); } else this.Pr.Brd.Left = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Right: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Right = new CDocumentBorder(); this.Pr.Brd.Right.Read_FromBinary( Reader ); } else this.Pr.Brd.Right = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Borders_Top: { // Bool : IsUndefined // если false // Variable : Border (CDocumentBorder) if ( false === Reader.GetBool() ) { this.Pr.Brd.Top = new CDocumentBorder(); this.Pr.Brd.Top.Read_FromBinary( Reader ); } else this.Pr.Brd.Top = undefined; this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_Pr: { // Bool : IsUndefined if ( true === Reader.GetBool() ) this.Pr = new CParaPr(); else { this.Pr = new CParaPr(); this.Pr.Read_FromBinary( Reader ); } this.CompiledPr.NeedRecalc = true; break; } case historyitem_Paragraph_PresentationPr_Bullet: { // Variable : Bullet var Bullet = new CPresentationBullet(); Bullet.Read_FromBinary( Reader ); this.PresentationPr.Bullet = Bullet; break; } case historyitem_Paragraph_PresentationPr_Level: { // Long : Level this.PresentationPr.Level = Reader.GetLong(); break; } case historyitem_Paragraph_FramePr: { // Bool : IsUndefined // false -> // Variable : CFramePr if ( false === Reader.GetBool() ) { this.Pr.FramePr = new CFramePr(); this.Pr.FramePr.Read_FromBinary( Reader ); } else { this.Pr.FramePr = undefined; } this.CompiledPr.NeedRecalc = true; break; } } this.RecalcInfo.Set_Type_0(pararecalc_0_All); this.RecalcInfo.Set_Type_0_Spell(pararecalc_0_Spell_All); }, Write_ToBinary2 : function(Writer) { Writer.WriteLong( historyitem_type_Paragraph ); // String : Id // String : Id родительского класса // Variable : ParaPr // String : Id TextPr // Long : количество элементов, у которых Is_RealContent = true Writer.WriteString2( "" + this.Id ); Writer.WriteString2( this.Parent.Get_Id() ); // Writer.WriteString2( this.Parent.Get_Id() ); this.Pr.Write_ToBinary( Writer ); Writer.WriteString2( this.TextPr.Get_Id() ); var StartPos = Writer.GetCurPosition(); Writer.Skip( 4 ); var Len = this.Content.length; var Count = 0; for ( var Index = 0; Index < Len; Index++ ) { var Item = this.Content[Index]; if ( true === Item.Is_RealContent() ) { Item.Write_ToBinary( Writer ); Count++; } } var EndPos = Writer.GetCurPosition(); Writer.Seek( StartPos ); Writer.WriteLong( Count ); Writer.Seek( EndPos ); }, Read_FromBinary2 : function(Reader) { // String : Id // String : Id родительского класса // Variable : ParaPr // String : Id TextPr // Long : количество элементов, у которых Is_RealContent = true this.Id = Reader.GetString2(); this.DrawingDocument = editor.WordControl.m_oLogicDocument.DrawingDocument; var LinkData = new Object(); LinkData.Parent = Reader.GetString2(); this.Pr = new CParaPr(); this.Pr.Read_FromBinary( Reader ); // this.TextPr = g_oTableId.Get_ById( Reader.GetString2() ); LinkData.TextPr = Reader.GetString2(); CollaborativeEditing.Add_LinkData(this, LinkData); this.Content = new Array(); var Count = Reader.GetLong(); for ( var Index = 0; Index < Count; Index++ ) { var Element = ParagraphContent_Read_FromBinary(Reader); if ( null != Element ) this.Content.push( Element ); } CollaborativeEditing.Add_NewObject( this ); }, Load_LinkData : function(LinkData) { if ( "undefined" != typeof(LinkData.Parent) ) this.Parent = g_oTableId.Get_ById( LinkData.Parent ); if ( "undefined" != typeof(LinkData.TextPr) ) this.TextPr = g_oTableId.Get_ById( LinkData.TextPr ); }, Clear_CollaborativeMarks : function() { for ( var Pos = 0; Pos < this.Content.length; Pos++ ) { var Item = this.Content[Pos]; if ( Item.Type == para_CollaborativeChangesEnd || Item.Type == para_CollaborativeChangesStart ) { this.Internal_Content_Remove( Pos ); Pos--; } } }, //----------------------------------------------------------------------------------- // Функции для работы с комментариями //----------------------------------------------------------------------------------- Add_Comment : function(Comment, bStart, bEnd) { var CursorPos_max = this.Internal_GetEndPos(); var CursorPos_min = this.Internal_GetStartPos(); if ( true === this.ApplyToAll ) { if ( true === bEnd ) { var PagePos = this.Internal_GetXYByContentPos( CursorPos_max ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_EndInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentEnd(Comment.Get_Id()); this.Internal_Content_Add( CursorPos_max, Item ); } if ( true === bStart ) { var PagePos = this.Internal_GetXYByContentPos( CursorPos_min ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_StartInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentStart(Comment.Get_Id()); this.Internal_Content_Add( CursorPos_min, Item ); } } else { if ( true === this.Selection.Use ) { var StartPos, EndPos; if ( this.Selection.StartPos < this.Selection.EndPos ) { StartPos = this.Selection.StartPos; EndPos = this.Selection.EndPos; } else { StartPos = this.Selection.EndPos; EndPos = this.Selection.StartPos; } if ( true === bEnd ) { EndPos = Math.max( CursorPos_min, Math.min( CursorPos_max, EndPos ) ); var PagePos = this.Internal_GetXYByContentPos( EndPos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_EndInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentEnd(Comment.Get_Id()); this.Internal_Content_Add( EndPos, Item ); } if ( true === bStart ) { StartPos = Math.max( CursorPos_min, Math.min( CursorPos_max, StartPos ) ); var PagePos = this.Internal_GetXYByContentPos( StartPos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_StartInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentStart(Comment.Get_Id()); this.Internal_Content_Add( StartPos, Item ); } } else { if ( true === bEnd ) { var Pos = Math.max( CursorPos_min, Math.min( CursorPos_max, this.CurPos.ContentPos ) ); var PagePos = this.Internal_GetXYByContentPos( Pos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_EndInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentEnd(Comment.Get_Id()); this.Internal_Content_Add( Pos, Item ); } if ( true === bStart ) { var Pos = Math.max( CursorPos_min, Math.min( CursorPos_max, this.CurPos.ContentPos ) ); var PagePos = this.Internal_GetXYByContentPos( Pos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_StartInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentStart(Comment.Get_Id()); this.Internal_Content_Add( Pos, Item ); } } } }, Add_Comment2 : function(Comment, ObjectId) { var Pos = -1; var Count = this.Content.length; for ( var Index = 0; Index < Count; Index++ ) { var Item = this.Content[Index]; if ( para_Drawing === Item.Type ) { Pos = Index; break; } } if ( -1 != Pos ) { var StartPos = Pos; var EndPos = Pos + 1; var PagePos = this.Internal_GetXYByContentPos( EndPos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_EndInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentEnd(Comment.Get_Id()); this.Internal_Content_Add( EndPos, Item ); var PagePos = this.Internal_GetXYByContentPos( StartPos ); var Line = this.Lines[PagePos.Internal.Line]; var LineA = Line.Metrics.Ascent; var LineH = Line.Bottom - Line.Top; Comment.Set_StartInfo( PagePos.PageNum, PagePos.X, PagePos.Y - LineA, LineH, this.Get_Id() ); var Item = new ParaCommentStart(Comment.Get_Id()); this.Internal_Content_Add( StartPos, Item ); } }, CanAdd_Comment : function() { if ( true === this.Selection.Use && true != this.Selection_IsEmpty() ) return true; return false; }, Remove_CommentMarks : function(Id) { var DocumentComments = editor.WordControl.m_oLogicDocument.Comments; var Count = this.Content.length; for ( var Pos = 0; Pos < Count; Pos++ ) { var Item = this.Content[Pos]; if ( ( para_CommentStart === Item.Type || para_CommentEnd === Item.Type ) && Id === Item.Id ) { if ( para_CommentStart === Item.Type ) DocumentComments.Set_StartInfo( Item.Id, 0, 0, 0, 0, null ); else DocumentComments.Set_EndInfo( Item.Id, 0, 0, 0, 0, null ); this.Internal_Content_Remove( Pos ); Pos--; Count--; } } }, Replace_MisspelledWord : function(Word, WordId) { var Element = this.SpellChecker.Elements[WordId]; var StartPos = Element.StartPos; var EndPos = Element.EndPos; for ( var Pos = EndPos; Pos >= StartPos; Pos-- ) { var ItemType = this.Content[Pos].Type; if ( para_TextPr != ItemType ) this.Internal_Content_Remove(Pos); } var Len = Word.length; for ( var Pos = 0; Pos < Len; Pos++ ) { this.Internal_Content_Add( StartPos + Pos, new ParaText( Word[Pos] ) ); } this.RecalcInfo.Set_Type_0( pararecalc_0_All ); this.Selection.Use = false; this.Selection.Start = false; this.Selection.StartPos = EndPos; this.Selection.EndPos = EndPos; this.Set_ContentPos( EndPos ); }, Ignore_MisspelledWord : function(WordId) { var Element = this.SpellChecker.Elements[WordId]; Element.Checked = true; this.ReDraw(); } }; var pararecalc_0_All = 0; var pararecalc_0_None = 1; var pararecalc_0_Spell_All = 0; var pararecalc_0_Spell_Pos = 1; var pararecalc_0_Spell_Lang = 2; var pararecalc_0_Spell_None = 3; function CParaRecalcInfo() { this.Recalc_0_Type = pararecalc_0_All; this.Recalc_0_Spell = { Type : pararecalc_0_All, StartPos : 0, EndPos : 0 }; } CParaRecalcInfo.prototype = { Set_Type_0 : function(Type) { this.Recalc_0_Type = Type; }, Set_Type_0_Spell : function(Type, StartPos, EndPos) { if ( pararecalc_0_Spell_All === this.Recalc_0_Spell.Type ) return; else if ( pararecalc_0_Spell_None === this.Recalc_0_Spell.Type || pararecalc_0_Spell_Lang === this.Recalc_0_Spell.Type ) { this.Recalc_0_Spell.Type = Type; if ( pararecalc_0_Spell_Pos === Type ) { this.Recalc_0_Spell.StartPos = StartPos; this.Recalc_0_Spell.EndPos = EndPos; } } else if ( pararecalc_0_Spell_Pos === this.Recalc_0_Spell.Type ) { if ( pararecalc_0_Spell_All === Type ) this.Recalc_0_Spell.Type = Type; else if ( pararecalc_0_Spell_Pos === Type ) { this.Recalc_0_Spell.StartPos = Math.min( StartPos, this.Recalc_0_Spell.StartPos ); this.Recalc_0_Spell.EndPos = Math.max( EndPos, this.Recalc_0_Spell.EndPos ); } } }, Update_Spell_OnChange : function(Pos, Count, bAdd) { if ( pararecalc_0_Spell_Pos === this.Recalc_0_Spell.Type ) { if ( true === bAdd ) { if ( this.Recalc_0_Spell.StartPos > Pos ) this.Recalc_0_Spell.StartPos++; if ( this.Recalc_0_Spell.EndPos >= Pos ) this.Recalc_0_Spell.EndPos++; } else { if ( this.Recalc_0_Spell.StartPos > Pos ) { if ( this.Recalc_0_Spell.StartPos > Pos + Count ) this.Recalc_0_Spell.StartPos -= Count; else this.Recalc_0_Spell.StartPos = Pos; } if ( this.Recalc_0_Spell.EndPos >= Pos ) { if ( this.Recalc_0_Spell.EndPos >= Pos + Count ) this.Recalc_0_Spell.EndPos -= Count; else this.Recalc_0_Spell.EndPos = Math.max( 0, Pos - 1 ); } } } } }; function CParaLineRange(X, XEnd) { this.X = X; this.XVisible = 0; this.W = 0; this.Words = 0; this.Spaces = 0; this.XEnd = XEnd; this.StartPos = 0; // Позиция в контенте параграфа, с которой начинается данный отрезок this.SpacePos = -1; // Позиция, с которой начинаем считать пробелы this.StartPos2 = -1; // Позиции начала и конца отрисовки выделения this.EndPos2 = -1; // текста(а также подчеркивания и зачеркивания) } CParaLineRange.prototype = { Shift : function(Dx, Dy) { this.X += Dx; this.XEnd += Dx; this.XVisible += Dx; } }; function CParaLineMetrics() { this.Ascent = 0; // Высота над BaseLine this.Descent = 0; // Высота после BaseLine this.TextAscent = 0; // Высота текста над BaseLine this.TextAscent2 = 0; // Высота текста над BaseLine this.TextDescent = 0; // Высота текста после BaseLine this.LineGap = 0; // Дополнительное расстояние между строками } CParaLineMetrics.prototype = { Update : function(TextAscent, TextAscent2, TextDescent, Ascent, Descent, ParaPr) { if ( TextAscent > this.TextAscent ) this.TextAscent = TextAscent; if ( TextAscent2 > this.TextAscent2 ) this.TextAscent2 = TextAscent2; if ( TextDescent > this.TextDescent ) this.TextDescent = TextDescent; if ( Ascent > this.Ascent ) this.Ascent = Ascent; if ( Descent > this.Descent ) this.Descent = Descent; if ( this.Ascent < this.TextAscent ) this.TextAscent = this.Ascent; if ( this.Descent < this.TextDescent ) this.TextDescent = this.Descent; this.LineGap = this.Recalculate_LineGap( ParaPr, this.TextAscent, this.TextDescent ); }, Recalculate_LineGap : function(ParaPr, TextAscent, TextDescent) { var LineGap = 0; switch ( ParaPr.Spacing.LineRule ) { case linerule_Auto: { LineGap = ( TextAscent + TextDescent ) * ( ParaPr.Spacing.Line - 1 ); break; } case linerule_Exact: { var ExactValue = Math.max( 1, ParaPr.Spacing.Line ); LineGap = ExactValue - ( TextAscent + TextDescent ); var Gap = this.Ascent + this.Descent - ExactValue; if ( Gap > 0 ) { var DescentDiff = this.Descent - this.TextDescent; if ( DescentDiff > 0 ) { if ( DescentDiff < Gap ) { this.Descent = this.TextDescent; Gap -= DescentDiff; } else { this.Descent -= Gap; Gap = 0; } } var AscentDiff = this.Ascent - this.TextAscent; if ( AscentDiff > 0 ) { if ( AscentDiff < Gap ) { this.Ascent = this.TextAscent; Gap -= AscentDiff; } else { this.Ascent -= Gap; Gap = 0; } } if ( Gap > 0 ) { // Уменьшаем пропорционально TextAscent и TextDescent var OldTA = this.TextAscent; var OldTD = this.TextDescent; var Sum = OldTA + OldTD; this.Ascent = OldTA * (Sum - Gap) / Sum; this.Descent = OldTD * (Sum - Gap) / Sum; } } else { this.Ascent -= Gap; // все в Ascent } LineGap = 0; break; } case linerule_AtLeast: { var LineGap1 = ParaPr.Spacing.Line; var LineGap2 = TextAscent + TextDescent; LineGap = Math.max( LineGap1, LineGap2 ) - ( TextAscent + TextDescent ); break; } } return LineGap; } } function CParaLine(StartPos) { this.Y = 0; // this.W = 0; this.Top = 0; this.Bottom = 0; this.Words = 0; this.Spaces = 0; // Количество пробелов между словами в строке (пробелы, идущие в конце строки, не учитываются) this.Metrics = new CParaLineMetrics(); this.Ranges = new Array(); // Массив CParaLineRanges this.RangeY = false; this.StartPos = StartPos; // Позиция в контенте параграфа, с которой начинается данная строка this.EndPos = StartPos; // Позиция последнего элемента в данной строке } CParaLine.prototype = { Add_Range : function(X, XEnd) { this.Ranges.push( new CParaLineRange( X, XEnd ) ); }, Shift : function(Dx, Dy) { var RangesCount = this.Ranges.length; for ( var Index = 0; Index < RangesCount; Index++ ) { this.Ranges[Index].Shift( Dx, Dy ); } }, Set_RangeStartPos : function(CurRange, StartPos) { if ( 0 === CurRange ) this.StartPos = StartPos; this.Ranges[CurRange].StartPos = StartPos; }, Reset : function(StartPos) { //this.Y = 0; // this.Top = 0; this.Bottom = 0; this.Words = 0; this.Spaces = 0; // Количество пробелов между словами в строке (пробелы, идущие в конце строки, не учитываются) this.Metrics = new CParaLineMetrics(); this.Ranges = new Array(); // Массив CParaLineRanges //this.RangeY = false; this.StartPos = StartPos; }, Set_EndPos : function(EndPos, Paragraph) { this.EndPos = EndPos; var Content = Paragraph.Content; var RangesCount = this.Ranges.length; for ( var CurRange = 0; CurRange < RangesCount; CurRange++ ) { var Range = this.Ranges[CurRange]; var StartRangePos = Range.StartPos; var EndRangePos = ( CurRange === RangesCount - 1 ? EndPos : this.Ranges[CurRange + 1].StartPos - 1 ); var nSpacesCount = 0; var bWord = false; var nSpaceLen = 0; var nSpacePos = -1; var nStartPos2 = -1; var nEndPos2 = -1; Range.W = 0; Range.Words = 0; Range.Spaces = 0; for ( var Pos = StartRangePos; Pos <= EndRangePos; Pos++ ) { var Item = Content[Pos]; if ( Pos === Paragraph.Numbering.Pos ) Range.W += Paragraph.Numbering.WidthVisible; switch( Item.Type ) { case para_Text: { if ( true != bWord ) { bWord = true; Range.Words++; } Range.W += Item.Width; // Если текущий символ, например, дефис, тогда на нем заканчивается слово if ( true === Item.SpaceAfter ) { Range.W += nSpaceLen; // Пробелы перед первым словом в строке не считаем if ( Range.Words > 1 ) Range.Spaces += nSpacesCount; bWord = false; nSpaceLen = 0; nSpacesCount = 0; } if ( EndRangePos === Pos ) Range.W += nSpaceLen; if ( -1 === nSpacePos ) nSpacePos = Pos; if ( -1 === nStartPos2 ) nStartPos2 = Pos; nEndPos2 = Pos; break; } case para_Space: { if ( true === bWord ) { Range.W += nSpaceLen; // Пробелы перед первым словом в строке не считаем if ( Range.Words > 1 ) Range.Spaces += nSpacesCount; bWord = false; nSpacesCount = 1; nSpaceLen = 0; } else nSpacesCount++; nSpaceLen += Item.Width; break; } case para_Drawing: { Range.Words++; Range.W += nSpaceLen; Range.Spaces += nSpacesCount; bWord = false; nSpacesCount = 0; nSpaceLen = 0; if ( true === Item.Is_Inline() || true === Paragraph.Parent.Is_DrawingShape() ) { Range.W += Item.Width; if ( -1 === nSpacePos ) nSpacePos = Pos; if ( -1 === nStartPos2 ) nStartPos2 = Pos; nEndPos2 = Pos; } break; } case para_PageNum: { Range.Words++; Range.W += nSpaceLen; Range.Spaces += nSpacesCount; bWord = false; nSpacesCount = 0; nSpaceLen = 0; Range.W += Item.Width; if ( -1 === nSpacePos ) nSpacePos = Pos; if ( -1 === nStartPos2 ) nStartPos2 = Pos; nEndPos2 = Pos; break; } case para_Tab: { Range.W += Item.Width; Range.W += nSpaceLen; Range.Words = 0; Range.Spaces = 0; nSpaceLen = 0; nSpacesCount = 0; bWord = false; nSpacePos = -1; break; } case para_NewLine: { if ( bWord && Range.Words > 1 ) Range.Spaces += nSpacesCount; nSpacesCount = 0; bWord = false; break; } case para_End: { if ( true === bWord ) Range.Spaces += nSpacesCount; break; } } } Range.SpacePos = nSpacePos; Range.StartPos2 = ( nStartPos2 === -1 ? StartRangePos : nStartPos2 ); Range.EndPos2 = ( nEndPos2 === -1 ? EndRangePos : nEndPos2 ); } } }; function CDocumentBounds(Left, Top, Right, Bottom) { this.Bottom = Bottom; this.Left = Left; this.Right = Right; this.Top = Top; } CDocumentBounds.prototype = { Shift : function(Dx, Dy) { this.Bottom += Dy; this.Top += Dy; this.Left += Dx; this.Right += Dx; } }; function CParaPage(X, Y, XLimit, YLimit, FirstLine) { this.X = X; this.Y = Y; this.XLimit = XLimit; this.YLimit = YLimit; this.FirstLine = FirstLine; this.Bounds = new CDocumentBounds( X, Y, XLimit, Y ); this.StartLine = FirstLine; // Номер строки, с которой начинается данная страница this.EndLine = FirstLine; // Номер последней строки на данной странице this.TextPr = null; // Расситанные текстовые настройки для начала страницы } CParaPage.prototype = { Reset : function(X, Y, XLimit, YLimit, FirstLine) { this.X = X; this.Y = Y; this.XLimit = XLimit; this.YLimit = YLimit; this.FirstLine = FirstLine; this.Bounds = new CDocumentBounds( X, Y, XLimit, Y ); this.StartLine = FirstLine; }, Shift : function(Dx, Dy) { this.X += Dx; this.Y += Dy; this.XLimit += Dx; this.YLimit += Dy; this.Bounds.Shift( Dx, Dy ); }, Set_EndLine : function(EndLine) { this.EndLine = EndLine; } }; function CParaPos(Range, Line, Page, Pos) { this.Range = Range; // Номер промежутка в строке this.Line = Line; // Номер строки this.Page = Page; // Номер страницы this.Pos = Pos; // Позиция в общем массиве } // используется в Internal_Draw_3 и Internal_Draw_5 function CParaDrawingRangeLinesElement(y0, y1, x0, x1, w, r, g, b, Additional) { this.y0 = y0; this.y1 = y1; this.x0 = x0; this.x1 = x1; this.w = w; this.r = r; this.g = g; this.b = b; this.Additional = Additional; } function CParaDrawingRangeLines() { this.Elements = new Array(); } CParaDrawingRangeLines.prototype = { Clear : function() { this.Elements = new Array(); }, Add : function (y0, y1, x0, x1, w, r, g, b, Additional) { this.Elements.push( new CParaDrawingRangeLinesElement(y0, y1, x0, x1, w, r, g, b, Additional) ); }, Get_Next : function() { var Count = this.Elements.length; if ( Count <= 0 ) return null; // Соединяем, начиная с конца, чтобы проще было обрезать массив var Element = this.Elements[Count - 1]; Count--; while ( Count > 0 ) { var PrevEl = this.Elements[Count - 1]; if ( Math.abs( PrevEl.y0 - Element.y0 ) < 0.001 && Math.abs( PrevEl.y1 - Element.y1 ) < 0.001 && Math.abs( PrevEl.x1 - Element.x0 ) < 0.001 && Math.abs( PrevEl.w - Element.w ) < 0.001 && PrevEl.r === Element.r && PrevEl.g === Element.g && PrevEl.b === Element.b ) { Element.x0 = PrevEl.x0; Count--; } else break; } this.Elements.length = Count; return Element; }, Correct_w_ForUnderline : function() { var Count = this.Elements.length; if ( Count <= 0 ) return; var CurElements = new Array(); for ( var Index = 0; Index < Count; Index++ ) { var Element = this.Elements[Index]; var CurCount = CurElements.length; if ( 0 === CurCount ) CurElements.push( Element ); else { var PrevEl = CurElements[CurCount - 1]; if ( Math.abs( PrevEl.y0 - Element.y0 ) < 0.001 && Math.abs( PrevEl.y1 - Element.y1 ) < 0.001 && Math.abs( PrevEl.x1 - Element.x0 ) < 0.001 ) { // Сравниваем толщины линий if ( Element.w > PrevEl.w ) { for ( var Index2 = 0; Index2 < CurCount; Index2++ ) CurElements[Index2].w = Element.w; } else Element.w = PrevEl.w; CurElements.push( Element ); } else { CurElements.length = 0; CurElements.push( Element ); } } } } };
Исправлен баг с копированием буквицы в автофигуру (баг 21400). git-svn-id: 9db5f3bf534fda1ae49cdb5ebc7e13fb9e7e48c1@50908 954022d7-b5bf-4e40-9824-e11837661b57
Word/Editor/Paragraph.js
Исправлен баг с копированием буквицы в автофигуру (баг 21400).
<ide><path>ord/Editor/Paragraph.js <ide> this.Internal_Draw_6( CurPage, pGraphics, Pr ); <ide> <ide> // Убираем обрезку <del> if ( undefined != FramePr ) <add> if ( undefined != FramePr && this.Parent instanceof CDocument ) <ide> { <ide> pGraphics.RestoreGrState(); <ide> }
JavaScript
mit
78ba11cdb6fbc0fd549c60e3f28c9e6846e28232
0
riyazshaikh/template-kitchen
var PRESETS = {}; PRESETS.default = { tweakJson: {}, webfontsJson: [] }; PRESETS.katana = { tweakJson: { "mainContentWidth": "1200px", "mainSpacingSide": "5%", "mainSpacingTop": "2.5%", "mainMetaWidth": "500px", "body-font": "{font-family:'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:16px;font-weight:300;line-height:1.5em;}", "banner-body-font": "{font-family:'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:24px;font-weight:300;line-height:1.3em;}", "banner-heading1-font": "{font-family:inherit;font-size:60px;font-weight:300;line-height:1.3em;}", "main-bgColor": "#fff", "main-textColor": "#333", // "main-linkColor": "#cf3f02", "main-metaColor": "rgba(15,15,15,0.5)", "alt-bgColor": "#f5f5f5", "alt-textColor": "#333", "banner-bgColor": "rgba(0,0,0,0.5)", "banner-textColor": "rgb(255,255,255)", "Header - Display": "Overlaid", "Header - Background": "Transparent", "Header Content - Layout": "Main", "Header Block - Display": "Hide", "Banner - Background": "Transparent", "Banner Description - Display": "Overlaid Caption", "Banner Description - Background": "Translucent", "Banner Description Content - Layout": "Main", "Banner Description Content - Align": "Center Left", "Page Content - Italic": "Dash" }, webfontsJson: [ "Open+Sans:300,300italic,700normal,700italic,500undefined" ] }; PRESETS.squaremart = { tweakJson: { "altContentWidth": "100%", "altSpacingSide": "5%", "altSpacingTop": "20px", "mainContentWidth": "1100px", "mainSpacingSide": "5%", "mainSpacingTop": "20px", "bannerContentWidth": "800px", "bannerSpacingSide": "5%", "bannerSpacingTop": "220px", "main-bgColor": "#fff", "main-textColor": "#323639", "main-headingColor": "#000", "alt-bgColor": "#101113", "alt-textColor": "#909499", "alt-headingColor": "#fff", "banner-bgColor": "rgb(16,17,19)", "banner-textColor": "#fff", "Header - Display": "Overlaid", "Header - Background": "Transparent", "Header Content - Layout": "Alternate", "Header Block - Display": "Hide", "Banner - Background": "Transparent", "Banner Image - Parallax": "Enable", "Banner Description - Display": "Hide", "Banner Blocks - Background": "Translucent", "Banner Blocks Content - Layout": "Banner", "Page Footer - Palette": "Banner", "Page Footer Image - Parallax": "Enable", "Page Footer Content - Layout": "Alternate", "Page Footer Content - Sticky": "within-site-bottom", "Page Footer Blocks - Background": "Translucent", }, webfontsJson: [ ] }; PRESETS.galleryscroll = { tweakJson: { "main-bgColor": "#fff", "main-textColor": "#323639", "main-headingColor": "#000", "Header - Palette": "Main", "Header - Background": "Transparent", "Header - Display": "Overlaid", // "Header - Sticky": "Within Site", "Header Content - Layout": "Alternate", "Header Block - Display": "Hide", "Header Slidebar - Display": "Always", "Header Nav - Display": "Hide", "Banner - Palette": "Main", "Banner Image - Parallax": "Enable", "Banner Description - Display": "Hide", "Banner Blocks Content - Layout": "Main", "Banner Blocks Content - Parallax": "Enable" }, webfontsJson: [ ] }; PRESETS.artassign = { tweakJson: { "Banner - Display": "Overlaid", "Banner - Background": "Transparent", "Banner - Palette": "Main", "Banner Blocks Content - Layout": "Main", "Banner Blocks Content - Italic": "Highlight", "Gallery Content - Layout": "Banner" }, webfontsJson: [ ] }; var mode = document.currentScript.getAttribute('src').split('mode=')[1]; if (!mode || !PRESETS[mode]) mode = 'default'; // process tweak names var newObj = {}; for(var name in PRESETS[mode].tweakJson) { var newName = name.match(/\s/) ? name.replace(/\s/g,'-').toLowerCase() : name; newObj[newName] = PRESETS[mode].tweakJson[name]; } PRESETS[mode].tweakJson = newObj; Y.use('squarespace-util', function(Y) { Y.Data.post({ url: '/api/template/SetTemplateTweakSettings', data: { tweakJson: Y.JSON.stringify(PRESETS[mode]['tweakJson']), webfontsJson: Y.JSON.stringify(PRESETS[mode]['webfontsJson']) }, success: function() { alert('Preset ' + mode + ' applied!'); } }); });
scripts/presets.js
var PRESETS = {}; PRESETS.default = { tweakJson: {}, webfontsJson: [] }; PRESETS.katana = { tweakJson: { "mainContentWidth": "1200px", "mainSpacingSide": "5%", "mainSpacingTop": "2.5%", "mainMetaWidth": "500px", "body-font": "{font-family:'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:16px;font-weight:300;line-height:1.5em;}", "banner-body-font": "{font-family:'Open Sans','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:24px;font-weight:300;line-height:1.3em;}", "banner-heading1-font": "{font-family:inherit;font-size:60px;font-weight:300;line-height:1.3em;}", "main-bgColor": "#fff", "main-textColor": "#333", // "main-linkColor": "#cf3f02", "main-metaColor": "rgba(15,15,15,0.5)", "alt-bgColor": "#f5f5f5", "alt-textColor": "#333", "banner-bgColor": "rgba(0,0,0,0.5)", "banner-textColor": "rgb(255,255,255)", "Header - Display": "Overlaid", "Header - Background": "Transparent", "Header Content - Layout": "Main", "Header Block - Display": "Hide", "Banner - Background": "Transparent", "Banner Description - Display": "Overlaid Caption", "Banner Description - Background": "Translucent", "Banner Description Content - Layout": "Main", "Banner Description Content - Align": "Center Left", "Page Content - Italic": "Dash" }, webfontsJson: [ "Open+Sans:300,300italic,700normal,700italic,500undefined" ] }; PRESETS.squaremart = { tweakJson: { "altContentWidth": "100%", "altSpacingSide": "5%", "altSpacingTop": "20px", "mainContentWidth": "1100px", "mainSpacingSide": "5%", "mainSpacingTop": "20px", "bannerContentWidth": "800px", "bannerSpacingSide": "5%", "bannerSpacingTop": "220px", "main-bgColor": "#fff", "main-textColor": "#323639", "main-headingColor": "#000", "alt-bgColor": "#101113", "alt-textColor": "#909499", "alt-headingColor": "#fff", "banner-bgColor": "rgb(16,17,19)", "banner-textColor": "#fff", "Header - Display": "Overlaid", "Header - Background": "Transparent", "Header Content - Layout": "Alternate", "Header Block - Display": "Hide", "Banner - Background": "Transparent", "Banner Image - Parallax": "Enable", "Banner Description - Display": "Hide", "Banner Blocks - Background": "Translucent", "Banner Blocks Content - Layout": "Banner", "Page Footer - Palette": "Banner", "Page Footer Image - Parallax": "Enable", "Page Footer Content - Layout": "Alternate", "Page Footer Content - Sticky": "within-site-bottom", "Page Footer Blocks - Background": "Translucent", }, webfontsJson: [ ] }; PRESETS.galleryscroll = { tweakJson: { "main-bgColor": "#fff", "main-textColor": "#323639", "main-headingColor": "#000", "Header - Palette": "Main", "Header - Background": "Transparent", "Header - Display": "Overlaid", "Header - Sticky": "Within Site", "Header Content - Layout": "Alternate", "Header Block - Display": "Hide", "Header Slidebar - Display": "Always", "Header Nav - Display": "Hide", "Banner - Palette": "Main", "Banner Image - Parallax": "Enable", "Banner Description - Display": "Hide", "Banner Blocks Content - Layout": "Main", "Banner Blocks Content - Parallax": "Enable" }, webfontsJson: [ ] }; PRESETS.artassign = { tweakJson: { "Banner - Display": "Overlaid", "Banner - Background": "Transparent", "Banner - Palette": "Main", "Banner Blocks Content - Layout": "Main", "Banner Blocks Content - Italic": "Highlight", "Gallery Content - Layout": "Banner" }, webfontsJson: [ ] }; var mode = document.currentScript.getAttribute('src').split('mode=')[1]; if (!mode || !PRESETS[mode]) mode = 'default'; // process tweak names var newObj = {}; for(var name in PRESETS[mode].tweakJson) { var newName = name.match(/\s/) ? name.replace(/\s/g,'-').toLowerCase() : name; newObj[newName] = PRESETS[mode].tweakJson[name]; } PRESETS[mode].tweakJson = newObj; Y.use('squarespace-util', function(Y) { Y.Data.post({ url: '/api/template/SetTemplateTweakSettings', data: { tweakJson: Y.JSON.stringify(PRESETS[mode]['tweakJson']), webfontsJson: Y.JSON.stringify(PRESETS[mode]['webfontsJson']) }, success: function() { alert('Preset ' + mode + ' applied!'); } }); });
debug
scripts/presets.js
debug
<ide><path>cripts/presets.js <ide> "Header - Palette": "Main", <ide> "Header - Background": "Transparent", <ide> "Header - Display": "Overlaid", <del> "Header - Sticky": "Within Site", <add> // "Header - Sticky": "Within Site", <ide> "Header Content - Layout": "Alternate", <ide> "Header Block - Display": "Hide", <ide> "Header Slidebar - Display": "Always",
JavaScript
apache-2.0
2cee3ef76db8322ebeb138cd5028d9247c117437
0
SAP/openui5,SAP/openui5,SAP/openui5,SAP/openui5
/* * ! ${copyright} */ // Provides control sap.m.P13nConditionPanel sap.ui.define([ './library', 'sap/ui/core/library', 'sap/ui/core/Control', 'sap/ui/core/IconPool', 'sap/ui/Device', 'sap/ui/core/InvisibleText', 'sap/ui/core/ResizeHandler', 'sap/ui/core/Item', 'sap/ui/core/ListItem', 'sap/ui/model/odata/type/Boolean', 'sap/ui/model/type/String', 'sap/ui/model/odata/type/String', 'sap/ui/model/type/Date', 'sap/ui/model/type/Time', 'sap/ui/model/odata/type/DateTime', 'sap/ui/model/type/Float', './Button', './OverflowToolbar', './OverflowToolbarLayoutData', './ToolbarSpacer', './Text', './SearchField', './CheckBox', './ComboBox', './Select', './Label', './Input', './DatePicker', './TimePicker', './DateTimePicker', 'sap/base/Log', 'sap/ui/thirdparty/jquery' ], function( library, coreLibrary, Control, IconPool, Device, InvisibleText, ResizeHandler, Item, ListItem, BooleanOdataType, StringType, StringOdataType, DateType, TimeType, DateTimeOdataType, FloatType, Button, OverflowToolbar, OverflowToolbarLayoutData, ToolbarSpacer, Text, SearchField, CheckBox, ComboBox, Select, Label, Input, DatePicker, TimePicker, DateTimePicker, Log, jQuery ) { "use strict"; // shortcut for sap.ui.core.ValueState var ValueState = coreLibrary.ValueState; // shortcut for sap.m.ButtonType var ButtonType = library.ButtonType; // shortcut for sap.m.ToolbarDesign var ToolbarDesign = library.ToolbarDesign; // shortcut for sap.ui.core.TextAlign var TextAlign = coreLibrary.TextAlign; // shortcut for sap.m.OverflowToolbarPriority var OverflowToolbarPriority = library.OverflowToolbarPriority; // lazy dependency to sap.ui.layout.Grid var Grid; // lazy dependency to sap.ui.layout.GridData var GridData; // lazy dependency to sap.ui.layout.HorizontalLayout var HorizontalLayout; // lazy dependency to sap.ui.comp.odata.type.StringDate var StringDateType; /** * Constructor for a new P13nConditionPanel. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] initial settings for the new control * @class The ConditionPanel Control will be used to implement the Sorting, Filtering and Grouping panel of the new Personalization dialog. * @extends sap.ui.core.Control * @version ${version} * @constructor * @public * @since 1.26.0 * @experimental since version 1.26 !!! THIS CONTROL IS ONLY FOR INTERNAL USE !!! * @alias sap.m.P13nConditionPanel * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var P13nConditionPanel = Control.extend("sap.m.P13nConditionPanel", /** @lends sap.m.P13nConditionPanel.prototype */ { metadata: { library: "sap.m", properties: { /** * defines the max number of conditions on the ConditionPanel */ maxConditions: { type: "string", group: "Misc", defaultValue: '-1' }, /** * exclude options for filter */ exclude: { type: "boolean", group: "Misc", defaultValue: false }, /** * defines if the mediaQuery or a ContainerResize will be used for layout update. * When the <code>P13nConditionPanel</code> is used on a dialog the property should be set to <code>true</code>! */ containerQuery: { type: "boolean", group: "Misc", defaultValue: false }, /** * adds initial a new empty condition row */ autoAddNewRow: { type: "boolean", group: "Misc", defaultValue: false }, /** * makes the remove icon on the first condition row disabled when only one condition exist. */ disableFirstRemoveIcon: { type: "boolean", group: "Misc", defaultValue: false }, /** * makes the Add icon visible on each condition row. If is set to false the Add is only visible at the end and you can only append a * new condition. */ alwaysShowAddIcon: { type: "boolean", group: "Misc", defaultValue: true }, /** * new added condition use the settings from the previous condition as default. */ usePrevConditionSetting: { type: "boolean", group: "Misc", defaultValue: true }, /** * KeyField value can only be selected once. When you set the property to <code>true</code> the ConditionPanel will automatically offers on the * KeyField drop down only the keyFields which are not used. The default behavior is that in each keyField dropdown all keyfields are * listed. */ autoReduceKeyFieldItems: { type: "boolean", group: "Misc", defaultValue: false }, /** * can be used to control the layout behavior. Default is "" which will automatically change the layout. With "Desktop", "Table" * or "Phone" you can set a fixed layout. */ layoutMode: { type: "string", group: "Misc", defaultValue: null }, /** * show additional labels in the condition */ showLabel: { type: "boolean", group: "Misc", defaultValue: false }, /** * This represents the displayFormat of the condition Values. With the value "UpperCase" the entered value of the condition will be * converted to upperCase. */ displayFormat: { type: "string", group: "Misc", defaultValue: null }, /** * Calls the validation listener tbd... */ validationExecutor: { type: "object", group: "Misc", defaultValue: null } }, aggregations: { /** * Content for the ConditionPanel. This aggregation is not public! */ content: { type: "sap.ui.core.Control", multiple: true, singularName: "content", visibility: "hidden" } }, events: { /** * Workaround for updating the binding */ dataChange: {} } }, renderer: function(oRm, oControl) { // start ConditionPanel oRm.write("<section"); oRm.writeControlData(oControl); oRm.addClass("sapMConditionPanel"); oRm.writeClasses(); oRm.writeStyles(); oRm.write(">"); // render content oRm.write("<div"); oRm.addClass("sapMConditionPanelContent"); oRm.addClass("sapMConditionPanelBG"); oRm.writeClasses(); oRm.write(">"); var aChildren = oControl.getAggregation("content"); var iLength = aChildren.length; for (var i = 0; i < iLength; i++) { oRm.renderControl(aChildren[i]); } oRm.write("</div>"); oRm.write("</section>"); } }); // EXC_ALL_CLOSURE_003 /** * This method must be used to assign a list of conditions. * * @param {object[]} aConditions array of Conditions. * @public */ P13nConditionPanel.prototype.setConditions = function(aConditions) { if (!aConditions) { Log.error("sap.m.P13nConditionPanel : aCondition is not defined"); } if (this._bIgnoreSetConditions) { return; } this._oConditionsMap = {}; this._aConditionKeys = []; this._iConditions = 0; for (var i = 0; i < aConditions.length; i++) { this._addCondition2Map(aConditions[i]); } this._clearConditions(); this._fillConditions(); }; /** * remove all conditions. * * @public */ P13nConditionPanel.prototype.removeAllConditions = function() { this._oConditionsMap = {}; this._aConditionKeys = []; this._iConditions = 0; this._clearConditions(); this._fillConditions(); }; /** * add a single condition. * * @param {object} oCondition the new condition of type <code>{ "key": "007", "operation": sap.m.P13nConditionOperation.Ascending, "keyField": * "keyFieldKey", "value1": "", "value2": ""};</code> * @public */ P13nConditionPanel.prototype.addCondition = function(oCondition) { if (this._bIgnoreSetConditions) { return; } oCondition.index = this._iConditions; this._addCondition2Map(oCondition); this._addCondition(oCondition); }; /** * insert a single condition. * * @param {object} oCondition the new condition of type <code>{ "key": "007", "operation": sap.m.P13nConditionOperation.Ascending, "keyField": * "keyFieldKey", "value1": "", "value2": ""};</code> * @param {int} index of the new condition * @public */ P13nConditionPanel.prototype.insertCondition = function(oCondition, index) { if (this._bIgnoreSetConditions) { return; } if (index !== undefined) { oCondition.index = index; } this._addCondition2Map(oCondition); this._addCondition(oCondition); }; /** * remove a single condition. * * @param {object} vCondition is the condition which should be removed. can be either a string with the key of the condition of the condition * object itself. * @public */ P13nConditionPanel.prototype.removeCondition = function(vCondition) { this._clearConditions(); if (typeof vCondition == "string") { this._removeConditionFromMap(vCondition); } if (typeof vCondition == "object") { this._removeConditionFromMap(vCondition.key); } this._fillConditions(); }; /** * add a single condition into the _oConditionMap. * * @private * @param {object} oCondition the new condition of type <code>{ "key": "007", "operation": sap.m.P13nConditionOperation.Ascending, "keyField": * "keyFieldKey", "value1": "", "value2": ""};</code> */ P13nConditionPanel.prototype._addCondition2Map = function(oCondition) { if (!oCondition.key) { oCondition.key = "condition_" + this._iConditions; if (this.getExclude()) { oCondition.key = "x" + oCondition.key; } } this._iConditions++; this._oConditionsMap[oCondition.key] = oCondition; this._aConditionKeys.push(oCondition.key); }; P13nConditionPanel.prototype._removeConditionFromMap = function(sKey) { this._iConditions--; delete this._oConditionsMap[sKey]; var i = this._aConditionKeys.indexOf(sKey); if (i >= 0) { this._aConditionKeys.splice(i, 1); } }; /** * returns array of all defined conditions. * * @public * @returns {object[]} array of Conditions */ P13nConditionPanel.prototype.getConditions = function() { var oCondition; var aConditions = []; if (this._oConditionsMap) { for (var conditionId in this._oConditionsMap) { oCondition = this._oConditionsMap[conditionId]; var sValue = oCondition.value; if (!sValue) { sValue = this._getFormatedConditionText(oCondition.operation, oCondition.value1, oCondition.value2, oCondition.exclude, oCondition.keyField, oCondition.showIfGrouped); } if (!oCondition._oGrid || oCondition._oGrid.select.getSelected()) { aConditions.push({ "key": conditionId, "text": sValue, "exclude": oCondition.exclude, "operation": oCondition.operation, "keyField": oCondition.keyField, "value1": oCondition.value1, "value2": oCondition.operation === P13nConditionOperation.BT ? oCondition.value2 : null, "showIfGrouped": oCondition.showIfGrouped }); } } } return aConditions; }; /** * setter for the supported operations which we show per condition row. This array of "default" operations will only be used when we do not have * on the keyfield itself some specific operations and a keyfield is of not of type date or numeric. * * @public * @param {sap.m.P13nConditionOperation[]} aOperations array of operations <code>[sap.m.P13nConditionOperation.BT, sap.m.P13nConditionOperation.EQ]</code> * @param {string} sType defines the type for which this operations will be used. is <code>sType</code> is not defined the operations will be used as default * operations. */ P13nConditionPanel.prototype.setOperations = function(aOperations, sType) { sType = sType || "default"; this._oTypeOperations[sType] = aOperations; this._updateAllOperations(); }; P13nConditionPanel.prototype.setValues = function(aValues, sType) { sType = sType || "default"; this._oTypeValues[sType] = aValues; // this._updateAllOperations(); }; /** * add a single operation * * @public * @param {sap.m.P13nConditionOperation} oOperation * @param {string} sType defines the type for which this operations will be used. */ P13nConditionPanel.prototype.addOperation = function(oOperation, sType) { sType = sType || "default"; this._oTypeOperations[sType].push(oOperation); this._updateAllOperations(); }; /** * remove all operations * * @public * @param {string} sType defines the type for which all operations should be removed */ P13nConditionPanel.prototype.removeAllOperations = function(sType) { sType = sType || "default"; this._oTypeOperations[sType] = []; this._updateAllOperations(); }; /** * returns the default array of operations * * @public * @param {string} sType defines the type for which the operations should be returned. * @returns {sap.m.P13nConditionOperation[]} array of operations */ P13nConditionPanel.prototype.getOperations = function(sType) { sType = sType || "default"; return this._oTypeOperations[sType]; }; /** * This method allows you to specify the KeyFields for the conditions. You can set an array of object with Key and Text properties to define the * keyfields. * * @public * @param {array} aKeyFields array of KeyFields <code>[{key: "CompanyCode", text: "ID"}, {key:"CompanyName", text : "Name"}]</code> */ P13nConditionPanel.prototype.setKeyFields = function(aKeyFields) { this._aKeyFields = aKeyFields; this._aKeyFields.forEach(function(oKeyField) { P13nConditionPanel._createKeyFieldTypeInstance(oKeyField); }, this); this._updateKeyFieldItems(this._oConditionsGrid, true); this._updateAllConditionsEnableStates(); this._createAndUpdateAllKeyFields(); this._updateAllOperations(); }; /** * add a single KeyField * * @public * @param {object} oKeyField {key: "CompanyCode", text: "ID"} */ P13nConditionPanel.prototype.addKeyField = function(oKeyField) { this._aKeyFields.push(oKeyField); P13nConditionPanel._createKeyFieldTypeInstance(oKeyField); this._updateKeyFieldItems(this._oConditionsGrid, true, true); this._updateAllConditionsEnableStates(); this._createAndUpdateAllKeyFields(); this._updateAllOperations(); }; P13nConditionPanel._createKeyFieldTypeInstance = function(oKeyField) { var oConstraints; //check if typeInstance exists, if not create the type instance if (!oKeyField.typeInstance) { switch (oKeyField.type) { case "boolean": //TODO in case the model is not an ODataModel we should use the sap.ui.model.type.Boolean oKeyField.typeInstance = new BooleanOdataType(); break; case "numc": if (!(oKeyField.formatSettings && oKeyField.formatSettings.isDigitSequence)) { Log.error("sap.m.P13nConditionPanel", "NUMC type support requires isDigitSequence==true!"); oKeyField.formatSettings = Object.assign({}, oKeyField.formatSettings, { isDigitSequence: true }); } oConstraints = oKeyField.formatSettings; if (oKeyField.maxLength) { oConstraints = Object.assign({}, oConstraints, { maxLength: oKeyField.maxLength }); } if (!oConstraints.maxLength) { Log.error("sap.m.P13nConditionPanel", "NUMC type suppport requires maxLength!"); } oKeyField.typeInstance = new StringOdataType({}, oConstraints); break; case "date": //TODO we should use the none odata date type, otherwise the returned oValue1 is not a date object oKeyField.typeInstance = new DateType(Object.assign({}, oKeyField.formatSettings, { strictParsing: true }), {}); break; case "time": //TODO we should use the none odata date type, otherwise the returned oValue1 is not a date object oKeyField.typeInstance = new TimeType(Object.assign({}, oKeyField.formatSettings, { strictParsing: true }), {}); break; case "datetime": oKeyField.typeInstance = new DateTimeOdataType(Object.assign({}, oKeyField.formatSettings, { strictParsing: true }), { displayFormat: "Date" }); // when the type is a DateTime type and isDateOnly==true, the type internal might use UTC=true // result is that date values which we format via formatValue(oDate, "string") are shown as the wrong date. // The current Date format is yyyy-mm-ddT00:00:00 GMT+01 // Workaround: changing the oFormat.oFormatOptions.UTC to false! var oType = oKeyField.typeInstance; if (!oType.oFormat) { // create a oFormat of the type by formating a dummy date oType.formatValue(new Date(), "string"); } if (oType.oFormat) { oType.oFormat.oFormatOptions.UTC = false; } break; case "stringdate": // TODO: Do we really need the COMP library here??? sap.ui.getCore().loadLibrary("sap.ui.comp"); StringDateType = StringDateType || sap.ui.requireSync("sap/ui/comp/odata/type/StringDate"); oKeyField.typeInstance = new StringDateType(Object.assign({}, oKeyField.formatSettings, { strictParsing: true })); break; case "numeric": if (oKeyField.precision || oKeyField.scale) { oConstraints = {}; if (oKeyField.precision) { oConstraints["maxIntegerDigits"] = parseInt(oKeyField.precision); } if (oKeyField.scale) { oConstraints["maxFractionDigits"] = parseInt(oKeyField.scale); } } oKeyField.typeInstance = new FloatType(oConstraints); break; default: var oFormatOptions = oKeyField.formatSettings; if (oKeyField.maxLength) { oFormatOptions = Object.assign({}, oFormatOptions, { maxLength: oKeyField.maxLength }); } oKeyField.typeInstance = new StringType({}, oFormatOptions); break; } } }; /** * removes all KeyFields * * @public */ P13nConditionPanel.prototype.removeAllKeyFields = function() { this._aKeyFields = []; this._updateKeyFieldItems(this._oConditionsGrid, true); }; /** * getter for KeyFields array * * @public * @returns {object[]} array of KeyFields <code>[{key: "CompanyCode", text: "ID"}, {key:"CompanyName", text : "Name"}]</code> */ P13nConditionPanel.prototype.getKeyFields = function() { return this._aKeyFields; }; /** * sets the AlwaysShowAddIcon. * * @private * @param {boolean} bEnabled makes the Add icon visible for each condition row. */ P13nConditionPanel.prototype.setAlwaysShowAddIcon = function(bEnabled) { this.setProperty("alwaysShowAddIcon", bEnabled); if (this._oConditionsGrid) { this._oConditionsGrid.toggleStyleClass("conditionRootGrid", this.getLayoutMode() !== "Desktop"); // && !this.getAlwaysShowAddIcon()); } return this; }; /** * sets the LayoutMode. If not set the layout depends on the size of the browser or the container. see ContainerQuery * * @private * @param {string} sLayoutMode define the layout mode for the condition row. The value can be Desktop, Tablet or Phone. * @returns {sap.m.P13nConditionPanel} <code>this</code> to allow method chaining */ P13nConditionPanel.prototype.setLayoutMode = function(sLayoutMode) { this.setProperty("layoutMode", sLayoutMode); if (this._oConditionsGrid) { this._oConditionsGrid.toggleStyleClass("conditionRootGrid", sLayoutMode !== "Desktop"); // && !this.getAlwaysShowAddIcon()); } this._updateConditionFieldSpans(sLayoutMode); // we have to refill the content grids this._clearConditions(); this._fillConditions(); return this; }; /** * sets the ContainerQuery. defines if the mediaQuery or a ContainerResize will be used for layout update. When the P13nConditionPanel is used on * a dialog the property should be set to <code>true</code>! * * @private * @since 1.30.0 * @param {boolean} bEnabled enables or disables the <code>ContainerQuery</code> * @returns {sap.m.P13nConditionPanel} <code>this</code> to allow method chaining */ P13nConditionPanel.prototype.setContainerQuery = function(bEnabled) { this._unregisterResizeHandler(); this.setProperty("containerQuery", bEnabled); this._registerResizeHandler(); // we have to refill the content grids this._clearConditions(); this._fillConditions(); return this; }; /** * sets the LayoutMode. * * @private * @param {string} sLayoutMode define the layout mode for the condition row. The value can be Desktop, Tablet or Phone. */ P13nConditionPanel.prototype._updateConditionFieldSpans = function(sMode) { if (this._aConditionsFields) { var bDesktop = sMode === "Desktop"; if (bDesktop) { // this._aConditionsFields[1].SpanFilter = "L1 M1 S1"; Label this._aConditionsFields[2].SpanFilter = "L3 M3 S3"; // this._aConditionsFields[3].SpanFilter = "L1 M1 S1"; Label this._aConditionsFields[4].SpanFilter = "L2 M2 S2"; this._aConditionsFields[5].SpanFilter = "L3 M3 S3"; this._aConditionsFields[6].SpanFilter = "L2 M2 S2"; this._aConditionsFields[7].SpanFilter = "L1 M1 S1"; } var bTablet = sMode === "Tablet"; if (bTablet) { // this._aConditionsFields[1].SpanFilter = "L1 M1 S1"; Label this._aConditionsFields[2].SpanFilter = "L5 M5 S5"; // this._aConditionsFields[3].SpanFilter = "L1 M1 S1"; Label this._aConditionsFields[4].SpanFilter = "L5 M5 S5"; this._aConditionsFields[5].SpanFilter = "L10 M10 S10"; this._aConditionsFields[6].SpanFilter = "L10 M10 S10"; this._aConditionsFields[7].SpanFilter = "L1 M1 S1"; } } }; /* * Initialize the control @private */ P13nConditionPanel.prototype.init = function() { // load the required layout lib sap.ui.getCore().loadLibrary("sap.ui.layout"); Grid = Grid || sap.ui.requireSync("sap/ui/layout/Grid"); GridData = GridData || sap.ui.requireSync("sap/ui/layout/GridData"); HorizontalLayout = HorizontalLayout || sap.ui.requireSync("sap/ui/layout/HorizontalLayout"); // init some resources this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m"); this._sFromLabelText = this._oRb.getText("CONDITIONPANEL_LABELFROM"); this._sToLabelText = this._oRb.getText("CONDITIONPANEL_LABELTO"); this._sValueLabelText = this._oRb.getText("CONDITIONPANEL_LABELVALUE"); this._sShowIfGroupedLabelText = this._oRb.getText("CONDITIONPANEL_LABELGROUPING"); this._sValidationDialogFieldMessage = this._oRb.getText("CONDITIONPANEL_FIELDMESSAGE"); this._oTypeOperations = { "default": [] }; this._oTypeValues = { "default": [] }; this._aKeyFields = []; this._oConditionsMap = {}; this._aConditionKeys = []; this._iConditions = 0; this._sLayoutMode = "Desktop"; this._sConditionType = "Filter"; this._sAddRemoveIconTooltip = "FILTER"; this._iBreakPointTablet = Device.media._predefinedRangeSets[Device.media.RANGESETS.SAP_STANDARD].points[0]; this._iBreakPointDesktop = Device.media._predefinedRangeSets[Device.media.RANGESETS.SAP_STANDARD].points[1]; // create the main grid and add it into the hidden content aggregation this._oConditionsGrid = new Grid({ width: "100%", defaultSpan: "L12 M12 S12", hSpacing: 0, vSpacing: 0 }).toggleStyleClass("conditionRootGrid", this.getLayoutMode() !== "Desktop"); // && !this.getAlwaysShowAddIcon()); this._oConditionsGrid.addStyleClass("sapUiRespGridOverflowHidden"); this._iFirstConditionIndex = 0; this._iConditionPageSize = 10; this._oInvisibleTextField = new InvisibleText({ text: this._oRb.getText("CONDITIONPANEL_FIELD_LABEL") }); this._oInvisibleTextOperator = new InvisibleText({ text: this._oRb.getText("CONDITIONPANEL_OPERATOR_LABEL") }); this.addAggregation("content", this._oInvisibleTextField); this.addAggregation("content", this._oInvisibleTextOperator); this.addAggregation("content", this._oConditionsGrid); this._registerResizeHandler(); this._aConditionsFields = [{ "ID": "select", "Label": "", "SpanFilter": "L1 M1 S1", "SpanSort": "L1 M1 S1", "SpanGroup": "L1 M1 S1", "Control": "CheckBox", "Value": "" }, { "ID": "keyFieldLabel", "Text": "Sort By", "SpanFilter": "L1 M1 S1", "SpanSort": "L1 M1 S1", "SpanGroup": "L1 M1 S1", "Control": "Label" }, { "ID": "keyField", "Label": "", "SpanFilter": "L3 M5 S10", "SpanSort": "L5 M5 S12", "SpanGroup": "L4 M4 S12", "Control": "ComboBox" }, { "ID": "operationLabel", "Text": "Sort Order", "SpanFilter": "L1 M1 S1", "SpanSort": "L1 M1 S1", "SpanGroup": "L1 M1 S1", "Control": "Label" }, { "ID": "operation", "Label": "", "SpanFilter": "L2 M5 S10", "SpanSort": Device.system.phone ? "L5 M5 S8" : "L5 M5 S9", "SpanGroup": "L2 M5 S10", "Control": "ComboBox" }, { "ID": "value1", "Label": this._sFromLabelText, "SpanFilter": "L3 M10 S10", "SpanSort": "L3 M10 S10", "SpanGroup": "L3 M10 S10", "Control": "TextField", "Value": "" }, { "ID": "value2", "Label": this._sToLabelText, "SpanFilter": "L2 M10 S10", "SpanSort": "L2 M10 S10", "SpanGroup": "L2 M10 S10", "Control": "TextField", "Value": "" }, { "ID": "showIfGrouped", "Label": this._sShowIfGroupedLabelText, "SpanFilter": "L1 M10 S10", "SpanSort": "L1 M10 S10", "SpanGroup": "L3 M4 S9", "Control": "CheckBox", "Value": "false" }]; this._oButtonGroupSpan = { "SpanFilter": "L2 M2 S2", "SpanSort": Device.system.phone ? "L2 M2 S4" : "L2 M2 S3", "SpanGroup": "L2 M2 S3" }; this._updateConditionFieldSpans(this.getLayoutMode()); // fill/update the content "oConditionGrid"s this._fillConditions(); }; /* * create the paginator toolbar * @private */ P13nConditionPanel.prototype._createPaginatorToolbar = function() { this._bPaginatorButtonsVisible = false; var that = this; this._oPrevButton = new Button({ icon: IconPool.getIconURI("navigation-left-arrow"), //tooltip: "Show Previous", tooltip: this._oRb.getText("WIZARD_FINISH"), //TODO create new resoucre visible: true, press: function(oEvent) { that._iFirstConditionIndex = Math.max(0, that._iFirstConditionIndex - that._iConditionPageSize); that._clearConditions(); that._fillConditions(); }, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.NeverOverflow }) }); this._oNextButton = new Button({ icon: IconPool.getIconURI("navigation-right-arrow"), //tooltip: "Show Next", tooltip: this._oRb.getText("WIZARD_NEXT"), //TODO create new resoucre visible: true, press: function(oEvent) { that._iFirstConditionIndex += that._iConditionPageSize; that._clearConditions(); that._fillConditions(); }, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.NeverOverflow }) }); this._oRemoveAllButton = new Button({ text: this._oRb.getText("CONDITIONPANEL_REMOVE_ALL"), // "Remove All", //icon: sap.ui.core.IconPool.getIconURI("sys-cancel"), //tooltip: "Remove All", visible: true, press: function(oEvent) { that._aConditionKeys.forEach(function(sKey, iIndex) { if (iIndex >= 0) { this.fireDataChange({ key: sKey, index: iIndex, operation: "remove", newData: null }); } }, that); this._iFirstConditionIndex = 0; that.removeAllConditions(); }, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.Low }) }); this._oAddButton = new Button({ icon: IconPool.getIconURI("add"), tooltip: this._oRb.getText("CONDITIONPANEL_ADD" + (this._sAddRemoveIconTooltipKey ? "_" + this._sAddRemoveIconTooltipKey : "") + "_TOOLTIP"), visible: true, press: function(oEvent) { var oConditionGrid = that._createConditionRow(that._oConditionsGrid, undefined, null, 0); that._changeField(oConditionGrid); // set the focus in a fields of the newly added condition setTimeout(function() { oConditionGrid.keyField.focus(); }); that._updatePaginatorToolbar(); }, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.Low }) }); this._oHeaderText = new Text({ wrapping: false, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.NeverOverflow }) }); this._oPageText = new Text({ wrapping: false, textAlign: TextAlign.Center, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.NeverOverflow }) }); this._oFilterField = new SearchField({ width: "12rem", layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.High }) }); this._oPaginatorToolbar = new OverflowToolbar({ height: "3rem", design: ToolbarDesign.Transparent, content: [ this._oHeaderText, new ToolbarSpacer(), this._oFilterField, this._oPrevButton, this._oPageText, this._oNextButton, this._oRemoveAllButton, this._oAddButton ] }); }; /* * update the paginator toolbar element * @private */ P13nConditionPanel.prototype._updatePaginatorToolbar = function() { if (this._sConditionType !== "Filter" || this.getMaxConditions() !== "-1") { return; } var iItems = this._aConditionKeys.length; var iPages = 1 + Math.floor(Math.max(0, iItems - 1) / this._iConditionPageSize); var iPage = 1 + Math.floor(this._iFirstConditionIndex / this._iConditionPageSize); var oParent = this.getParent(); if (!this._oPaginatorToolbar) { if (iItems > this._iConditionPageSize) { this._createPaginatorToolbar(); this.insertAggregation("content", this._oPaginatorToolbar, 0); this._onGridResize(); } else { if (oParent && oParent.setHeaderText) { if (this._sOrgHeaderText == undefined) { this._sOrgHeaderText = oParent.getHeaderText(); } oParent.setHeaderText(this._sOrgHeaderText + (iItems > 0 ? " (" + iItems + ")" : "")); } return; } } this._oPrevButton.setEnabled(this._iFirstConditionIndex > 0); this._oNextButton.setEnabled(this._iFirstConditionIndex + this._iConditionPageSize < iItems); if (oParent && oParent.setHeaderToolbar) { if (!oParent.getHeaderToolbar()) { this.removeAggregation("content", this._oPaginatorToolbar); oParent.setHeaderToolbar(this._oPaginatorToolbar); oParent.attachExpand(function(oEvent) { this._setToolbarElementVisibility(oEvent.getSource().getExpanded() && this._bPaginatorButtonsVisible); }.bind(this)); } } if (oParent && oParent.setHeaderText) { if (this._sOrgHeaderText == undefined) { this._sOrgHeaderText = oParent.getHeaderText(); } var sHeader = this._sOrgHeaderText + (iItems > 0 ? " (" + iItems + ")" : ""); oParent.setHeaderText(sHeader); this._oHeaderText.setText(sHeader); } else { this._oHeaderText.setText(iItems + " Conditions"); } this._oPageText.setText(iPage + "/" + iPages); this._bPaginatorButtonsVisible = this._bPaginatorButtonsVisible || iPages > 1; this._setToolbarElementVisibility(this._bPaginatorButtonsVisible); if (iPage > iPages) { // update the FirstConditionIndex and rerender this._iFirstConditionIndex -= Math.max(0, this._iConditionPageSize); this._clearConditions(); this._fillConditions(); } var nValidGrids = 0; this._oConditionsGrid.getContent().forEach(function(oGrid) { if (oGrid.select.getSelected()) { nValidGrids++; } }, this); if (iPages == iPage && (iItems - this._iFirstConditionIndex) > nValidGrids) { // check if we have to rerender the current last page this._clearConditions(); this._fillConditions(); } }; /* * make all toolbar elements visible or invisible * @private */ P13nConditionPanel.prototype._setToolbarElementVisibility = function(bVisible) { this._oPrevButton.setVisible(bVisible); this._oNextButton.setVisible(bVisible); this._oPageText.setVisible(bVisible); this._oFilterField.setVisible(false); //bVisible); this._oAddButton.setVisible(bVisible); this._oRemoveAllButton.setVisible(bVisible); }; /* * destroy and remove all internal references * @private */ P13nConditionPanel.prototype.exit = function() { this._clearConditions(); this._unregisterResizeHandler(); this._aConditionsFields = null; this._aKeys = null; this._aKeyFields = null; this._oTypeOperations = null; this._oRb = null; this._sFromLabelText = null; this._sToLabelText = null; this._sValueLabelText = null; this._sValidationDialogFieldMessage = null; this._oConditionsMap = null; this._aConditionKeys = []; }; /* * removes all condition rows from the main ConditionGrid. @private */ P13nConditionPanel.prototype._clearConditions = function() { var aGrid = this._oConditionsGrid.getContent(); aGrid.forEach(function(oGrid) { for (var iField in this._aConditionsFields) { var field = this._aConditionsFields[iField]; if (oGrid[field["ID"]] && oGrid.getContent().indexOf(oGrid[field["ID"]]) === -1) { // TODO: notice that since these fields could have been removed from // the inner aggregation, and thus would not be destroyed otherwise, // we destroy them separately here oGrid[field["ID"]].destroy(); } } }, this); this._oConditionsGrid.destroyContent(); }; /* * creates all condition rows and updated the values of the fields. @private */ P13nConditionPanel.prototype._fillConditions = function() { var oCondition, sConditionKey; var i = 0, iMaxConditions = this._getMaxConditionsAsNumber(), n = this._aConditionKeys.length; // fill existing conditions if (this._oConditionsMap) { var iPageSize = this._sConditionType !== "Filter" || this.getMaxConditions() !== "-1" ? 9999 : this._iConditionPageSize; n = Math.min(n, Math.min(iMaxConditions, this._iFirstConditionIndex + iPageSize)); for (i = this._iFirstConditionIndex; i < n; i++) { sConditionKey = this._aConditionKeys[i]; oCondition = this._oConditionsMap[sConditionKey]; this._createConditionRow(this._oConditionsGrid, oCondition, sConditionKey); } } this._updatePaginatorToolbar(); // create empty Conditions row/fields if ((this.getAutoAddNewRow() || this._oConditionsGrid.getContent().length === 0) && this._oConditionsGrid.getContent().length < iMaxConditions) { this._createConditionRow(this._oConditionsGrid); } }; /* * add one condition @private */ P13nConditionPanel.prototype._addCondition = function(oCondition) { var i = 0; var iMaxConditions = this._getMaxConditionsAsNumber(); //TODO page handling missing if (this._oConditionsMap) { for (var conditionId in this._oConditionsMap) { if (i < iMaxConditions && oCondition === this._oConditionsMap[conditionId]) { this._createConditionRow(this._oConditionsGrid, oCondition, conditionId, i); } i++; } } this._updatePaginatorToolbar(); }; P13nConditionPanel.prototype._getMaxConditionsAsNumber = function() { return this.getMaxConditions() === "-1" ? 9999 : parseInt(this.getMaxConditions()); }; P13nConditionPanel.prototype.onAfterRendering = function() { if (this.getLayoutMode()) { this._sLayoutMode = this.getLayoutMode(); return; } }; P13nConditionPanel.prototype._handleMediaChange = function(p) { this._sLayoutMode = p.name; // if (window.console) { // window.console.log(" ---> MediaChange " + p.name); // } this._updateLayout(p); }; P13nConditionPanel.prototype._unregisterResizeHandler = function() { if (this._sContainerResizeListener) { ResizeHandler.deregister(this._sContainerResizeListener); this._sContainerResizeListener = null; } Device.media.detachHandler(this._handleMediaChange, this, Device.media.RANGESETS.SAP_STANDARD); }; P13nConditionPanel.prototype._registerResizeHandler = function() { if (this.getContainerQuery()) { this._sContainerResizeListener = ResizeHandler.register(this._oConditionsGrid, this._onGridResize.bind(this)); this._onGridResize(); } else { Device.media.attachHandler(this._handleMediaChange, this, Device.media.RANGESETS.SAP_STANDARD); } }; /** * returns the key of the condition grid or creates a new key * * @private * @param {object} oConditionGrid * @returns {string} the new or existing key */ P13nConditionPanel.prototype._getKeyFromConditionGrid = function(oConditionGrid) { var sKey = oConditionGrid.data("_key"); if (!sKey) { sKey = this._createConditionKey(); } return sKey; }; /** * creates a new key for the condition grids * * @private * @returns {string} the new key */ P13nConditionPanel.prototype._createConditionKey = function() { var i = 0; var sKey; do { sKey = "condition_" + i; if (this.getExclude()) { sKey = "x" + sKey; } i++; } while (this._oConditionsMap[sKey]); return sKey; }; /** * appends a new condition grid with all containing controls in the main grid * * @private * @param {grid} oTargetGrid the main grid in which the new condition grid will be added * @param {object} oConditionGridData the condition data for the new added condition grid controls * @param {string} sKey the key for the new added condition grid * @param {int} iPos the index of the new condition in the targetGrid */ P13nConditionPanel.prototype._createConditionRow = function(oTargetGrid, oConditionGridData, sKey, iPos) { var oButtonContainer = null; var oGrid; var that = this; if (iPos === undefined) { iPos = oTargetGrid.getContent().length; } var oConditionGrid = new Grid({ width: "100%", defaultSpan: "L12 M12 S12", hSpacing: 1, vSpacing: 0, containerQuery: this.getContainerQuery() }).data("_key", sKey); oConditionGrid.addStyleClass("sapUiRespGridOverflowHidden"); /* eslint-disable no-loop-func */ for (var iField in this._aConditionsFields) { var oControl; var field = this._aConditionsFields[iField]; switch (field["Control"]) { case "CheckBox": // the CheckBox is not visible and only used internal to validate if a condition is // filled correct. oControl = new CheckBox({ enabled: false, visible: false, layoutData: new GridData({ span: field["Span" + this._sConditionType] }) }); if (field["ID"] === "showIfGrouped") { oControl.setEnabled(true); oControl.setText(field["Label"]); oControl.attachSelect(function() { that._changeField(oConditionGrid); }); oControl.setSelected(oConditionGridData ? oConditionGridData.showIfGrouped : true); } else { if (oConditionGridData) { oControl.setSelected(true); oControl.setEnabled(true); } } break; case "ComboBox": if (field["ID"] === "keyField") { oControl = new ComboBox({ // before we used the new sap.m.Select control width: "100%", ariaLabelledBy: this._oInvisibleTextField }); var fOriginalKey = oControl.setSelectedKey.bind(oControl); oControl.setSelectedKey = function(sKey) { fOriginalKey(sKey); var fValidate = that.getValidationExecutor(); if (fValidate) { fValidate(); } }; var fOriginalItem = oControl.setSelectedItem.bind(oControl); oControl.setSelectedItem = function(oItem) { fOriginalItem(oItem); var fValidate = that.getValidationExecutor(); if (fValidate) { fValidate(); } }; oControl.setLayoutData(new GridData({ span: field["Span" + this._sConditionType] })); this._fillKeyFieldListItems(oControl, this._aKeyFields); if (oControl.attachSelectionChange) { oControl.attachSelectionChange(function(oEvent) { var fValidate = that.getValidationExecutor(); if (fValidate) { fValidate(); } that._handleSelectionChangeOnKeyField(oTargetGrid, oConditionGrid); }); } if (oControl.attachChange) { oControl.attachChange(function(oEvent) { oConditionGrid.keyField.close(); that._handleChangeOnKeyField(oTargetGrid, oConditionGrid); }); } if (oControl.setSelectedItem) { if (oConditionGridData) { oControl.setSelectedKey(oConditionGridData.keyField); this._aKeyFields.forEach(function(oKeyField, index) { var key = oKeyField.key; if (key === undefined) { key = oKeyField; } if (oConditionGridData.keyField === key) { oControl.setSelectedItem(oControl.getItems()[index]); } }, this); } else { if (this.getUsePrevConditionSetting() && !this.getAutoReduceKeyFieldItems()) { // select the key from the condition above if (iPos > 0 && !sKey) { oGrid = oTargetGrid.getContent()[iPos - 1]; if (oGrid.keyField.getSelectedKey()) { oControl.setSelectedKey(oGrid.keyField.getSelectedKey()); } else { // if no item is selected, we have to select at least the first keyFieldItem if (!oControl.getSelectedItem() && oControl.getItems().length > 0) { oControl.setSelectedItem(oControl.getItems()[0]); } } } else { this._aKeyFields.some(function(oKeyField, index) { if (oKeyField.isDefault) { oControl.setSelectedItem(oControl.getItems()[index]); return true; } if (!oControl.getSelectedItem() && oKeyField.type !== "boolean") { oControl.setSelectedItem(oControl.getItems()[index]); } }, this); // if no item is selected, we have to select at least the first keyFieldItem if (!oControl.getSelectedItem() && oControl.getItems().length > 0) { oControl.setSelectedItem(oControl.getItems()[0]); } } } else { this._aKeyFields.forEach(function(oKeyField, index) { if (oKeyField.isDefault) { oControl.setSelectedItem(oControl.getItems()[index]); } }, this); } } } } if (field["ID"] === "operation") { oControl = new Select({ width: "100%", ariaLabelledBy: this._oInvisibleTextOperator, layoutData: new GridData({ span: field["Span" + this._sConditionType] }) }); oControl.attachChange(function() { that._handleChangeOnOperationField(oTargetGrid, oConditionGrid); }); // oControl.attachSelectionChange(function() { // that._handleChangeOnOperationField(oTargetGrid, oConditionGrid); // }); // fill some operations to the control to be able to set the selected items oConditionGrid[field["ID"]] = oControl; this._updateOperationItems(oTargetGrid, oConditionGrid); if (oConditionGridData) { var oKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); var aOperations = this._oTypeOperations["default"]; if (oKeyField) { if (oKeyField.type && this._oTypeOperations[oKeyField.type]) { aOperations = this._oTypeOperations[oKeyField.type]; } if (oKeyField.operations) { aOperations = oKeyField.operations; } } aOperations.some(function(oOperation, index) { if (oConditionGridData.operation === oOperation) { oControl.setSelectedKey(oOperation); return true; } }, this); } else { if (this.getUsePrevConditionSetting()) { // select the key from the condition above if (iPos > 0 && sKey === null) { var oGrid = oTargetGrid.getContent()[iPos - 1]; oControl.setSelectedKey(oGrid.operation.getSelectedKey()); } } } } // init tooltip of select control if (oControl.getSelectedItem && oControl.getSelectedItem()) { oControl.setTooltip(oControl.getSelectedItem().getTooltip() || oControl.getSelectedItem().getText()); } break; case "TextField": var oCurrentKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); oControl = this._createValueField(oCurrentKeyField, field, oConditionGrid); oControl.oTargetGrid = oTargetGrid; if (oConditionGridData && oConditionGridData[field["ID"]] !== undefined) { var vValue = oConditionGridData[field["ID"]]; if (oControl instanceof Select) { if (typeof vValue === "boolean") { oControl.setSelectedIndex(vValue ? 2 : 1); } } else if (vValue !== null && oConditionGrid.oType) { // In case vValue is of type string, and type is StringDate we can set the value without formatting. if (typeof vValue === "string" && oConditionGrid.oType.getName() === "sap.ui.comp.odata.type.StringDate") { oControl.setValue(vValue); } else { // In case vValue is of type string, we try to convert it into the type based format. if (typeof vValue === "string" && ["String", "sap.ui.model.odata.type.String", "sap.ui.model.odata.type.Decimal"].indexOf(oConditionGrid.oType.getName()) == -1) { try { vValue = oConditionGrid.oType.parseValue(vValue, "string"); oControl.setValue(oConditionGrid.oType.formatValue(vValue, "string")); } catch (err) { Log.error("sap.m.P13nConditionPanel", "Value '" + vValue + "' does not have the expected type format for " + oConditionGrid.oType.getName() + ".parseValue()"); } } else { oControl.setValue(oConditionGrid.oType.formatValue(vValue, "string")); } } } else { oControl.setValue(vValue); } } break; case "Label": oControl = new Label({ text: field["Text"] + ":", visible: this.getShowLabel(), layoutData: new GridData({ span: field["Span" + this._sConditionType] }) }).addStyleClass("conditionLabel"); oControl.oTargetGrid = oTargetGrid; break; } oConditionGrid[field["ID"]] = oControl; oConditionGrid.addContent(oControl); } /* eslint-enable no-loop-func */ // create a hLayout container for the remove and add buttons oButtonContainer = new HorizontalLayout({ layoutData: new GridData({ span: this.getLayoutMode() === "Desktop" ? "L2 M2 S2" : this._oButtonGroupSpan["Span" + this._sConditionType] }) }).addStyleClass("floatRight"); oConditionGrid.addContent(oButtonContainer); oConditionGrid["ButtonContainer"] = oButtonContainer; // create "Remove button" var oRemoveControl = new Button({ type: ButtonType.Transparent, icon: IconPool.getIconURI("sys-cancel"), tooltip: this._oRb.getText("CONDITIONPANEL_REMOVE" + (this._sAddRemoveIconTooltipKey ? "_" + this._sAddRemoveIconTooltipKey : "") + "_TOOLTIP"), press: function() { that._handleRemoveCondition(this.oTargetGrid, oConditionGrid); }, layoutData: new GridData({ span: this.getLayoutMode() === "Desktop" ? "L1 M1 S1" : "L1 M2 S2" }) }); oRemoveControl.oTargetGrid = oTargetGrid; oButtonContainer.addContent(oRemoveControl); oConditionGrid["remove"] = oRemoveControl; // create "Add button" var oAddControl = new Button({ type: ButtonType.Transparent, icon: IconPool.getIconURI("add"), tooltip: this._oRb.getText("CONDITIONPANEL_ADD" + (this._sAddRemoveIconTooltipKey ? "_" + this._sAddRemoveIconTooltipKey : "") + "_TOOLTIP"), press: function() { that._handleAddCondition(this.oTargetGrid, oConditionGrid); }, layoutData: new GridData({ span: this.getLayoutMode() === "Desktop" ? "L1 M1 S1" : "L1 M10 S10" }) }); oAddControl.oTargetGrid = oTargetGrid; oAddControl.addStyleClass("conditionAddBtnFloatRight"); oButtonContainer.addContent(oAddControl); oConditionGrid["add"] = oAddControl; // Add the new create condition oTargetGrid.insertContent(oConditionGrid, iPos); // update Operations for all conditions this._updateOperationItems(oTargetGrid, oConditionGrid); this._changeOperationValueFields(oTargetGrid, oConditionGrid); // disable fields if the selectedKeyField value is none this._updateAllConditionsEnableStates(); // update the add/remove buttons visibility this._updateConditionButtons(oTargetGrid); if (this.getAutoReduceKeyFieldItems()) { this._updateKeyFieldItems(oTargetGrid, false); } if (this._sLayoutMode) { this._updateLayout({ name: this._sLayoutMode }); } if (oConditionGridData) { var sConditionText = this._getFormatedConditionText(oConditionGridData.operation, oConditionGridData.value1, oConditionGridData.value2, oConditionGridData.exclude, oConditionGridData.keyField, oConditionGridData.showIfGrouped); oConditionGridData._oGrid = oConditionGrid; oConditionGridData.value = sConditionText; this._oConditionsMap[sKey] = oConditionGridData; } var sOperation = oConditionGrid.operation.getSelectedKey(); // in case of a BT and a Date type try to set the minDate/maxDate for the From/To value datepicker if (sOperation === "BT" && oConditionGrid.value1.setMinDate && oConditionGrid.value2.setMaxDate) { var oValue1 = oConditionGrid.value1.getDateValue(); var oValue2 = oConditionGrid.value2.getDateValue(); this._updateMinMaxDate(oConditionGrid, oValue1, oValue2); } else { this._updateMinMaxDate(oConditionGrid, null, null); } return oConditionGrid; }; /** * press handler for the remove Condition buttons * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid from where the Remove is triggered */ P13nConditionPanel.prototype._handleRemoveCondition = function(oTargetGrid, oConditionGrid) { // search index of the condition grid to set the focus later to the previous condition var idx = oTargetGrid.getContent().indexOf(oConditionGrid); this._removeCondition(oTargetGrid, oConditionGrid); if (this.getAutoReduceKeyFieldItems()) { this._updateKeyFieldItems(oTargetGrid, false); } // set the focus on the remove button of the newly added condition if (idx >= 0) { idx = Math.min(idx, oTargetGrid.getContent().length - 1); var oConditionGrid = oTargetGrid.getContent()[idx]; setTimeout(function() { oConditionGrid.remove.focus(); }); } this._updatePaginatorToolbar(); }; /** * press handler for the add condition buttons * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oSourceConditionGrid from where the Add is triggered */ P13nConditionPanel.prototype._handleAddCondition = function(oTargetGrid, oSourceConditionGrid) { var iPos = oTargetGrid.getContent().indexOf(oSourceConditionGrid); var oConditionGrid = this._createConditionRow(oTargetGrid, undefined, null, iPos + 1); this._changeField(oConditionGrid); // set the focus in a fields of the newly added condition setTimeout(function() { oConditionGrid.keyField.focus(); }); this._updatePaginatorToolbar(); }; /** * returns the selectedKeyFields item from the KeyField control. * * @private * @param {control} oKeyFieldCtrl the Select/ComboBox * @returns {object} the selected Keyfields object */ P13nConditionPanel.prototype._getCurrentKeyFieldItem = function(oKeyFieldCtrl) { if (oKeyFieldCtrl.getSelectedKey && oKeyFieldCtrl.getSelectedKey()) { var sKey = oKeyFieldCtrl.getSelectedKey(); var aItems = this._aKeyFields; for (var iItem in aItems) { var oItem = aItems[iItem]; if (oItem.key === sKey) { return oItem; } } } return null; }; /** * creates a new control for the condition value1 and value2 field. Control can be an Input or DatePicker * * @private * @param {object} oCurrentKeyField object of the current selected KeyField which contains type of the column ("string", "date", "time", "numeric" or "boolean") and * a maxLength information * @param {object} oFieldInfo * @param {grid} oConditionGrid which should contain the new created field * @returns {sap.ui.core.Control} the created control instance either Input or DatePicker */ P13nConditionPanel.prototype._createValueField = function(oCurrentKeyField, oFieldInfo, oConditionGrid) { var oControl; var sCtrlType; var that = this; var params = { value: oFieldInfo["Value"], width: "100%", placeholder: oFieldInfo["Label"], change: function(oEvent) { that._validateAndFormatFieldValue(oEvent); that._changeField(oConditionGrid); }, layoutData: new GridData({ span: oFieldInfo["Span" + this._sConditionType] }) }; if (oCurrentKeyField && oCurrentKeyField.typeInstance) { var oType = oCurrentKeyField.typeInstance; sCtrlType = this._findConfig(oType, "ctrl"); // use the DatePicker when type is sap.ui.model.odata.type.DateTime and displayFormat = Date if (sCtrlType === "DateTimePicker" && oType.getMetadata().getName() === "sap.ui.model.odata.type.DateTime") { if (!(oType.oConstraints && oType.oConstraints.isDateOnly)) { Log.error("sap.m.P13nConditionPanel", "sap.ui.model.odata.type.DateTime without displayFormat = Date is not supported!"); oType.oConstraints = Object.assign({}, oType.oConstraints, { isDateOnly : true }); } sCtrlType = "DatePicker"; } //var aOperators = this._findConfig(oType, "operators"); oConditionGrid.oType = oType; if (sCtrlType == "select") { var aItems = []; var aValues = oCurrentKeyField.values || this._oTypeValues[sCtrlType] || [ "", oType.formatValue(false, "string"), oType.formatValue(true, "string") ]; aValues.forEach(function(oValue, index) { aItems.push(new Item({ key: index.toString(), text: oValue.toString() })); }); params = { width: "100%", items: aItems, change: function() { that._changeField(oConditionGrid); }, layoutData: new GridData({ span: oFieldInfo["Span" + this._sConditionType] }) }; oControl = new Select(params); } else if (sCtrlType == "TimePicker") { if (oType.oFormatOptions && oType.oFormatOptions.style) { params.displayFormat = oType.oFormatOptions.style; } oControl = new TimePicker(params); } else if (sCtrlType == "DateTimePicker") { if (oType.oFormatOptions && oType.oFormatOptions.style) { params.displayFormat = oType.oFormatOptions.style; } oControl = new DateTimePicker(params); } else if (sCtrlType == "DatePicker") { if (oType.oFormatOptions && oType.oFormatOptions.style) { params.displayFormat = oType.oFormatOptions.style; } oControl = new DatePicker(params); if (oType && oType.getName() === "sap.ui.comp.odata.type.StringDate") { oControl.setValueFormat("yyyyMMdd"); oControl.setDisplayFormat(oType.oFormatOptions.style || oType.oFormatOptions.pattern); } } else { oControl = new Input(params); //TODO oType should only be set when type is string! if (this._fSuggestCallback) { oCurrentKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); if (oCurrentKeyField && oCurrentKeyField.key) { var oSuggestProvider = this._fSuggestCallback(oControl, oCurrentKeyField.key); if (oSuggestProvider) { oControl._oSuggestProvider = oSuggestProvider; } } } } } else { // for a new added dummy row, which does not have a oCurrentKeyField, we have to create a dummy input field. oConditionGrid.oType = null; oControl = new Input(params); } if (sCtrlType !== "boolean" && sCtrlType !== "enum" && oControl) { oControl.onpaste = function(oEvent) { var sOriginalText; // for the purpose to copy from column in excel and paste in MultiInput/MultiComboBox if (window.clipboardData) { //IE sOriginalText = window.clipboardData.getData("Text"); } else { // Chrome, Firefox, Safari sOriginalText = oEvent.originalEvent.clipboardData.getData('text/plain'); } var oConditionGrid = oEvent.srcControl.getParent(); var aSeparatedText = sOriginalText.split(/\r\n|\r|\n/g); var oOperation = oConditionGrid.operation; var op = oOperation.getSelectedKey(); if (aSeparatedText && aSeparatedText.length > 1 && op !== "BT") { setTimeout(function() { var iLength = aSeparatedText ? aSeparatedText.length : 0; var oKeyField = that._getCurrentKeyFieldItem(oConditionGrid.keyField); var oOperation = oConditionGrid.operation; for (var i = 0; i < iLength; i++) { if (that._aConditionKeys.length >= that._getMaxConditionsAsNumber()) { break; } var sPastedValue = aSeparatedText[i].trim(); if (sPastedValue) { var oPastedValue; if (oKeyField.typeInstance) { // If a typeInstance exist, we have to parse and validate the pastedValue before we can add it a value into the condition. // or we do not handle the paste for all types except String! try { oPastedValue = oKeyField.typeInstance.parseValue(sPastedValue, "string"); oKeyField.typeInstance.validateValue(oPastedValue); } catch (err) { Log.error("sap.m.P13nConditionPanel.onPaste", "not able to parse value " + sPastedValue + " with type " + oKeyField.typeInstance.getName()); sPastedValue = ""; oPastedValue = null; } if (!oPastedValue) { continue; } } var oCondition = { "key": that._createConditionKey(), "exclude": that.getExclude(), "operation": oOperation.getSelectedKey(), "keyField": oKeyField.key, "value1": oPastedValue, "value2": null }; that._addCondition2Map(oCondition); that.fireDataChange({ key: oCondition.key, index: oCondition.index, operation: "add", newData: oCondition }); } } that._clearConditions(); that._fillConditions(); }, 0); } }; } if (oCurrentKeyField && oCurrentKeyField.maxLength && oControl.setMaxLength) { var l = -1; if (typeof oCurrentKeyField.maxLength === "string") { l = parseInt(oCurrentKeyField.maxLength); } if (typeof oCurrentKeyField.maxLength === "number") { l = oCurrentKeyField.maxLength; } if (l > 0 && (!oControl.getShowSuggestion || !oControl.getShowSuggestion())) { oControl.setMaxLength(l); } } return oControl; }; /** * fill all operations from the aOperation array into the select control items list * * @private * @param {control} oCtrl the select control which should be filled * @param {array} aOperations array of operations * @param {string} sType the type prefix for resource access */ P13nConditionPanel.prototype._fillOperationListItems = function(oCtrl, aOperations, sType) { if (sType === "_STRING_") { // ignore the "String" Type when accessing the resource text sType = ""; } if (sType === "_TIME_" || sType === "_DATETIME_") { sType = "_DATE_"; } if (sType === "_BOOLEAN_" || sType === "_NUMC_") { sType = ""; } oCtrl.destroyItems(); for (var iOperation in aOperations) { var sText = this._oRb.getText("CONDITIONPANEL_OPTION" + sType + aOperations[iOperation]); if (sText.startsWith("CONDITIONPANEL_OPTION")) { // when for the specified type the resource does not exist use the normal string resource text sText = this._oRb.getText("CONDITIONPANEL_OPTION" + aOperations[iOperation]); } oCtrl.addItem(new ListItem({ key: aOperations[iOperation], text: sText, tooltip: sText })); } }; /** * fill all KeyFieldItems from the aItems array into the select control items list * * @private * @param {control} oCtrl the select control which should be filled * @param {array} aItems array of keyfields */ P13nConditionPanel.prototype._fillKeyFieldListItems = function(oCtrl, aItems) { oCtrl.destroyItems(); for (var iItem in aItems) { var oItem = aItems[iItem]; oCtrl.addItem(new ListItem({ key: oItem.key, text: oItem.text, tooltip: oItem.tooltip ? oItem.tooltip : oItem.text })); } oCtrl.setEditable(oCtrl.getItems().length > 1); }; /** * change handler for the Operation field * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the Operation control which has been changed */ P13nConditionPanel.prototype._handleChangeOnOperationField = function(oTargetGrid, oConditionGrid) { this._changeOperationValueFields(oTargetGrid, oConditionGrid); this._changeField(oConditionGrid); }; /** * SelectionChange handler for the KeyField field * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the KeyField control which has been changed */ P13nConditionPanel.prototype._handleSelectionChangeOnKeyField = function(oTargetGrid, oConditionGrid) { if (this._sConditionType === "Filter") { this._updateOperationItems(oTargetGrid, oConditionGrid); // update the value fields for the KeyField this._createAndUpdateValueFields(oTargetGrid, oConditionGrid); this._changeOperationValueFields(oTargetGrid, oConditionGrid); } this._changeField(oConditionGrid); }; /** * change handler for the KeyField field * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the KeyField control which has been changed */ P13nConditionPanel.prototype._handleChangeOnKeyField = function(oTargetGrid, oConditionGrid) { if (this.getAutoReduceKeyFieldItems()) { this._updateKeyFieldItems(oTargetGrid, false, false, oConditionGrid.keyField); } }; P13nConditionPanel.prototype._createAndUpdateAllKeyFields = function() { var aConditionGrids = this._oConditionsGrid.getContent(); aConditionGrids.forEach(function(oConditionGrid) { this._createAndUpdateValueFields(this._oConditionsGrid, oConditionGrid); this._changeOperationValueFields(this._oConditionsGrid, oConditionGrid); }, this); }; /** * creates the Value1/2 fields based on the KeyField Type * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the KeyField control which has been changed */ P13nConditionPanel.prototype._createAndUpdateValueFields = function(oTargetGrid, oConditionGrid) { // update the value fields for the KeyField var oCurrentKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); var fnCreateAndUpdateField = function(oConditionGrid, oCtrl, index) { var sOldValue = oCtrl.getValue ? oCtrl.getValue() : ""; var ctrlIndex = oConditionGrid.indexOfContent(oCtrl); // we have to remove the control into the content with rerendering (bSuppressInvalidate=false) the UI, // otherwise in some use cases the "between" value fields will not be rendered. // This additional rerender might trigger some problems for screenreader. oConditionGrid.removeContent(oCtrl); //oConditionGrid.removeAggregation("content", oCtrl, true); if (oCtrl._oSuggestProvider) { oCtrl._oSuggestProvider.destroy(); oCtrl._oSuggestProvider = null; } oCtrl.destroy(); var fieldInfo = this._aConditionsFields[index]; oCtrl = this._createValueField(oCurrentKeyField, fieldInfo, oConditionGrid); oConditionGrid[fieldInfo["ID"]] = oCtrl; oConditionGrid.insertContent(oCtrl, ctrlIndex === -1 ? oConditionGrid.indexOfContent(oConditionGrid.operation) + 1 : ctrlIndex); var oValue, sValue; if (oConditionGrid.oType && sOldValue) { try { oValue = oConditionGrid.oType.parseValue(sOldValue, "string"); oConditionGrid.oType.validateValue(oValue); sValue = oConditionGrid.oType.formatValue(oValue, "string"); oCtrl.setValue(sValue); } catch (err) { var sMsg = err.message; this._makeFieldValid(oCtrl, false, sMsg); oCtrl.setValue(sOldValue); } } }; // update Value1 field control fnCreateAndUpdateField.bind(this)(oConditionGrid, oConditionGrid.value1, 5); // update Value2 field control fnCreateAndUpdateField.bind(this)(oConditionGrid, oConditionGrid.value2, 6); }; P13nConditionPanel.prototype._updateAllOperations = function() { var aConditionGrids = this._oConditionsGrid.getContent(); aConditionGrids.forEach(function(oConditionGrid) { this._updateOperationItems(this._oConditionsGrid, oConditionGrid); this._changeOperationValueFields(this._oConditionsGrid, oConditionGrid); }, this); }; /** * update the Operations for a condition row based on the type of the selected keyField * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the KeyField control and the Operations field which will be updated */ P13nConditionPanel.prototype._updateOperationItems = function(oTargetGrid, oConditionGrid) { var sType = ""; var oKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); var oOperation = oConditionGrid.operation; var aOperations = this._oTypeOperations["default"]; var oCurrentSelectedItem = oOperation.getSelectedItem(); if (oKeyField) { if (oKeyField.type && oKeyField.type !== "" && this._oTypeOperations[oKeyField.type]) { sType = oKeyField.type; aOperations = this._oTypeOperations[sType]; } if (oKeyField.operations) { aOperations = oKeyField.operations; } } this._fillOperationListItems(oOperation, aOperations, sType ? "_" + sType.toUpperCase() + "_" : ""); if (oCurrentSelectedItem && oOperation.getItemByKey(oCurrentSelectedItem.getKey())) { // when old selected items key exist select the same key oOperation.setSelectedKey(oCurrentSelectedItem.getKey()); } else { oOperation.setSelectedItem(oOperation.getItems()[0]); } this._sConditionType = "Filter"; if (aOperations[0] === P13nConditionOperation.Ascending || aOperations[0] === P13nConditionOperation.Descending) { this._sConditionType = "Sort"; } if (aOperations[0] === P13nConditionOperation.GroupAscending || aOperations[0] === P13nConditionOperation.GroupDescending) { this._sConditionType = "Group"; } this._adjustValue1Span(oConditionGrid); }; /** * update the Items from all KeyFields * * @private * @param {grid} oTargetGrid the main grid * @param {boolean} bFillAll fills all KeyFields or only the none used * @param {boolean} bAppendLast adds only the last Keyfield to the Items of the selected controls */ P13nConditionPanel.prototype._updateKeyFieldItems = function(oTargetGrid, bFillAll, bAppendLast, oIgnoreKeyField) { var n = oTargetGrid.getContent().length; var i; // collect all used Keyfields var oUsedItems = {}; if (!bFillAll) { for (i = 0; i < n; i++) { var oKeyField = oTargetGrid.getContent()[i].keyField; var sKey = oKeyField.getSelectedKey(); if (sKey != null && sKey !== "") { oUsedItems[sKey] = true; } } } for (i = 0; i < n; i++) { var oKeyField = oTargetGrid.getContent()[i].keyField; var oSelectCheckbox = oTargetGrid.getContent()[i].select; var sOldKey = oKeyField.getSelectedKey(); var j = 0; var aItems = this._aKeyFields; if (oKeyField !== oIgnoreKeyField) { if (bAppendLast) { j = aItems.length - 1; } else { // clean the items oKeyField.destroyItems(); } // fill all or only the not used items for (j; j < aItems.length; j++) { var oItem = aItems[j]; if (oItem.key == null || oItem.key === "" || !oUsedItems[oItem.key] || oItem.key === sOldKey) { oKeyField.addItem(new ListItem({ key: oItem.key, text: oItem.text, tooltip: oItem.tooltip ? oItem.tooltip : oItem.text })); } } oKeyField.setEditable(oKeyField.getItems().length > 1); } if (sOldKey) { oKeyField.setSelectedKey(sOldKey); } else if (oKeyField.getItems().length > 0) { // make at least the first item the selected item. We need this for updating the tooltip oKeyField.setSelectedItem(oKeyField.getItems()[0]); } if (!oSelectCheckbox.getSelected()) { // set/update the isDefault keyfield as selected item for an empty condition row /* eslint-disable no-loop-func */ this._aKeyFields.some(function(oKeyFieldItem, index) { if (oKeyFieldItem.isDefault) { oKeyField.setSelectedItem(oKeyField.getItems()[index]); return true; } if (!oKeyField.getSelectedItem()) { if (oKeyFieldItem.type !== "boolean") { oKeyField.setSelectedItem(oKeyField.getItems()[index]); } } }, this); } // update the tooltip if (oKeyField.getSelectedItem()) { oKeyField.setTooltip(oKeyField.getSelectedItem().getTooltip() || oKeyField.getSelectedItem().getText()); } } }; /** * called when the user makes a change on the condition operation. The function will update all other fields in the condition grid. * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the Operation control which has been changed */ P13nConditionPanel.prototype._changeOperationValueFields = function(oTargetGrid, oConditionGrid) { // var oKeyfield = oConditionGrid.keyField; var oOperation = oConditionGrid.operation; var sOperation = oOperation.getSelectedKey(); var oValue1 = oConditionGrid.value1; var oValue2 = oConditionGrid.value2; var oShowIfGroupedvalue = oConditionGrid.showIfGrouped; if (!sOperation) { return; } if (sOperation === P13nConditionOperation.BT) { // for the "between" operation we enable both fields if (oValue1.setPlaceholder && oValue1.getPlaceholder() !== this._sFromLabelText) { oValue1.setPlaceholder(this._sFromLabelText); } if (!oValue1.getVisible()) { oValue1.setVisible(true); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.insertContent(oValue1, oConditionGrid.getContent().length - 1); } if (oValue2.setPlaceholder && oValue2.getPlaceholder() !== this._sToLabelText) { oValue2.setPlaceholder(this._sToLabelText); } if (!oValue2.getVisible()) { oValue2.setVisible(true); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.insertContent(oValue2, oConditionGrid.getContent().length - 1); } } else { if (sOperation === P13nConditionOperation.GroupAscending || sOperation === P13nConditionOperation.GroupDescending) { // update visible of fields if (oValue1.getVisible()) { oValue1.setVisible(false); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.removeContent(oValue1); } if (oValue2.getVisible()) { oValue2.setVisible(false); oConditionGrid.removeContent(oValue2); } if (oOperation.getVisible()) { oOperation.setVisible(false); oConditionGrid.removeContent(oOperation); } oShowIfGroupedvalue.setVisible(this._getMaxConditionsAsNumber() != 1); } else { if (sOperation === P13nConditionOperation.NotEmpty || sOperation === P13nConditionOperation.Empty || sOperation === P13nConditionOperation.Initial || sOperation === P13nConditionOperation.Ascending || sOperation === P13nConditionOperation.Descending || sOperation === P13nConditionOperation.Total || sOperation === P13nConditionOperation.Average || sOperation === P13nConditionOperation.Minimum || sOperation === P13nConditionOperation.Maximum) { // for this operations we disable both value fields if (oValue1.getVisible()) { oValue1.setVisible(false); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.removeContent(oValue1); } if (oValue2.getVisible()) { oValue2.setVisible(false); oConditionGrid.removeContent(oValue2); } // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.removeContent(oShowIfGroupedvalue); } else { // for all other operations we enable only the Value1 fields if (oValue1.setPlaceholder && oValue1.getPlaceholder() !== this._sValueLabelText) { oValue1.setPlaceholder(this._sValueLabelText); } if (!oValue1.getVisible()) { oValue1.setVisible(true); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.insertContent(oValue1, oConditionGrid.getContent().length - 1); } if (oValue2.getVisible()) { oValue2.setVisible(false); oConditionGrid.removeContent(oValue2); } } } } this._adjustValue1Span(oConditionGrid); }; /* * toggle the value1 field span between L5 and L3 depending on the selected operation */ P13nConditionPanel.prototype._adjustValue1Span = function(oConditionGrid) { if (this._sConditionType === "Filter" && oConditionGrid.value1 && oConditionGrid.operation) { var oOperation = oConditionGrid.operation; var sNewSpan = this._aConditionsFields[5]["Span" + this._sConditionType]; if (oOperation.getSelectedKey() !== "BT") { sNewSpan = "L5 M10 S10"; } var oLayoutData = oConditionGrid.value1.getLayoutData(); if (oLayoutData.getSpan() !== sNewSpan) { oLayoutData.setSpan(sNewSpan); } } }; /* * return the index of the oConditionGrid, the none valid condition will be ignored. */ P13nConditionPanel.prototype._getIndexOfCondition = function(oConditionGrid) { var iIndex = -1; oConditionGrid.getParent().getContent().some(function(oGrid) { if (oGrid.select.getSelected()) { iIndex++; } return (oGrid === oConditionGrid); }, this); return iIndex + this._iFirstConditionIndex; }; /* * makes a control valid or invalid, means it gets a warning state and shows a warning message attached to the field. * */ P13nConditionPanel.prototype._makeFieldValid = function(oCtrl, bValid, sMsg) { if (bValid) { oCtrl.setValueState(ValueState.None); oCtrl.setValueStateText(""); } else { oCtrl.setValueState(ValueState.Warning); oCtrl.setValueStateText(sMsg ? sMsg : this._sValidationDialogFieldMessage); } }; /* * change event handler for a value1 and value2 field control */ P13nConditionPanel.prototype._validateAndFormatFieldValue = function(oEvent) { var oCtrl = oEvent.oSource; var oConditionGrid = oCtrl.getParent(); var sValue; if (oCtrl.getDateValue && oEvent) { sValue = oEvent.getParameter("value"); var bValid = oEvent.getParameter("valid"); this._makeFieldValid(oCtrl, bValid); return; } else { sValue = oCtrl.getValue && oCtrl.getValue(); } if (!oConditionGrid) { return; } if (this.getDisplayFormat() === "UpperCase" && sValue) { sValue = sValue.toUpperCase(); oCtrl.setValue(sValue); } if (oConditionGrid.oType && sValue) { try { var oValue = oConditionGrid.oType.parseValue(sValue, "string"); oConditionGrid.oType.validateValue(oValue); this._makeFieldValid(oCtrl, true); sValue = oConditionGrid.oType.formatValue(oValue, "string"); oCtrl.setValue(sValue); } catch (err) { var sMsg = err.message; this._makeFieldValid(oCtrl, false, sMsg); } } else { this._makeFieldValid(oCtrl, true); } }; P13nConditionPanel.prototype._updateMinMaxDate = function(oConditionGrid, oValue1, oValue2) { if (oConditionGrid.value1.setMinDate && oConditionGrid.value2.setMaxDate) { if (oConditionGrid.value1 && oConditionGrid.value1.setMaxDate) { oConditionGrid.value1.setMaxDate(oValue2 instanceof Date ? oValue2 : null); } if (oConditionGrid.value2 && oConditionGrid.value2.setMinDate) { oConditionGrid.value2.setMinDate(oValue1 instanceof Date ? oValue1 : null); } } }; /** * called when the user makes a change in one of the condition fields. The function will update, remove or add the conditions for this condition. * * @private * @param {grid} oConditionGrid Grid which contains the Operation control which has been changed */ P13nConditionPanel.prototype._changeField = function(oConditionGrid, oEvent) { var sKeyField = oConditionGrid.keyField.getSelectedKey(); if (oConditionGrid.keyField.getSelectedItem()) { oConditionGrid.keyField.setTooltip(oConditionGrid.keyField.getSelectedItem().getTooltip() || oConditionGrid.keyField.getSelectedItem().getText()); } else { oConditionGrid.keyField.setTooltip(null); } var sOperation = oConditionGrid.operation.getSelectedKey(); if (oConditionGrid.operation.getSelectedItem()) { oConditionGrid.operation.setTooltip(oConditionGrid.operation.getSelectedItem().getTooltip() || oConditionGrid.operation.getSelectedItem().getText()); } else { oConditionGrid.operation.setTooltip(null); } var getValuesFromField = function(oControl, oType) { var sValue; var oValue; if (oControl.getDateValue && !(oControl.isA("sap.m.TimePicker")) && oType.getName() !== "sap.ui.comp.odata.type.StringDate") { oValue = oControl.getDateValue(); if (oType && oValue) { sValue = oType.formatValue(oValue, "string"); } } else { sValue = this._getValueTextFromField(oControl); oValue = sValue; if (oType && oType.getName() === "sap.ui.comp.odata.type.StringDate") { sValue = oType.formatValue(oValue, "string"); } else if (oType && sValue) { try { oValue = oType.parseValue(sValue, "string"); oType.validateValue(oValue); } catch (err) { sValue = ""; Log.error("sap.m.P13nConditionPanel", "not able to parse value " + sValue + " with type " + oType.getName()); } } } return [oValue, sValue]; }.bind(this); // update Value1 field control var aValues = getValuesFromField(oConditionGrid.value1, oConditionGrid.oType); var oValue1 = aValues[0], sValue1 = aValues[1]; // update Value2 field control aValues = getValuesFromField(oConditionGrid.value2, oConditionGrid.oType); var oValue2 = aValues[0], sValue2 = aValues[1]; // in case of a BT and a Date type try to set the minDate/maxDate for the From/To value datepicker if (sOperation === "BT") { this._updateMinMaxDate(oConditionGrid, oValue1, oValue2); } else { this._updateMinMaxDate(oConditionGrid, null, null); } var oCurrentKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); if (oCurrentKeyField && oCurrentKeyField.type === "numc") { // in case of type numc and Contains or EndsWith operator the leading 0 will be removed if ([P13nConditionOperation.Contains, P13nConditionOperation.EndsWith].indexOf(sOperation) != -1) { oValue1 = oConditionGrid.oType.formatValue(oValue1, "string"); } } var bShowIfGrouped = oConditionGrid.showIfGrouped.getSelected(); var bExclude = this.getExclude(); var oSelectCheckbox = oConditionGrid.select; var sValue = ""; var sKey; if (sKeyField === "" || sKeyField == null) { // handling of "(none)" or wrong entered keyField value sKeyField = null; sKey = this._getKeyFromConditionGrid(oConditionGrid); this._removeConditionFromMap(sKey); this._enableCondition(oConditionGrid, false); var iIndex = this._getIndexOfCondition(oConditionGrid); if (oSelectCheckbox.getSelected()) { oSelectCheckbox.setSelected(false); oSelectCheckbox.setEnabled(false); this._bIgnoreSetConditions = true; this.fireDataChange({ key: sKey, index: iIndex, operation: "remove", newData: null }); this._bIgnoreSetConditions = false; } return; } this._enableCondition(oConditionGrid, true); sValue = this._getFormatedConditionText(sOperation, sValue1, sValue2, bExclude, sKeyField, bShowIfGrouped); var oConditionData = { "value": sValue, "exclude": bExclude, "operation": sOperation, "keyField": sKeyField, "value1": oValue1, "value2": sOperation === P13nConditionOperation.BT ? oValue2 : null, "showIfGrouped": bShowIfGrouped }; sKey = this._getKeyFromConditionGrid(oConditionGrid); if (sValue !== "") { oSelectCheckbox.setSelected(true); oSelectCheckbox.setEnabled(true); var sOperation = "update"; if (!this._oConditionsMap[sKey]) { sOperation = "add"; } this._oConditionsMap[sKey] = oConditionData; if (sOperation === "add") { this._aConditionKeys.splice(this._getIndexOfCondition(oConditionGrid), 0, sKey); } //this._addCondition2Map(oConditionData, this._getIndexOfCondition(oConditionGrid)); oConditionGrid.data("_key", sKey); this.fireDataChange({ key: sKey, index: this._getIndexOfCondition(oConditionGrid), operation: sOperation, newData: oConditionData }); } else if (this._oConditionsMap[sKey] !== undefined) { this._removeConditionFromMap(sKey); oConditionGrid.data("_key", null); var iIndex = this._getIndexOfCondition(oConditionGrid); if (oSelectCheckbox.getSelected()) { oSelectCheckbox.setSelected(false); oSelectCheckbox.setEnabled(false); this._bIgnoreSetConditions = true; this.fireDataChange({ key: sKey, index: iIndex, operation: "remove", newData: null }); this._bIgnoreSetConditions = false; } } this._updatePaginatorToolbar(); }; /* * returns the value as text from a Value field. */ P13nConditionPanel.prototype._getValueTextFromField = function(oControl) { if (oControl instanceof Select) { return oControl.getSelectedItem() ? oControl.getSelectedItem().getText() : ""; } return oControl.getValue(); }; /** * update the enabled state for all conditions * * @private */ P13nConditionPanel.prototype._updateAllConditionsEnableStates = function() { var aConditionGrids = this._oConditionsGrid.getContent(); aConditionGrids.forEach(function(oConditionGrid) { var oKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); var sKeyField = oKeyField && oKeyField.key !== undefined ? oKeyField.key : oKeyField; var bEnabled = sKeyField !== "" && sKeyField !== null; this._enableCondition(oConditionGrid, bEnabled); }, this); }; /** * makes all controls in a condition Grid enabled or disabled * * @private * @param {grid} oConditionGrid instance * @param {boolean} bEnable state */ P13nConditionPanel.prototype._enableCondition = function(oConditionGrid, bEnable) { oConditionGrid.operation.setEnabled(bEnable); oConditionGrid.value1.setEnabled(bEnable); oConditionGrid.value2.setEnabled(bEnable); oConditionGrid.showIfGrouped.setEnabled(bEnable); }; /** * press handler for the remove condition buttons * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid from where the remove is triggered */ P13nConditionPanel.prototype._removeCondition = function(oTargetGrid, oConditionGrid) { var sKey = this._getKeyFromConditionGrid(oConditionGrid); var iIndex = -1; if (oConditionGrid.select.getSelected()) { iIndex = this._getIndexOfCondition(oConditionGrid); } this._removeConditionFromMap(sKey); oConditionGrid.destroy(); if (oTargetGrid.getContent().length < 1) { this._createConditionRow(oTargetGrid); } else { this._updateConditionButtons(oTargetGrid); } if (iIndex >= 0) { this.fireDataChange({ key: sKey, index: iIndex, operation: "remove", newData: null }); } }; /** * update the condition add/remove buttons visibility * * @private * @param {grid} oTargetGrid the main grid */ P13nConditionPanel.prototype._updateConditionButtons = function(oTargetGrid) { var iMaxConditions = this._getMaxConditionsAsNumber(); var n = oTargetGrid.getContent().length; // if (n >= this._aKeyFields.length-1 && this.getAutoReduceKeyFieldItems()) { // // if the number of condition_rows-1 is the same as the KeyFields we hide the Add icon on all // condition rows. // iMax = 0; // } for (var i = 0; i < n; i++) { var oAddBtn = oTargetGrid.getContent()[i].add; if ((this.getAlwaysShowAddIcon() && (n < iMaxConditions)) || (i === n - 1 && i < iMaxConditions - 1)) { // show the Add only for the last condition row and if the Max value is not reached oAddBtn.removeStyleClass("displayNone"); } else { oAddBtn.addStyleClass("displayNone"); } var oRemoveBtn = oTargetGrid.getContent()[i].remove; if (iMaxConditions === 1 || (i === 0 && n === 1 && this.getDisableFirstRemoveIcon())) { oRemoveBtn.addStyleClass("displayNone"); } else { oRemoveBtn.removeStyleClass("displayNone"); } } }; /** * check if the entered/modified conditions are correct, marks invalid fields yellow (Warning state) and can be used to show error message dialog and give the * user the feedback that some values are wrong or missing. * * @private * @returns {boolean} <code>True</code> if all conditions are valid, <code>false</code> otherwise. * */ P13nConditionPanel.prototype.validateConditions = function() { var that = this; var fnCheckConditions = function(aGrids) { var bValid = true; for (var i = 0; i < aGrids.length; i++) { var oGrid = aGrids[i]; var bIsValid = that._checkCondition(oGrid, i === aGrids.length - 1); bValid = bValid && bIsValid; } return bValid; }; return fnCheckConditions(this._oConditionsGrid.getContent()); }; /** * removes all errors/warning states from the value1/2 fields of all conditions. * * @public * @since 1.28.0 */ P13nConditionPanel.prototype.removeValidationErrors = function() { this._oConditionsGrid.getContent().forEach(function(oConditionGrid) { var oValue1 = oConditionGrid.value1; var oValue2 = oConditionGrid.value2; oValue1.setValueState(ValueState.None); oValue1.setValueStateText(""); oValue2.setValueState(ValueState.None); oValue2.setValueStateText(""); }, this); }; /** * removes all invalid conditions. * * @public * @since 1.28.0 */ P13nConditionPanel.prototype.removeInvalidConditions = function() { var aInvalidConditionGrids = []; this._oConditionsGrid.getContent().forEach(function(oConditionGrid) { if (oConditionGrid.value1.getValueState() !== ValueState.None || oConditionGrid.value2.getValueState() !== ValueState.None) { aInvalidConditionGrids.push(oConditionGrid); } }, this); aInvalidConditionGrids.forEach(function(oConditionGrid) { this._removeCondition(this._oConditionsGrid, oConditionGrid); if (this.getAutoReduceKeyFieldItems()) { this._updateKeyFieldItems(this._oConditionsGrid, false); } }, this); }; /** * checks on a single condition if the values are filled correct and set the Status of invalid fields to Warning. The condition is invalid, when * e.g. in the BT condition one or both of the values is/are empty of for other condition operations the value1 field is not filled. * * @private * @param {Grid} oConditionGrid which contains the fields of a single condition * @param {boolean} isLast indicated if this is the last condition in the group * @returns {boolean} true, when the condition is filled correct, else false. */ P13nConditionPanel.prototype._checkCondition = function(oConditionGrid, isLast) { var bValid = true; var value1 = oConditionGrid.value1; var value2 = oConditionGrid.value2; var bValue1Empty = value1 && (value1.getVisible() && !this._getValueTextFromField(value1)); var bValue1State = value1 && value1.getVisible() && value1.getValueState ? value1.getValueState() : ValueState.None; var bValue2Empty = value2 && (value2.getVisible() && !this._getValueTextFromField(value2)); var bValue2State = value2 && value2.getVisible() && value2.getValueState ? value2.getValueState() : ValueState.None; var sOperation = oConditionGrid.operation.getSelectedKey(); if (sOperation === P13nConditionOperation.BT) { if (!bValue1Empty ? bValue2Empty : !bValue2Empty) { // XOR if (bValue1Empty) { value1.setValueState(ValueState.Warning); value1.setValueStateText(this._sValidationDialogFieldMessage); } if (bValue2Empty) { value2.setValueState(ValueState.Warning); value2.setValueStateText(this._sValidationDialogFieldMessage); } bValid = false; } else if (bValue1State !== ValueState.None || bValue2State !== ValueState.None) { bValid = false; } else { value1.setValueState(ValueState.None); value1.setValueStateText(""); value2.setValueState(ValueState.None); value2.setValueStateText(""); } } if ((value1.getVisible() && value1.getValueState && value1.getValueState() !== ValueState.None) || (value2.getVisible() && value2.getValueState && value2.getValueState() !== ValueState.None)) { bValid = false; } return bValid; }; /** * creates and returns the text for a condition * * @private * @param {string} sOperation the operation type sap.m.P13nConditionOperation * @param {string} sValue1 text of the first condition field * @param {string} sValue2 text of the second condition field * @param {boolean} bExclude indicates if the condition is an Exclude condition * @param {string} sKeyField id * @returns {string} the condition text */ P13nConditionPanel.prototype._getFormatedConditionText = function(sOperation, sValue1, sValue2, bExclude, sKeyField, bShowIfGrouped) { var sConditionText = P13nConditionPanel.getFormatedConditionText(sOperation, sValue1, sValue2, bExclude); if (!sConditionText) { switch (sOperation) { case P13nConditionOperation.Initial: sConditionText = "=''"; break; case P13nConditionOperation.NotEmpty: sConditionText = "!''"; break; case P13nConditionOperation.Ascending: sConditionText = "ascending"; break; case P13nConditionOperation.GroupAscending: sConditionText = "ascending"; sConditionText += " showIfGrouped:" + bShowIfGrouped; break; case P13nConditionOperation.Descending: sConditionText = "descending"; break; case P13nConditionOperation.GroupDescending: sConditionText = "descending"; sConditionText += " showIfGrouped:" + bShowIfGrouped; break; case P13nConditionOperation.Total: sConditionText = "total"; break; case P13nConditionOperation.Average: sConditionText = "average"; break; case P13nConditionOperation.Minimum: sConditionText = "minimum"; break; case P13nConditionOperation.Maximum: sConditionText = "maximum"; break; } if (bExclude && sConditionText !== "") { sConditionText = "!(" + sConditionText + ")"; } } if (this._aKeyFields && this._aKeyFields.length > 1) { var sKeyFieldText = null; // search the text for the KeyField for (var i = 0; i < this._aKeyFields.length; i++) { var oKeyField = this._aKeyFields[i]; if (typeof oKeyField !== "string") { if (oKeyField.key === sKeyField && oKeyField.text) { sKeyFieldText = oKeyField.text; } } } if (sKeyFieldText && sConditionText !== "") { sConditionText = sKeyFieldText + ": " + sConditionText; } } return sConditionText; }; /** * @enum {string} * @public * @experimental since version 1.26 !!! THIS TYPE IS ONLY FOR INTERNAL USE !!! */ // TODO: move to library.js var P13nConditionOperation = sap.m.P13nConditionOperation = { // filter operations BT: "BT", EQ: "EQ", Contains: "Contains", StartsWith: "StartsWith", EndsWith: "EndsWith", LT: "LT", LE: "LE", GT: "GT", GE: "GE", Initial: "Initial", Empty: "Empty", NotEmpty: "NotEmpty", // sort operations Ascending: "Ascending", Descending: "Descending", // group operations GroupAscending: "GroupAscending", GroupDescending: "GroupDescending", // calculation operations Total: "Total", Average: "Average", Minimum: "Minimum", Maximum: "Maximum" }; P13nConditionPanel._oConditionMap = { "EQ": "=$0", "GT": ">$0", "GE": ">=$0", "LT": "<$0", "LE": "<=$0", "Contains": "*$0*", "StartsWith": "$0*", "EndsWith": "*$0", "BT": "$0...$1", "Empty": "<$r>" }; // Replase $r params in operation by resource bundle text (function() { var _oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m"); P13nConditionPanel._oConditionMap[P13nConditionOperation.Empty] = P13nConditionPanel._oConditionMap[P13nConditionOperation.Empty].replace("$r", _oRb.getText("CONDITIONPANEL_OPTIONEmpty")); })(); /** * fills the template string placeholder $0, $1 with the values from the aValues array and returns a formatted text for the specified condition * @private * @param {string} sTemplate the template which should be filled * @param {string[]} aValues value array for the template placeholder * @returns {string} the filled template text */ P13nConditionPanel._templateReplace = function(sTemplate, aValues) { return sTemplate.replace(/\$\d/g, function(sMatch) { return aValues[parseInt(sMatch.substr(1))]; }); }; /** * creates and returns a formatted text for the specified condition * @public * @param {string} sOperation the operation type sap.m.P13nConditionOperation * @param {string} sValue1 value of the first range field * @param {string} sValue2 value of the second range field * @param {boolean} bExclude indicates if the range is an Exclude range * @returns {string} the range token text. An empty string when no operation matches or the values for the operation are wrong */ P13nConditionPanel.getFormatedConditionText = function(sOperation, sValue1, sValue2, bExclude) { var sConditionText = ""; switch (sOperation) { case P13nConditionOperation.Empty: sConditionText = P13nConditionPanel._templateReplace(P13nConditionPanel._oConditionMap[sOperation], []); break; case P13nConditionOperation.EQ: case P13nConditionOperation.GT: case P13nConditionOperation.GE: case P13nConditionOperation.LT: case P13nConditionOperation.LE: case P13nConditionOperation.Contains: case P13nConditionOperation.StartsWith: case P13nConditionOperation.EndsWith: if (sValue1 !== "" && sValue1 !== undefined) { sConditionText = P13nConditionPanel._templateReplace(P13nConditionPanel._oConditionMap[sOperation], [sValue1]); } break; case P13nConditionOperation.BT: if (sValue1 !== "" && sValue1 !== undefined) { if (sValue2 !== "" && sValue2 !== undefined) { sConditionText = P13nConditionPanel._templateReplace(P13nConditionPanel._oConditionMap[sOperation], [sValue1, sValue2]); } } break; default: break; } if (bExclude && sConditionText !== "") { sConditionText = "!(" + sConditionText + ")"; } return sConditionText; }; P13nConditionPanel.prototype._updateLayout = function(oRangeInfo) { if (!this._oConditionsGrid) { return; } // if (window.console) { // window.console.log(" ---> " + oRangeInfo.name); // } var aGrids = this._oConditionsGrid.getContent(); var n = this._aConditionsFields.length; var newIndex = n; if (oRangeInfo.name === "Tablet") { newIndex = 5; } if (oRangeInfo.name === "Phone") { newIndex = 3; } if (this._sConditionType === "Filter") { for (var i = 0; i < aGrids.length; i++) { var grid = aGrids[i]; grid.ButtonContainer.removeStyleClass("floatRight"); grid.removeContent(grid.ButtonContainer); grid.insertContent(grid.ButtonContainer, newIndex); if (!this.getAlwaysShowAddIcon()) { if (newIndex !== n) { grid.ButtonContainer.removeContent(grid.add); grid.addContent(grid.add); } else { grid.removeContent(grid.add); grid.ButtonContainer.addContent(grid.add); } } } } }; P13nConditionPanel.prototype._onGridResize = function() { var w; // update the paginator toolbar width if exist if (this._oPaginatorToolbar && this._oConditionsGrid && this._oConditionsGrid.getContent().length > 0) { var oGrid = this._oConditionsGrid.getContent()[0]; if (oGrid.remove && oGrid.remove.$().position()) { w = 0; if (this._oPaginatorToolbar.getParent() && this._oPaginatorToolbar.getParent().getExpandable && this._oPaginatorToolbar.getParent().getExpandable()) { w = 48 - 4; } var iToolbarWidth = oGrid.remove.$().position().left - w + oGrid.remove.$().width(); //TODO - Panel expand button width + remove icon width this._oPaginatorToolbar.setWidth(iToolbarWidth + "px"); } } var domElement = this._oConditionsGrid.getDomRef(); if (!domElement) { return; } if (!jQuery(domElement).is(":visible")) { return; } w = domElement.clientWidth; var oRangeInfo = {}; if (w <= this._iBreakPointTablet) { oRangeInfo.name = "Phone"; } else if ((w > this._iBreakPointTablet) && (w <= this._iBreakPointDesktop)) { oRangeInfo.name = "Tablet"; } else { oRangeInfo.name = "Desktop"; } //if (window.console) { //window.console.log(w + " resize ---> " + oRangeInfo.name); //} if (oRangeInfo.name === "Phone" && this._sLayoutMode !== oRangeInfo.name) { this._updateLayout(oRangeInfo); this._sLayoutMode = oRangeInfo.name; } if (oRangeInfo.name === "Tablet" && this._sLayoutMode !== oRangeInfo.name) { this._updateLayout(oRangeInfo); this._sLayoutMode = oRangeInfo.name; } if (oRangeInfo.name === "Desktop" && this._sLayoutMode !== oRangeInfo.name) { this._updateLayout(oRangeInfo); this._sLayoutMode = oRangeInfo.name; } }; // this._findConfig("sap.ui.model.odata.type.Date", "operators") -->["EQ", "BT", "LE", "LT", "GE", "GT", "NE"] // this._findConfig("sap.ui.model.odata.type.Date", "ctrl") -->"DatePicker" P13nConditionPanel.prototype._findConfig = function(vType, sConfigName) { if (typeof vType === "object") { vType = vType.getMetadata().getName(); } var oConfig; while (vType && !(oConfig = this._getConfig(vType, sConfigName))) { // search until we have a type with known operators vType = this._getParentType(vType); // go to parent type } // either vType is undefined because no type in the hierarchy had the config, or oConfig does now have the desired information return oConfig; // TODO: return base config if undefined? However, this only makes a difference when a type is not derived from base. Would this be intentional or an error? }; P13nConditionPanel.prototype._getConfig = function(sType, sConfigName) { // no vType support here, because called often var oConfig = this._mOpsForType[sType]; if (oConfig) { return oConfig[sConfigName]; } }; P13nConditionPanel.prototype._getParentType = function(sType) { return this._mTypes[sType]; }; P13nConditionPanel.prototype._mTypes = { // basic "base": undefined, // TODO: needed? "string": "base", "numeric": "base", "date": "base", "time": "base", "boolean": "base", "int": "numeric", "float": "numeric", // simple "sap.ui.model.type.Boolean": "boolean", "sap.ui.model.type.Date": "date", "sap.ui.model.type.FileSize": "string", "sap.ui.model.type.Float": "float", "sap.ui.model.type.Integer": "int", "sap.ui.model.type.String": "string", "sap.ui.model.type.Time": "time", "sap.ui.comp.odata.type.StringDate": "date", // odata "sap.ui.model.odata.type.Boolean": "boolean", "sap.ui.model.odata.type.Byte": "int", "sap.ui.model.odata.type.Date": "date", "sap.ui.model.odata.type.DateTime": "datetime", "sap.ui.model.odata.type.DateTimeOffset": "datetime", "sap.ui.model.odata.type.Decimal": "float", "sap.ui.model.odata.type.Double": "float", "sap.ui.model.odata.type.Single": "float", "sap.ui.model.odata.type.Guid": "string", "sap.ui.model.odata.type.Int16": "int", "sap.ui.model.odata.type.Int32": "int", "sap.ui.model.odata.type.Int64": "int", "sap.ui.model.odata.type.Raw": "string", "sap.ui.model.odata.type.SByte": "int", "sap.ui.model.odata.type.String": "string", "sap.ui.model.odata.type.Time": "time", "sap.ui.model.odata.type.TimeOfDay": "time", //edm "Edm.Boolean": "sap.ui.model.odata.type.Boolean", "Edm.Byte": "sap.ui.model.odata.type.Byte", "Edm.Date": "sap.ui.model.odata.type.Date", // V4 Date "Edm.DateTime": "sap.ui.model.odata.type.DateTime", // only for V2 constraints: {displayFormat: 'Date' } "Edm.DateTimeOffset": "sap.ui.model.odata.type.DateTimeOffset", //constraints: { V4: true, precision: n } "Edm.Decimal": "sap.ui.model.odata.type.Decimal", //constraints: { precision, scale, minimum, maximum, minimumExclusive, maximumExclusive} "Edm.Double": "sap.ui.model.odata.type.Double", "Edm.Single": "sap.ui.model.odata.type.Single", "Edm.Guid": "sap.ui.model.odata.type.Guid", "Edm.Int16": "sap.ui.model.odata.type.Int16", "Edm.Int32": "sap.ui.model.odata.type.Int32", "Edm.Int64": "sap.ui.model.odata.type.Int64", //Edm.Raw not supported "Edm.SByte": "sap.ui.model.odata.type.SByte", "Edm.String": "sap.ui.model.odata.type.String", //constraints: {maxLength, isDigitSequence} "Edm.Time": "sap.ui.model.odata.type.Time", // only V2 "Edm.TimeOfDay": "sap.ui.model.odata.type.TimeOfDay" // V4 constraints: {precision} }; P13nConditionPanel.prototype._mOpsForType = { // defines operators for types "base": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT", "NE"], // defaultOperator: "EQ", ctrl: "input" }, "string": { // operators: ["Contains", "EQ", "BT", "StartsWith", "EndsWith", "LE", "LT", "GE", "GT", "NE"], // defaultOperator: "StartsWith", ctrl: "input" }, "date": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT", "NE"], ctrl: "DatePicker" }, "datetime": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT", "NE"], ctrl: "DateTimePicker" }, "numeric": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT", "NE"], ctrl: "input" }, "time": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT"], ctrl: "TimePicker" }, "boolean": { // operators: ["EQ", "NE"], ctrl: "select" } }; return P13nConditionPanel; });
src/sap.m/src/sap/m/P13nConditionPanel.js
/* * ! ${copyright} */ // Provides control sap.m.P13nConditionPanel sap.ui.define([ './library', 'sap/ui/core/library', 'sap/ui/core/Control', 'sap/ui/core/IconPool', 'sap/ui/Device', 'sap/ui/core/InvisibleText', 'sap/ui/core/ResizeHandler', 'sap/ui/core/Item', 'sap/ui/core/ListItem', 'sap/ui/model/odata/type/Boolean', 'sap/ui/model/type/String', 'sap/ui/model/odata/type/String', 'sap/ui/model/type/Date', 'sap/ui/model/type/Time', 'sap/ui/model/odata/type/DateTime', 'sap/ui/model/type/Float', './Button', './OverflowToolbar', './OverflowToolbarLayoutData', './ToolbarSpacer', './Text', './SearchField', './CheckBox', './ComboBox', './Select', './Label', './Input', './DatePicker', './TimePicker', './DateTimePicker', 'sap/base/Log', 'sap/ui/thirdparty/jquery' ], function( library, coreLibrary, Control, IconPool, Device, InvisibleText, ResizeHandler, Item, ListItem, BooleanOdataType, StringType, StringOdataType, DateType, TimeType, DateTimeOdataType, FloatType, Button, OverflowToolbar, OverflowToolbarLayoutData, ToolbarSpacer, Text, SearchField, CheckBox, ComboBox, Select, Label, Input, DatePicker, TimePicker, DateTimePicker, Log, jQuery ) { "use strict"; // shortcut for sap.ui.core.ValueState var ValueState = coreLibrary.ValueState; // shortcut for sap.m.ButtonType var ButtonType = library.ButtonType; // shortcut for sap.m.ToolbarDesign var ToolbarDesign = library.ToolbarDesign; // shortcut for sap.ui.core.TextAlign var TextAlign = coreLibrary.TextAlign; // shortcut for sap.m.OverflowToolbarPriority var OverflowToolbarPriority = library.OverflowToolbarPriority; // lazy dependency to sap.ui.layout.Grid var Grid; // lazy dependency to sap.ui.layout.GridData var GridData; // lazy dependency to sap.ui.layout.HorizontalLayout var HorizontalLayout; // lazy dependency to sap.ui.comp.odata.type.StringDate var StringDateType; /** * Constructor for a new P13nConditionPanel. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] initial settings for the new control * @class The ConditionPanel Control will be used to implement the Sorting, Filtering and Grouping panel of the new Personalization dialog. * @extends sap.ui.core.Control * @version ${version} * @constructor * @public * @since 1.26.0 * @experimental since version 1.26 !!! THIS CONTROL IS ONLY FOR INTERNAL USE !!! * @alias sap.m.P13nConditionPanel * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var P13nConditionPanel = Control.extend("sap.m.P13nConditionPanel", /** @lends sap.m.P13nConditionPanel.prototype */ { metadata: { library: "sap.m", properties: { /** * defines the max number of conditions on the ConditionPanel */ maxConditions: { type: "string", group: "Misc", defaultValue: '-1' }, /** * exclude options for filter */ exclude: { type: "boolean", group: "Misc", defaultValue: false }, /** * defines if the mediaQuery or a ContainerResize will be used for layout update. * When the <code>P13nConditionPanel</code> is used on a dialog the property should be set to <code>true</code>! */ containerQuery: { type: "boolean", group: "Misc", defaultValue: false }, /** * adds initial a new empty condition row */ autoAddNewRow: { type: "boolean", group: "Misc", defaultValue: false }, /** * makes the remove icon on the first condition row disabled when only one condition exist. */ disableFirstRemoveIcon: { type: "boolean", group: "Misc", defaultValue: false }, /** * makes the Add icon visible on each condition row. If is set to false the Add is only visible at the end and you can only append a * new condition. */ alwaysShowAddIcon: { type: "boolean", group: "Misc", defaultValue: true }, /** * new added condition use the settings from the previous condition as default. */ usePrevConditionSetting: { type: "boolean", group: "Misc", defaultValue: true }, /** * KeyField value can only be selected once. When you set the property to <code>true</code> the ConditionPanel will automatically offers on the * KeyField drop down only the keyFields which are not used. The default behavior is that in each keyField dropdown all keyfields are * listed. */ autoReduceKeyFieldItems: { type: "boolean", group: "Misc", defaultValue: false }, /** * can be used to control the layout behavior. Default is "" which will automatically change the layout. With "Desktop", "Table" * or "Phone" you can set a fixed layout. */ layoutMode: { type: "string", group: "Misc", defaultValue: null }, /** * show additional labels in the condition */ showLabel: { type: "boolean", group: "Misc", defaultValue: false }, /** * This represents the displayFormat of the condition Values. With the value "UpperCase" the entered value of the condition will be * converted to upperCase. */ displayFormat: { type: "string", group: "Misc", defaultValue: null }, /** * Calls the validation listener tbd... */ validationExecutor: { type: "object", group: "Misc", defaultValue: null } }, aggregations: { /** * Content for the ConditionPanel. This aggregation is not public! */ content: { type: "sap.ui.core.Control", multiple: true, singularName: "content", visibility: "hidden" } }, events: { /** * Workaround for updating the binding */ dataChange: {} } }, renderer: function(oRm, oControl) { // start ConditionPanel oRm.write("<section"); oRm.writeControlData(oControl); oRm.addClass("sapMConditionPanel"); oRm.writeClasses(); oRm.writeStyles(); oRm.write(">"); // render content oRm.write("<div"); oRm.addClass("sapMConditionPanelContent"); oRm.addClass("sapMConditionPanelBG"); oRm.writeClasses(); oRm.write(">"); var aChildren = oControl.getAggregation("content"); var iLength = aChildren.length; for (var i = 0; i < iLength; i++) { oRm.renderControl(aChildren[i]); } oRm.write("</div>"); oRm.write("</section>"); } }); // EXC_ALL_CLOSURE_003 /** * This method must be used to assign a list of conditions. * * @param {object[]} aConditions array of Conditions. * @public */ P13nConditionPanel.prototype.setConditions = function(aConditions) { if (!aConditions) { Log.error("sap.m.P13nConditionPanel : aCondition is not defined"); } if (this._bIgnoreSetConditions) { return; } this._oConditionsMap = {}; this._aConditionKeys = []; this._iConditions = 0; for (var i = 0; i < aConditions.length; i++) { this._addCondition2Map(aConditions[i]); } this._clearConditions(); this._fillConditions(); }; /** * remove all conditions. * * @public */ P13nConditionPanel.prototype.removeAllConditions = function() { this._oConditionsMap = {}; this._aConditionKeys = []; this._iConditions = 0; this._clearConditions(); this._fillConditions(); }; /** * add a single condition. * * @param {object} oCondition the new condition of type <code>{ "key": "007", "operation": sap.m.P13nConditionOperation.Ascending, "keyField": * "keyFieldKey", "value1": "", "value2": ""};</code> * @public */ P13nConditionPanel.prototype.addCondition = function(oCondition) { if (this._bIgnoreSetConditions) { return; } oCondition.index = this._iConditions; this._addCondition2Map(oCondition); this._addCondition(oCondition); }; /** * insert a single condition. * * @param {object} oCondition the new condition of type <code>{ "key": "007", "operation": sap.m.P13nConditionOperation.Ascending, "keyField": * "keyFieldKey", "value1": "", "value2": ""};</code> * @param {int} index of the new condition * @public */ P13nConditionPanel.prototype.insertCondition = function(oCondition, index) { if (this._bIgnoreSetConditions) { return; } if (index !== undefined) { oCondition.index = index; } this._addCondition2Map(oCondition); this._addCondition(oCondition); }; /** * remove a single condition. * * @param {object} vCondition is the condition which should be removed. can be either a string with the key of the condition of the condition * object itself. * @public */ P13nConditionPanel.prototype.removeCondition = function(vCondition) { this._clearConditions(); if (typeof vCondition == "string") { this._removeConditionFromMap(vCondition); } if (typeof vCondition == "object") { this._removeConditionFromMap(vCondition.key); } this._fillConditions(); }; /** * add a single condition into the _oConditionMap. * * @private * @param {object} oCondition the new condition of type <code>{ "key": "007", "operation": sap.m.P13nConditionOperation.Ascending, "keyField": * "keyFieldKey", "value1": "", "value2": ""};</code> */ P13nConditionPanel.prototype._addCondition2Map = function(oCondition) { if (!oCondition.key) { oCondition.key = "condition_" + this._iConditions; if (this.getExclude()) { oCondition.key = "x" + oCondition.key; } } this._iConditions++; this._oConditionsMap[oCondition.key] = oCondition; this._aConditionKeys.push(oCondition.key); }; P13nConditionPanel.prototype._removeConditionFromMap = function(sKey) { this._iConditions--; delete this._oConditionsMap[sKey]; var i = this._aConditionKeys.indexOf(sKey); if (i >= 0) { this._aConditionKeys.splice(i, 1); } }; /** * returns array of all defined conditions. * * @public * @returns {object[]} array of Conditions */ P13nConditionPanel.prototype.getConditions = function() { var oCondition; var aConditions = []; if (this._oConditionsMap) { for (var conditionId in this._oConditionsMap) { oCondition = this._oConditionsMap[conditionId]; var sValue = oCondition.value; if (!sValue) { sValue = this._getFormatedConditionText(oCondition.operation, oCondition.value1, oCondition.value2, oCondition.exclude, oCondition.keyField, oCondition.showIfGrouped); } if (!oCondition._oGrid || oCondition._oGrid.select.getSelected()) { aConditions.push({ "key": conditionId, "text": sValue, "exclude": oCondition.exclude, "operation": oCondition.operation, "keyField": oCondition.keyField, "value1": oCondition.value1, "value2": oCondition.operation === P13nConditionOperation.BT ? oCondition.value2 : null, "showIfGrouped": oCondition.showIfGrouped }); } } } return aConditions; }; /** * setter for the supported operations which we show per condition row. This array of "default" operations will only be used when we do not have * on the keyfield itself some specific operations and a keyfield is of not of type date or numeric. * * @public * @param {sap.m.P13nConditionOperation[]} aOperations array of operations <code>[sap.m.P13nConditionOperation.BT, sap.m.P13nConditionOperation.EQ]</code> * @param {string} sType defines the type for which this operations will be used. is <code>sType</code> is not defined the operations will be used as default * operations. */ P13nConditionPanel.prototype.setOperations = function(aOperations, sType) { sType = sType || "default"; this._oTypeOperations[sType] = aOperations; this._updateAllOperations(); }; P13nConditionPanel.prototype.setValues = function(aValues, sType) { sType = sType || "default"; this._oTypeValues[sType] = aValues; // this._updateAllOperations(); }; /** * add a single operation * * @public * @param {sap.m.P13nConditionOperation} oOperation * @param {string} sType defines the type for which this operations will be used. */ P13nConditionPanel.prototype.addOperation = function(oOperation, sType) { sType = sType || "default"; this._oTypeOperations[sType].push(oOperation); this._updateAllOperations(); }; /** * remove all operations * * @public * @param {string} sType defines the type for which all operations should be removed */ P13nConditionPanel.prototype.removeAllOperations = function(sType) { sType = sType || "default"; this._oTypeOperations[sType] = []; this._updateAllOperations(); }; /** * returns the default array of operations * * @public * @param {string} sType defines the type for which the operations should be returned. * @returns {sap.m.P13nConditionOperation[]} array of operations */ P13nConditionPanel.prototype.getOperations = function(sType) { sType = sType || "default"; return this._oTypeOperations[sType]; }; /** * This method allows you to specify the KeyFields for the conditions. You can set an array of object with Key and Text properties to define the * keyfields. * * @public * @param {array} aKeyFields array of KeyFields <code>[{key: "CompanyCode", text: "ID"}, {key:"CompanyName", text : "Name"}]</code> */ P13nConditionPanel.prototype.setKeyFields = function(aKeyFields) { this._aKeyFields = aKeyFields; this._aKeyFields.forEach(function(oKeyField) { P13nConditionPanel._createKeyFieldTypeInstance(oKeyField); }, this); this._updateKeyFieldItems(this._oConditionsGrid, true); this._updateAllConditionsEnableStates(); this._createAndUpdateAllKeyFields(); this._updateAllOperations(); }; /** * add a single KeyField * * @public * @param {object} oKeyField {key: "CompanyCode", text: "ID"} */ P13nConditionPanel.prototype.addKeyField = function(oKeyField) { this._aKeyFields.push(oKeyField); P13nConditionPanel._createKeyFieldTypeInstance(oKeyField); this._updateKeyFieldItems(this._oConditionsGrid, true, true); this._updateAllConditionsEnableStates(); this._createAndUpdateAllKeyFields(); this._updateAllOperations(); }; P13nConditionPanel._createKeyFieldTypeInstance = function(oKeyField) { var oConstraints; //check if typeInstance exists, if not create the type instance if (!oKeyField.typeInstance) { switch (oKeyField.type) { case "boolean": //TODO in case the model is not an ODataModel we should use the sap.ui.model.type.Boolean oKeyField.typeInstance = new BooleanOdataType(); break; case "numc": if (!(oKeyField.formatSettings && oKeyField.formatSettings.isDigitSequence)) { Log.error("sap.m.P13nConditionPanel", "NUMC type support requires isDigitSequence==true!"); oKeyField.formatSettings = Object.assign({}, oKeyField.formatSettings, { isDigitSequence: true }); } oConstraints = oKeyField.formatSettings; if (oKeyField.maxLength) { oConstraints = Object.assign({}, oConstraints, { maxLength: oKeyField.maxLength }); } if (!oConstraints.maxLength) { Log.error("sap.m.P13nConditionPanel", "NUMC type suppport requires maxLength!"); } oKeyField.typeInstance = new StringOdataType({}, oConstraints); break; case "date": //TODO we should use the none odata date type, otherwise the returned oValue1 is not a date object oKeyField.typeInstance = new DateType(Object.assign({}, oKeyField.formatSettings, { strictParsing: true }), {}); break; case "time": //TODO we should use the none odata date type, otherwise the returned oValue1 is not a date object oKeyField.typeInstance = new TimeType(Object.assign({}, oKeyField.formatSettings, { strictParsing: true }), {}); break; case "datetime": oKeyField.typeInstance = new DateTimeOdataType(Object.assign({}, oKeyField.formatSettings, { strictParsing: true }), { displayFormat: "Date" }); // when the type is a DateTime type and isDateOnly==true, the type internal might use UTC=true // result is that date values which we format via formatValue(oDate, "string") are shown as the wrong date. // The current Date format is yyyy-mm-ddT00:00:00 GMT+01 // Workaround: changing the oFormat.oFormatOptions.UTC to false! var oType = oKeyField.typeInstance; if (!oType.oFormat) { // create a oFormat of the type by formating a dummy date oType.formatValue(new Date(), "string"); } if (oType.oFormat) { oType.oFormat.oFormatOptions.UTC = false; } break; case "stringdate": // TODO: Do we really need the COMP library here??? sap.ui.getCore().loadLibrary("sap.ui.comp"); StringDateType = StringDateType || sap.ui.requireSync("sap/ui/comp/odata/type/StringDate"); oKeyField.typeInstance = new StringDateType(Object.assign({}, oKeyField.formatSettings, { strictParsing: true })); break; case "numeric": if (oKeyField.precision || oKeyField.scale) { oConstraints = {}; if (oKeyField.precision) { oConstraints["maxIntegerDigits"] = parseInt(oKeyField.precision); } if (oKeyField.scale) { oConstraints["maxFractionDigits"] = parseInt(oKeyField.scale); } } oKeyField.typeInstance = new FloatType(oConstraints); break; default: var oFormatOptions = oKeyField.formatSettings; if (oKeyField.maxLength) { oFormatOptions = Object.assign({}, oFormatOptions, { maxLength: oKeyField.maxLength }); } oKeyField.typeInstance = new StringType({}, oFormatOptions); break; } } }; /** * removes all KeyFields * * @public */ P13nConditionPanel.prototype.removeAllKeyFields = function() { this._aKeyFields = []; this._updateKeyFieldItems(this._oConditionsGrid, true); }; /** * getter for KeyFields array * * @public * @returns {object[]} array of KeyFields <code>[{key: "CompanyCode", text: "ID"}, {key:"CompanyName", text : "Name"}]</code> */ P13nConditionPanel.prototype.getKeyFields = function() { return this._aKeyFields; }; /** * sets the AlwaysShowAddIcon. * * @private * @param {boolean} bEnabled makes the Add icon visible for each condition row. */ P13nConditionPanel.prototype.setAlwaysShowAddIcon = function(bEnabled) { this.setProperty("alwaysShowAddIcon", bEnabled); if (this._oConditionsGrid) { this._oConditionsGrid.toggleStyleClass("conditionRootGrid", this.getLayoutMode() !== "Desktop"); // && !this.getAlwaysShowAddIcon()); } return this; }; /** * sets the LayoutMode. If not set the layout depends on the size of the browser or the container. see ContainerQuery * * @private * @param {string} sLayoutMode define the layout mode for the condition row. The value can be Desktop, Tablet or Phone. * @returns {sap.m.P13nConditionPanel} <code>this</code> to allow method chaining */ P13nConditionPanel.prototype.setLayoutMode = function(sLayoutMode) { this.setProperty("layoutMode", sLayoutMode); if (this._oConditionsGrid) { this._oConditionsGrid.toggleStyleClass("conditionRootGrid", sLayoutMode !== "Desktop"); // && !this.getAlwaysShowAddIcon()); } this._updateConditionFieldSpans(sLayoutMode); // we have to refill the content grids this._clearConditions(); this._fillConditions(); return this; }; /** * sets the ContainerQuery. defines if the mediaQuery or a ContainerResize will be used for layout update. When the P13nConditionPanel is used on * a dialog the property should be set to <code>true</code>! * * @private * @since 1.30.0 * @param {boolean} bEnabled enables or disables the <code>ContainerQuery</code> * @returns {sap.m.P13nConditionPanel} <code>this</code> to allow method chaining */ P13nConditionPanel.prototype.setContainerQuery = function(bEnabled) { this._unregisterResizeHandler(); this.setProperty("containerQuery", bEnabled); this._registerResizeHandler(); // we have to refill the content grids this._clearConditions(); this._fillConditions(); return this; }; /** * sets the LayoutMode. * * @private * @param {string} sLayoutMode define the layout mode for the condition row. The value can be Desktop, Tablet or Phone. */ P13nConditionPanel.prototype._updateConditionFieldSpans = function(sMode) { if (this._aConditionsFields) { var bDesktop = sMode === "Desktop"; if (bDesktop) { // this._aConditionsFields[1].SpanFilter = "L1 M1 S1"; Label this._aConditionsFields[2].SpanFilter = "L3 M3 S3"; // this._aConditionsFields[3].SpanFilter = "L1 M1 S1"; Label this._aConditionsFields[4].SpanFilter = "L2 M2 S2"; this._aConditionsFields[5].SpanFilter = "L3 M3 S3"; this._aConditionsFields[6].SpanFilter = "L2 M2 S2"; this._aConditionsFields[7].SpanFilter = "L1 M1 S1"; } var bTablet = sMode === "Tablet"; if (bTablet) { // this._aConditionsFields[1].SpanFilter = "L1 M1 S1"; Label this._aConditionsFields[2].SpanFilter = "L5 M5 S5"; // this._aConditionsFields[3].SpanFilter = "L1 M1 S1"; Label this._aConditionsFields[4].SpanFilter = "L5 M5 S5"; this._aConditionsFields[5].SpanFilter = "L10 M10 S10"; this._aConditionsFields[6].SpanFilter = "L10 M10 S10"; this._aConditionsFields[7].SpanFilter = "L1 M1 S1"; } } }; /* * Initialize the control @private */ P13nConditionPanel.prototype.init = function() { // load the required layout lib sap.ui.getCore().loadLibrary("sap.ui.layout"); Grid = Grid || sap.ui.requireSync("sap/ui/layout/Grid"); GridData = GridData || sap.ui.requireSync("sap/ui/layout/GridData"); HorizontalLayout = HorizontalLayout || sap.ui.requireSync("sap/ui/layout/HorizontalLayout"); // init some resources this._oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m"); this._sFromLabelText = this._oRb.getText("CONDITIONPANEL_LABELFROM"); this._sToLabelText = this._oRb.getText("CONDITIONPANEL_LABELTO"); this._sValueLabelText = this._oRb.getText("CONDITIONPANEL_LABELVALUE"); this._sShowIfGroupedLabelText = this._oRb.getText("CONDITIONPANEL_LABELGROUPING"); this._sValidationDialogFieldMessage = this._oRb.getText("CONDITIONPANEL_FIELDMESSAGE"); this._oTypeOperations = { "default": [] }; this._oTypeValues = { "default": [] }; this._aKeyFields = []; this._oConditionsMap = {}; this._aConditionKeys = []; this._iConditions = 0; this._sLayoutMode = "Desktop"; this._sConditionType = "Filter"; this._sAddRemoveIconTooltip = "FILTER"; this._iBreakPointTablet = Device.media._predefinedRangeSets[Device.media.RANGESETS.SAP_STANDARD].points[0]; this._iBreakPointDesktop = Device.media._predefinedRangeSets[Device.media.RANGESETS.SAP_STANDARD].points[1]; // create the main grid and add it into the hidden content aggregation this._oConditionsGrid = new Grid({ width: "100%", defaultSpan: "L12 M12 S12", hSpacing: 0, vSpacing: 0 }).toggleStyleClass("conditionRootGrid", this.getLayoutMode() !== "Desktop"); // && !this.getAlwaysShowAddIcon()); this._oConditionsGrid.addStyleClass("sapUiRespGridOverflowHidden"); this._iFirstConditionIndex = 0; this._iConditionPageSize = 10; this._oInvisibleTextField = new InvisibleText({ text: this._oRb.getText("CONDITIONPANEL_FIELD_LABEL") }); this._oInvisibleTextOperator = new InvisibleText({ text: this._oRb.getText("CONDITIONPANEL_OPERATOR_LABEL") }); this.addAggregation("content", this._oInvisibleTextField); this.addAggregation("content", this._oInvisibleTextOperator); this.addAggregation("content", this._oConditionsGrid); this._registerResizeHandler(); this._aConditionsFields = [{ "ID": "select", "Label": "", "SpanFilter": "L1 M1 S1", "SpanSort": "L1 M1 S1", "SpanGroup": "L1 M1 S1", "Control": "CheckBox", "Value": "" }, { "ID": "keyFieldLabel", "Text": "Sort By", "SpanFilter": "L1 M1 S1", "SpanSort": "L1 M1 S1", "SpanGroup": "L1 M1 S1", "Control": "Label" }, { "ID": "keyField", "Label": "", "SpanFilter": "L3 M5 S10", "SpanSort": "L5 M5 S12", "SpanGroup": "L4 M4 S12", "Control": "ComboBox" }, { "ID": "operationLabel", "Text": "Sort Order", "SpanFilter": "L1 M1 S1", "SpanSort": "L1 M1 S1", "SpanGroup": "L1 M1 S1", "Control": "Label" }, { "ID": "operation", "Label": "", "SpanFilter": "L2 M5 S10", "SpanSort": Device.system.phone ? "L5 M5 S8" : "L5 M5 S9", "SpanGroup": "L2 M5 S10", "Control": "ComboBox" }, { "ID": "value1", "Label": this._sFromLabelText, "SpanFilter": "L3 M10 S10", "SpanSort": "L3 M10 S10", "SpanGroup": "L3 M10 S10", "Control": "TextField", "Value": "" }, { "ID": "value2", "Label": this._sToLabelText, "SpanFilter": "L2 M10 S10", "SpanSort": "L2 M10 S10", "SpanGroup": "L2 M10 S10", "Control": "TextField", "Value": "" }, { "ID": "showIfGrouped", "Label": this._sShowIfGroupedLabelText, "SpanFilter": "L1 M10 S10", "SpanSort": "L1 M10 S10", "SpanGroup": "L3 M4 S9", "Control": "CheckBox", "Value": "false" }]; this._oButtonGroupSpan = { "SpanFilter": "L2 M2 S2", "SpanSort": Device.system.phone ? "L2 M2 S4" : "L2 M2 S3", "SpanGroup": "L2 M2 S3" }; this._updateConditionFieldSpans(this.getLayoutMode()); // fill/update the content "oConditionGrid"s this._fillConditions(); }; /* * create the paginator toolbar * @private */ P13nConditionPanel.prototype._createPaginatorToolbar = function() { this._bPaginatorButtonsVisible = false; var that = this; this._oPrevButton = new Button({ icon: IconPool.getIconURI("navigation-left-arrow"), //tooltip: "Show Previous", tooltip: this._oRb.getText("WIZARD_FINISH"), //TODO create new resoucre visible: true, press: function(oEvent) { that._iFirstConditionIndex = Math.max(0, that._iFirstConditionIndex - that._iConditionPageSize); that._clearConditions(); that._fillConditions(); }, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.NeverOverflow }) }); this._oNextButton = new Button({ icon: IconPool.getIconURI("navigation-right-arrow"), //tooltip: "Show Next", tooltip: this._oRb.getText("WIZARD_NEXT"), //TODO create new resoucre visible: true, press: function(oEvent) { that._iFirstConditionIndex += that._iConditionPageSize; that._clearConditions(); that._fillConditions(); }, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.NeverOverflow }) }); this._oRemoveAllButton = new Button({ text: this._oRb.getText("CONDITIONPANEL_REMOVE_ALL"), // "Remove All", //icon: sap.ui.core.IconPool.getIconURI("sys-cancel"), //tooltip: "Remove All", visible: true, press: function(oEvent) { that._aConditionKeys.forEach(function(sKey, iIndex) { if (iIndex >= 0) { this.fireDataChange({ key: sKey, index: iIndex, operation: "remove", newData: null }); } }, that); this._iFirstConditionIndex = 0; that.removeAllConditions(); }, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.Low }) }); this._oAddButton = new Button({ icon: IconPool.getIconURI("add"), tooltip: this._oRb.getText("CONDITIONPANEL_ADD" + (this._sAddRemoveIconTooltipKey ? "_" + this._sAddRemoveIconTooltipKey : "") + "_TOOLTIP"), visible: true, press: function(oEvent) { var oConditionGrid = that._createConditionRow(that._oConditionsGrid, undefined, null, 0); that._changeField(oConditionGrid); // set the focus in a fields of the newly added condition setTimeout(function() { oConditionGrid.keyField.focus(); }); that._updatePaginatorToolbar(); }, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.Low }) }); this._oHeaderText = new Text({ wrapping: false, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.NeverOverflow }) }); this._oPageText = new Text({ wrapping: false, textAlign: TextAlign.Center, layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.NeverOverflow }) }); this._oFilterField = new SearchField({ width: "12rem", layoutData: new OverflowToolbarLayoutData({ priority: OverflowToolbarPriority.High }) }); this._oPaginatorToolbar = new OverflowToolbar({ height: "3rem", design: ToolbarDesign.Transparent, content: [ this._oHeaderText, new ToolbarSpacer(), this._oFilterField, this._oPrevButton, this._oPageText, this._oNextButton, this._oRemoveAllButton, this._oAddButton ] }); }; /* * update the paginator toolbar element * @private */ P13nConditionPanel.prototype._updatePaginatorToolbar = function() { if (this._sConditionType !== "Filter" || this.getMaxConditions() !== "-1") { return; } var iItems = this._aConditionKeys.length; var iPages = 1 + Math.floor(Math.max(0, iItems - 1) / this._iConditionPageSize); var iPage = 1 + Math.floor(this._iFirstConditionIndex / this._iConditionPageSize); var oParent = this.getParent(); if (!this._oPaginatorToolbar) { if (iItems > this._iConditionPageSize) { this._createPaginatorToolbar(); this.insertAggregation("content", this._oPaginatorToolbar, 0); this._onGridResize(); } else { if (oParent && oParent.setHeaderText) { if (this._sOrgHeaderText == undefined) { this._sOrgHeaderText = oParent.getHeaderText(); } oParent.setHeaderText(this._sOrgHeaderText + (iItems > 0 ? " (" + iItems + ")" : "")); } return; } } this._oPrevButton.setEnabled(this._iFirstConditionIndex > 0); this._oNextButton.setEnabled(this._iFirstConditionIndex + this._iConditionPageSize < iItems); if (oParent && oParent.setHeaderToolbar) { if (!oParent.getHeaderToolbar()) { this.removeAggregation("content", this._oPaginatorToolbar); oParent.setHeaderToolbar(this._oPaginatorToolbar); oParent.attachExpand(function(oEvent) { this._setToolbarElementVisibility(oEvent.getSource().getExpanded() && this._bPaginatorButtonsVisible); }.bind(this)); } } if (oParent && oParent.setHeaderText) { if (this._sOrgHeaderText == undefined) { this._sOrgHeaderText = oParent.getHeaderText(); } var sHeader = this._sOrgHeaderText + (iItems > 0 ? " (" + iItems + ")" : ""); oParent.setHeaderText(sHeader); this._oHeaderText.setText(sHeader); } else { this._oHeaderText.setText(iItems + " Conditions"); } this._oPageText.setText(iPage + "/" + iPages); this._bPaginatorButtonsVisible = this._bPaginatorButtonsVisible || iPages > 1; this._setToolbarElementVisibility(this._bPaginatorButtonsVisible); if (iPage > iPages) { // update the FirstConditionIndex and rerender this._iFirstConditionIndex -= Math.max(0, this._iConditionPageSize); this._clearConditions(); this._fillConditions(); } var nValidGrids = 0; this._oConditionsGrid.getContent().forEach(function(oGrid) { if (oGrid.select.getSelected()) { nValidGrids++; } }, this); if (iPages == iPage && (iItems - this._iFirstConditionIndex) > nValidGrids) { // check if we have to rerender the current last page this._clearConditions(); this._fillConditions(); } }; /* * make all toolbar elements visible or invisible * @private */ P13nConditionPanel.prototype._setToolbarElementVisibility = function(bVisible) { this._oPrevButton.setVisible(bVisible); this._oNextButton.setVisible(bVisible); this._oPageText.setVisible(bVisible); this._oFilterField.setVisible(false); //bVisible); this._oAddButton.setVisible(bVisible); this._oRemoveAllButton.setVisible(bVisible); }; /* * destroy and remove all internal references * @private */ P13nConditionPanel.prototype.exit = function() { this._clearConditions(); this._unregisterResizeHandler(); this._aConditionsFields = null; this._aKeys = null; this._aKeyFields = null; this._oTypeOperations = null; this._oRb = null; this._sFromLabelText = null; this._sToLabelText = null; this._sValueLabelText = null; this._sValidationDialogFieldMessage = null; this._oConditionsMap = null; this._aConditionKeys = []; }; /* * removes all condition rows from the main ConditionGrid. @private */ P13nConditionPanel.prototype._clearConditions = function() { var aGrid = this._oConditionsGrid.getContent(); aGrid.forEach(function(oGrid) { for (var iField in this._aConditionsFields) { var field = this._aConditionsFields[iField]; if (oGrid[field["ID"]] && oGrid.getContent().indexOf(oGrid[field["ID"]]) === -1) { // TODO: notice that since these fields could have been removed from // the inner aggregation, and thus would not be destroyed otherwise, // we destroy them separately here oGrid[field["ID"]].destroy(); } } }, this); this._oConditionsGrid.destroyContent(); }; /* * creates all condition rows and updated the values of the fields. @private */ P13nConditionPanel.prototype._fillConditions = function() { var oCondition, sConditionKey; var i = 0, iMaxConditions = this._getMaxConditionsAsNumber(), n = this._aConditionKeys.length; // fill existing conditions if (this._oConditionsMap) { var iPageSize = this._sConditionType !== "Filter" || this.getMaxConditions() !== "-1" ? 9999 : this._iConditionPageSize; n = Math.min(n, Math.min(iMaxConditions, this._iFirstConditionIndex + iPageSize)); for (i = this._iFirstConditionIndex; i < n; i++) { sConditionKey = this._aConditionKeys[i]; oCondition = this._oConditionsMap[sConditionKey]; this._createConditionRow(this._oConditionsGrid, oCondition, sConditionKey); } } this._updatePaginatorToolbar(); // create empty Conditions row/fields if ((this.getAutoAddNewRow() || this._oConditionsGrid.getContent().length === 0) && this._oConditionsGrid.getContent().length < iMaxConditions) { this._createConditionRow(this._oConditionsGrid); } }; /* * add one condition @private */ P13nConditionPanel.prototype._addCondition = function(oCondition) { var i = 0; var iMaxConditions = this._getMaxConditionsAsNumber(); //TODO page handling missing if (this._oConditionsMap) { for (var conditionId in this._oConditionsMap) { if (i < iMaxConditions && oCondition === this._oConditionsMap[conditionId]) { this._createConditionRow(this._oConditionsGrid, oCondition, conditionId, i); } i++; } } this._updatePaginatorToolbar(); }; P13nConditionPanel.prototype._getMaxConditionsAsNumber = function() { return this.getMaxConditions() === "-1" ? 9999 : parseInt(this.getMaxConditions()); }; P13nConditionPanel.prototype.onAfterRendering = function() { if (this.getLayoutMode()) { this._sLayoutMode = this.getLayoutMode(); return; } }; P13nConditionPanel.prototype._handleMediaChange = function(p) { this._sLayoutMode = p.name; // if (window.console) { // window.console.log(" ---> MediaChange " + p.name); // } this._updateLayout(p); }; P13nConditionPanel.prototype._unregisterResizeHandler = function() { if (this._sContainerResizeListener) { ResizeHandler.deregister(this._sContainerResizeListener); this._sContainerResizeListener = null; } Device.media.detachHandler(this._handleMediaChange, this, Device.media.RANGESETS.SAP_STANDARD); }; P13nConditionPanel.prototype._registerResizeHandler = function() { if (this.getContainerQuery()) { this._sContainerResizeListener = ResizeHandler.register(this._oConditionsGrid, this._onGridResize.bind(this)); this._onGridResize(); } else { Device.media.attachHandler(this._handleMediaChange, this, Device.media.RANGESETS.SAP_STANDARD); } }; /** * returns the key of the condition grid or creates a new key * * @private * @param {object} oConditionGrid * @returns {string} the new or existing key */ P13nConditionPanel.prototype._getKeyFromConditionGrid = function(oConditionGrid) { var sKey = oConditionGrid.data("_key"); if (!sKey) { sKey = this._createConditionKey(); } return sKey; }; /** * creates a new key for the condition grids * * @private * @returns {string} the new key */ P13nConditionPanel.prototype._createConditionKey = function() { var i = 0; var sKey; do { sKey = "condition_" + i; if (this.getExclude()) { sKey = "x" + sKey; } i++; } while (this._oConditionsMap[sKey]); return sKey; }; /** * appends a new condition grid with all containing controls in the main grid * * @private * @param {grid} oTargetGrid the main grid in which the new condition grid will be added * @param {object} oConditionGridData the condition data for the new added condition grid controls * @param {string} sKey the key for the new added condition grid * @param {int} iPos the index of the new condition in the targetGrid */ P13nConditionPanel.prototype._createConditionRow = function(oTargetGrid, oConditionGridData, sKey, iPos) { var oButtonContainer = null; var oGrid; var that = this; if (iPos === undefined) { iPos = oTargetGrid.getContent().length; } var oConditionGrid = new Grid({ width: "100%", defaultSpan: "L12 M12 S12", hSpacing: 1, vSpacing: 0, containerQuery: this.getContainerQuery() }).data("_key", sKey); oConditionGrid.addStyleClass("sapUiRespGridOverflowHidden"); /* eslint-disable no-loop-func */ for (var iField in this._aConditionsFields) { var oControl; var field = this._aConditionsFields[iField]; switch (field["Control"]) { case "CheckBox": // the CheckBox is not visible and only used internal to validate if a condition is // filled correct. oControl = new CheckBox({ enabled: false, visible: false, layoutData: new GridData({ span: field["Span" + this._sConditionType] }) }); if (field["ID"] === "showIfGrouped") { oControl.setEnabled(true); oControl.setText(field["Label"]); oControl.attachSelect(function() { that._changeField(oConditionGrid); }); oControl.setSelected(oConditionGridData ? oConditionGridData.showIfGrouped : true); } else { if (oConditionGridData) { oControl.setSelected(true); oControl.setEnabled(true); } } break; case "ComboBox": if (field["ID"] === "keyField") { oControl = new ComboBox({ // before we used the new sap.m.Select control width: "100%", ariaLabelledBy: this._oInvisibleTextField }); var fOriginalKey = oControl.setSelectedKey.bind(oControl); oControl.setSelectedKey = function(sKey) { fOriginalKey(sKey); var fValidate = that.getValidationExecutor(); if (fValidate) { fValidate(); } }; var fOriginalItem = oControl.setSelectedItem.bind(oControl); oControl.setSelectedItem = function(oItem) { fOriginalItem(oItem); var fValidate = that.getValidationExecutor(); if (fValidate) { fValidate(); } }; oControl.setLayoutData(new GridData({ span: field["Span" + this._sConditionType] })); this._fillKeyFieldListItems(oControl, this._aKeyFields); if (oControl.attachSelectionChange) { oControl.attachSelectionChange(function(oEvent) { var fValidate = that.getValidationExecutor(); if (fValidate) { fValidate(); } that._handleSelectionChangeOnKeyField(oTargetGrid, oConditionGrid); }); } if (oControl.attachChange) { oControl.attachChange(function(oEvent) { oConditionGrid.keyField.close(); that._handleChangeOnKeyField(oTargetGrid, oConditionGrid); }); } if (oControl.setSelectedItem) { if (oConditionGridData) { oControl.setSelectedKey(oConditionGridData.keyField); this._aKeyFields.forEach(function(oKeyField, index) { var key = oKeyField.key; if (key === undefined) { key = oKeyField; } if (oConditionGridData.keyField === key) { oControl.setSelectedItem(oControl.getItems()[index]); } }, this); } else { if (this.getUsePrevConditionSetting() && !this.getAutoReduceKeyFieldItems()) { // select the key from the condition above if (iPos > 0 && !sKey) { oGrid = oTargetGrid.getContent()[iPos - 1]; if (oGrid.keyField.getSelectedKey()) { oControl.setSelectedKey(oGrid.keyField.getSelectedKey()); } else { // if no item is selected, we have to select at least the first keyFieldItem if (!oControl.getSelectedItem() && oControl.getItems().length > 0) { oControl.setSelectedItem(oControl.getItems()[0]); } } } else { this._aKeyFields.some(function(oKeyField, index) { if (oKeyField.isDefault) { oControl.setSelectedItem(oControl.getItems()[index]); return true; } if (!oControl.getSelectedItem() && oKeyField.type !== "boolean") { oControl.setSelectedItem(oControl.getItems()[index]); } }, this); // if no item is selected, we have to select at least the first keyFieldItem if (!oControl.getSelectedItem() && oControl.getItems().length > 0) { oControl.setSelectedItem(oControl.getItems()[0]); } } } else { this._aKeyFields.forEach(function(oKeyField, index) { if (oKeyField.isDefault) { oControl.setSelectedItem(oControl.getItems()[index]); } }, this); } } } } if (field["ID"] === "operation") { oControl = new Select({ width: "100%", ariaLabelledBy: this._oInvisibleTextOperator, layoutData: new GridData({ span: field["Span" + this._sConditionType] }) }); oControl.attachChange(function() { that._handleChangeOnOperationField(oTargetGrid, oConditionGrid); }); // oControl.attachSelectionChange(function() { // that._handleChangeOnOperationField(oTargetGrid, oConditionGrid); // }); // fill some operations to the control to be able to set the selected items oConditionGrid[field["ID"]] = oControl; this._updateOperationItems(oTargetGrid, oConditionGrid); if (oConditionGridData) { var oKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); var aOperations = this._oTypeOperations["default"]; if (oKeyField) { if (oKeyField.type && this._oTypeOperations[oKeyField.type]) { aOperations = this._oTypeOperations[oKeyField.type]; } if (oKeyField.operations) { aOperations = oKeyField.operations; } } aOperations.some(function(oOperation, index) { if (oConditionGridData.operation === oOperation) { oControl.setSelectedKey(oOperation); return true; } }, this); } else { if (this.getUsePrevConditionSetting()) { // select the key from the condition above if (iPos > 0 && sKey === null) { var oGrid = oTargetGrid.getContent()[iPos - 1]; oControl.setSelectedKey(oGrid.operation.getSelectedKey()); } } } } // init tooltip of select control if (oControl.getSelectedItem && oControl.getSelectedItem()) { oControl.setTooltip(oControl.getSelectedItem().getTooltip() || oControl.getSelectedItem().getText()); } break; case "TextField": var oCurrentKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); oControl = this._createValueField(oCurrentKeyField, field, oConditionGrid); oControl.oTargetGrid = oTargetGrid; if (oConditionGridData && oConditionGridData[field["ID"]] !== undefined) { var vValue = oConditionGridData[field["ID"]]; if (oControl instanceof Select) { if (typeof vValue === "boolean") { oControl.setSelectedIndex(vValue ? 2 : 1); } } else if (vValue !== null && oConditionGrid.oType) { // In case vValue is of type string, and type is StringDate we can set the value without formatting. if (typeof vValue === "string" && oConditionGrid.oType.getName() === "sap.ui.comp.odata.type.StringDate") { oControl.setValue(vValue); } else { // In case vValue is of type string, we try to convert it into the type based format. if (typeof vValue === "string" && ["String", "sap.ui.model.odata.type.String", "sap.ui.model.odata.type.Decimal"].indexOf(oConditionGrid.oType.getName()) == -1) { try { vValue = oConditionGrid.oType.parseValue(vValue, "string"); oControl.setValue(oConditionGrid.oType.formatValue(vValue, "string")); } catch (err) { Log.error("sap.m.P13nConditionPanel", "Value '" + vValue + "' does not have the expected type format for " + oConditionGrid.oType.getName() + ".parseValue()"); } } else { oControl.setValue(oConditionGrid.oType.formatValue(vValue, "string")); } } } else { oControl.setValue(vValue); } } break; case "Label": oControl = new Label({ text: field["Text"] + ":", visible: this.getShowLabel(), layoutData: new GridData({ span: field["Span" + this._sConditionType] }) }).addStyleClass("conditionLabel"); oControl.oTargetGrid = oTargetGrid; break; } oConditionGrid[field["ID"]] = oControl; oConditionGrid.addContent(oControl); } /* eslint-enable no-loop-func */ // create a hLayout container for the remove and add buttons oButtonContainer = new HorizontalLayout({ layoutData: new GridData({ span: this.getLayoutMode() === "Desktop" ? "L2 M2 S2" : this._oButtonGroupSpan["Span" + this._sConditionType] }) }).addStyleClass("floatRight"); oConditionGrid.addContent(oButtonContainer); oConditionGrid["ButtonContainer"] = oButtonContainer; // create "Remove button" var oRemoveControl = new Button({ type: ButtonType.Transparent, icon: IconPool.getIconURI("sys-cancel"), tooltip: this._oRb.getText("CONDITIONPANEL_REMOVE" + (this._sAddRemoveIconTooltipKey ? "_" + this._sAddRemoveIconTooltipKey : "") + "_TOOLTIP"), press: function() { that._handleRemoveCondition(this.oTargetGrid, oConditionGrid); }, layoutData: new GridData({ span: this.getLayoutMode() === "Desktop" ? "L1 M1 S1" : "L1 M2 S2" }) }); oRemoveControl.oTargetGrid = oTargetGrid; oButtonContainer.addContent(oRemoveControl); oConditionGrid["remove"] = oRemoveControl; // create "Add button" var oAddControl = new Button({ type: ButtonType.Transparent, icon: IconPool.getIconURI("add"), tooltip: this._oRb.getText("CONDITIONPANEL_ADD" + (this._sAddRemoveIconTooltipKey ? "_" + this._sAddRemoveIconTooltipKey : "") + "_TOOLTIP"), press: function() { that._handleAddCondition(this.oTargetGrid, oConditionGrid); }, layoutData: new GridData({ span: this.getLayoutMode() === "Desktop" ? "L1 M1 S1" : "L1 M10 S10" }) }); oAddControl.oTargetGrid = oTargetGrid; oAddControl.addStyleClass("conditionAddBtnFloatRight"); oButtonContainer.addContent(oAddControl); oConditionGrid["add"] = oAddControl; // Add the new create condition oTargetGrid.insertContent(oConditionGrid, iPos); // update Operations for all conditions this._updateOperationItems(oTargetGrid, oConditionGrid); this._changeOperationValueFields(oTargetGrid, oConditionGrid); // disable fields if the selectedKeyField value is none this._updateAllConditionsEnableStates(); // update the add/remove buttons visibility this._updateConditionButtons(oTargetGrid); if (this.getAutoReduceKeyFieldItems()) { this._updateKeyFieldItems(oTargetGrid, false); } if (this._sLayoutMode) { this._updateLayout({ name: this._sLayoutMode }); } if (oConditionGridData) { var sConditionText = this._getFormatedConditionText(oConditionGridData.operation, oConditionGridData.value1, oConditionGridData.value2, oConditionGridData.exclude, oConditionGridData.keyField, oConditionGridData.showIfGrouped); oConditionGridData._oGrid = oConditionGrid; oConditionGridData.value = sConditionText; this._oConditionsMap[sKey] = oConditionGridData; } var sOperation = oConditionGrid.operation.getSelectedKey(); // in case of a BT and a Date type try to set the minDate/maxDate for the From/To value datepicker if (sOperation === "BT" && oConditionGrid.value1.setMinDate && oConditionGrid.value2.setMaxDate) { var oValue1 = oConditionGrid.value1.getDateValue(); var oValue2 = oConditionGrid.value2.getDateValue(); this._updateMinMaxDate(oConditionGrid, oValue1, oValue2); } else { this._updateMinMaxDate(oConditionGrid, null, null); } return oConditionGrid; }; /** * press handler for the remove Condition buttons * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid from where the Remove is triggered */ P13nConditionPanel.prototype._handleRemoveCondition = function(oTargetGrid, oConditionGrid) { // search index of the condition grid to set the focus later to the previous condition var idx = oTargetGrid.getContent().indexOf(oConditionGrid); this._removeCondition(oTargetGrid, oConditionGrid); if (this.getAutoReduceKeyFieldItems()) { this._updateKeyFieldItems(oTargetGrid, false); } // set the focus on the remove button of the newly added condition if (idx >= 0) { idx = Math.min(idx, oTargetGrid.getContent().length - 1); var oConditionGrid = oTargetGrid.getContent()[idx]; setTimeout(function() { oConditionGrid.remove.focus(); }); } this._updatePaginatorToolbar(); }; /** * press handler for the add condition buttons * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oSourceConditionGrid from where the Add is triggered */ P13nConditionPanel.prototype._handleAddCondition = function(oTargetGrid, oSourceConditionGrid) { var iPos = oTargetGrid.getContent().indexOf(oSourceConditionGrid); var oConditionGrid = this._createConditionRow(oTargetGrid, undefined, null, iPos + 1); this._changeField(oConditionGrid); // set the focus in a fields of the newly added condition setTimeout(function() { oConditionGrid.keyField.focus(); }); this._updatePaginatorToolbar(); }; /** * returns the selectedKeyFields item from the KeyField control. * * @private * @param {control} oKeyFieldCtrl the Select/ComboBox * @returns {object} the selected Keyfields object */ P13nConditionPanel.prototype._getCurrentKeyFieldItem = function(oKeyFieldCtrl) { if (oKeyFieldCtrl.getSelectedKey && oKeyFieldCtrl.getSelectedKey()) { var sKey = oKeyFieldCtrl.getSelectedKey(); var aItems = this._aKeyFields; for (var iItem in aItems) { var oItem = aItems[iItem]; if (oItem.key === sKey) { return oItem; } } } return null; }; /** * creates a new control for the condition value1 and value2 field. Control can be an Input or DatePicker * * @private * @param {object} oCurrentKeyField object of the current selected KeyField which contains type of the column ("string", "date", "time", "numeric" or "boolean") and * a maxLength information * @param {object} oFieldInfo * @param {grid} oConditionGrid which should contain the new created field * @returns {sap.ui.core.Control} the created control instance either Input or DatePicker */ P13nConditionPanel.prototype._createValueField = function(oCurrentKeyField, oFieldInfo, oConditionGrid) { var oControl; var sCtrlType; var that = this; var params = { value: oFieldInfo["Value"], width: "100%", placeholder: oFieldInfo["Label"], change: function(oEvent) { that._validateAndFormatFieldValue(oEvent); that._changeField(oConditionGrid); }, layoutData: new GridData({ span: oFieldInfo["Span" + this._sConditionType] }) }; if (oCurrentKeyField && oCurrentKeyField.typeInstance) { var oType = oCurrentKeyField.typeInstance; sCtrlType = this._findConfig(oType, "ctrl"); // use the DatePicker when type is sap.ui.model.odata.type.DateTime and displayFormat = Date if (sCtrlType === "DateTimePicker" && oType.getMetadata().getName() === "sap.ui.model.odata.type.DateTime") { if (!(oType.oConstraints && oType.oConstraints.isDateOnly)) { Log.error("sap.m.P13nConditionPanel", "sap.ui.model.odata.type.DateTime without displayFormat = Date is not supported!"); oType.oConstraints = Object.assign({}, oType.oConstraints, { isDateOnly : true }); } sCtrlType = "DatePicker"; } //var aOperators = this._findConfig(oType, "operators"); oConditionGrid.oType = oType; if (sCtrlType == "select") { var aItems = []; var aValues = oCurrentKeyField.values || this._oTypeValues[sCtrlType] || [ "", oType.formatValue(false, "string"), oType.formatValue(true, "string") ]; aValues.forEach(function(oValue, index) { aItems.push(new Item({ key: index.toString(), text: oValue.toString() })); }); params = { width: "100%", items: aItems, change: function() { that._changeField(oConditionGrid); }, layoutData: new GridData({ span: oFieldInfo["Span" + this._sConditionType] }) }; oControl = new Select(params); } else if (sCtrlType == "TimePicker") { if (oType.oFormatOptions && oType.oFormatOptions.style) { params.displayFormat = oType.oFormatOptions.style; } oControl = new TimePicker(params); } else if (sCtrlType == "DateTimePicker") { if (oType.oFormatOptions && oType.oFormatOptions.style) { params.displayFormat = oType.oFormatOptions.style; } oControl = new DateTimePicker(params); } else if (sCtrlType == "DatePicker") { if (oType.oFormatOptions && oType.oFormatOptions.style) { params.displayFormat = oType.oFormatOptions.style; } oControl = new DatePicker(params); if (oType && oType.getName() === "sap.ui.comp.odata.type.StringDate") { oControl.setValueFormat("yyyyMMdd"); oControl.setDisplayFormat(oType.oFormatOptions.style || oType.oFormatOptions.pattern); } } else { oControl = new Input(params); //TODO oType should only be set when type is string! if (this._fSuggestCallback) { oCurrentKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); if (oCurrentKeyField && oCurrentKeyField.key) { var oSuggestProvider = this._fSuggestCallback(oControl, oCurrentKeyField.key); if (oSuggestProvider) { oControl._oSuggestProvider = oSuggestProvider; } } } } } else { // for a new added dummy row, which does not have a oCurrentKeyField, we have to create a dummy input field. oConditionGrid.oType = null; oControl = new Input(params); } if (sCtrlType !== "boolean" && sCtrlType !== "enum" && oControl) { oControl.onpaste = function(oEvent) { var sOriginalText; // for the purpose to copy from column in excel and paste in MultiInput/MultiComboBox if (window.clipboardData) { //IE sOriginalText = window.clipboardData.getData("Text"); } else { // Chrome, Firefox, Safari sOriginalText = oEvent.originalEvent.clipboardData.getData('text/plain'); } var oConditionGrid = oEvent.srcControl.getParent(); var aSeparatedText = sOriginalText.split(/\r\n|\r|\n/g); var oOperation = oConditionGrid.operation; var op = oOperation.getSelectedKey(); if (aSeparatedText && aSeparatedText.length > 1 && op !== "BT") { setTimeout(function() { var iLength = aSeparatedText ? aSeparatedText.length : 0; var oKeyField = that._getCurrentKeyFieldItem(oConditionGrid.keyField); var oOperation = oConditionGrid.operation; for (var i = 0; i < iLength; i++) { if (that._aConditionKeys.length >= that._getMaxConditionsAsNumber()) { break; } var sPastedValue = aSeparatedText[i].trim(); if (sPastedValue) { var oCondition = { "key": that._createConditionKey(), "exclude": that.getExclude(), "operation": oOperation.getSelectedKey(), "keyField": oKeyField.key, "value1": sPastedValue, "value2": null }; that._addCondition2Map(oCondition); that.fireDataChange({ key: oCondition.key, index: oCondition.index, operation: "add", newData: oCondition }); } } that._clearConditions(); that._fillConditions(); }, 0); } }; } if (oCurrentKeyField && oCurrentKeyField.maxLength && oControl.setMaxLength) { var l = -1; if (typeof oCurrentKeyField.maxLength === "string") { l = parseInt(oCurrentKeyField.maxLength); } if (typeof oCurrentKeyField.maxLength === "number") { l = oCurrentKeyField.maxLength; } if (l > 0 && (!oControl.getShowSuggestion || !oControl.getShowSuggestion())) { oControl.setMaxLength(l); } } return oControl; }; /** * fill all operations from the aOperation array into the select control items list * * @private * @param {control} oCtrl the select control which should be filled * @param {array} aOperations array of operations * @param {string} sType the type prefix for resource access */ P13nConditionPanel.prototype._fillOperationListItems = function(oCtrl, aOperations, sType) { if (sType === "_STRING_") { // ignore the "String" Type when accessing the resource text sType = ""; } if (sType === "_TIME_" || sType === "_DATETIME_") { sType = "_DATE_"; } if (sType === "_BOOLEAN_" || sType === "_NUMC_") { sType = ""; } oCtrl.destroyItems(); for (var iOperation in aOperations) { var sText = this._oRb.getText("CONDITIONPANEL_OPTION" + sType + aOperations[iOperation]); if (sText.startsWith("CONDITIONPANEL_OPTION")) { // when for the specified type the resource does not exist use the normal string resource text sText = this._oRb.getText("CONDITIONPANEL_OPTION" + aOperations[iOperation]); } oCtrl.addItem(new ListItem({ key: aOperations[iOperation], text: sText, tooltip: sText })); } }; /** * fill all KeyFieldItems from the aItems array into the select control items list * * @private * @param {control} oCtrl the select control which should be filled * @param {array} aItems array of keyfields */ P13nConditionPanel.prototype._fillKeyFieldListItems = function(oCtrl, aItems) { oCtrl.destroyItems(); for (var iItem in aItems) { var oItem = aItems[iItem]; oCtrl.addItem(new ListItem({ key: oItem.key, text: oItem.text, tooltip: oItem.tooltip ? oItem.tooltip : oItem.text })); } oCtrl.setEditable(oCtrl.getItems().length > 1); }; /** * change handler for the Operation field * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the Operation control which has been changed */ P13nConditionPanel.prototype._handleChangeOnOperationField = function(oTargetGrid, oConditionGrid) { this._changeOperationValueFields(oTargetGrid, oConditionGrid); this._changeField(oConditionGrid); }; /** * SelectionChange handler for the KeyField field * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the KeyField control which has been changed */ P13nConditionPanel.prototype._handleSelectionChangeOnKeyField = function(oTargetGrid, oConditionGrid) { if (this._sConditionType === "Filter") { this._updateOperationItems(oTargetGrid, oConditionGrid); // update the value fields for the KeyField this._createAndUpdateValueFields(oTargetGrid, oConditionGrid); this._changeOperationValueFields(oTargetGrid, oConditionGrid); } this._changeField(oConditionGrid); }; /** * change handler for the KeyField field * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the KeyField control which has been changed */ P13nConditionPanel.prototype._handleChangeOnKeyField = function(oTargetGrid, oConditionGrid) { if (this.getAutoReduceKeyFieldItems()) { this._updateKeyFieldItems(oTargetGrid, false, false, oConditionGrid.keyField); } }; P13nConditionPanel.prototype._createAndUpdateAllKeyFields = function() { var aConditionGrids = this._oConditionsGrid.getContent(); aConditionGrids.forEach(function(oConditionGrid) { this._createAndUpdateValueFields(this._oConditionsGrid, oConditionGrid); this._changeOperationValueFields(this._oConditionsGrid, oConditionGrid); }, this); }; /** * creates the Value1/2 fields based on the KeyField Type * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the KeyField control which has been changed */ P13nConditionPanel.prototype._createAndUpdateValueFields = function(oTargetGrid, oConditionGrid) { // update the value fields for the KeyField var oCurrentKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); var fnCreateAndUpdateField = function(oConditionGrid, oCtrl, index) { var sOldValue = oCtrl.getValue ? oCtrl.getValue() : ""; var ctrlIndex = oConditionGrid.indexOfContent(oCtrl); // we have to remove the control into the content with rerendering (bSuppressInvalidate=false) the UI, // otherwise in some use cases the "between" value fields will not be rendered. // This additional rerender might trigger some problems for screenreader. oConditionGrid.removeContent(oCtrl); //oConditionGrid.removeAggregation("content", oCtrl, true); if (oCtrl._oSuggestProvider) { oCtrl._oSuggestProvider.destroy(); oCtrl._oSuggestProvider = null; } oCtrl.destroy(); var fieldInfo = this._aConditionsFields[index]; oCtrl = this._createValueField(oCurrentKeyField, fieldInfo, oConditionGrid); oConditionGrid[fieldInfo["ID"]] = oCtrl; oConditionGrid.insertContent(oCtrl, ctrlIndex === -1 ? oConditionGrid.indexOfContent(oConditionGrid.operation) + 1 : ctrlIndex); var oValue, sValue; if (oConditionGrid.oType && sOldValue) { try { oValue = oConditionGrid.oType.parseValue(sOldValue, "string"); oConditionGrid.oType.validateValue(oValue); sValue = oConditionGrid.oType.formatValue(oValue, "string"); oCtrl.setValue(sValue); } catch (err) { var sMsg = err.message; this._makeFieldValid(oCtrl, false, sMsg); oCtrl.setValue(sOldValue); } } }; // update Value1 field control fnCreateAndUpdateField.bind(this)(oConditionGrid, oConditionGrid.value1, 5); // update Value2 field control fnCreateAndUpdateField.bind(this)(oConditionGrid, oConditionGrid.value2, 6); }; P13nConditionPanel.prototype._updateAllOperations = function() { var aConditionGrids = this._oConditionsGrid.getContent(); aConditionGrids.forEach(function(oConditionGrid) { this._updateOperationItems(this._oConditionsGrid, oConditionGrid); this._changeOperationValueFields(this._oConditionsGrid, oConditionGrid); }, this); }; /** * update the Operations for a condition row based on the type of the selected keyField * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the KeyField control and the Operations field which will be updated */ P13nConditionPanel.prototype._updateOperationItems = function(oTargetGrid, oConditionGrid) { var sType = ""; var oKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); var oOperation = oConditionGrid.operation; var aOperations = this._oTypeOperations["default"]; var oCurrentSelectedItem = oOperation.getSelectedItem(); if (oKeyField) { if (oKeyField.type && oKeyField.type !== "" && this._oTypeOperations[oKeyField.type]) { sType = oKeyField.type; aOperations = this._oTypeOperations[sType]; } if (oKeyField.operations) { aOperations = oKeyField.operations; } } this._fillOperationListItems(oOperation, aOperations, sType ? "_" + sType.toUpperCase() + "_" : ""); if (oCurrentSelectedItem && oOperation.getItemByKey(oCurrentSelectedItem.getKey())) { // when old selected items key exist select the same key oOperation.setSelectedKey(oCurrentSelectedItem.getKey()); } else { oOperation.setSelectedItem(oOperation.getItems()[0]); } this._sConditionType = "Filter"; if (aOperations[0] === P13nConditionOperation.Ascending || aOperations[0] === P13nConditionOperation.Descending) { this._sConditionType = "Sort"; } if (aOperations[0] === P13nConditionOperation.GroupAscending || aOperations[0] === P13nConditionOperation.GroupDescending) { this._sConditionType = "Group"; } this._adjustValue1Span(oConditionGrid); }; /** * update the Items from all KeyFields * * @private * @param {grid} oTargetGrid the main grid * @param {boolean} bFillAll fills all KeyFields or only the none used * @param {boolean} bAppendLast adds only the last Keyfield to the Items of the selected controls */ P13nConditionPanel.prototype._updateKeyFieldItems = function(oTargetGrid, bFillAll, bAppendLast, oIgnoreKeyField) { var n = oTargetGrid.getContent().length; var i; // collect all used Keyfields var oUsedItems = {}; if (!bFillAll) { for (i = 0; i < n; i++) { var oKeyField = oTargetGrid.getContent()[i].keyField; var sKey = oKeyField.getSelectedKey(); if (sKey != null && sKey !== "") { oUsedItems[sKey] = true; } } } for (i = 0; i < n; i++) { var oKeyField = oTargetGrid.getContent()[i].keyField; var oSelectCheckbox = oTargetGrid.getContent()[i].select; var sOldKey = oKeyField.getSelectedKey(); var j = 0; var aItems = this._aKeyFields; if (oKeyField !== oIgnoreKeyField) { if (bAppendLast) { j = aItems.length - 1; } else { // clean the items oKeyField.destroyItems(); } // fill all or only the not used items for (j; j < aItems.length; j++) { var oItem = aItems[j]; if (oItem.key == null || oItem.key === "" || !oUsedItems[oItem.key] || oItem.key === sOldKey) { oKeyField.addItem(new ListItem({ key: oItem.key, text: oItem.text, tooltip: oItem.tooltip ? oItem.tooltip : oItem.text })); } } oKeyField.setEditable(oKeyField.getItems().length > 1); } if (sOldKey) { oKeyField.setSelectedKey(sOldKey); } else if (oKeyField.getItems().length > 0) { // make at least the first item the selected item. We need this for updating the tooltip oKeyField.setSelectedItem(oKeyField.getItems()[0]); } if (!oSelectCheckbox.getSelected()) { // set/update the isDefault keyfield as selected item for an empty condition row /* eslint-disable no-loop-func */ this._aKeyFields.some(function(oKeyFieldItem, index) { if (oKeyFieldItem.isDefault) { oKeyField.setSelectedItem(oKeyField.getItems()[index]); return true; } if (!oKeyField.getSelectedItem()) { if (oKeyFieldItem.type !== "boolean") { oKeyField.setSelectedItem(oKeyField.getItems()[index]); } } }, this); } // update the tooltip if (oKeyField.getSelectedItem()) { oKeyField.setTooltip(oKeyField.getSelectedItem().getTooltip() || oKeyField.getSelectedItem().getText()); } } }; /** * called when the user makes a change on the condition operation. The function will update all other fields in the condition grid. * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid Grid which contains the Operation control which has been changed */ P13nConditionPanel.prototype._changeOperationValueFields = function(oTargetGrid, oConditionGrid) { // var oKeyfield = oConditionGrid.keyField; var oOperation = oConditionGrid.operation; var sOperation = oOperation.getSelectedKey(); var oValue1 = oConditionGrid.value1; var oValue2 = oConditionGrid.value2; var oShowIfGroupedvalue = oConditionGrid.showIfGrouped; if (!sOperation) { return; } if (sOperation === P13nConditionOperation.BT) { // for the "between" operation we enable both fields if (oValue1.setPlaceholder && oValue1.getPlaceholder() !== this._sFromLabelText) { oValue1.setPlaceholder(this._sFromLabelText); } if (!oValue1.getVisible()) { oValue1.setVisible(true); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.insertContent(oValue1, oConditionGrid.getContent().length - 1); } if (oValue2.setPlaceholder && oValue2.getPlaceholder() !== this._sToLabelText) { oValue2.setPlaceholder(this._sToLabelText); } if (!oValue2.getVisible()) { oValue2.setVisible(true); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.insertContent(oValue2, oConditionGrid.getContent().length - 1); } } else { if (sOperation === P13nConditionOperation.GroupAscending || sOperation === P13nConditionOperation.GroupDescending) { // update visible of fields if (oValue1.getVisible()) { oValue1.setVisible(false); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.removeContent(oValue1); } if (oValue2.getVisible()) { oValue2.setVisible(false); oConditionGrid.removeContent(oValue2); } if (oOperation.getVisible()) { oOperation.setVisible(false); oConditionGrid.removeContent(oOperation); } oShowIfGroupedvalue.setVisible(this._getMaxConditionsAsNumber() != 1); } else { if (sOperation === P13nConditionOperation.NotEmpty || sOperation === P13nConditionOperation.Empty || sOperation === P13nConditionOperation.Initial || sOperation === P13nConditionOperation.Ascending || sOperation === P13nConditionOperation.Descending || sOperation === P13nConditionOperation.Total || sOperation === P13nConditionOperation.Average || sOperation === P13nConditionOperation.Minimum || sOperation === P13nConditionOperation.Maximum) { // for this operations we disable both value fields if (oValue1.getVisible()) { oValue1.setVisible(false); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.removeContent(oValue1); } if (oValue2.getVisible()) { oValue2.setVisible(false); oConditionGrid.removeContent(oValue2); } // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.removeContent(oShowIfGroupedvalue); } else { // for all other operations we enable only the Value1 fields if (oValue1.setPlaceholder && oValue1.getPlaceholder() !== this._sValueLabelText) { oValue1.setPlaceholder(this._sValueLabelText); } if (!oValue1.getVisible()) { oValue1.setVisible(true); // workaround: making fields invisible for all mode L/M/S does not work, so we remove the fields from the grid. oConditionGrid.insertContent(oValue1, oConditionGrid.getContent().length - 1); } if (oValue2.getVisible()) { oValue2.setVisible(false); oConditionGrid.removeContent(oValue2); } } } } this._adjustValue1Span(oConditionGrid); }; /* * toggle the value1 field span between L5 and L3 depending on the selected operation */ P13nConditionPanel.prototype._adjustValue1Span = function(oConditionGrid) { if (this._sConditionType === "Filter" && oConditionGrid.value1 && oConditionGrid.operation) { var oOperation = oConditionGrid.operation; var sNewSpan = this._aConditionsFields[5]["Span" + this._sConditionType]; if (oOperation.getSelectedKey() !== "BT") { sNewSpan = "L5 M10 S10"; } var oLayoutData = oConditionGrid.value1.getLayoutData(); if (oLayoutData.getSpan() !== sNewSpan) { oLayoutData.setSpan(sNewSpan); } } }; /* * return the index of the oConditionGrid, the none valid condition will be ignored. */ P13nConditionPanel.prototype._getIndexOfCondition = function(oConditionGrid) { var iIndex = -1; oConditionGrid.getParent().getContent().some(function(oGrid) { if (oGrid.select.getSelected()) { iIndex++; } return (oGrid === oConditionGrid); }, this); return iIndex + this._iFirstConditionIndex; }; /* * makes a control valid or invalid, means it gets a warning state and shows a warning message attached to the field. * */ P13nConditionPanel.prototype._makeFieldValid = function(oCtrl, bValid, sMsg) { if (bValid) { oCtrl.setValueState(ValueState.None); oCtrl.setValueStateText(""); } else { oCtrl.setValueState(ValueState.Warning); oCtrl.setValueStateText(sMsg ? sMsg : this._sValidationDialogFieldMessage); } }; /* * change event handler for a value1 and value2 field control */ P13nConditionPanel.prototype._validateAndFormatFieldValue = function(oEvent) { var oCtrl = oEvent.oSource; var oConditionGrid = oCtrl.getParent(); var sValue; if (oCtrl.getDateValue && oEvent) { sValue = oEvent.getParameter("value"); var bValid = oEvent.getParameter("valid"); this._makeFieldValid(oCtrl, bValid); return; } else { sValue = oCtrl.getValue && oCtrl.getValue(); } if (!oConditionGrid) { return; } if (this.getDisplayFormat() === "UpperCase" && sValue) { sValue = sValue.toUpperCase(); oCtrl.setValue(sValue); } if (oConditionGrid.oType && sValue) { try { var oValue = oConditionGrid.oType.parseValue(sValue, "string"); oConditionGrid.oType.validateValue(oValue); this._makeFieldValid(oCtrl, true); sValue = oConditionGrid.oType.formatValue(oValue, "string"); oCtrl.setValue(sValue); } catch (err) { var sMsg = err.message; this._makeFieldValid(oCtrl, false, sMsg); } } else { this._makeFieldValid(oCtrl, true); } }; P13nConditionPanel.prototype._updateMinMaxDate = function(oConditionGrid, oValue1, oValue2) { if (oConditionGrid.value1.setMinDate && oConditionGrid.value2.setMaxDate) { if (oConditionGrid.value1 && oConditionGrid.value1.setMaxDate) { oConditionGrid.value1.setMaxDate(oValue2 instanceof Date ? oValue2 : null); } if (oConditionGrid.value2 && oConditionGrid.value2.setMinDate) { oConditionGrid.value2.setMinDate(oValue1 instanceof Date ? oValue1 : null); } } }; /** * called when the user makes a change in one of the condition fields. The function will update, remove or add the conditions for this condition. * * @private * @param {grid} oConditionGrid Grid which contains the Operation control which has been changed */ P13nConditionPanel.prototype._changeField = function(oConditionGrid, oEvent) { var sKeyField = oConditionGrid.keyField.getSelectedKey(); if (oConditionGrid.keyField.getSelectedItem()) { oConditionGrid.keyField.setTooltip(oConditionGrid.keyField.getSelectedItem().getTooltip() || oConditionGrid.keyField.getSelectedItem().getText()); } else { oConditionGrid.keyField.setTooltip(null); } var sOperation = oConditionGrid.operation.getSelectedKey(); if (oConditionGrid.operation.getSelectedItem()) { oConditionGrid.operation.setTooltip(oConditionGrid.operation.getSelectedItem().getTooltip() || oConditionGrid.operation.getSelectedItem().getText()); } else { oConditionGrid.operation.setTooltip(null); } var getValuesFromField = function(oControl, oType) { var sValue; var oValue; if (oControl.getDateValue && !(oControl.isA("sap.m.TimePicker")) && oType.getName() !== "sap.ui.comp.odata.type.StringDate") { oValue = oControl.getDateValue(); if (oType && oValue) { sValue = oType.formatValue(oValue, "string"); } } else { sValue = this._getValueTextFromField(oControl); oValue = sValue; if (oType && oType.getName() === "sap.ui.comp.odata.type.StringDate") { sValue = oType.formatValue(oValue, "string"); } else if (oType && sValue) { try { oValue = oType.parseValue(sValue, "string"); oType.validateValue(oValue); } catch (err) { sValue = ""; Log.error("sap.m.P13nConditionPanel", "not able to parse value " + sValue + " with type " + oType.getName()); } } } return [oValue, sValue]; }.bind(this); // update Value1 field control var aValues = getValuesFromField(oConditionGrid.value1, oConditionGrid.oType); var oValue1 = aValues[0], sValue1 = aValues[1]; // update Value2 field control aValues = getValuesFromField(oConditionGrid.value2, oConditionGrid.oType); var oValue2 = aValues[0], sValue2 = aValues[1]; // in case of a BT and a Date type try to set the minDate/maxDate for the From/To value datepicker if (sOperation === "BT") { this._updateMinMaxDate(oConditionGrid, oValue1, oValue2); } else { this._updateMinMaxDate(oConditionGrid, null, null); } var oCurrentKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); if (oCurrentKeyField && oCurrentKeyField.type === "numc") { // in case of type numc and Contains or EndsWith operator the leading 0 will be removed if ([P13nConditionOperation.Contains, P13nConditionOperation.EndsWith].indexOf(sOperation) != -1) { oValue1 = oConditionGrid.oType.formatValue(oValue1, "string"); } } var bShowIfGrouped = oConditionGrid.showIfGrouped.getSelected(); var bExclude = this.getExclude(); var oSelectCheckbox = oConditionGrid.select; var sValue = ""; var sKey; if (sKeyField === "" || sKeyField == null) { // handling of "(none)" or wrong entered keyField value sKeyField = null; sKey = this._getKeyFromConditionGrid(oConditionGrid); this._removeConditionFromMap(sKey); this._enableCondition(oConditionGrid, false); var iIndex = this._getIndexOfCondition(oConditionGrid); if (oSelectCheckbox.getSelected()) { oSelectCheckbox.setSelected(false); oSelectCheckbox.setEnabled(false); this._bIgnoreSetConditions = true; this.fireDataChange({ key: sKey, index: iIndex, operation: "remove", newData: null }); this._bIgnoreSetConditions = false; } return; } this._enableCondition(oConditionGrid, true); sValue = this._getFormatedConditionText(sOperation, sValue1, sValue2, bExclude, sKeyField, bShowIfGrouped); var oConditionData = { "value": sValue, "exclude": bExclude, "operation": sOperation, "keyField": sKeyField, "value1": oValue1, "value2": sOperation === P13nConditionOperation.BT ? oValue2 : null, "showIfGrouped": bShowIfGrouped }; sKey = this._getKeyFromConditionGrid(oConditionGrid); if (sValue !== "") { oSelectCheckbox.setSelected(true); oSelectCheckbox.setEnabled(true); var sOperation = "update"; if (!this._oConditionsMap[sKey]) { sOperation = "add"; } this._oConditionsMap[sKey] = oConditionData; if (sOperation === "add") { this._aConditionKeys.splice(this._getIndexOfCondition(oConditionGrid), 0, sKey); } //this._addCondition2Map(oConditionData, this._getIndexOfCondition(oConditionGrid)); oConditionGrid.data("_key", sKey); this.fireDataChange({ key: sKey, index: this._getIndexOfCondition(oConditionGrid), operation: sOperation, newData: oConditionData }); } else if (this._oConditionsMap[sKey] !== undefined) { this._removeConditionFromMap(sKey); oConditionGrid.data("_key", null); var iIndex = this._getIndexOfCondition(oConditionGrid); if (oSelectCheckbox.getSelected()) { oSelectCheckbox.setSelected(false); oSelectCheckbox.setEnabled(false); this._bIgnoreSetConditions = true; this.fireDataChange({ key: sKey, index: iIndex, operation: "remove", newData: null }); this._bIgnoreSetConditions = false; } } this._updatePaginatorToolbar(); }; /* * returns the value as text from a Value field. */ P13nConditionPanel.prototype._getValueTextFromField = function(oControl) { if (oControl instanceof Select) { return oControl.getSelectedItem() ? oControl.getSelectedItem().getText() : ""; } return oControl.getValue(); }; /** * update the enabled state for all conditions * * @private */ P13nConditionPanel.prototype._updateAllConditionsEnableStates = function() { var aConditionGrids = this._oConditionsGrid.getContent(); aConditionGrids.forEach(function(oConditionGrid) { var oKeyField = this._getCurrentKeyFieldItem(oConditionGrid.keyField); var sKeyField = oKeyField && oKeyField.key !== undefined ? oKeyField.key : oKeyField; var bEnabled = sKeyField !== "" && sKeyField !== null; this._enableCondition(oConditionGrid, bEnabled); }, this); }; /** * makes all controls in a condition Grid enabled or disabled * * @private * @param {grid} oConditionGrid instance * @param {boolean} bEnable state */ P13nConditionPanel.prototype._enableCondition = function(oConditionGrid, bEnable) { oConditionGrid.operation.setEnabled(bEnable); oConditionGrid.value1.setEnabled(bEnable); oConditionGrid.value2.setEnabled(bEnable); oConditionGrid.showIfGrouped.setEnabled(bEnable); }; /** * press handler for the remove condition buttons * * @private * @param {grid} oTargetGrid the main grid * @param {grid} oConditionGrid from where the remove is triggered */ P13nConditionPanel.prototype._removeCondition = function(oTargetGrid, oConditionGrid) { var sKey = this._getKeyFromConditionGrid(oConditionGrid); var iIndex = -1; if (oConditionGrid.select.getSelected()) { iIndex = this._getIndexOfCondition(oConditionGrid); } this._removeConditionFromMap(sKey); oConditionGrid.destroy(); if (oTargetGrid.getContent().length < 1) { this._createConditionRow(oTargetGrid); } else { this._updateConditionButtons(oTargetGrid); } if (iIndex >= 0) { this.fireDataChange({ key: sKey, index: iIndex, operation: "remove", newData: null }); } }; /** * update the condition add/remove buttons visibility * * @private * @param {grid} oTargetGrid the main grid */ P13nConditionPanel.prototype._updateConditionButtons = function(oTargetGrid) { var iMaxConditions = this._getMaxConditionsAsNumber(); var n = oTargetGrid.getContent().length; // if (n >= this._aKeyFields.length-1 && this.getAutoReduceKeyFieldItems()) { // // if the number of condition_rows-1 is the same as the KeyFields we hide the Add icon on all // condition rows. // iMax = 0; // } for (var i = 0; i < n; i++) { var oAddBtn = oTargetGrid.getContent()[i].add; if ((this.getAlwaysShowAddIcon() && (n < iMaxConditions)) || (i === n - 1 && i < iMaxConditions - 1)) { // show the Add only for the last condition row and if the Max value is not reached oAddBtn.removeStyleClass("displayNone"); } else { oAddBtn.addStyleClass("displayNone"); } var oRemoveBtn = oTargetGrid.getContent()[i].remove; if (iMaxConditions === 1 || (i === 0 && n === 1 && this.getDisableFirstRemoveIcon())) { oRemoveBtn.addStyleClass("displayNone"); } else { oRemoveBtn.removeStyleClass("displayNone"); } } }; /** * check if the entered/modified conditions are correct, marks invalid fields yellow (Warning state) and can be used to show error message dialog and give the * user the feedback that some values are wrong or missing. * * @private * @returns {boolean} <code>True</code> if all conditions are valid, <code>false</code> otherwise. * */ P13nConditionPanel.prototype.validateConditions = function() { var that = this; var fnCheckConditions = function(aGrids) { var bValid = true; for (var i = 0; i < aGrids.length; i++) { var oGrid = aGrids[i]; var bIsValid = that._checkCondition(oGrid, i === aGrids.length - 1); bValid = bValid && bIsValid; } return bValid; }; return fnCheckConditions(this._oConditionsGrid.getContent()); }; /** * removes all errors/warning states from the value1/2 fields of all conditions. * * @public * @since 1.28.0 */ P13nConditionPanel.prototype.removeValidationErrors = function() { this._oConditionsGrid.getContent().forEach(function(oConditionGrid) { var oValue1 = oConditionGrid.value1; var oValue2 = oConditionGrid.value2; oValue1.setValueState(ValueState.None); oValue1.setValueStateText(""); oValue2.setValueState(ValueState.None); oValue2.setValueStateText(""); }, this); }; /** * removes all invalid conditions. * * @public * @since 1.28.0 */ P13nConditionPanel.prototype.removeInvalidConditions = function() { var aInvalidConditionGrids = []; this._oConditionsGrid.getContent().forEach(function(oConditionGrid) { if (oConditionGrid.value1.getValueState() !== ValueState.None || oConditionGrid.value2.getValueState() !== ValueState.None) { aInvalidConditionGrids.push(oConditionGrid); } }, this); aInvalidConditionGrids.forEach(function(oConditionGrid) { this._removeCondition(this._oConditionsGrid, oConditionGrid); if (this.getAutoReduceKeyFieldItems()) { this._updateKeyFieldItems(this._oConditionsGrid, false); } }, this); }; /** * checks on a single condition if the values are filled correct and set the Status of invalid fields to Warning. The condition is invalid, when * e.g. in the BT condition one or both of the values is/are empty of for other condition operations the value1 field is not filled. * * @private * @param {Grid} oConditionGrid which contains the fields of a single condition * @param {boolean} isLast indicated if this is the last condition in the group * @returns {boolean} true, when the condition is filled correct, else false. */ P13nConditionPanel.prototype._checkCondition = function(oConditionGrid, isLast) { var bValid = true; var value1 = oConditionGrid.value1; var value2 = oConditionGrid.value2; var bValue1Empty = value1 && (value1.getVisible() && !this._getValueTextFromField(value1)); var bValue1State = value1 && value1.getVisible() && value1.getValueState ? value1.getValueState() : ValueState.None; var bValue2Empty = value2 && (value2.getVisible() && !this._getValueTextFromField(value2)); var bValue2State = value2 && value2.getVisible() && value2.getValueState ? value2.getValueState() : ValueState.None; var sOperation = oConditionGrid.operation.getSelectedKey(); if (sOperation === P13nConditionOperation.BT) { if (!bValue1Empty ? bValue2Empty : !bValue2Empty) { // XOR if (bValue1Empty) { value1.setValueState(ValueState.Warning); value1.setValueStateText(this._sValidationDialogFieldMessage); } if (bValue2Empty) { value2.setValueState(ValueState.Warning); value2.setValueStateText(this._sValidationDialogFieldMessage); } bValid = false; } else if (bValue1State !== ValueState.None || bValue2State !== ValueState.None) { bValid = false; } else { value1.setValueState(ValueState.None); value1.setValueStateText(""); value2.setValueState(ValueState.None); value2.setValueStateText(""); } } if ((value1.getVisible() && value1.getValueState && value1.getValueState() !== ValueState.None) || (value2.getVisible() && value2.getValueState && value2.getValueState() !== ValueState.None)) { bValid = false; } return bValid; }; /** * creates and returns the text for a condition * * @private * @param {string} sOperation the operation type sap.m.P13nConditionOperation * @param {string} sValue1 text of the first condition field * @param {string} sValue2 text of the second condition field * @param {boolean} bExclude indicates if the condition is an Exclude condition * @param {string} sKeyField id * @returns {string} the condition text */ P13nConditionPanel.prototype._getFormatedConditionText = function(sOperation, sValue1, sValue2, bExclude, sKeyField, bShowIfGrouped) { var sConditionText = P13nConditionPanel.getFormatedConditionText(sOperation, sValue1, sValue2, bExclude); if (!sConditionText) { switch (sOperation) { case P13nConditionOperation.Initial: sConditionText = "=''"; break; case P13nConditionOperation.NotEmpty: sConditionText = "!''"; break; case P13nConditionOperation.Ascending: sConditionText = "ascending"; break; case P13nConditionOperation.GroupAscending: sConditionText = "ascending"; sConditionText += " showIfGrouped:" + bShowIfGrouped; break; case P13nConditionOperation.Descending: sConditionText = "descending"; break; case P13nConditionOperation.GroupDescending: sConditionText = "descending"; sConditionText += " showIfGrouped:" + bShowIfGrouped; break; case P13nConditionOperation.Total: sConditionText = "total"; break; case P13nConditionOperation.Average: sConditionText = "average"; break; case P13nConditionOperation.Minimum: sConditionText = "minimum"; break; case P13nConditionOperation.Maximum: sConditionText = "maximum"; break; } if (bExclude && sConditionText !== "") { sConditionText = "!(" + sConditionText + ")"; } } if (this._aKeyFields && this._aKeyFields.length > 1) { var sKeyFieldText = null; // search the text for the KeyField for (var i = 0; i < this._aKeyFields.length; i++) { var oKeyField = this._aKeyFields[i]; if (typeof oKeyField !== "string") { if (oKeyField.key === sKeyField && oKeyField.text) { sKeyFieldText = oKeyField.text; } } } if (sKeyFieldText && sConditionText !== "") { sConditionText = sKeyFieldText + ": " + sConditionText; } } return sConditionText; }; /** * @enum {string} * @public * @experimental since version 1.26 !!! THIS TYPE IS ONLY FOR INTERNAL USE !!! */ // TODO: move to library.js var P13nConditionOperation = sap.m.P13nConditionOperation = { // filter operations BT: "BT", EQ: "EQ", Contains: "Contains", StartsWith: "StartsWith", EndsWith: "EndsWith", LT: "LT", LE: "LE", GT: "GT", GE: "GE", Initial: "Initial", Empty: "Empty", NotEmpty: "NotEmpty", // sort operations Ascending: "Ascending", Descending: "Descending", // group operations GroupAscending: "GroupAscending", GroupDescending: "GroupDescending", // calculation operations Total: "Total", Average: "Average", Minimum: "Minimum", Maximum: "Maximum" }; P13nConditionPanel._oConditionMap = { "EQ": "=$0", "GT": ">$0", "GE": ">=$0", "LT": "<$0", "LE": "<=$0", "Contains": "*$0*", "StartsWith": "$0*", "EndsWith": "*$0", "BT": "$0...$1", "Empty": "<$r>" }; // Replase $r params in operation by resource bundle text (function() { var _oRb = sap.ui.getCore().getLibraryResourceBundle("sap.m"); P13nConditionPanel._oConditionMap[P13nConditionOperation.Empty] = P13nConditionPanel._oConditionMap[P13nConditionOperation.Empty].replace("$r", _oRb.getText("CONDITIONPANEL_OPTIONEmpty")); })(); /** * fills the template string placeholder $0, $1 with the values from the aValues array and returns a formatted text for the specified condition * @private * @param {string} sTemplate the template which should be filled * @param {string[]} aValues value array for the template placeholder * @returns {string} the filled template text */ P13nConditionPanel._templateReplace = function(sTemplate, aValues) { return sTemplate.replace(/\$\d/g, function(sMatch) { return aValues[parseInt(sMatch.substr(1))]; }); }; /** * creates and returns a formatted text for the specified condition * @public * @param {string} sOperation the operation type sap.m.P13nConditionOperation * @param {string} sValue1 value of the first range field * @param {string} sValue2 value of the second range field * @param {boolean} bExclude indicates if the range is an Exclude range * @returns {string} the range token text. An empty string when no operation matches or the values for the operation are wrong */ P13nConditionPanel.getFormatedConditionText = function(sOperation, sValue1, sValue2, bExclude) { var sConditionText = ""; switch (sOperation) { case P13nConditionOperation.Empty: sConditionText = P13nConditionPanel._templateReplace(P13nConditionPanel._oConditionMap[sOperation], []); break; case P13nConditionOperation.EQ: case P13nConditionOperation.GT: case P13nConditionOperation.GE: case P13nConditionOperation.LT: case P13nConditionOperation.LE: case P13nConditionOperation.Contains: case P13nConditionOperation.StartsWith: case P13nConditionOperation.EndsWith: if (sValue1 !== "" && sValue1 !== undefined) { sConditionText = P13nConditionPanel._templateReplace(P13nConditionPanel._oConditionMap[sOperation], [sValue1]); } break; case P13nConditionOperation.BT: if (sValue1 !== "" && sValue1 !== undefined) { if (sValue2 !== "" && sValue2 !== undefined) { sConditionText = P13nConditionPanel._templateReplace(P13nConditionPanel._oConditionMap[sOperation], [sValue1, sValue2]); } } break; default: break; } if (bExclude && sConditionText !== "") { sConditionText = "!(" + sConditionText + ")"; } return sConditionText; }; P13nConditionPanel.prototype._updateLayout = function(oRangeInfo) { if (!this._oConditionsGrid) { return; } // if (window.console) { // window.console.log(" ---> " + oRangeInfo.name); // } var aGrids = this._oConditionsGrid.getContent(); var n = this._aConditionsFields.length; var newIndex = n; if (oRangeInfo.name === "Tablet") { newIndex = 5; } if (oRangeInfo.name === "Phone") { newIndex = 3; } if (this._sConditionType === "Filter") { for (var i = 0; i < aGrids.length; i++) { var grid = aGrids[i]; grid.ButtonContainer.removeStyleClass("floatRight"); grid.removeContent(grid.ButtonContainer); grid.insertContent(grid.ButtonContainer, newIndex); if (!this.getAlwaysShowAddIcon()) { if (newIndex !== n) { grid.ButtonContainer.removeContent(grid.add); grid.addContent(grid.add); } else { grid.removeContent(grid.add); grid.ButtonContainer.addContent(grid.add); } } } } }; P13nConditionPanel.prototype._onGridResize = function() { var w; // update the paginator toolbar width if exist if (this._oPaginatorToolbar && this._oConditionsGrid && this._oConditionsGrid.getContent().length > 0) { var oGrid = this._oConditionsGrid.getContent()[0]; if (oGrid.remove && oGrid.remove.$().position()) { w = 0; if (this._oPaginatorToolbar.getParent() && this._oPaginatorToolbar.getParent().getExpandable && this._oPaginatorToolbar.getParent().getExpandable()) { w = 48 - 4; } var iToolbarWidth = oGrid.remove.$().position().left - w + oGrid.remove.$().width(); //TODO - Panel expand button width + remove icon width this._oPaginatorToolbar.setWidth(iToolbarWidth + "px"); } } var domElement = this._oConditionsGrid.getDomRef(); if (!domElement) { return; } if (!jQuery(domElement).is(":visible")) { return; } w = domElement.clientWidth; var oRangeInfo = {}; if (w <= this._iBreakPointTablet) { oRangeInfo.name = "Phone"; } else if ((w > this._iBreakPointTablet) && (w <= this._iBreakPointDesktop)) { oRangeInfo.name = "Tablet"; } else { oRangeInfo.name = "Desktop"; } //if (window.console) { //window.console.log(w + " resize ---> " + oRangeInfo.name); //} if (oRangeInfo.name === "Phone" && this._sLayoutMode !== oRangeInfo.name) { this._updateLayout(oRangeInfo); this._sLayoutMode = oRangeInfo.name; } if (oRangeInfo.name === "Tablet" && this._sLayoutMode !== oRangeInfo.name) { this._updateLayout(oRangeInfo); this._sLayoutMode = oRangeInfo.name; } if (oRangeInfo.name === "Desktop" && this._sLayoutMode !== oRangeInfo.name) { this._updateLayout(oRangeInfo); this._sLayoutMode = oRangeInfo.name; } }; // this._findConfig("sap.ui.model.odata.type.Date", "operators") -->["EQ", "BT", "LE", "LT", "GE", "GT", "NE"] // this._findConfig("sap.ui.model.odata.type.Date", "ctrl") -->"DatePicker" P13nConditionPanel.prototype._findConfig = function(vType, sConfigName) { if (typeof vType === "object") { vType = vType.getMetadata().getName(); } var oConfig; while (vType && !(oConfig = this._getConfig(vType, sConfigName))) { // search until we have a type with known operators vType = this._getParentType(vType); // go to parent type } // either vType is undefined because no type in the hierarchy had the config, or oConfig does now have the desired information return oConfig; // TODO: return base config if undefined? However, this only makes a difference when a type is not derived from base. Would this be intentional or an error? }; P13nConditionPanel.prototype._getConfig = function(sType, sConfigName) { // no vType support here, because called often var oConfig = this._mOpsForType[sType]; if (oConfig) { return oConfig[sConfigName]; } }; P13nConditionPanel.prototype._getParentType = function(sType) { return this._mTypes[sType]; }; P13nConditionPanel.prototype._mTypes = { // basic "base": undefined, // TODO: needed? "string": "base", "numeric": "base", "date": "base", "time": "base", "boolean": "base", "int": "numeric", "float": "numeric", // simple "sap.ui.model.type.Boolean": "boolean", "sap.ui.model.type.Date": "date", "sap.ui.model.type.FileSize": "string", "sap.ui.model.type.Float": "float", "sap.ui.model.type.Integer": "int", "sap.ui.model.type.String": "string", "sap.ui.model.type.Time": "time", "sap.ui.comp.odata.type.StringDate": "date", // odata "sap.ui.model.odata.type.Boolean": "boolean", "sap.ui.model.odata.type.Byte": "int", "sap.ui.model.odata.type.Date": "date", "sap.ui.model.odata.type.DateTime": "datetime", "sap.ui.model.odata.type.DateTimeOffset": "datetime", "sap.ui.model.odata.type.Decimal": "float", "sap.ui.model.odata.type.Double": "float", "sap.ui.model.odata.type.Single": "float", "sap.ui.model.odata.type.Guid": "string", "sap.ui.model.odata.type.Int16": "int", "sap.ui.model.odata.type.Int32": "int", "sap.ui.model.odata.type.Int64": "int", "sap.ui.model.odata.type.Raw": "string", "sap.ui.model.odata.type.SByte": "int", "sap.ui.model.odata.type.String": "string", "sap.ui.model.odata.type.Time": "time", "sap.ui.model.odata.type.TimeOfDay": "time", //edm "Edm.Boolean": "sap.ui.model.odata.type.Boolean", "Edm.Byte": "sap.ui.model.odata.type.Byte", "Edm.Date": "sap.ui.model.odata.type.Date", // V4 Date "Edm.DateTime": "sap.ui.model.odata.type.DateTime", // only for V2 constraints: {displayFormat: 'Date' } "Edm.DateTimeOffset": "sap.ui.model.odata.type.DateTimeOffset", //constraints: { V4: true, precision: n } "Edm.Decimal": "sap.ui.model.odata.type.Decimal", //constraints: { precision, scale, minimum, maximum, minimumExclusive, maximumExclusive} "Edm.Double": "sap.ui.model.odata.type.Double", "Edm.Single": "sap.ui.model.odata.type.Single", "Edm.Guid": "sap.ui.model.odata.type.Guid", "Edm.Int16": "sap.ui.model.odata.type.Int16", "Edm.Int32": "sap.ui.model.odata.type.Int32", "Edm.Int64": "sap.ui.model.odata.type.Int64", //Edm.Raw not supported "Edm.SByte": "sap.ui.model.odata.type.SByte", "Edm.String": "sap.ui.model.odata.type.String", //constraints: {maxLength, isDigitSequence} "Edm.Time": "sap.ui.model.odata.type.Time", // only V2 "Edm.TimeOfDay": "sap.ui.model.odata.type.TimeOfDay" // V4 constraints: {precision} }; P13nConditionPanel.prototype._mOpsForType = { // defines operators for types "base": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT", "NE"], // defaultOperator: "EQ", ctrl: "input" }, "string": { // operators: ["Contains", "EQ", "BT", "StartsWith", "EndsWith", "LE", "LT", "GE", "GT", "NE"], // defaultOperator: "StartsWith", ctrl: "input" }, "date": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT", "NE"], ctrl: "DatePicker" }, "datetime": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT", "NE"], ctrl: "DateTimePicker" }, "numeric": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT", "NE"], ctrl: "input" }, "time": { // operators: ["EQ", "BT", "LE", "LT", "GE", "GT"], ctrl: "TimePicker" }, "boolean": { // operators: ["EQ", "NE"], ctrl: "select" } }; return P13nConditionPanel; });
[INTERNAL] P13nCondtionPanel.js : handling of pasted Date or other types are parsed Type validateValue will be used which e.g. check the maxLength BCP: 1980160792 Change-Id: Ic28b1aafb2672b77880b169c5ab8d6911aa5c77b
src/sap.m/src/sap/m/P13nConditionPanel.js
[INTERNAL] P13nCondtionPanel.js : handling of pasted
<ide><path>rc/sap.m/src/sap/m/P13nConditionPanel.js <ide> var sPastedValue = aSeparatedText[i].trim(); <ide> <ide> if (sPastedValue) { <add> var oPastedValue; <add> <add> if (oKeyField.typeInstance) { <add> // If a typeInstance exist, we have to parse and validate the pastedValue before we can add it a value into the condition. <add> // or we do not handle the paste for all types except String! <add> try { <add> oPastedValue = oKeyField.typeInstance.parseValue(sPastedValue, "string"); <add> oKeyField.typeInstance.validateValue(oPastedValue); <add> } catch (err) { <add> Log.error("sap.m.P13nConditionPanel.onPaste", "not able to parse value " + sPastedValue + " with type " + oKeyField.typeInstance.getName()); <add> sPastedValue = ""; <add> oPastedValue = null; <add> } <add> <add> if (!oPastedValue) { <add> continue; <add> } <add> } <add> <ide> var oCondition = { <ide> "key": that._createConditionKey(), <ide> "exclude": that.getExclude(), <ide> "operation": oOperation.getSelectedKey(), <ide> "keyField": oKeyField.key, <del> "value1": sPastedValue, <add> "value1": oPastedValue, <ide> "value2": null <ide> }; <ide> that._addCondition2Map(oCondition);
Java
epl-1.0
de4120515de550e2ba55bda0ac47abbfbde7ab77
0
rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.script; import java.util.HashMap; import java.util.Map; import org.eclipse.birt.core.data.DataType; import org.eclipse.birt.core.data.DataTypeUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.script.JavascriptEvalUtil; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.expression.ColumnReferenceExpression; import org.eclipse.birt.data.engine.expression.CompiledExpression; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.impl.ExprManager; import org.eclipse.birt.data.engine.impl.ModeManager; import org.eclipse.birt.data.engine.odi.IResultIterator; import org.eclipse.birt.data.engine.odi.IResultObject; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; /** * */ public class JSResultSetRow extends ScriptableObject { private ExprManager exprManager; private IResultIterator odiResult; private int currRowIndex; private Map valueCacheMap; private Scriptable scope; /** */ private static final long serialVersionUID = 649424371394281464L; /** * @param dataSet */ public JSResultSetRow( ExprManager exprManager, IResultIterator odiResult, Scriptable scope ) { this.exprManager = exprManager; this.odiResult = odiResult; this.currRowIndex = -1; this.valueCacheMap = new HashMap( ); this.scope = scope; } /* * @see org.mozilla.javascript.ScriptableObject#getClassName() */ public String getClassName( ) { return "ResultSetRow"; } /* * @see org.mozilla.javascript.ScriptableObject#has(int, * org.mozilla.javascript.Scriptable) */ public boolean has( int index, Scriptable start ) { return this.has( String.valueOf( index ), start ); } /* * @see org.mozilla.javascript.ScriptableObject#has(java.lang.String, * org.mozilla.javascript.Scriptable) */ public boolean has( String name, Scriptable start ) { return exprManager.getExpr( name ) != null; } /* * @see org.mozilla.javascript.ScriptableObject#get(int, * org.mozilla.javascript.Scriptable) */ public Object get( int index, Scriptable start ) { return this.get( String.valueOf( index ), start ); } /** * @param rsObject * @param index * @param name * @return value * @throws DataException */ public Object getValue( IResultObject rsObject, int index, String name ) throws DataException { if ( ModeManager.isOldMode( ) ) return rsObject.getFieldValue( index ); Object value = null; if ( name.startsWith( "_{" ) ) { try { value = rsObject.getFieldValue( name ); } catch ( DataException e ) { // ignore } } else { IBaseExpression dataExpr = this.exprManager.getExpr( name ); try { value = evaluateValue( dataExpr, -1, rsObject, this.scope ); value = JavascriptEvalUtil.convertJavascriptValue( value ); } catch ( BirtException e ) { } } return value; } /* * @see org.mozilla.javascript.ScriptableObject#get(java.lang.String, * org.mozilla.javascript.Scriptable) */ public Object get( String name, Scriptable start ) { int rowIndex = -1; try { rowIndex = odiResult.getCurrentResultIndex( ); } catch ( BirtException e1 ) { // impossible, ignore } if ( rowIndex == currRowIndex && valueCacheMap.containsKey( name ) ) { return valueCacheMap.get( name ); } else { Object value = null; try { IBaseExpression dataExpr = this.exprManager.getExpr( name ); value = evaluateValue( dataExpr, this.odiResult.getCurrentResultIndex( ), this.odiResult.getCurrentResult( ), this.scope ); } catch ( BirtException e ) { value = null; } if ( this.currRowIndex != rowIndex ) { this.valueCacheMap.clear( ); this.currRowIndex = rowIndex; } valueCacheMap.put( name, value ); return value; } } /** * @param dataExpr * @return * @throws BirtException */ private static Object evaluateValue( IBaseExpression dataExpr, int index, IResultObject roObject, Scriptable scope ) throws BirtException { Object exprValue = null; // TODO: find reasons Object handle = dataExpr == null ? null:dataExpr.getHandle( ); if ( handle instanceof CompiledExpression ) { CompiledExpression expr = (CompiledExpression) handle; Object value = evaluateCompiledExpression( expr, index, roObject, scope ); try { exprValue = DataTypeUtil.convert( value, dataExpr.getDataType( ) ); } catch ( BirtException e ) { throw new DataException( ResourceConstants.INCONVERTIBLE_DATATYPE, new Object[]{ value, value.getClass( ), DataType.getClass( dataExpr.getDataType( ) ) } ); } } else if ( handle instanceof ConditionalExpression ) { ConditionalExpression ce = (ConditionalExpression) handle; Object resultExpr = evaluateValue( ce.getExpression( ), index, roObject, scope ); Object resultOp1 = ce.getOperand1( ) != null ? evaluateValue( ce.getOperand1( ), index, roObject, scope ) : null; Object resultOp2 = ce.getOperand2( ) != null ? evaluateValue( ce.getOperand2( ), index, roObject, scope ) : null; String op1Text = ce.getOperand1( ) != null ? ce.getOperand1( ) .getText( ) : null; String op2Text = ce.getOperand2( ) != null ? ce.getOperand2( ) .getText( ) : null; exprValue = ScriptEvalUtil.evalConditionalExpr( resultExpr, ce.getOperator( ), ScriptEvalUtil.newExprInfo( op1Text, resultOp1 ), ScriptEvalUtil.newExprInfo( op2Text, resultOp2 ) ); } else { DataException e = new DataException( ResourceConstants.INVALID_EXPR_HANDLE ); throw e; } // the result might be a DataExceptionMocker. if ( exprValue instanceof DataExceptionMocker ) { throw ( (DataExceptionMocker) exprValue ).getCause( ); } return exprValue; } /** * @param expr * @param odiResult * @param scope * @return * @throws DataException */ private static Object evaluateCompiledExpression( CompiledExpression expr, int index, IResultObject roObject, Scriptable scope ) throws DataException { // Special case for DirectColRefExpr: it's faster to directly access // column value using the Odi IResultIterator. if ( expr instanceof ColumnReferenceExpression ) { // Direct column reference ColumnReferenceExpression colref = (ColumnReferenceExpression) expr; if ( colref.isIndexed( ) ) { int idx = colref.getColumnindex( ); // Special case: row[0] refers to internal rowID if ( idx == 0 ) return new Integer( index ); else if ( roObject != null ) return roObject.getFieldValue( idx ); else return null; } else { String name = colref.getColumnName( ); // Special case: row._rowPosition refers to internal rowID if ( JSRowObject.ROW_POSITION.equals( name ) ) return new Integer( index ); else if ( roObject != null ) return roObject.getFieldValue( name ); else return null; } } else { Context cx = Context.enter(); try { return expr.evaluate( cx, scope ); } finally { Context.exit(); } } } /* * @see org.mozilla.javascript.ScriptableObject#put(int, * org.mozilla.javascript.Scriptable, java.lang.Object) */ public void put( int index, Scriptable scope, Object value ) { throw new IllegalArgumentException( "Put value on result set row is not supported." ); } /* * @see org.mozilla.javascript.ScriptableObject#put(java.lang.String, * org.mozilla.javascript.Scriptable, java.lang.Object) */ public void put( String name, Scriptable scope, Object value ) { throw new IllegalArgumentException( "Put value on result set row is not supported." ); } }
data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.script; import java.util.HashMap; import java.util.Map; import org.eclipse.birt.core.data.DataType; import org.eclipse.birt.core.data.DataTypeUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.script.JavascriptEvalUtil; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.expression.ColumnReferenceExpression; import org.eclipse.birt.data.engine.expression.CompiledExpression; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.impl.ExprManager; import org.eclipse.birt.data.engine.impl.ModeManager; import org.eclipse.birt.data.engine.odi.IResultIterator; import org.eclipse.birt.data.engine.odi.IResultObject; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; /** * */ public class JSResultSetRow extends ScriptableObject { private ExprManager exprManager; private IResultIterator odiResult; private int currRowIndex; private Map valueCacheMap; private Scriptable scope; /** */ private static final long serialVersionUID = 649424371394281464L; /** * @param dataSet */ public JSResultSetRow( ExprManager exprManager, IResultIterator odiResult, Scriptable scope ) { this.exprManager = exprManager; this.odiResult = odiResult; this.currRowIndex = -1; this.valueCacheMap = new HashMap( ); this.scope = scope; } /* * @see org.mozilla.javascript.ScriptableObject#getClassName() */ public String getClassName( ) { return "ResultSetRow"; } /* * @see org.mozilla.javascript.ScriptableObject#has(int, * org.mozilla.javascript.Scriptable) */ public boolean has( int index, Scriptable start ) { throw new IllegalArgumentException( "Put value on result set row is not supported." ); } /* * @see org.mozilla.javascript.ScriptableObject#has(java.lang.String, * org.mozilla.javascript.Scriptable) */ public boolean has( String name, Scriptable start ) { return exprManager.getExpr( name ) != null; } /* * @see org.mozilla.javascript.ScriptableObject#get(int, * org.mozilla.javascript.Scriptable) */ public Object get( int index, Scriptable start ) { throw new IllegalArgumentException( "Put value on result set row is not supported." ); } /** * @param rsObject * @param index * @param name * @return value * @throws DataException */ public Object getValue( IResultObject rsObject, int index, String name ) throws DataException { if ( ModeManager.isOldMode( ) ) return rsObject.getFieldValue( index ); Object value = null; if ( name.startsWith( "_{" ) ) { try { value = rsObject.getFieldValue( name ); } catch ( DataException e ) { // ignore } } else { IBaseExpression dataExpr = this.exprManager.getExpr( name ); try { value = evaluateValue( dataExpr, -1, rsObject, this.scope ); value = JavascriptEvalUtil.convertJavascriptValue( value ); } catch ( BirtException e ) { } } return value; } /* * @see org.mozilla.javascript.ScriptableObject#get(java.lang.String, * org.mozilla.javascript.Scriptable) */ public Object get( String name, Scriptable start ) { int rowIndex = -1; try { rowIndex = odiResult.getCurrentResultIndex( ); } catch ( BirtException e1 ) { // impossible, ignore } if ( rowIndex == currRowIndex && valueCacheMap.containsKey( name ) ) { return valueCacheMap.get( name ); } else { Object value = null; try { IBaseExpression dataExpr = this.exprManager.getExpr( name ); value = evaluateValue( dataExpr, this.odiResult.getCurrentResultIndex( ), this.odiResult.getCurrentResult( ), this.scope ); } catch ( BirtException e ) { value = null; } if ( this.currRowIndex != rowIndex ) { this.valueCacheMap.clear( ); this.currRowIndex = rowIndex; } valueCacheMap.put( name, value ); return value; } } /** * @param dataExpr * @return * @throws BirtException */ private static Object evaluateValue( IBaseExpression dataExpr, int index, IResultObject roObject, Scriptable scope ) throws BirtException { Object exprValue = null; // TODO: find reasons Object handle = dataExpr == null ? null:dataExpr.getHandle( ); if ( handle instanceof CompiledExpression ) { CompiledExpression expr = (CompiledExpression) handle; Object value = evaluateCompiledExpression( expr, index, roObject, scope ); try { exprValue = DataTypeUtil.convert( value, dataExpr.getDataType( ) ); } catch ( BirtException e ) { throw new DataException( ResourceConstants.INCONVERTIBLE_DATATYPE, new Object[]{ value, value.getClass( ), DataType.getClass( dataExpr.getDataType( ) ) } ); } } else if ( handle instanceof ConditionalExpression ) { ConditionalExpression ce = (ConditionalExpression) handle; Object resultExpr = evaluateValue( ce.getExpression( ), index, roObject, scope ); Object resultOp1 = ce.getOperand1( ) != null ? evaluateValue( ce.getOperand1( ), index, roObject, scope ) : null; Object resultOp2 = ce.getOperand2( ) != null ? evaluateValue( ce.getOperand2( ), index, roObject, scope ) : null; String op1Text = ce.getOperand1( ) != null ? ce.getOperand1( ) .getText( ) : null; String op2Text = ce.getOperand2( ) != null ? ce.getOperand2( ) .getText( ) : null; exprValue = ScriptEvalUtil.evalConditionalExpr( resultExpr, ce.getOperator( ), ScriptEvalUtil.newExprInfo( op1Text, resultOp1 ), ScriptEvalUtil.newExprInfo( op2Text, resultOp2 ) ); } else { DataException e = new DataException( ResourceConstants.INVALID_EXPR_HANDLE ); throw e; } // the result might be a DataExceptionMocker. if ( exprValue instanceof DataExceptionMocker ) { throw ( (DataExceptionMocker) exprValue ).getCause( ); } return exprValue; } /** * @param expr * @param odiResult * @param scope * @return * @throws DataException */ private static Object evaluateCompiledExpression( CompiledExpression expr, int index, IResultObject roObject, Scriptable scope ) throws DataException { // Special case for DirectColRefExpr: it's faster to directly access // column value using the Odi IResultIterator. if ( expr instanceof ColumnReferenceExpression ) { // Direct column reference ColumnReferenceExpression colref = (ColumnReferenceExpression) expr; if ( colref.isIndexed( ) ) { int idx = colref.getColumnindex( ); // Special case: row[0] refers to internal rowID if ( idx == 0 ) return new Integer( index ); else if ( roObject != null ) return roObject.getFieldValue( idx ); else return null; } else { String name = colref.getColumnName( ); // Special case: row._rowPosition refers to internal rowID if ( JSRowObject.ROW_POSITION.equals( name ) ) return new Integer( index ); else if ( roObject != null ) return roObject.getFieldValue( name ); else return null; } } else { Context cx = Context.enter(); try { return expr.evaluate( cx, scope ); } finally { Context.exit(); } } } /* * @see org.mozilla.javascript.ScriptableObject#put(int, * org.mozilla.javascript.Scriptable, java.lang.Object) */ public void put( int index, Scriptable scope, Object value ) { throw new IllegalArgumentException( "Put value on result set row is not supported." ); } /* * @see org.mozilla.javascript.ScriptableObject#put(java.lang.String, * org.mozilla.javascript.Scriptable, java.lang.Object) */ public void put( String name, Scriptable scope, Object value ) { throw new IllegalArgumentException( "Put value on result set row is not supported." ); } }
Treat index as column name, since index usage is not allowed.
data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java
Treat index as column name, since index usage is not allowed.
<ide><path>ata/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java <ide> */ <ide> public boolean has( int index, Scriptable start ) <ide> { <del> throw new IllegalArgumentException( "Put value on result set row is not supported." ); <add> return this.has( String.valueOf( index ), start ); <ide> } <ide> <ide> /* <ide> */ <ide> public Object get( int index, Scriptable start ) <ide> { <del> throw new IllegalArgumentException( "Put value on result set row is not supported." ); <add> return this.get( String.valueOf( index ), start ); <ide> } <ide> <ide> /**
JavaScript
mit
a3ab040ac0f591f4db9132b2a6617c248586f3d3
0
bobbybouwmann/icapresents
// public/controllers/admin.js /** * Expose admin controllers and routes */ (function() { angular.module('admin', []) .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider .when('/admin', { templateUrl: '/views/adminpanel.html', controller: 'AdminPanelController' }) $locationProvider.html5Mode(true); }]) .controller('AdminPanelController', ['$http', '$scope', '$routeParams', function($http, $scope, $routeParams) { $http.get('/api/profiles') .success (function (data) { $scope.profiles = data; }); $scope.addProfile = function () { $http.post('/api/profiles', $scope.formDataProfile) .success (function (data) { console.log(data); $scope.profiles = data; }) .error (function (data) { console.log("error: " + data); }); }; $scope.removeProfile = function () { var box = document.getElementById('profileSelect'); var selected = box.options[box.selectedIndex].value; alert(selected); $http.delete('/api/profiles/' + selected) .success (function (data) { $location.path('/profiles'); }) .error (function (data){ console.log("error: " + data); }); }; }]); })();
public/controllers/admin.js
// public/controllers/admin.js /** * Expose admin controllers and routes */ (function() { angular.module('admin', []) .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider .when('/admin', { templateUrl: '/views/adminpanel.html', controller: 'AdminPanelController' }) $locationProvider.html5Mode(true); }]) .controller('AdminPanelController', ['$http', '$scope', '$routeParams', function($http, $scope, $routeParams) { $http.get('/api/profiles') .success (function (data) { $scope.profiles = data; }); $scope.addProfile = function () { $http.post('/api/profiles', $scope.formDataProfile) .success (function (data) { console.log(data); }) .error (function (data) { console.log("error: " + data); }); }; $scope.removeProfile = function () { var box = document.getElementById('profileSelect'); var selected = box.options[box.selectedIndex].text; alert(selected); $http.delete('/api/profiles/' + selected) .success (function (data) { $location.path('/profiles'); }) .error (function (data){ console.log("error: " + data); }); }; }]); })();
fixes
public/controllers/admin.js
fixes
<ide><path>ublic/controllers/admin.js <ide> $http.post('/api/profiles', $scope.formDataProfile) <ide> .success (function (data) { <ide> console.log(data); <add> $scope.profiles = data; <ide> }) <ide> .error (function (data) { <ide> console.log("error: " + data); <ide> <ide> $scope.removeProfile = function () { <ide> var box = document.getElementById('profileSelect'); <del> var selected = box.options[box.selectedIndex].text; <add> var selected = box.options[box.selectedIndex].value; <ide> alert(selected); <ide> $http.delete('/api/profiles/' + selected) <ide> .success (function (data) {
Java
lgpl-2.1
1491e35f78ee70a57856cbbc3cd804b3fc5fd4f2
0
viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import net.sf.jaer.Description; /** * This class will scan for filters and print out the wiki page that indexes them. * * When the file-selection box pops up, make a text-file to write to. You can * then copy this file into the wiki page at: * https://sourceforge.net/apps/trac/jaer/wiki/FilterIndex * to update the list of filters. * * @author Peter */ public class FilterIndexPrinter { public static void main(final String[] args) throws IOException { final List<String> classList = SubclassFinder.findSubclassesOf("net.sf.jaer.eventprocessing.EventFilter2D"); class Filter implements Comparable<Filter> { final String fullName; final String shortName; Filter(final String longName) { fullName = longName; final int point = longName.lastIndexOf("."); shortName = longName.substring(point + 1, longName.length()); } @Override public int compareTo(final Filter o) { return shortName.compareTo(o.shortName); } } final List<Filter> filterList = new ArrayList<Filter>(); for (final String c : classList) { filterList.add(new Filter(c)); } Collections.sort(filterList); /** Get file to save into */ final JFileChooser fileChooser = new JFileChooser("."); final int status = fileChooser.showOpenDialog(null); File selectedFile = null; if (status == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); // System.out.println(selectedFile.getParent()); // System.out.println(selectedFile.getName()); } else if (status == JFileChooser.CANCEL_OPTION) { // System.out.println(JFileChooser.CANCEL_OPTION); } if (selectedFile == null) { return; } FileOutputStream fout = null; try { fout = new FileOutputStream(selectedFile); } catch (final FileNotFoundException ex) { Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); return; } // Print the file. System.out.println("Printing file ..."); final PrintStream ps = new PrintStream(fout); ps.println("# List of Event-Processing Filters"); ps.println(); ps.println("Click on a filter for more info."); ps.println(); ps.println("|Filter Name|Description|Package|"); ps.println("|-----------|-----------|-------|"); for (final Filter f : filterList) { Description des = null; try { final Class<?> c = Class.forName(f.fullName); if (c.isAnnotationPresent(Description.class)) { des = c.getAnnotation(Description.class); } } catch (final SecurityException ex) { Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); } catch (final ClassNotFoundException ex) { Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); } String description; if (des == null) { description = " "; } else { description = des.value(); } ps.println("|[" + f.shortName + "](filt." + f.fullName + ")|" + description + "|" + f.fullName.substring(0, f.fullName.length() - f.shortName.length() - 1) + "|"); } ps.println(); ps.println("Run the class net.sf.jaer.util.FilterIndexPrinter to regenerate this list."); ps.close(); fout.close(); System.out.println("Done"); } }
src/net/sf/jaer/util/FilterIndexPrinter.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.sf.jaer.util; import java.awt.FileDialog; import java.awt.Frame; import java.io.*; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import net.sf.jaer.Description; import net.sf.jaer.eventprocessing.EventFilter2D; /** * This class will scan for filters and print out the wiki page that indexes them. * * When the file-selection box pops up, make a text-file to write to. You can * then copy this file into the wiki page at: * https://sourceforge.net/apps/trac/jaer/wiki/FilterIndex * to update the list of filters. * * @author Peter */ public class FilterIndexPrinter { public static void main(String[] args) throws IOException { // List<String> classList=ListClasses.listClasses(); List<String> classList=SubclassFinder.findSubclassesOf("net.sf.jaer.eventprocessing.EventFilter2D"); class Filter implements Comparable<Filter> { final String fullName; final String shortName; Filter(String longName) { fullName=longName; int point=longName.lastIndexOf("."); shortName=longName.substring(point+1,longName.length()); } @Override public int compareTo(Filter o) { return shortName.compareTo(o.shortName); } } List<Filter> filterList=new ArrayList(); for(String c:classList) filterList.add(new Filter(c)); Collections.sort(filterList); /** Get file to save into */ JFileChooser fileChooser = new JFileChooser("."); // FileFilter filter1 = new FileExtensionFilter("JPG and JPEG", new String[] { "JPG", "JPEG" }); // fileChooser.setFileFilter(filter1); int status = fileChooser.showOpenDialog(null); File selectedFile=null; if (status == JFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); // System.out.println(selectedFile.getParent()); // System.out.println(selectedFile.getName()); } else if (status == JFileChooser.CANCEL_OPTION) { // System.out.println(JFileChooser.CANCEL_OPTION); } // File file=fileDialog. // String file=fileDialog.getFile(); if (selectedFile==null) return; FileOutputStream fout=null; try { fout=new FileOutputStream(selectedFile); } catch (FileNotFoundException ex) { Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); return; } // Print the file. System.out.print("Printing file...."); PrintStream ps = new PrintStream(fout); ps.println("= List of Event-Processing Filters ="); ps.println(); ps.println("Click on a filter for more info."); ps.println(); // ps.println("||'''Filter Name'''||'''Description'''||'''Package'''||'''doc/src'''||"); // Some weird problem happened with the page getting cut off when we added this ps.println("||'''Filter Name'''||'''Description'''||'''Package'''||"); for (Filter f:filterList) { Description des=null; Method method = null; try { Class c = Class.forName(f.fullName); // method = c.getDeclaredMethod ("getDescription"); if (c.isAnnotationPresent(Description.class)) des = (Description) c.getAnnotation(Description.class); // } catch (NoSuchMethodException ex) { //Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); } String description; if (des==null) description=" "; else description=des.value(); // ps.println("||[wiki:\"filt/"+f.fullName+"\" "+f.shortName+"]||"+description+"||"+f.fullName.substring(0,f.fullName.length()-f.shortName.length()-1)+"||[http://jaer.svn.sourceforge.net/viewvc/jaer/trunk/host/java/src/"+f.fullName.replaceAll("\\.", "/")+".java?view=markup" +" .]||"); // ps.println("||[wiki:\"filt/"+f.fullName+"\" "+f.shortName+"]||"+description+"||"+f.fullName.substring(0,f.fullName.length()-f.shortName.length()-1)+"||[http://jaer.sourceforge.net/javadoc/"+f.fullName.replaceAll("\\.", "/")+".html" +" D] [http://jaer.svn.sourceforge.net/viewvc/jaer/trunk/host/java/src/"+f.fullName.replaceAll("\\.", "/")+".java?view=markup" +" S] ||"); ps.println("||[wiki:\"filt/"+f.fullName+"\" "+f.shortName+"]||"+description+"||"+f.fullName.substring(0,f.fullName.length()-f.shortName.length()-1)+"||"); ps.println(); } ps.println(); String footer="Run the class net.sf.jaer.util.!FilterIndexPrinter to regenerate this list."; fout.write(footer.getBytes()); ps.close(); fout.close(); System.out.print("Done"); } }
Update FilterIndexPrinter to correctly output new SF Allura Markdown syntax. git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@3999 b7f4320f-462c-0410-a916-d9f35bb82d52
src/net/sf/jaer/util/FilterIndexPrinter.java
Update FilterIndexPrinter to correctly output new SF Allura Markdown syntax.
<ide><path>rc/net/sf/jaer/util/FilterIndexPrinter.java <ide> */ <ide> package net.sf.jaer.util; <ide> <del>import java.awt.FileDialog; <del>import java.awt.Frame; <del>import java.io.*; <del>import java.lang.reflect.Method; <add>import java.io.File; <add>import java.io.FileNotFoundException; <add>import java.io.FileOutputStream; <add>import java.io.IOException; <add>import java.io.PrintStream; <ide> import java.util.ArrayList; <ide> import java.util.Collections; <ide> import java.util.List; <ide> import java.util.logging.Level; <ide> import java.util.logging.Logger; <add> <ide> import javax.swing.JFileChooser; <add> <ide> import net.sf.jaer.Description; <del>import net.sf.jaer.eventprocessing.EventFilter2D; <ide> <ide> /** <ide> * This class will scan for filters and print out the wiki page that indexes them. <ide> * <del> * When the file-selection box pops up, make a text-file to write to. You can <add> * When the file-selection box pops up, make a text-file to write to. You can <ide> * then copy this file into the wiki page at: <ide> * https://sourceforge.net/apps/trac/jaer/wiki/FilterIndex <ide> * to update the list of filters. <ide> * @author Peter <ide> */ <ide> public class FilterIndexPrinter { <del> <del> public static void main(String[] args) throws IOException <del> { <del> <del>// List<String> classList=ListClasses.listClasses(); <del> List<String> classList=SubclassFinder.findSubclassesOf("net.sf.jaer.eventprocessing.EventFilter2D"); <del> <del> class Filter implements Comparable<Filter> <del> { final String fullName; <del> final String shortName; <del> Filter(String longName) <del> { <del> fullName=longName; <del> int point=longName.lastIndexOf("."); <del> shortName=longName.substring(point+1,longName.length()); <del> <del> } <del> <del> @Override <del> public int compareTo(Filter o) { <del> return shortName.compareTo(o.shortName); <del> } <del> } <del> <del> List<Filter> filterList=new ArrayList(); <del> for(String c:classList) <del> filterList.add(new Filter(c)); <del> <del> Collections.sort(filterList); <del> <del> <del> <del> /** Get file to save into */ <del> JFileChooser fileChooser = new JFileChooser("."); <del>// FileFilter filter1 = new FileExtensionFilter("JPG and JPEG", new String[] { "JPG", "JPEG" }); <del>// fileChooser.setFileFilter(filter1); <del> int status = fileChooser.showOpenDialog(null); <del> <del> File selectedFile=null; <del> if (status == JFileChooser.APPROVE_OPTION) { <del> selectedFile = fileChooser.getSelectedFile(); <del>// System.out.println(selectedFile.getParent()); <del>// System.out.println(selectedFile.getName()); <del> } else if (status == JFileChooser.CANCEL_OPTION) { <del>// System.out.println(JFileChooser.CANCEL_OPTION); <del> } <del> <del>// File file=fileDialog. <del> <del>// String file=fileDialog.getFile(); <del> <del> if (selectedFile==null) <del> return; <del> <del> FileOutputStream fout=null; <del> try { <del> fout=new FileOutputStream(selectedFile); <del> } catch (FileNotFoundException ex) { <del> Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); <del> return; <del> } <del> <del> <del> // Print the file. <del> System.out.print("Printing file...."); <del> PrintStream ps = new PrintStream(fout); <del> ps.println("= List of Event-Processing Filters ="); <del> ps.println(); <del> ps.println("Click on a filter for more info."); <del> ps.println(); <del> <del>// ps.println("||'''Filter Name'''||'''Description'''||'''Package'''||'''doc/src'''||"); // Some weird problem happened with the page getting cut off when we added this <del> ps.println("||'''Filter Name'''||'''Description'''||'''Package'''||"); <del> <del> for (Filter f:filterList) <del> { <del> Description des=null; <del> <del> Method method = null; <del> try { <del> Class c = Class.forName(f.fullName); <del> <del>// method = c.getDeclaredMethod ("getDescription"); <del> <del> if (c.isAnnotationPresent(Description.class)) <del> des = (Description) c.getAnnotation(Description.class); <del> <del>// } catch (NoSuchMethodException ex) { <del> //Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); <del> } catch (SecurityException ex) { <del> Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); <del> } catch (ClassNotFoundException ex) { <del> Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); <del> } <del> <del> String description; <del> if (des==null) <del> description=" "; <del> else <del> description=des.value(); <del> <del>// ps.println("||[wiki:\"filt/"+f.fullName+"\" "+f.shortName+"]||"+description+"||"+f.fullName.substring(0,f.fullName.length()-f.shortName.length()-1)+"||[http://jaer.svn.sourceforge.net/viewvc/jaer/trunk/host/java/src/"+f.fullName.replaceAll("\\.", "/")+".java?view=markup" +" .]||"); <del> <del>// ps.println("||[wiki:\"filt/"+f.fullName+"\" "+f.shortName+"]||"+description+"||"+f.fullName.substring(0,f.fullName.length()-f.shortName.length()-1)+"||[http://jaer.sourceforge.net/javadoc/"+f.fullName.replaceAll("\\.", "/")+".html" +" D] [http://jaer.svn.sourceforge.net/viewvc/jaer/trunk/host/java/src/"+f.fullName.replaceAll("\\.", "/")+".java?view=markup" +" S] ||"); <del> ps.println("||[wiki:\"filt/"+f.fullName+"\" "+f.shortName+"]||"+description+"||"+f.fullName.substring(0,f.fullName.length()-f.shortName.length()-1)+"||"); <del> <del> ps.println(); <del> } <del> <del> ps.println(); <del> String footer="Run the class net.sf.jaer.util.!FilterIndexPrinter to regenerate this list."; <del> fout.write(footer.getBytes()); <del> ps.close(); <del> fout.close(); <del> System.out.print("Done"); <del> } <del> <del> <add> public static void main(final String[] args) throws IOException { <add> final List<String> classList = SubclassFinder.findSubclassesOf("net.sf.jaer.eventprocessing.EventFilter2D"); <add> <add> class Filter implements Comparable<Filter> { <add> final String fullName; <add> final String shortName; <add> <add> Filter(final String longName) { <add> fullName = longName; <add> final int point = longName.lastIndexOf("."); <add> shortName = longName.substring(point + 1, longName.length()); <add> <add> } <add> <add> @Override <add> public int compareTo(final Filter o) { <add> return shortName.compareTo(o.shortName); <add> } <add> } <add> <add> final List<Filter> filterList = new ArrayList<Filter>(); <add> for (final String c : classList) { <add> filterList.add(new Filter(c)); <add> } <add> <add> Collections.sort(filterList); <add> <add> /** Get file to save into */ <add> final JFileChooser fileChooser = new JFileChooser("."); <add> final int status = fileChooser.showOpenDialog(null); <add> <add> File selectedFile = null; <add> if (status == JFileChooser.APPROVE_OPTION) { <add> selectedFile = fileChooser.getSelectedFile(); <add> // System.out.println(selectedFile.getParent()); <add> // System.out.println(selectedFile.getName()); <add> } <add> else if (status == JFileChooser.CANCEL_OPTION) { <add> // System.out.println(JFileChooser.CANCEL_OPTION); <add> } <add> <add> if (selectedFile == null) { <add> return; <add> } <add> <add> FileOutputStream fout = null; <add> try { <add> fout = new FileOutputStream(selectedFile); <add> } <add> catch (final FileNotFoundException ex) { <add> Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); <add> return; <add> } <add> <add> // Print the file. <add> System.out.println("Printing file ..."); <add> final PrintStream ps = new PrintStream(fout); <add> ps.println("# List of Event-Processing Filters"); <add> ps.println(); <add> ps.println("Click on a filter for more info."); <add> ps.println(); <add> <add> ps.println("|Filter Name|Description|Package|"); <add> ps.println("|-----------|-----------|-------|"); <add> <add> for (final Filter f : filterList) { <add> Description des = null; <add> <add> try { <add> final Class<?> c = Class.forName(f.fullName); <add> <add> if (c.isAnnotationPresent(Description.class)) { <add> des = c.getAnnotation(Description.class); <add> } <add> } <add> catch (final SecurityException ex) { <add> Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); <add> } <add> catch (final ClassNotFoundException ex) { <add> Logger.getLogger(FilterIndexPrinter.class.getName()).log(Level.SEVERE, null, ex); <add> } <add> <add> String description; <add> if (des == null) { <add> description = " "; <add> } <add> else { <add> description = des.value(); <add> } <add> <add> ps.println("|[" + f.shortName + "](filt." + f.fullName + ")|" + description + "|" <add> + f.fullName.substring(0, f.fullName.length() - f.shortName.length() - 1) + "|"); <add> } <add> <add> ps.println(); <add> ps.println("Run the class net.sf.jaer.util.FilterIndexPrinter to regenerate this list."); <add> <add> ps.close(); <add> fout.close(); <add> System.out.println("Done"); <add> } <ide> }
Java
apache-2.0
77c8654cc91997383fc5aa9b77f9a7604bcbaf2e
0
nroduit/XChart,timmolter/XChart
package org.knowm.xchart.internal.chartpart; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import org.knowm.xchart.XYChart; import org.knowm.xchart.internal.series.Series; import org.knowm.xchart.style.Styler; import org.knowm.xchart.style.XYStyler; /** @author timmolter */ public abstract class PlotContent_<ST extends Styler, S extends Series> implements ChartPart { final Chart<ST, S> chart; ToolTips toolTips; ChartZoom chartZoom; // TODO create a PlotContent_Axes class to put this in. static final Stroke ERROR_BAR_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); /** * Constructor * * @param chart - The Chart */ PlotContent_(Chart<ST, S> chart) { this.chart = chart; } protected abstract void doPaint(Graphics2D g); @Override public void paint(Graphics2D g) { Rectangle2D bounds = getBounds(); // g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); // g.setColor(Color.red); // g.draw(bounds); // if the area to draw a chart on is so small, don't even bother if (bounds.getWidth() < 30) { return; } java.awt.Shape saveClip = g.getClip(); // this is for preventing the series to be drawn outside the plot area if min and max is // overridden to fall inside the data range if (saveClip != null) { g.setClip(bounds.createIntersection(saveClip.getBounds2D())); } else { g.setClip(bounds); } // chart.cursor.prepare(bounds, (Map<String, Series>) chart.getSeriesMap()); doPaint(g); // after painting the plot content, paint the tooltip(s) if necessary if (chart.getStyler().isToolTipsEnabled()) { toolTips.paint(g); } // chart.cursor.paint(g); // TODO here the annotation classes are added. Refactor this! // for (ChartPart part : chart.getPlotParts()) { // part.paint(g); // } // TODO create a PlotContent_Axes class to put this in. if (chart instanceof XYChart && ((XYStyler) chart.getStyler()).isZoomEnabled()) { chartZoom.paint(g); } g.setClip(saveClip); } @Override public Rectangle2D getBounds() { return chart.getPlot().getBounds(); } /** Closes a path for area charts if one is available. */ void closePath( Graphics2D g, Path2D.Double path, double previousX, Rectangle2D bounds, double yTopMargin) { if (path != null) { double yBottomOfArea = getBounds().getY() + getBounds().getHeight() - yTopMargin; path.lineTo(previousX, yBottomOfArea); path.closePath(); g.fill(path); } } public void setToolTips(ToolTips toolTips) { this.toolTips = toolTips; } public void setChartZoom(ChartZoom chartZoom) { this.chartZoom = chartZoom; } }
xchart/src/main/java/org/knowm/xchart/internal/chartpart/PlotContent_.java
package org.knowm.xchart.internal.chartpart; import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.Stroke; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import org.knowm.xchart.internal.series.Series; import org.knowm.xchart.style.Styler; /** @author timmolter */ public abstract class PlotContent_<ST extends Styler, S extends Series> implements ChartPart { final Chart<ST, S> chart; ToolTips toolTips; ChartZoom chartZoom; // TODO create a PlotContent_Axes class to put this in. static final Stroke ERROR_BAR_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); /** * Constructor * * @param chart - The Chart */ PlotContent_(Chart<ST, S> chart) { this.chart = chart; } protected abstract void doPaint(Graphics2D g); @Override public void paint(Graphics2D g) { Rectangle2D bounds = getBounds(); // g.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); // g.setColor(Color.red); // g.draw(bounds); // if the area to draw a chart on is so small, don't even bother if (bounds.getWidth() < 30) { return; } java.awt.Shape saveClip = g.getClip(); // this is for preventing the series to be drawn outside the plot area if min and max is // overridden to fall inside the data range if (saveClip != null) { g.setClip(bounds.createIntersection(saveClip.getBounds2D())); } else { g.setClip(bounds); } // chart.cursor.prepare(bounds, (Map<String, Series>) chart.getSeriesMap()); doPaint(g); // after painting the plot content, paint the tooltip(s) if necessary if (chart.getStyler().isToolTipsEnabled()) { toolTips.paint(g); } // chart.cursor.paint(g); // TODO here the annotation classes are added. Refactor this! // for (ChartPart part : chart.getPlotParts()) { // part.paint(g); // } chartZoom.paint(g); g.setClip(saveClip); } @Override public Rectangle2D getBounds() { return chart.getPlot().getBounds(); } /** Closes a path for area charts if one is available. */ void closePath( Graphics2D g, Path2D.Double path, double previousX, Rectangle2D bounds, double yTopMargin) { if (path != null) { double yBottomOfArea = getBounds().getY() + getBounds().getHeight() - yTopMargin; path.lineTo(previousX, yBottomOfArea); path.closePath(); g.fill(path); } } public void setToolTips(ToolTips toolTips) { this.toolTips = toolTips; } public void setChartZoom(ChartZoom chartZoom) { this.chartZoom = chartZoom; } }
fix broken ChartZoom (2)
xchart/src/main/java/org/knowm/xchart/internal/chartpart/PlotContent_.java
fix broken ChartZoom (2)
<ide><path>chart/src/main/java/org/knowm/xchart/internal/chartpart/PlotContent_.java <ide> import java.awt.Stroke; <ide> import java.awt.geom.Path2D; <ide> import java.awt.geom.Rectangle2D; <add> <add>import org.knowm.xchart.XYChart; <ide> import org.knowm.xchart.internal.series.Series; <ide> import org.knowm.xchart.style.Styler; <add>import org.knowm.xchart.style.XYStyler; <ide> <ide> /** @author timmolter */ <ide> public abstract class PlotContent_<ST extends Styler, S extends Series> implements ChartPart { <ide> // part.paint(g); <ide> // } <ide> <del> chartZoom.paint(g); <add> // TODO create a PlotContent_Axes class to put this in. <add> if (chart instanceof XYChart && ((XYStyler) chart.getStyler()).isZoomEnabled()) { <add> chartZoom.paint(g); <add> } <ide> <ide> g.setClip(saveClip); <ide> }
Java
apache-2.0
0b29374c2626dc0dd64d0edb2a88834ca57dd8eb
0
kurtharriger/spring-osgi
/* * Copyright 2002-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.osgi.service.collection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry; import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry; import org.springframework.beans.factory.InitializingBean; import org.springframework.osgi.service.TargetSourceLifecycleListener; import org.springframework.osgi.service.importer.ReferenceClassLoadingOptions; import org.springframework.osgi.service.interceptor.OsgiServiceInvoker; import org.springframework.osgi.service.interceptor.OsgiServiceStaticInterceptor; import org.springframework.osgi.service.interceptor.ServiceReferenceAwareAdvice; import org.springframework.osgi.service.util.OsgiServiceBindingUtils; import org.springframework.osgi.util.OsgiListenerUtils; import org.springframework.util.Assert; /** * OSGi service dynamic collection - allows iterating while the underlying * storage is being shrunk/expanded. This collection is read-only - its content * is being retrieved dynamically from the OSGi platform. * * <p/> This collection and its iterators are thread-safe. That is, multiple * threads can access the collection. However, since the collection is * read-only, it cannot be modified by the client. * * @see Collection * @author Costin Leau */ public class OsgiServiceCollection implements Collection, InitializingBean { /** * Listener tracking the OSGi services which form the dynamic collection. * * @author Costin Leau */ private class Listener implements ServiceListener { public void serviceChanged(ServiceEvent event) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); ServiceReference ref = event.getServiceReference(); Long serviceId = (Long) ref.getProperty(Constants.SERVICE_ID); boolean found = false; switch (event.getType()) { case (ServiceEvent.REGISTERED): case (ServiceEvent.MODIFIED): // same as ServiceEvent.REGISTERED synchronized (serviceIDs) { if (!serviceReferences.containsKey(serviceId)) { found = true; serviceReferences.put(serviceId, createServiceProxy(ref)); serviceIDs.add(serviceId); } } // inform listeners // TODO: should this be part of the lock also? if (found) OsgiServiceBindingUtils.callListenersBind(context, ref, listeners); break; case (ServiceEvent.UNREGISTERING): synchronized (serviceIDs) { // remove servce Object proxy = serviceReferences.remove(serviceId); found = serviceIDs.remove(serviceId); if (proxy != null) { invalidateProxy(proxy); assignLastDeadProxy(proxy); } } // TODO: should this be part of the lock also? if (found) OsgiServiceBindingUtils.callListenersUnbind(context, ref, listeners); break; default: throw new IllegalArgumentException("unsupported event type:" + event); } } // OSGi swallows these exceptions so make sure we get a chance to // see them. catch (Throwable re) { if (log.isWarnEnabled()) { log.warn("serviceChanged() processing failed", re); } } finally { Thread.currentThread().setContextClassLoader(tccl); } } } private static final Log log = LogFactory.getLog(OsgiServiceCollection.class); // map of services // the service id is used as key while the service proxy is used for // values // Map<ServiceId, ServiceProxy> // // NOTE: this collection is protected by the 'serviceIDs' lock. protected final Map serviceReferences = new LinkedHashMap(8); /** * list binding the service IDs to the map of service proxies */ protected final Collection serviceIDs = createInternalDynamicStorage(); /** * Recall the last proxy for the rare case, where a service goes down * between the #hasNext() and #next() call of an iterator. * * Subclasses should implement their own strategy when it comes to assign a * value to it through */ protected volatile Object lastDeadProxy; private final Filter filter; private final BundleContext context; private int contextClassLoader = ReferenceClassLoadingOptions.CLIENT; protected final ClassLoader classLoader; // advices to be applied when creating service proxy private Object[] interceptors = new Object[0]; private TargetSourceLifecycleListener[] listeners = new TargetSourceLifecycleListener[0]; private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance(); public OsgiServiceCollection(Filter filter, BundleContext context, ClassLoader classLoader) { Assert.notNull(classLoader, "ClassLoader is required"); Assert.notNull(context, "context is required"); this.filter = filter; this.context = context; this.classLoader = classLoader; } /* * (non-Javadoc) * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ public void afterPropertiesSet() { if (log.isTraceEnabled()) log.trace("adding osgi listener for services matching [" + filter + "]"); OsgiListenerUtils.addServiceListener(context, new Listener(), filter); } /** * Create the dynamic storage used internally. The storage <strong>has</strong> * to be thread-safe. */ protected Collection createInternalDynamicStorage() { return new DynamicCollection(); } /** * Create a service proxy over the service reference. The proxy purpose is * to transparently decouple the client from holding a strong reference to * the service (which might go away). * * @param ref */ protected Object createServiceProxy(ServiceReference ref) { // get classes under which the service was registered String[] classes = (String[]) ref.getProperty(Constants.OBJECTCLASS); List intfs = new ArrayList(); Class proxyClass = null; for (int i = 0; i < classes.length; i++) { // resolve classes (using the proper classloader) Bundle loader = ref.getBundle(); try { Class clazz = loader.loadClass(classes[i]); // FIXME: discover lower class if multiple class names are used // (basically detect the lowest subclass) if (clazz.isInterface()) intfs.add(clazz); else { proxyClass = clazz; } } catch (ClassNotFoundException cnfex) { throw (RuntimeException) new IllegalArgumentException("cannot create proxy").initCause(cnfex); } } ProxyFactory factory = new ProxyFactory(); if (!intfs.isEmpty()) factory.setInterfaces((Class[]) intfs.toArray(new Class[intfs.size()])); if (proxyClass != null) { factory.setProxyTargetClass(true); factory.setTargetClass(proxyClass); } // add the interceptors if (this.interceptors != null) { for (int i = 0; i < this.interceptors.length; i++) { factory.addAdvisor(this.advisorAdapterRegistry.wrap(this.interceptors[i])); } } addEndingInterceptors(factory, ref); // TODO: why not add these? // factory.setOptimize(true); // factory.setFrozen(true); return factory.getProxy(classLoader); } /** * Add the ending interceptors such as lookup and Service Reference aware. * @param pf */ protected void addEndingInterceptors(ProxyFactory factory, ServiceReference ref) { OsgiServiceInvoker invoker = new OsgiServiceStaticInterceptor(context, ref, contextClassLoader, classLoader); factory.addAdvice(new ServiceReferenceAwareAdvice(invoker)); factory.addAdvice(invoker); } private void invalidateProxy(Object proxy) { // TODO: add proxy invalidation } /** * Hook for tracking the last disappearing service to cope with the rare * case, where the last service in the collection disappears between calls * to hasNext() and next() on an iterator at the end of the collection. * * @param proxy */ protected void assignLastDeadProxy(Object proxy) { this.lastDeadProxy = proxy; } public Iterator iterator() { // use the service map not just the list of indexes return new Iterator() { // dynamic thread-safe iterator private final Iterator iter = serviceIDs.iterator(); public boolean hasNext() { return iter.hasNext(); } public Object next() { synchronized (serviceIDs) { Object id = iter.next(); return (id == null ? lastDeadProxy : serviceReferences.get(id)); } } public void remove() { // write operations disabled throw new UnsupportedOperationException(); } }; } public int size() { return serviceIDs.size(); } public String toString() { synchronized (serviceIDs) { return serviceReferences.values().toString(); } } // // write operations forbidden // public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } public boolean add(Object o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } public boolean contains(Object o) { synchronized (serviceIDs) { return serviceReferences.containsValue(o); } } public boolean containsAll(Collection c) { synchronized (serviceIDs) { return serviceReferences.values().containsAll(c); } } public boolean isEmpty() { return size() == 0; } public Object[] toArray() { synchronized (serviceIDs) { return serviceReferences.values().toArray(); } } public Object[] toArray(Object[] array) { synchronized (serviceIDs) { return serviceReferences.values().toArray(array); } } /** * @return Returns the interceptors. */ public Object[] getInterceptors() { return interceptors; } /** * The optional interceptors used when proxying each service. These will * always be added before the OsgiServiceStaticInterceptor. * * @param interceptors The interceptors to set. */ public void setInterceptors(Object[] interceptors) { Assert.notNull(interceptors, "argument should not be null"); this.interceptors = interceptors; } /** * @param listeners The listeners to set. */ public void setListeners(TargetSourceLifecycleListener[] listeners) { Assert.notNull(listeners, "argument should not be null"); this.listeners = listeners; } /** * @param contextClassLoader The contextClassLoader to set. */ public void setContextClassLoader(int contextClassLoader) { this.contextClassLoader = contextClassLoader; } }
core/src/main/java/org/springframework/osgi/service/collection/OsgiServiceCollection.java
/* * Copyright 2002-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.osgi.service.collection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.ServiceEvent; import org.osgi.framework.ServiceListener; import org.osgi.framework.ServiceReference; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry; import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry; import org.springframework.beans.factory.InitializingBean; import org.springframework.osgi.service.TargetSourceLifecycleListener; import org.springframework.osgi.service.importer.ReferenceClassLoadingOptions; import org.springframework.osgi.service.interceptor.OsgiServiceInvoker; import org.springframework.osgi.service.interceptor.OsgiServiceStaticInterceptor; import org.springframework.osgi.service.interceptor.ServiceReferenceAwareAdvice; import org.springframework.osgi.service.util.OsgiServiceBindingUtils; import org.springframework.osgi.util.OsgiListenerUtils; import org.springframework.util.Assert; /** * OSGi service dynamic collection - allows iterating while the underlying * storage is being shrunk/expanded. This collection is read-only - its content * is being retrieved dynamically from the OSGi platform. * * <p/> This collection and its iterators are thread-safe. That is, multiple * threads can access the collection. However, since the collection is read-only, * it cannot be modified by the client. * * @see Collection * @author Costin Leau */ public class OsgiServiceCollection implements Collection, InitializingBean { /** * Listener tracking the OSGi services which form the dynamic collection. * * @author Costin Leau */ private class Listener implements ServiceListener { public void serviceChanged(ServiceEvent event) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); ServiceReference ref = event.getServiceReference(); Long serviceId = (Long) ref.getProperty(Constants.SERVICE_ID); boolean found = false; switch (event.getType()) { case (ServiceEvent.REGISTERED): case (ServiceEvent.MODIFIED): // same as ServiceEvent.REGISTERED synchronized (serviceIDs) { if (!serviceReferences.containsKey(serviceId)) { found = true; serviceReferences.put(serviceId, createServiceProxy(ref)); serviceIDs.add(serviceId); } } // inform listeners // TODO: should this be part of the lock also? if (found) OsgiServiceBindingUtils.callListenersBind(context, ref, listeners); break; case (ServiceEvent.UNREGISTERING): synchronized (serviceIDs) { // remove servce Object proxy = serviceReferences.remove(serviceId); found = serviceIDs.remove(serviceId); if (proxy != null) { invalidateProxy(proxy); lastDeadProxy = proxy; } } // TODO: should this be part of the lock also? if (found) OsgiServiceBindingUtils.callListenersUnbind(context, ref, listeners); break; default: throw new IllegalArgumentException("unsupported event type:" + event); } } // OSGi swallows these exceptions so make sure we get a chance to // see them. catch (Throwable re) { if (log.isWarnEnabled()) { log.warn("serviceChanged() processing failed", re); } } finally { Thread.currentThread().setContextClassLoader(tccl); } } } private static final Log log = LogFactory.getLog(OsgiServiceCollection.class); // map of services // the service id is used as key while the service proxy is used for // values // Map<ServiceId, ServiceProxy> // // NOTE: this collection is protected by the 'serviceIDs' lock. protected final Map serviceReferences = new LinkedHashMap(8); /** * list binding the service IDs to the map of service proxies */ protected final Collection serviceIDs = createInternalDynamicStorage(); /** * Recall the last proxy for the rare case, where a service goes down * between the #hasNext() and #next() call of an iterator. */ protected volatile Object lastDeadProxy; private final Filter filter; private final BundleContext context; private int contextClassLoader = ReferenceClassLoadingOptions.CLIENT; protected final ClassLoader classLoader; // advices to be applied when creating service proxy private Object[] interceptors = new Object[0]; private TargetSourceLifecycleListener[] listeners = new TargetSourceLifecycleListener[0]; private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance(); public OsgiServiceCollection(Filter filter, BundleContext context, ClassLoader classLoader) { Assert.notNull(classLoader, "ClassLoader is required"); Assert.notNull(context, "context is required"); this.filter = filter; this.context = context; this.classLoader = classLoader; } /* * (non-Javadoc) * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ public void afterPropertiesSet() { if (log.isTraceEnabled()) log.trace("adding osgi listener for services matching [" + filter + "]"); OsgiListenerUtils.addServiceListener(context, new Listener(), filter); } /** * Create the dynamic storage used internally. The storage <strong>has</strong> * to be thread-safe. */ protected Collection createInternalDynamicStorage() { return new DynamicCollection(); } /** * Create a service proxy over the service reference. The proxy purpose is * to transparently decouple the client from holding a strong reference to * the service (which might go away). * * @param ref */ private Object createServiceProxy(ServiceReference ref) { // get classes under which the service was registered String[] classes = (String[]) ref.getProperty(Constants.OBJECTCLASS); List intfs = new ArrayList(); Class proxyClass = null; for (int i = 0; i < classes.length; i++) { // resolve classes (using the proper classloader) Bundle loader = ref.getBundle(); try { Class clazz = loader.loadClass(classes[i]); // FIXME: discover lower class if multiple class names are used // (basically detect the lowest subclass) if (clazz.isInterface()) intfs.add(clazz); else { proxyClass = clazz; } } catch (ClassNotFoundException cnfex) { throw (RuntimeException) new IllegalArgumentException("cannot create proxy").initCause(cnfex); } } ProxyFactory factory = new ProxyFactory(); if (!intfs.isEmpty()) factory.setInterfaces((Class[]) intfs.toArray(new Class[intfs.size()])); if (proxyClass != null) { factory.setProxyTargetClass(true); factory.setTargetClass(proxyClass); } // add the interceptors if (this.interceptors != null) { for (int i = 0; i < this.interceptors.length; i++) { factory.addAdvisor(this.advisorAdapterRegistry.wrap(this.interceptors[i])); } } addEndingInterceptors(factory, ref); // TODO: why not add these? // factory.setOptimize(true); // factory.setFrozen(true); return factory.getProxy(classLoader); } /** * Add the ending interceptors such as lookup and Service Reference aware. * @param pf */ protected void addEndingInterceptors(ProxyFactory factory, ServiceReference ref) { OsgiServiceInvoker invoker = new OsgiServiceStaticInterceptor(context, ref, contextClassLoader, classLoader); factory.addAdvice(new ServiceReferenceAwareAdvice(invoker)); factory.addAdvice(invoker); } private void invalidateProxy(Object proxy) { // TODO: add proxy invalidation } public Iterator iterator() { // use the service map not just the list of indexes return new Iterator() { // dynamic thread-safe iterator private final Iterator iter = serviceIDs.iterator(); public boolean hasNext() { return iter.hasNext(); } public Object next() { synchronized (serviceIDs) { Object id = iter.next(); return (id == null ? lastDeadProxy : serviceReferences.get(id)); } } public void remove() { // write operations disabled throw new UnsupportedOperationException(); } }; } public int size() { return serviceIDs.size(); } public String toString() { synchronized (serviceIDs) { return serviceReferences.values().toString(); } } // // write operations forbidden // public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } public boolean add(Object o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } public boolean contains(Object o) { synchronized (serviceIDs) { return serviceReferences.containsValue(o); } } public boolean containsAll(Collection c) { synchronized (serviceIDs) { return serviceReferences.values().containsAll(c); } } public boolean isEmpty() { return size() == 0; } public Object[] toArray() { synchronized (serviceIDs) { return serviceReferences.values().toArray(); } } public Object[] toArray(Object[] array) { synchronized (serviceIDs) { return serviceReferences.values().toArray(array); } } /** * @return Returns the interceptors. */ public Object[] getInterceptors() { return interceptors; } /** * The optional interceptors used when proxying each service. These will * always be added before the OsgiServiceStaticInterceptor. * * @param interceptors The interceptors to set. */ public void setInterceptors(Object[] interceptors) { Assert.notNull(interceptors, "argument should not be null"); this.interceptors = interceptors; } /** * @param listeners The listeners to set. */ public void setListeners(TargetSourceLifecycleListener[] listeners) { Assert.notNull(listeners, "argument should not be null"); this.listeners = listeners; } /** * @param contextClassLoader The contextClassLoader to set. */ public void setContextClassLoader(int contextClassLoader) { this.contextClassLoader = contextClassLoader; } }
forgot to commit missing class
core/src/main/java/org/springframework/osgi/service/collection/OsgiServiceCollection.java
forgot to commit missing class
<ide><path>ore/src/main/java/org/springframework/osgi/service/collection/OsgiServiceCollection.java <ide> * is being retrieved dynamically from the OSGi platform. <ide> * <ide> * <p/> This collection and its iterators are thread-safe. That is, multiple <del> * threads can access the collection. However, since the collection is read-only, <del> * it cannot be modified by the client. <add> * threads can access the collection. However, since the collection is <add> * read-only, it cannot be modified by the client. <ide> * <ide> * @see Collection <ide> * @author Costin Leau <ide> found = serviceIDs.remove(serviceId); <ide> if (proxy != null) { <ide> invalidateProxy(proxy); <del> lastDeadProxy = proxy; <add> assignLastDeadProxy(proxy); <ide> } <ide> } <ide> // TODO: should this be part of the lock also? <ide> /** <ide> * Recall the last proxy for the rare case, where a service goes down <ide> * between the #hasNext() and #next() call of an iterator. <add> * <add> * Subclasses should implement their own strategy when it comes to assign a <add> * value to it through <ide> */ <ide> protected volatile Object lastDeadProxy; <ide> <ide> * <ide> * @param ref <ide> */ <del> private Object createServiceProxy(ServiceReference ref) { <add> protected Object createServiceProxy(ServiceReference ref) { <ide> // get classes under which the service was registered <ide> String[] classes = (String[]) ref.getProperty(Constants.OBJECTCLASS); <ide> <ide> // TODO: add proxy invalidation <ide> } <ide> <add> /** <add> * Hook for tracking the last disappearing service to cope with the rare <add> * case, where the last service in the collection disappears between calls <add> * to hasNext() and next() on an iterator at the end of the collection. <add> * <add> * @param proxy <add> */ <add> protected void assignLastDeadProxy(Object proxy) { <add> this.lastDeadProxy = proxy; <add> } <add> <ide> public Iterator iterator() { <ide> // use the service map not just the list of indexes <ide> return new Iterator() {
JavaScript
mit
082828caa334ff4e996b262346edfa3f9cde1b85
0
formio/formio.js,formio/formio.js,formio/formio.js
import Component from '../_classes/component/Component'; export default class HTMLComponent extends Component { static schema(...extend) { return Component.schema({ label: 'HTML', type: 'htmlelement', tag: 'p', attrs: [], content: '', input: false, persistent: false }, ...extend); } static get builderInfo() { return { title: 'HTML Element', group: 'layout', icon: 'code', weight: 0, documentation: 'http://help.form.io/userguide/#html-element-component', schema: HTMLComponent.schema() }; } get defaultSchema() { return HTMLComponent.schema(); } get content() { return this.component.content ? this.interpolate(this.component.content, { data: this.rootValue, row: this.data }) : ''; } get singleTags() { return ['br', 'img', 'hr']; } checkRefreshOn(changed) { super.checkRefreshOn(changed); if (!this.builderMode && this.component.refreshOnChange && this.element) { this.setContent(this.element, this.renderContent()); } } renderContent() { return this.renderTemplate('html', { component: this.component, tag: this.component.tag, attrs: (this.component.attrs || []).map((attr) => { return { attr: attr.attr, value: this.interpolate(attr.value, { data: this.rootValue, row: this.data }) }; }), content: this.content, singleTags: this.singleTags, }); } render() { return super.render(this.renderContent()); } attach(element) { this.loadRefs(element, { html: 'single' }); return super.attach(element); } }
src/components/html/HTML.js
import Component from '../_classes/component/Component'; export default class HTMLComponent extends Component { static schema(...extend) { return Component.schema({ label: 'HTML', type: 'htmlelement', tag: 'p', attrs: [], content: '', input: false, persistent: false }, ...extend); } static get builderInfo() { return { title: 'HTML Element', group: 'layout', icon: 'code', weight: 0, documentation: 'http://help.form.io/userguide/#html-element-component', schema: HTMLComponent.schema() }; } get defaultSchema() { return HTMLComponent.schema(); } get content() { return this.component.content ? this.interpolate(this.component.content, { data: this.rootValue, row: this.data }) : ''; } get singleTags() { return ['br', 'img', 'hr']; } checkRefreshOn(changed) { super.checkRefreshOn(changed); if (!this.builderMode && this.component.refreshOnChange && this.refs.html) { this.setContent(this.element, this.renderContent()); } } renderContent() { return this.renderTemplate('html', { component: this.component, tag: this.component.tag, attrs: (this.component.attrs || []).map((attr) => { return { attr: attr.attr, value: this.interpolate(attr.value, { data: this.rootValue, row: this.data }) }; }), content: this.content, singleTags: this.singleTags, }); } render() { return super.render(this.renderContent()); } attach(element) { this.loadRefs(element, { html: 'single' }); return super.attach(element); } }
Check for element instead of html ref.
src/components/html/HTML.js
Check for element instead of html ref.
<ide><path>rc/components/html/HTML.js <ide> <ide> checkRefreshOn(changed) { <ide> super.checkRefreshOn(changed); <del> if (!this.builderMode && this.component.refreshOnChange && this.refs.html) { <add> if (!this.builderMode && this.component.refreshOnChange && this.element) { <ide> this.setContent(this.element, this.renderContent()); <ide> } <ide> }
JavaScript
mit
fc8fe935049a134fded87bef90bd60bf41312227
0
squatsandsciencelabs/OpenBarbellApp,squatsandsciencelabs/OpenBarbellApp,squatsandsciencelabs/OpenBarbellApp,squatsandsciencelabs/OpenBarbellApp,squatsandsciencelabs/OpenBarbellApp
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import SetForm from 'app/shared_features/set_card/expanded/SetForm'; import * as Actions from './EditHistorySetFormActions'; import * as DateUtils from 'app/utility/transforms/DateUtils'; const mapStateToProps = (state, ownProps) => { const rpeDisabled = !DateUtils.checkDateWithinRange(7, ownProps.initialStartTime) return { rpeDisabled: rpeDisabled, }; } const mapDispatchToProps = (dispatch) => { return bindActionCreators({ saveSet: Actions.saveSet, tapExercise: Actions.presentExercise, tapTags: Actions.presentTags, tapRPE: Actions.editRPE, tapWeight: Actions.editWeight, dismissRPE: Actions.dismissRPE, dismissWeight: Actions.dismissWeight, toggleMetric: Actions.toggleMetric, }, dispatch); }; const EditHistorySetFormScreen = connect( mapStateToProps, mapDispatchToProps )(SetForm); export default EditHistorySetFormScreen;
app/features/history/card/expanded/form/EditHistorySetFormScreen.js
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import SetForm from 'app/shared_features/set_card/expanded/SetForm'; import * as Actions from './EditHistorySetFormActions'; import * as DateUtils from 'app/utility/transforms/DateUtils'; const mapStateToProps = (state, ownProps) => { const rpeDisabled = !DateUtils.checkDateWithinRange(7, ownProps.initialStartTime) return { rpeDisabled: rpeDisabled, } } const mapDispatchToProps = (dispatch) => { return bindActionCreators({ saveSet: Actions.saveSet, tapExercise: Actions.presentExercise, tapTags: Actions.presentTags, tapRPE: Actions.editRPE, tapWeight: Actions.editWeight, dismissRPE: Actions.dismissRPE, dismissWeight: Actions.dismissWeight, toggleMetric: Actions.toggleMetric, }, dispatch); }; const EditHistorySetFormScreen = connect( mapStateToProps, mapDispatchToProps )(SetForm); export default EditHistorySetFormScreen;
Semicolon
app/features/history/card/expanded/form/EditHistorySetFormScreen.js
Semicolon
<ide><path>pp/features/history/card/expanded/form/EditHistorySetFormScreen.js <ide> <ide> return { <ide> rpeDisabled: rpeDisabled, <del> } <add> }; <ide> } <ide> <ide> const mapDispatchToProps = (dispatch) => {
Java
apache-2.0
a6e94eff463b6dea0d31ad933aaec42e2d095acb
0
datastax/java-driver,datastax/java-driver
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.api.querybuilder.relation; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.driver.api.querybuilder.BuildableQuery; import com.datastax.oss.driver.api.querybuilder.CqlSnippet; import com.datastax.oss.driver.api.querybuilder.term.Term; import com.datastax.oss.driver.internal.core.CqlIdentifiers; import com.datastax.oss.driver.internal.querybuilder.relation.CustomIndexRelation; import com.datastax.oss.driver.internal.querybuilder.relation.DefaultColumnComponentRelationBuilder; import com.datastax.oss.driver.internal.querybuilder.relation.DefaultColumnRelationBuilder; import com.datastax.oss.driver.internal.querybuilder.relation.DefaultMultiColumnRelationBuilder; import com.datastax.oss.driver.internal.querybuilder.relation.DefaultTokenRelationBuilder; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.Arrays; /** * A relation in a WHERE clause. * * <p>To build instances of this type, use the factory methods, such as {@link #column(String) * column}, {@link #token(String...) token}, etc. * * <p>They are used as arguments to the {@link OngoingWhereClause#where(Iterable) where} method, for * example: * * <pre>{@code * selectFrom("foo").all().where(Relation.column("k").isEqualTo(literal(1))) * // SELECT * FROM foo WHERE k=1 * }</pre> * * There are also shortcuts in the fluent API when you build a statement, for example: * * <pre>{@code * selectFrom("foo").all().whereColumn("k").isEqualTo(literal(1)) * // SELECT * FROM foo WHERE k=1 * }</pre> */ public interface Relation extends CqlSnippet { /** * Builds a relation testing a column. * * <p>This must be chained with an operator call, for example: * * <pre>{@code * Relation r = Relation.column("k").isEqualTo(bindMarker()); * }</pre> */ @NonNull static ColumnRelationBuilder<Relation> column(@NonNull CqlIdentifier id) { return new DefaultColumnRelationBuilder(id); } /** Shortcut for {@link #column(CqlIdentifier) column(CqlIdentifier.fromCql(name))} */ @NonNull static ColumnRelationBuilder<Relation> column(@NonNull String name) { return column(CqlIdentifier.fromCql(name)); } /** Builds a relation testing a value in a map (Cassandra 4 and above). */ @NonNull static ColumnComponentRelationBuilder<Relation> mapValue( @NonNull CqlIdentifier columnId, @NonNull Term index) { // The concept could easily be extended to list elements and tuple components, so use a generic // name internally, we'll add other shortcuts if necessary. return new DefaultColumnComponentRelationBuilder(columnId, index); } /** * Shortcut for {@link #mapValue(CqlIdentifier, Term) mapValue(CqlIdentifier.fromCql(columnName), * index)} */ @NonNull static ColumnComponentRelationBuilder<Relation> mapValue( @NonNull String columnName, @NonNull Term index) { return mapValue(CqlIdentifier.fromCql(columnName), index); } /** Builds a relation testing a token generated from a set of columns. */ @NonNull static TokenRelationBuilder<Relation> tokenFromIds(@NonNull Iterable<CqlIdentifier> identifiers) { return new DefaultTokenRelationBuilder(identifiers); } /** Var-arg equivalent of {@link #tokenFromIds(Iterable)}. */ @NonNull static TokenRelationBuilder<Relation> token(@NonNull CqlIdentifier... identifiers) { return tokenFromIds(Arrays.asList(identifiers)); } /** * Equivalent of {@link #tokenFromIds(Iterable)} with raw strings; the names are converted with * {@link CqlIdentifier#fromCql(String)}. */ @NonNull static TokenRelationBuilder<Relation> token(@NonNull Iterable<String> names) { return tokenFromIds(CqlIdentifiers.wrap(names)); } /** Var-arg equivalent of {@link #token(Iterable)}. */ @NonNull static TokenRelationBuilder<Relation> token(@NonNull String... names) { return token(Arrays.asList(names)); } /** Builds a multi-column relation, as in {@code WHERE (c1, c2, c3) IN ...}. */ @NonNull static MultiColumnRelationBuilder<Relation> columnIds( @NonNull Iterable<CqlIdentifier> identifiers) { return new DefaultMultiColumnRelationBuilder(identifiers); } /** Var-arg equivalent of {@link #columnIds(Iterable)}. */ @NonNull static MultiColumnRelationBuilder<Relation> columns(@NonNull CqlIdentifier... identifiers) { return columnIds(Arrays.asList(identifiers)); } /** * Equivalent of {@link #columnIds(Iterable)} with raw strings; the names are converted with * {@link CqlIdentifier#fromCql(String)}. */ @NonNull static MultiColumnRelationBuilder<Relation> columns(@NonNull Iterable<String> names) { return columnIds(CqlIdentifiers.wrap(names)); } /** Var-arg equivalent of {@link #columns(Iterable)}. */ @NonNull static MultiColumnRelationBuilder<Relation> columns(@NonNull String... names) { return columns(Arrays.asList(names)); } /** Builds a relation on a custom index. */ @NonNull static Relation customIndex(@NonNull CqlIdentifier indexId, @NonNull Term expression) { return new CustomIndexRelation(indexId, expression); } /** * Shortcut for {@link #customIndex(CqlIdentifier, Term) * customIndex(CqlIdentifier.fromCql(indexName), expression)} */ @NonNull static Relation customIndex(@NonNull String indexName, @NonNull Term expression) { return customIndex(CqlIdentifier.fromCql(indexName), expression); } /** * Whether this relation is idempotent. * * <p>That is, whether it always selects the same rows when used multiple times. For example, * {@code WHERE c=1} is idempotent, {@code WHERE c=now()} isn't. * * <p>This is used internally by the query builder to compute the {@link Statement#isIdempotent()} * flag on the UPDATE and DELETE statements generated by {@link BuildableQuery#build()} (this is * not relevant for SELECT statement, which are always idempotent). If a term is ambiguous (for * example a raw snippet or a call to a user function in the right operands), the builder is * pessimistic and assumes the term is not idempotent. */ boolean isIdempotent(); }
query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/relation/Relation.java
/* * Copyright DataStax, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.oss.driver.api.querybuilder.relation; import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.cql.Statement; import com.datastax.oss.driver.api.querybuilder.BuildableQuery; import com.datastax.oss.driver.api.querybuilder.CqlSnippet; import com.datastax.oss.driver.api.querybuilder.term.Term; import com.datastax.oss.driver.internal.core.CqlIdentifiers; import com.datastax.oss.driver.internal.querybuilder.relation.CustomIndexRelation; import com.datastax.oss.driver.internal.querybuilder.relation.DefaultColumnComponentRelationBuilder; import com.datastax.oss.driver.internal.querybuilder.relation.DefaultColumnRelationBuilder; import com.datastax.oss.driver.internal.querybuilder.relation.DefaultMultiColumnRelationBuilder; import com.datastax.oss.driver.internal.querybuilder.relation.DefaultTokenRelationBuilder; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.Arrays; /** * A relation in a WHERE clause. * * <p>To build instances of this type, use the factory methods, such as {@link #column(String) * column}, {@link #token(String...) token}, etc. * * <p>They are used as arguments to the {@link OngoingWhereClause#where(Iterable) where} method, for * example: * * <pre>{@code * selectFrom("foo").all().whereColumn("k").isEqualTo(literal(1)) * // SELECT * FROM foo WHERE k=1 * }</pre> * * There are also shortcuts in the fluent API when you build a statement, for example: * * <pre>{@code * selectFrom("foo").all().whereColumn("k").isEqualTo(literal(1)) * // SELECT * FROM foo WHERE k=1 * }</pre> */ public interface Relation extends CqlSnippet { /** * Builds a relation testing a column. * * <p>This must be chained with an operator call, for example: * * <pre>{@code * Relation r = Relation.column("k").isEqualTo(bindMarker()); * }</pre> */ @NonNull static ColumnRelationBuilder<Relation> column(@NonNull CqlIdentifier id) { return new DefaultColumnRelationBuilder(id); } /** Shortcut for {@link #column(CqlIdentifier) column(CqlIdentifier.fromCql(name))} */ @NonNull static ColumnRelationBuilder<Relation> column(@NonNull String name) { return column(CqlIdentifier.fromCql(name)); } /** Builds a relation testing a value in a map (Cassandra 4 and above). */ @NonNull static ColumnComponentRelationBuilder<Relation> mapValue( @NonNull CqlIdentifier columnId, @NonNull Term index) { // The concept could easily be extended to list elements and tuple components, so use a generic // name internally, we'll add other shortcuts if necessary. return new DefaultColumnComponentRelationBuilder(columnId, index); } /** * Shortcut for {@link #mapValue(CqlIdentifier, Term) mapValue(CqlIdentifier.fromCql(columnName), * index)} */ @NonNull static ColumnComponentRelationBuilder<Relation> mapValue( @NonNull String columnName, @NonNull Term index) { return mapValue(CqlIdentifier.fromCql(columnName), index); } /** Builds a relation testing a token generated from a set of columns. */ @NonNull static TokenRelationBuilder<Relation> tokenFromIds(@NonNull Iterable<CqlIdentifier> identifiers) { return new DefaultTokenRelationBuilder(identifiers); } /** Var-arg equivalent of {@link #tokenFromIds(Iterable)}. */ @NonNull static TokenRelationBuilder<Relation> token(@NonNull CqlIdentifier... identifiers) { return tokenFromIds(Arrays.asList(identifiers)); } /** * Equivalent of {@link #tokenFromIds(Iterable)} with raw strings; the names are converted with * {@link CqlIdentifier#fromCql(String)}. */ @NonNull static TokenRelationBuilder<Relation> token(@NonNull Iterable<String> names) { return tokenFromIds(CqlIdentifiers.wrap(names)); } /** Var-arg equivalent of {@link #token(Iterable)}. */ @NonNull static TokenRelationBuilder<Relation> token(@NonNull String... names) { return token(Arrays.asList(names)); } /** Builds a multi-column relation, as in {@code WHERE (c1, c2, c3) IN ...}. */ @NonNull static MultiColumnRelationBuilder<Relation> columnIds( @NonNull Iterable<CqlIdentifier> identifiers) { return new DefaultMultiColumnRelationBuilder(identifiers); } /** Var-arg equivalent of {@link #columnIds(Iterable)}. */ @NonNull static MultiColumnRelationBuilder<Relation> columns(@NonNull CqlIdentifier... identifiers) { return columnIds(Arrays.asList(identifiers)); } /** * Equivalent of {@link #columnIds(Iterable)} with raw strings; the names are converted with * {@link CqlIdentifier#fromCql(String)}. */ @NonNull static MultiColumnRelationBuilder<Relation> columns(@NonNull Iterable<String> names) { return columnIds(CqlIdentifiers.wrap(names)); } /** Var-arg equivalent of {@link #columns(Iterable)}. */ @NonNull static MultiColumnRelationBuilder<Relation> columns(@NonNull String... names) { return columns(Arrays.asList(names)); } /** Builds a relation on a custom index. */ @NonNull static Relation customIndex(@NonNull CqlIdentifier indexId, @NonNull Term expression) { return new CustomIndexRelation(indexId, expression); } /** * Shortcut for {@link #customIndex(CqlIdentifier, Term) * customIndex(CqlIdentifier.fromCql(indexName), expression)} */ @NonNull static Relation customIndex(@NonNull String indexName, @NonNull Term expression) { return customIndex(CqlIdentifier.fromCql(indexName), expression); } /** * Whether this relation is idempotent. * * <p>That is, whether it always selects the same rows when used multiple times. For example, * {@code WHERE c=1} is idempotent, {@code WHERE c=now()} isn't. * * <p>This is used internally by the query builder to compute the {@link Statement#isIdempotent()} * flag on the UPDATE and DELETE statements generated by {@link BuildableQuery#build()} (this is * not relevant for SELECT statement, which are always idempotent). If a term is ambiguous (for * example a raw snippet or a call to a user function in the right operands), the builder is * pessimistic and assumes the term is not idempotent. */ boolean isIdempotent(); }
Fix wrong example in Relation class javadocs
query-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/relation/Relation.java
Fix wrong example in Relation class javadocs
<ide><path>uery-builder/src/main/java/com/datastax/oss/driver/api/querybuilder/relation/Relation.java <ide> * example: <ide> * <ide> * <pre>{@code <del> * selectFrom("foo").all().whereColumn("k").isEqualTo(literal(1)) <add> * selectFrom("foo").all().where(Relation.column("k").isEqualTo(literal(1))) <ide> * // SELECT * FROM foo WHERE k=1 <ide> * }</pre> <ide> *
Java
apache-2.0
31ca34b9547f83b236320f83599c5c2ed6bb5125
0
i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie,i2p/i2p.itoopie
package net.i2p.router.peermanager; import net.i2p.data.DataHelper; import net.i2p.router.RouterContext; import net.i2p.stat.Rate; import net.i2p.stat.RateStat; import net.i2p.util.Log; /** * Quantify how fast the peer is - how fast they respond to our requests, how fast * they pass messages on, etc. This should be affected both by their bandwidth/latency, * as well as their load. The essence of the current algorithm is to determine * approximately how many 2KB messages the peer can pass round trip within a single * minute - not based just on itself though, but including the delays of other peers * in the tunnels. As such, more events make it more accurate. * */ public class SpeedCalculator extends Calculator { private Log _log; private RouterContext _context; /** * minimum number of events to use a particular period's data. If this many * events haven't occurred in the period yet, the next largest period is tried. */ public static final String PROP_EVENT_THRESHOLD = "speedCalculator.eventThreshold"; public static final int DEFAULT_EVENT_THRESHOLD = 50; /** should the calculator use instantaneous rates, or period averages? */ public static final String PROP_USE_INSTANTANEOUS_RATES = "speedCalculator.useInstantaneousRates"; public static final boolean DEFAULT_USE_INSTANTANEOUS_RATES = false; /** should the calculator use tunnel test time only, or include all data? */ public static final String PROP_USE_TUNNEL_TEST_ONLY = "speedCalculator.useTunnelTestOnly"; public static final boolean DEFAULT_USE_TUNNEL_TEST_ONLY = false; public SpeedCalculator(RouterContext context) { _context = context; _log = context.logManager().getLog(SpeedCalculator.class); } public double calc(PeerProfile profile) { long threshold = getEventThreshold(); boolean tunnelTestOnly = getUseTunnelTestOnly(); long period = 10*60*1000; long events = getEventCount(profile, period, tunnelTestOnly); if (events < threshold) { period = 60*60*1000l; events = getEventCount(profile, period, tunnelTestOnly); if (events < threshold) { period = 24*60*60*1000; events = getEventCount(profile, period, tunnelTestOnly); if (events < threshold) { period = -1; events = getEventCount(profile, period, tunnelTestOnly); } } } double measuredRoundTripTime = getMeasuredRoundTripTime(profile, period, tunnelTestOnly); double measuredRTPerMinute = 0; if (measuredRoundTripTime > 0) measuredRTPerMinute = (60000.0d / measuredRoundTripTime); double estimatedRTPerMinute = 0; double estimatedRoundTripTime = 0; if (!tunnelTestOnly) { estimatedRoundTripTime = getEstimatedRoundTripTime(profile, period); if (estimatedRoundTripTime > 0) estimatedRTPerMinute = (60000.0d / estimatedRoundTripTime); } double estimateFactor = getEstimateFactor(threshold, events); double rv = (1-estimateFactor)*measuredRTPerMinute + (estimateFactor)*estimatedRTPerMinute; if (_log.shouldLog(Log.DEBUG)) { _log.debug("\n\nrv: " + rv + " events: " + events + " threshold: " + threshold + " period: " + period + " useTunnelTestOnly? " + tunnelTestOnly + "\n" + "measuredRTT: " + measuredRoundTripTime + " measured events per minute: " + measuredRTPerMinute + "\n" + "estimateRTT: " + estimatedRoundTripTime + " estimated events per minute: " + estimatedRTPerMinute + "\n" + "estimateFactor: " + estimateFactor + "\n" + "for peer: " + profile.getPeer().toBase64()); } rv += profile.getSpeedBonus(); return rv; } /** * How much do we want to prefer the measured values more than the estimated * values, as a fraction. The value 1 means ignore the measured values, while * the value 0 means ignore the estimate, and everything inbetween means, well * everything inbetween. * */ private double getEstimateFactor(long eventThreshold, long numEvents) { if (true) return 0.0d; // never use the estimate if (numEvents > eventThreshold) return 0.0d; else return numEvents / eventThreshold; } /** * How many measured events do we have for the given period? If the period is negative, * return the lifetime events. * */ private long getEventCount(PeerProfile profile, long period, boolean tunnelTestOnly) { if (period < 0) { Rate dbResponseRate = profile.getDbResponseTime().getRate(60*60*1000l); Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(60*60*1000l); Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(60*60*1000l); long dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeEventCount(); long tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeEventCount(); long tunnelTests = tunnelTestRate.getLifetimeEventCount(); return dbResponses + tunnelResponses + tunnelTests; } else { Rate dbResponseRate = profile.getDbResponseTime().getRate(period); Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(period); Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(period); long dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getCurrentEventCount() + dbResponseRate.getLastEventCount(); long tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getCurrentEventCount() + tunnelResponseRate.getLastEventCount(); long tunnelTests = tunnelTestRate.getCurrentEventCount() + tunnelTestRate.getLastEventCount(); if (_log.shouldLog(Log.DEBUG)) _log.debug("TunnelTests for period " + period + ": " + tunnelTests + " last: " + tunnelTestRate.getLastEventCount() + " lifetime: " + tunnelTestRate.getLifetimeEventCount()); return dbResponses + tunnelResponses + tunnelTests; } } /** * Retrieve the average measured round trip time within the period specified (including * db responses, tunnel create responses, and tunnel tests). If the period is negative, * it uses the lifetime stats. In addition, it weights each of those three measurements * equally according to their event count (e.g. 4 dbResponses @ 10 seconds and 1 tunnel test * at 5 seconds will leave the average at 9 seconds) * */ private double getMeasuredRoundTripTime(PeerProfile profile, long period, boolean tunnelTestOnly) { double activityTime = 0; double rtt = 0; double dbResponseTime = 0; double tunnelResponseTime = 0; double tunnelTestTime = 0; long dbResponses = 0; long tunnelResponses = 0; long tunnelTests = 0; long events = 0; if (period < 0) { Rate dbResponseRate = profile.getDbResponseTime().getRate(60*60*1000l); Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(60*60*1000l); Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(60*60*1000l); dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeEventCount(); tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeEventCount(); tunnelTests = tunnelTestRate.getLifetimeEventCount(); dbResponseTime = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeAverageValue(); tunnelResponseTime = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeAverageValue(); tunnelTestTime = tunnelTestRate.getLifetimeAverageValue(); events = dbResponses + tunnelResponses + tunnelTests; if (events <= 0) return 0; activityTime = (dbResponses*dbResponseTime + tunnelResponses*tunnelResponseTime + tunnelTests*tunnelTestTime); rtt = activityTime / events; } else { Rate dbResponseRate = profile.getDbResponseTime().getRate(period); Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(period); Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(period); dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getCurrentEventCount() + dbResponseRate.getLastEventCount(); tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getCurrentEventCount() + tunnelResponseRate.getLastEventCount(); tunnelTests = tunnelTestRate.getCurrentEventCount() + tunnelTestRate.getLastEventCount(); if (!tunnelTestOnly) { dbResponseTime = avg(dbResponseRate); tunnelResponseTime = avg(tunnelResponseRate); } tunnelTestTime = avg(tunnelTestRate); events = dbResponses + tunnelResponses + tunnelTests; if (events <= 0) return 0; activityTime = (dbResponses*dbResponseTime + tunnelResponses*tunnelResponseTime + tunnelTests*tunnelTestTime); rtt = activityTime / events; } if (_log.shouldLog(Log.DEBUG)) _log.debug("\nMeasured response time for " + profile.getPeer().toBase64() + " over " + DataHelper.formatDuration(period) + " with activityTime of " + activityTime + ": " + rtt + "\nover " + events + " events (" + dbResponses + " dbResponses, " + tunnelResponses + " tunnelResponses, " + tunnelTests + " tunnelTests)\ntimes (" + dbResponseTime + "ms, " + tunnelResponseTime + "ms, " + tunnelTestTime + "ms respectively)"); return rtt; } private double avg(Rate rate) { long events = rate.getCurrentEventCount() + rate.getLastEventCount(); long time = rate.getCurrentTotalEventTime() + rate.getLastTotalEventTime(); if ( (events > 0) && (time > 0) ) return time / events; else return 0.0d; } private double getEstimatedRoundTripTime(PeerProfile profile, long period) { double estSendTime = getEstimatedSendTime(profile, period); double estRecvTime = getEstimatedReceiveTime(profile, period); return estSendTime + estRecvTime; } private double getEstimatedSendTime(PeerProfile profile, long period) { double bps = calcRate(profile.getSendSuccessSize(), period); if (bps <= 0) return 0.0d; else return 2048.0d / bps; } private double getEstimatedReceiveTime(PeerProfile profile, long period) { double bps = calcRate(profile.getReceiveSize(), period); if (bps <= 0) return 0.0d; else return 2048.0d / bps; } private double calcRate(RateStat stat, long period) { Rate rate = stat.getRate(period); if (rate == null) return 0.0d; return calcRate(rate, period); } private double calcRate(Rate rate, long period) { long events = rate.getCurrentEventCount(); if (events >= 1) { double ms = rate.getCurrentTotalEventTime(); double bytes = rate.getCurrentTotalValue(); if (_log.shouldLog(Log.DEBUG)) _log.debug("calculating rate: ms=" + ((int)ms) + " bytes=" + ((int)bytes)); if ( (bytes > 0) && (ms > 0) ) { if (getUseInstantaneousRates()) { return (bytes * 1000.0d) / ms; } else { // period average return (bytes * 1000.0d) / period; } } } return 0.0d; } /** * What is the minimum number of measured events we want in a period before * trusting the values? This first checks the router's configuration, then * the context, and then finally falls back on a static default (100). * */ private long getEventThreshold() { if (_context.router() != null) { String threshold = _context.router().getConfigSetting(PROP_EVENT_THRESHOLD); if (threshold != null) { try { return Long.parseLong(threshold); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Event threshold for speed improperly set in the router config [" + threshold + "]", nfe); } } } String threshold = _context.getProperty(PROP_EVENT_THRESHOLD, ""+DEFAULT_EVENT_THRESHOLD); if (threshold != null) { try { return Long.parseLong(threshold); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Event threshold for speed improperly set in the router environment [" + threshold + "]", nfe); } } return DEFAULT_EVENT_THRESHOLD; } /** * Should we use instantaneous rates for the estimated speed, or the period rates? * This first checks the router's configuration, then the context, and then * finally falls back on a static default (true). * * @return true if we should use instantaneous rates, false if we should use period averages */ private boolean getUseInstantaneousRates() { if (_context.router() != null) { String val = _context.router().getConfigSetting(PROP_USE_INSTANTANEOUS_RATES); if (val != null) { try { return Boolean.getBoolean(val); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Instantaneous rate for speed improperly set in the router config [" + val + "]", nfe); } } } String val = _context.getProperty(PROP_USE_INSTANTANEOUS_RATES, ""+DEFAULT_USE_INSTANTANEOUS_RATES); if (val != null) { try { return Boolean.getBoolean(val); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Instantaneous rate for speed improperly set in the router environment [" + val + "]", nfe); } } return DEFAULT_USE_INSTANTANEOUS_RATES; } /** * Should we only use the measured tunnel testing time, or should we include * measurements on the db responses and tunnel create responses. This first * checks the router's configuration, then the context, and then finally falls * back on a static default (true). * * @return true if we should use tunnel test time only, false if we should use all available */ private boolean getUseTunnelTestOnly() { if (_context.router() != null) { String val = _context.router().getConfigSetting(PROP_USE_TUNNEL_TEST_ONLY); if (val != null) { try { boolean rv = Boolean.getBoolean(val); if (_log.shouldLog(Log.DEBUG)) _log.debug("router config said " + PROP_USE_TUNNEL_TEST_ONLY + '=' + val); return rv; } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Tunnel test only for speed improperly set in the router config [" + val + "]", nfe); } } } String val = _context.getProperty(PROP_USE_TUNNEL_TEST_ONLY, ""+DEFAULT_USE_TUNNEL_TEST_ONLY); if (val != null) { try { boolean rv = Boolean.getBoolean(val); if (_log.shouldLog(Log.DEBUG)) _log.debug("router context said " + PROP_USE_TUNNEL_TEST_ONLY + '=' + val); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Tunnel test only for speed improperly set in the router environment [" + val + "]", nfe); } } if (_log.shouldLog(Log.DEBUG)) _log.debug("no config for " + PROP_USE_TUNNEL_TEST_ONLY + ", using " + DEFAULT_USE_TUNNEL_TEST_ONLY); return DEFAULT_USE_TUNNEL_TEST_ONLY; } }
router/java/src/net/i2p/router/peermanager/SpeedCalculator.java
package net.i2p.router.peermanager; import net.i2p.router.RouterContext; import net.i2p.stat.Rate; import net.i2p.stat.RateStat; import net.i2p.util.Log; /** * Quantify how fast the peer is - how fast they respond to our requests, how fast * they pass messages on, etc. This should be affected both by their bandwidth/latency, * as well as their load. The essence of the current algorithm is to determine * approximately how many 2KB messages the peer can pass round trip within a single * minute - not based just on itself though, but including the delays of other peers * in the tunnels. As such, more events make it more accurate. * */ public class SpeedCalculator extends Calculator { private Log _log; private RouterContext _context; /** * minimum number of events to use a particular period's data. If this many * events haven't occurred in the period yet, the next largest period is tried. */ public static final String PROP_EVENT_THRESHOLD = "speedCalculator.eventThreshold"; public static final int DEFAULT_EVENT_THRESHOLD = 50; /** should the calculator use instantaneous rates, or period averages? */ public static final String PROP_USE_INSTANTANEOUS_RATES = "speedCalculator.useInstantaneousRates"; public static final boolean DEFAULT_USE_INSTANTANEOUS_RATES = false; /** should the calculator use tunnel test time only, or include all data? */ public static final String PROP_USE_TUNNEL_TEST_ONLY = "speedCalculator.useTunnelTestOnly"; public static final boolean DEFAULT_USE_TUNNEL_TEST_ONLY = false; public SpeedCalculator(RouterContext context) { _context = context; _log = context.logManager().getLog(SpeedCalculator.class); } public double calc(PeerProfile profile) { long threshold = getEventThreshold(); boolean tunnelTestOnly = getUseTunnelTestOnly(); long period = 10*60*1000; long events = getEventCount(profile, period, tunnelTestOnly); if (events < threshold) { period = 60*60*1000l; events = getEventCount(profile, period, tunnelTestOnly); if (events < threshold) { period = 24*60*60*1000; events = getEventCount(profile, period, tunnelTestOnly); if (events < threshold) { period = -1; events = getEventCount(profile, period, tunnelTestOnly); } } } double measuredRoundTripTime = getMeasuredRoundTripTime(profile, period, tunnelTestOnly); double measuredRTPerMinute = 0; if (measuredRoundTripTime > 0) measuredRTPerMinute = (60000.0d / measuredRoundTripTime); double estimatedRTPerMinute = 0; double estimatedRoundTripTime = 0; if (!tunnelTestOnly) { estimatedRoundTripTime = getEstimatedRoundTripTime(profile, period); if (estimatedRoundTripTime > 0) estimatedRTPerMinute = (60000.0d / estimatedRoundTripTime); } double estimateFactor = getEstimateFactor(threshold, events); double rv = (1-estimateFactor)*measuredRTPerMinute + (estimateFactor)*estimatedRTPerMinute; if (_log.shouldLog(Log.DEBUG)) { _log.debug("\n\nrv: " + rv + " events: " + events + " threshold: " + threshold + " period: " + period + " useTunnelTestOnly? " + tunnelTestOnly + "\n" + "measuredRTT: " + measuredRoundTripTime + " measured events per minute: " + measuredRTPerMinute + "\n" + "estimateRTT: " + estimatedRoundTripTime + " estimated events per minute: " + estimatedRTPerMinute + "\n" + "estimateFactor: " + estimateFactor + "\n" + "for peer: " + profile.getPeer().toBase64()); } rv += profile.getSpeedBonus(); return rv; } /** * How much do we want to prefer the measured values more than the estimated * values, as a fraction. The value 1 means ignore the measured values, while * the value 0 means ignore the estimate, and everything inbetween means, well * everything inbetween. * */ private double getEstimateFactor(long eventThreshold, long numEvents) { if (true) return 0.0d; // never use the estimate if (numEvents > eventThreshold) return 0.0d; else return numEvents / eventThreshold; } /** * How many measured events do we have for the given period? If the period is negative, * return the lifetime events. * */ private long getEventCount(PeerProfile profile, long period, boolean tunnelTestOnly) { if (period < 0) { Rate dbResponseRate = profile.getDbResponseTime().getRate(60*60*1000l); Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(60*60*1000l); Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(60*60*1000l); long dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeEventCount(); long tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeEventCount(); long tunnelTests = tunnelTestRate.getLifetimeEventCount(); return dbResponses + tunnelResponses + tunnelTests; } else { Rate dbResponseRate = profile.getDbResponseTime().getRate(period); Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(period); Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(period); long dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getCurrentEventCount() + dbResponseRate.getLastEventCount(); long tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getCurrentEventCount() + tunnelResponseRate.getLastEventCount(); long tunnelTests = tunnelTestRate.getCurrentEventCount() + tunnelTestRate.getLastEventCount(); if (_log.shouldLog(Log.DEBUG)) _log.debug("TunnelTests for period " + period + ": " + tunnelTests + " last: " + tunnelTestRate.getLastEventCount() + " lifetime: " + tunnelTestRate.getLifetimeEventCount()); return dbResponses + tunnelResponses + tunnelTests; } } /** * Retrieve the average measured round trip time within the period specified (including * db responses, tunnel create responses, and tunnel tests). If the period is negative, * it uses the lifetime stats. In addition, it weights each of those three measurements * equally according to their event count (e.g. 4 dbResponses @ 10 seconds and 1 tunnel test * at 5 seconds will leave the average at 9 seconds) * */ private double getMeasuredRoundTripTime(PeerProfile profile, long period, boolean tunnelTestOnly) { if (period < 0) { Rate dbResponseRate = profile.getDbResponseTime().getRate(60*60*1000l); Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(60*60*1000l); Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(60*60*1000l); long dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeEventCount(); long tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeEventCount(); long tunnelTests = tunnelTestRate.getLifetimeEventCount(); double dbResponseTime = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeAverageValue(); double tunnelResponseTime = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeAverageValue(); double tunnelTestTime = tunnelTestRate.getLifetimeAverageValue(); long events = dbResponses + tunnelResponses + tunnelTests; if (events <= 0) return 0; return (dbResponses*dbResponseTime + tunnelResponses*tunnelResponseTime + tunnelTests*tunnelTestTime) / events; } else { Rate dbResponseRate = profile.getDbResponseTime().getRate(period); Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(period); Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(period); long dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getCurrentEventCount() + dbResponseRate.getLastEventCount(); long tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getCurrentEventCount() + tunnelResponseRate.getLastEventCount(); long tunnelTests = tunnelTestRate.getCurrentEventCount() + tunnelTestRate.getLastEventCount(); double dbResponseTime = tunnelTestOnly ? 0 : dbResponseRate.getAverageValue(); double tunnelResponseTime = tunnelTestOnly ? 0 : tunnelResponseRate.getAverageValue(); double tunnelTestTime = tunnelTestRate.getAverageValue(); long events = dbResponses + tunnelResponses + tunnelTests; if (events <= 0) return 0; return (dbResponses*dbResponseTime + tunnelResponses*tunnelResponseTime + tunnelTests*tunnelTestTime) / events; } } private double getEstimatedRoundTripTime(PeerProfile profile, long period) { double estSendTime = getEstimatedSendTime(profile, period); double estRecvTime = getEstimatedReceiveTime(profile, period); return estSendTime + estRecvTime; } private double getEstimatedSendTime(PeerProfile profile, long period) { double bps = calcRate(profile.getSendSuccessSize(), period); if (bps <= 0) return 0.0d; else return 2048.0d / bps; } private double getEstimatedReceiveTime(PeerProfile profile, long period) { double bps = calcRate(profile.getReceiveSize(), period); if (bps <= 0) return 0.0d; else return 2048.0d / bps; } private double calcRate(RateStat stat, long period) { Rate rate = stat.getRate(period); if (rate == null) return 0.0d; return calcRate(rate, period); } private double calcRate(Rate rate, long period) { long events = rate.getCurrentEventCount(); if (events >= 1) { double ms = rate.getCurrentTotalEventTime(); double bytes = rate.getCurrentTotalValue(); if (_log.shouldLog(Log.DEBUG)) _log.debug("calculating rate: ms=" + ((int)ms) + " bytes=" + ((int)bytes)); if ( (bytes > 0) && (ms > 0) ) { if (getUseInstantaneousRates()) { return (bytes * 1000.0d) / ms; } else { // period average return (bytes * 1000.0d) / period; } } } return 0.0d; } /** * What is the minimum number of measured events we want in a period before * trusting the values? This first checks the router's configuration, then * the context, and then finally falls back on a static default (100). * */ private long getEventThreshold() { if (_context.router() != null) { String threshold = _context.router().getConfigSetting(PROP_EVENT_THRESHOLD); if (threshold != null) { try { return Long.parseLong(threshold); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Event threshold for speed improperly set in the router config [" + threshold + "]", nfe); } } } String threshold = _context.getProperty(PROP_EVENT_THRESHOLD, ""+DEFAULT_EVENT_THRESHOLD); if (threshold != null) { try { return Long.parseLong(threshold); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Event threshold for speed improperly set in the router environment [" + threshold + "]", nfe); } } return DEFAULT_EVENT_THRESHOLD; } /** * Should we use instantaneous rates for the estimated speed, or the period rates? * This first checks the router's configuration, then the context, and then * finally falls back on a static default (true). * * @return true if we should use instantaneous rates, false if we should use period averages */ private boolean getUseInstantaneousRates() { if (_context.router() != null) { String val = _context.router().getConfigSetting(PROP_USE_INSTANTANEOUS_RATES); if (val != null) { try { return Boolean.getBoolean(val); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Instantaneous rate for speed improperly set in the router config [" + val + "]", nfe); } } } String val = _context.getProperty(PROP_USE_INSTANTANEOUS_RATES, ""+DEFAULT_USE_INSTANTANEOUS_RATES); if (val != null) { try { return Boolean.getBoolean(val); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Instantaneous rate for speed improperly set in the router environment [" + val + "]", nfe); } } return DEFAULT_USE_INSTANTANEOUS_RATES; } /** * Should we only use the measured tunnel testing time, or should we include * measurements on the db responses and tunnel create responses. This first * checks the router's configuration, then the context, and then finally falls * back on a static default (true). * * @return true if we should use tunnel test time only, false if we should use all available */ private boolean getUseTunnelTestOnly() { if (_context.router() != null) { String val = _context.router().getConfigSetting(PROP_USE_TUNNEL_TEST_ONLY); if (val != null) { try { boolean rv = Boolean.getBoolean(val); if (_log.shouldLog(Log.DEBUG)) _log.debug("router config said " + PROP_USE_TUNNEL_TEST_ONLY + '=' + val); return rv; } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Tunnel test only for speed improperly set in the router config [" + val + "]", nfe); } } } String val = _context.getProperty(PROP_USE_TUNNEL_TEST_ONLY, ""+DEFAULT_USE_TUNNEL_TEST_ONLY); if (val != null) { try { boolean rv = Boolean.getBoolean(val); if (_log.shouldLog(Log.DEBUG)) _log.debug("router context said " + PROP_USE_TUNNEL_TEST_ONLY + '=' + val); } catch (NumberFormatException nfe) { if (_log.shouldLog(Log.WARN)) _log.warn("Tunnel test only for speed improperly set in the router environment [" + val + "]", nfe); } } if (_log.shouldLog(Log.DEBUG)) _log.debug("no config for " + PROP_USE_TUNNEL_TEST_ONLY + ", using " + DEFAULT_USE_TUNNEL_TEST_ONLY); return DEFAULT_USE_TUNNEL_TEST_ONLY; } }
rate.getAverageValue returns the average of the last fully completed period, but we want to include the current partial period as well
router/java/src/net/i2p/router/peermanager/SpeedCalculator.java
rate.getAverageValue returns the average of the last fully completed period, but we want to include the current partial period as well
<ide><path>outer/java/src/net/i2p/router/peermanager/SpeedCalculator.java <ide> package net.i2p.router.peermanager; <ide> <add>import net.i2p.data.DataHelper; <ide> import net.i2p.router.RouterContext; <ide> import net.i2p.stat.Rate; <ide> import net.i2p.stat.RateStat; <ide> * <ide> */ <ide> private double getMeasuredRoundTripTime(PeerProfile profile, long period, boolean tunnelTestOnly) { <del> if (period < 0) { <add> double activityTime = 0; <add> double rtt = 0; <add> double dbResponseTime = 0; <add> double tunnelResponseTime = 0; <add> double tunnelTestTime = 0; <add> <add> long dbResponses = 0; <add> long tunnelResponses = 0; <add> long tunnelTests = 0; <add> <add> long events = 0; <add> <add> if (period < 0) { <ide> Rate dbResponseRate = profile.getDbResponseTime().getRate(60*60*1000l); <ide> Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(60*60*1000l); <ide> Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(60*60*1000l); <ide> <del> long dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeEventCount(); <del> long tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeEventCount(); <del> long tunnelTests = tunnelTestRate.getLifetimeEventCount(); <del> <del> double dbResponseTime = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeAverageValue(); <del> double tunnelResponseTime = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeAverageValue(); <del> double tunnelTestTime = tunnelTestRate.getLifetimeAverageValue(); <del> <del> long events = dbResponses + tunnelResponses + tunnelTests; <add> dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeEventCount(); <add> tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeEventCount(); <add> tunnelTests = tunnelTestRate.getLifetimeEventCount(); <add> <add> dbResponseTime = tunnelTestOnly ? 0 : dbResponseRate.getLifetimeAverageValue(); <add> tunnelResponseTime = tunnelTestOnly ? 0 : tunnelResponseRate.getLifetimeAverageValue(); <add> tunnelTestTime = tunnelTestRate.getLifetimeAverageValue(); <add> <add> events = dbResponses + tunnelResponses + tunnelTests; <ide> if (events <= 0) return 0; <del> return (dbResponses*dbResponseTime + tunnelResponses*tunnelResponseTime + tunnelTests*tunnelTestTime) <del> / events; <add> activityTime = (dbResponses*dbResponseTime + tunnelResponses*tunnelResponseTime + tunnelTests*tunnelTestTime); <add> rtt = activityTime / events; <ide> } else { <ide> Rate dbResponseRate = profile.getDbResponseTime().getRate(period); <ide> Rate tunnelResponseRate = profile.getTunnelCreateResponseTime().getRate(period); <ide> Rate tunnelTestRate = profile.getTunnelTestResponseTime().getRate(period); <ide> <del> long dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getCurrentEventCount() + dbResponseRate.getLastEventCount(); <del> long tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getCurrentEventCount() + tunnelResponseRate.getLastEventCount(); <del> long tunnelTests = tunnelTestRate.getCurrentEventCount() + tunnelTestRate.getLastEventCount(); <del> <del> double dbResponseTime = tunnelTestOnly ? 0 : dbResponseRate.getAverageValue(); <del> double tunnelResponseTime = tunnelTestOnly ? 0 : tunnelResponseRate.getAverageValue(); <del> double tunnelTestTime = tunnelTestRate.getAverageValue(); <del> <del> long events = dbResponses + tunnelResponses + tunnelTests; <add> dbResponses = tunnelTestOnly ? 0 : dbResponseRate.getCurrentEventCount() + dbResponseRate.getLastEventCount(); <add> tunnelResponses = tunnelTestOnly ? 0 : tunnelResponseRate.getCurrentEventCount() + tunnelResponseRate.getLastEventCount(); <add> tunnelTests = tunnelTestRate.getCurrentEventCount() + tunnelTestRate.getLastEventCount(); <add> <add> if (!tunnelTestOnly) { <add> dbResponseTime = avg(dbResponseRate); <add> tunnelResponseTime = avg(tunnelResponseRate); <add> } <add> tunnelTestTime = avg(tunnelTestRate); <add> <add> events = dbResponses + tunnelResponses + tunnelTests; <ide> if (events <= 0) return 0; <del> return (dbResponses*dbResponseTime + tunnelResponses*tunnelResponseTime + tunnelTests*tunnelTestTime) <del> / events; <del> } <add> activityTime = (dbResponses*dbResponseTime + tunnelResponses*tunnelResponseTime + tunnelTests*tunnelTestTime); <add> rtt = activityTime / events; <add> } <add> if (_log.shouldLog(Log.DEBUG)) <add> _log.debug("\nMeasured response time for " + profile.getPeer().toBase64() + " over " <add> + DataHelper.formatDuration(period) + " with activityTime of " + activityTime <add> + ": " + rtt + "\nover " + events + " events (" <add> + dbResponses + " dbResponses, " + tunnelResponses + " tunnelResponses, " <add> + tunnelTests + " tunnelTests)\ntimes (" <add> + dbResponseTime + "ms, " + tunnelResponseTime + "ms, " <add> + tunnelTestTime + "ms respectively)"); <add> return rtt; <add> } <add> <add> private double avg(Rate rate) { <add> long events = rate.getCurrentEventCount() + rate.getLastEventCount(); <add> long time = rate.getCurrentTotalEventTime() + rate.getLastTotalEventTime(); <add> if ( (events > 0) && (time > 0) ) <add> return time / events; <add> else <add> return 0.0d; <ide> } <ide> <ide> private double getEstimatedRoundTripTime(PeerProfile profile, long period) {
Java
apache-2.0
6ce3a3a9d30af710d10964ab05932d94f501d6da
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing; import com.intellij.diagnostic.PerformanceWatcher; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.ControlFlowException; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.impl.CoreProgressManager; import com.intellij.openapi.progress.impl.ProgressSuspender; import com.intellij.openapi.project.*; import com.intellij.openapi.roots.ContentIterator; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.util.indexing.diagnostic.dto.JsonScanningStatistics; import com.intellij.util.indexing.roots.IndexableFileScanner; import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdater; import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdaterImpl; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.util.ExceptionUtil; import com.intellij.util.SystemProperties; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.contentQueue.IndexUpdateRunner; import com.intellij.util.indexing.diagnostic.IndexDiagnosticDumper; import com.intellij.util.indexing.diagnostic.IndexingJobStatistics; import com.intellij.util.indexing.diagnostic.ProjectIndexingHistory; import com.intellij.util.indexing.diagnostic.ScanningStatistics; import com.intellij.util.indexing.roots.IndexableFilesDeduplicateFilter; import com.intellij.util.indexing.roots.IndexableFilesIterator; import com.intellij.util.indexing.roots.SdkIndexableFilesIteratorImpl; import com.intellij.util.indexing.roots.kind.SdkOrigin; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.progress.ConcurrentTasksProgressManager; import com.intellij.util.progress.SubTaskProgressIndicator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.VisibleForTesting; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; public final class UnindexedFilesUpdater extends DumbModeTask { private static final Logger LOG = Logger.getInstance(UnindexedFilesUpdater.class); private static final int DEFAULT_MAX_INDEXER_THREADS = 4; public enum TestMode { PUSHING, PUSHING_AND_SCANNING } @SuppressWarnings("StaticNonFinalField") @VisibleForTesting public static volatile TestMode ourTestMode; public static final ExecutorService GLOBAL_INDEXING_EXECUTOR = AppExecutorUtil.createBoundedApplicationPoolExecutor( "Indexing", getMaxNumberOfIndexingThreads() ); private static final @NotNull Key<Boolean> CONTENT_SCANNED = Key.create("CONTENT_SCANNED"); private static final @NotNull Key<UnindexedFilesUpdater> RUNNING_TASK = Key.create("RUNNING_INDEX_UPDATER_TASK"); private static final Object ourLastRunningTaskLock = new Object(); private final FileBasedIndexImpl myIndex = (FileBasedIndexImpl)FileBasedIndex.getInstance(); private final Project myProject; private final boolean myStartSuspended; private final boolean myRunExtensionsForFilesMarkedAsIndexed; private final PushedFilePropertiesUpdater myPusher; public UnindexedFilesUpdater(@NotNull Project project, boolean startSuspended, boolean runExtensionsForFilesMarkedAsIndexed) { super(project); myProject = project; myStartSuspended = startSuspended; myRunExtensionsForFilesMarkedAsIndexed = runExtensionsForFilesMarkedAsIndexed; myPusher = PushedFilePropertiesUpdater.getInstance(myProject); myProject.putUserData(CONTENT_SCANNED, null); synchronized (ourLastRunningTaskLock) { UnindexedFilesUpdater runningTask = myProject.getUserData(RUNNING_TASK); if (runningTask != null) { DumbService.getInstance(project).cancelTask(runningTask); } myProject.putUserData(RUNNING_TASK, this); } } @Override public void dispose() { synchronized (ourLastRunningTaskLock) { UnindexedFilesUpdater lastRunningTask = myProject.getUserData(RUNNING_TASK); if (lastRunningTask == this) { myProject.putUserData(RUNNING_TASK, null); } } } public UnindexedFilesUpdater(@NotNull Project project) { // If we haven't succeeded to fully scan the project content yet, then we must keep trying to run // file based index extensions for all project files until at least one of UnindexedFilesUpdater-s finishes without cancellation. // This is important, for example, for shared indexes: all files must be associated with their locally available shared index chunks. this(project, false, !isProjectContentFullyScanned(project)); } private void updateUnindexedFiles(@NotNull ProjectIndexingHistory projectIndexingHistory, @NotNull ProgressIndicator indicator) { if (!IndexInfrastructure.hasIndices()) return; LOG.info("Started"); ProgressSuspender suspender = ProgressSuspender.getSuspender(indicator); if (suspender != null) { listenToProgressSuspenderForSuspendedTimeDiagnostic(suspender, projectIndexingHistory); } if (myStartSuspended) { if (suspender == null) { throw new IllegalStateException("Indexing progress indicator must be suspendable!"); } if (!suspender.isSuspended()) { suspender.suspendProcess(IndexingBundle.message("progress.indexing.started.as.suspended")); } } indicator.setIndeterminate(true); indicator.setText(IndexingBundle.message("progress.indexing.scanning")); boolean trackResponsiveness = !ApplicationManager.getApplication().isUnitTestMode(); PerformanceWatcher.Snapshot snapshot = PerformanceWatcher.takeSnapshot(); Instant pushPropertiesStart = Instant.now(); try { myPusher.pushAllPropertiesNow(); } finally { projectIndexingHistory.getTimes().setPushPropertiesDuration(Duration.between(pushPropertiesStart, Instant.now())); } if (trackResponsiveness) { LOG.info(snapshot.getLogResponsivenessSinceCreationMessage("Pushing properties")); } myIndex.clearIndicesIfNecessary(); snapshot = PerformanceWatcher.takeSnapshot(); Instant scanFilesStart = Instant.now(); List<IndexableFilesIterator> orderedProviders; Map<IndexableFilesIterator, List<VirtualFile>> providerToFiles; try { orderedProviders = getOrderedProviders(); providerToFiles = collectIndexableFilesConcurrently(myProject, indicator, orderedProviders, projectIndexingHistory); myProject.putUserData(CONTENT_SCANNED, true); } finally { projectIndexingHistory.getTimes().setScanFilesDuration(Duration.between(scanFilesStart, Instant.now())); } logScanningCompletedStage(projectIndexingHistory); if (trackResponsiveness) { LOG.info(snapshot.getLogResponsivenessSinceCreationMessage("Scanning completed")); } if (!ApplicationManager.getApplication().isUnitTestMode()) { // full VFS refresh makes sense only after it's loaded, i.e. after scanning files to index is finished scheduleInitialVfsRefresh(); } int totalFiles = providerToFiles.values().stream().mapToInt(it -> it.size()).sum(); if (totalFiles == 0 || SystemProperties.getBooleanProperty("idea.indexes.pretendNoFiles", false)) { return; } snapshot = PerformanceWatcher.takeSnapshot(); ProgressIndicator poweredIndicator = PoweredProgressIndicator.wrap(indicator, getPowerForSmoothProgressIndicator()); poweredIndicator.setIndeterminate(false); poweredIndicator.setFraction(0); poweredIndicator.setText(IndexingBundle.message("progress.indexing.updating")); ConcurrentTasksProgressManager concurrentTasksProgressManager = new ConcurrentTasksProgressManager(poweredIndicator, totalFiles); int numberOfIndexingThreads = getNumberOfIndexingThreads(); LOG.info("Use " + numberOfIndexingThreads + " indexing " + StringUtil.pluralize("thread", numberOfIndexingThreads) + ", " + getNumberOfScanningThreads() + " scanning " + StringUtil.pluralize("thread", numberOfIndexingThreads)); IndexUpdateRunner indexUpdateRunner = new IndexUpdateRunner(myIndex, GLOBAL_INDEXING_EXECUTOR, numberOfIndexingThreads); Instant startIndexing = Instant.now(); try { for (IndexableFilesIterator provider : orderedProviders) { List<VirtualFile> providerFiles = providerToFiles.get(provider); if (providerFiles == null || providerFiles.isEmpty()) { continue; } concurrentTasksProgressManager.setText(provider.getIndexingProgressText()); SubTaskProgressIndicator subTaskIndicator = concurrentTasksProgressManager.createSubTaskIndicator(providerFiles.size()); try { IndexingJobStatistics statistics; IndexUpdateRunner.IndexingInterruptedException exception = null; try { statistics = indexUpdateRunner.indexFiles(myProject, provider.getDebugName(), providerFiles, subTaskIndicator); } catch (IndexUpdateRunner.IndexingInterruptedException e) { exception = e; statistics = e.myStatistics; } try { projectIndexingHistory.addProviderStatistics(statistics); } catch (Exception e) { LOG.error("Failed to add indexing statistics for " + provider.getDebugName(), e); } if (exception != null) { ExceptionUtil.rethrow(exception.getCause()); } } finally { subTaskIndicator.finished(); } } } finally { projectIndexingHistory.getTimes().setIndexingDuration(Duration.between(startIndexing, Instant.now())); } if (trackResponsiveness) { LOG.info(snapshot.getLogResponsivenessSinceCreationMessage("Unindexed files update")); } myIndex.dumpIndexStatistics(); } private static void logScanningCompletedStage(ProjectIndexingHistory projectIndexingHistory) { List<JsonScanningStatistics> statistics = projectIndexingHistory.getScanningStatistics(); int numberOfScannedFiles = statistics.stream().mapToInt(s -> s.getNumberOfScannedFiles()).sum(); int numberOfFilesForIndexing = statistics.stream().mapToInt(s -> s.getNumberOfFilesForIndexing()).sum(); LOG.info("Scanning completed. Number of scanned files: " + numberOfScannedFiles + "; " + "Number of files for indexing: " + numberOfFilesForIndexing); } private void listenToProgressSuspenderForSuspendedTimeDiagnostic(@NotNull ProgressSuspender suspender, @NotNull ProjectIndexingHistory projectIndexingHistory) { MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(this); connection.subscribe(ProgressSuspender.TOPIC, new ProgressSuspender.SuspenderListener() { private volatile Instant suspensionStart = null; @Override public void suspendedStatusChanged(@NotNull ProgressSuspender changedSuspender) { if (suspender == changedSuspender) { if (suspender.isSuspended()) { suspensionStart = Instant.now(); } else { Instant now = Instant.now(); Instant start = suspensionStart; suspensionStart = null; if (start != null && start.compareTo(now) < 0) { Duration thisDuration = Duration.between(start, now); Duration currentTotalDuration = projectIndexingHistory.getTimes().getSuspendedDuration(); Duration newTotalSuspendedDuration = currentTotalDuration.plus(thisDuration); projectIndexingHistory.getTimes().setSuspendedDuration(newTotalSuspendedDuration); } } } } }); } static boolean isProjectContentFullyScanned(@NotNull Project project) { return Boolean.TRUE.equals(project.getUserData(CONTENT_SCANNED)); } /** * Returns providers of files. Since LAB-22 (Smart Dumb Mode) is not implemented yet, the order of the providers is not strictly specified. * For shared indexes it is a good idea to index JDKs in the last turn (because they likely have shared index available) * so this method moves all SDK providers to the end. */ @NotNull private List<IndexableFilesIterator> getOrderedProviders() { List<IndexableFilesIterator> originalOrderedProviders = myIndex.getOrderedIndexableFilesProviders(myProject); List<IndexableFilesIterator> orderedProviders = new ArrayList<>(); originalOrderedProviders.stream() .filter(p -> !(p.getOrigin() instanceof SdkOrigin)) .collect(Collectors.toCollection(() -> orderedProviders)); originalOrderedProviders.stream() .filter(p -> p.getOrigin() instanceof SdkOrigin) .collect(Collectors.toCollection(() -> orderedProviders)); return orderedProviders; } @NotNull private Map<IndexableFilesIterator, List<VirtualFile>> collectIndexableFilesConcurrently( @NotNull Project project, @NotNull ProgressIndicator indicator, @NotNull List<IndexableFilesIterator> providers, @NotNull ProjectIndexingHistory projectIndexingHistory ) { if (providers.isEmpty()) { return Collections.emptyMap(); } List<IndexableFileScanner.ScanSession> sessions = ContainerUtil.map(IndexableFileScanner.EP_NAME.getExtensionList(), scanner -> scanner.startSession(project)); UnindexedFilesFinder unindexedFileFinder = new UnindexedFilesFinder(project, myIndex, myRunExtensionsForFilesMarkedAsIndexed); Map<IndexableFilesIterator, List<VirtualFile>> providerToFiles = new IdentityHashMap<>(); IndexableFilesDeduplicateFilter indexableFilesDeduplicateFilter = IndexableFilesDeduplicateFilter.create(); indicator.setText(IndexingBundle.message("progress.indexing.scanning")); indicator.setIndeterminate(false); indicator.setFraction(0); ConcurrentTasksProgressManager concurrentTasksProgressManager = new ConcurrentTasksProgressManager(indicator, providers.size()); List<Runnable> tasks = ContainerUtil.map(providers, provider -> { SubTaskProgressIndicator subTaskIndicator = concurrentTasksProgressManager.createSubTaskIndicator(1); List<VirtualFile> files = new ArrayList<>(); ScanningStatistics scanningStatistics = new ScanningStatistics(provider.getDebugName()); providerToFiles.put(provider, files); List<IndexableFileScanner.@NotNull IndexableFileVisitor> fileScannerVisitors = ContainerUtil.mapNotNull(sessions, s -> s.createVisitor(provider.getOrigin())); IndexableFilesDeduplicateFilter thisProviderDeduplicateFilter = IndexableFilesDeduplicateFilter.createDelegatingTo(indexableFilesDeduplicateFilter); ContentIterator collectingIterator = fileOrDir -> { if (subTaskIndicator.isCanceled()) { return false; } PushedFilePropertiesUpdaterImpl.applyScannersToFile(fileOrDir, fileScannerVisitors); UnindexedFileStatus status; long statusTime = System.nanoTime(); try { status = ourTestMode == TestMode.PUSHING ? null : unindexedFileFinder.getFileStatus(fileOrDir); } finally { statusTime = System.nanoTime() - statusTime; } if (status != null) { if (status.getShouldIndex() && ourTestMode == null) { files.add(fileOrDir); } scanningStatistics.addStatus(fileOrDir, status, statusTime, project); } return true; }; return () -> { subTaskIndicator.setText(provider.getRootsScanningProgressText()); try { provider.iterateFiles(project, collectingIterator, thisProviderDeduplicateFilter); } finally { scanningStatistics.setNumberOfSkippedFiles(thisProviderDeduplicateFilter.getNumberOfSkippedFiles()); synchronized (projectIndexingHistory) { projectIndexingHistory.addScanningStatistics(scanningStatistics); } subTaskIndicator.finished(); } }; }); PushedFilePropertiesUpdaterImpl.invokeConcurrentlyIfPossible(tasks); return providerToFiles; } private void scheduleInitialVfsRefresh() { ProjectRootManagerEx.getInstanceEx(myProject).markRootsForRefresh(); Application app = ApplicationManager.getApplication(); if (!app.isCommandLine() || CoreProgressManager.shouldRunHeadlessTasksSynchronously()) { long sessionId = VirtualFileManager.getInstance().asyncRefresh(null); MessageBusConnection connection = app.getMessageBus().connect(); connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosed(@NotNull Project project) { if (project == myProject) { RefreshQueue.getInstance().cancelSession(sessionId); connection.disconnect(); } } }); } else { ApplicationManager.getApplication().invokeAndWait(() -> VirtualFileManager.getInstance().syncRefresh()); } } private static double getPowerForSmoothProgressIndicator() { String rawValue = Registry.stringValue("indexing.progress.indicator.power"); if ("-".equals(rawValue)) { return 1.0; } try { return Double.parseDouble(rawValue); } catch (NumberFormatException e) { return 1.0; } } @Override public void performInDumbMode(@NotNull ProgressIndicator indicator) { ProjectIndexingHistory projectIndexingHistory = new ProjectIndexingHistory(myProject); myIndex.filesUpdateStarted(myProject); try { updateUnindexedFiles(projectIndexingHistory, indicator); } catch (Throwable e) { projectIndexingHistory.getTimes().setWasInterrupted(true); if (e instanceof ControlFlowException) { LOG.info("Cancelled"); } throw e; } finally { myIndex.filesUpdateFinished(myProject); projectIndexingHistory.getTimes().setUpdatingEnd(ZonedDateTime.now(ZoneOffset.UTC)); IndexDiagnosticDumper.INSTANCE.dumpProjectIndexingHistoryIfNecessary(projectIndexingHistory); } } /** * Returns the best number of threads to be used for indexing at this moment. * It may change during execution of the IDE depending on other activities' load. */ public static int getNumberOfIndexingThreads() { int threadCount = Registry.intValue("caches.indexerThreadsCount"); if (threadCount <= 0) { int coresToLeaveForOtherActivity = ApplicationManager.getApplication().isCommandLine() ? 0 : 1; threadCount = Math.max(1, Math.min(Runtime.getRuntime().availableProcessors() - coresToLeaveForOtherActivity, DEFAULT_MAX_INDEXER_THREADS)); } return threadCount; } /** * Returns the maximum number of threads to be used for indexing during this execution of the IDE. */ public static int getMaxNumberOfIndexingThreads() { // Change of the registry option requires IDE restart. int threadCount = Registry.intValue("caches.indexerThreadsCount"); return threadCount <= 0 ? DEFAULT_MAX_INDEXER_THREADS : threadCount; } /** * Scanning activity can be scaled well across number of threads, so we're trying to use all available resources to do it faster. */ public static int getNumberOfScanningThreads() { int scanningThreadCount = Registry.intValue("caches.scanningThreadsCount"); if (scanningThreadCount > 0) return scanningThreadCount; int coresToLeaveForOtherActivity = ApplicationManager.getApplication().isCommandLine() ? 0 : 1; return Math.max(Runtime.getRuntime().availableProcessors() - coresToLeaveForOtherActivity, getNumberOfIndexingThreads()); } }
platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesUpdater.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing; import com.intellij.diagnostic.PerformanceWatcher; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.ControlFlowException; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.impl.CoreProgressManager; import com.intellij.openapi.progress.impl.ProgressSuspender; import com.intellij.openapi.project.*; import com.intellij.openapi.roots.ContentIterator; import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.util.indexing.diagnostic.dto.JsonScanningStatistics; import com.intellij.util.indexing.roots.IndexableFileScanner; import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdater; import com.intellij.openapi.roots.impl.PushedFilePropertiesUpdaterImpl; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.util.ExceptionUtil; import com.intellij.util.SystemProperties; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.contentQueue.IndexUpdateRunner; import com.intellij.util.indexing.diagnostic.IndexDiagnosticDumper; import com.intellij.util.indexing.diagnostic.IndexingJobStatistics; import com.intellij.util.indexing.diagnostic.ProjectIndexingHistory; import com.intellij.util.indexing.diagnostic.ScanningStatistics; import com.intellij.util.indexing.roots.IndexableFilesDeduplicateFilter; import com.intellij.util.indexing.roots.IndexableFilesIterator; import com.intellij.util.indexing.roots.SdkIndexableFilesIteratorImpl; import com.intellij.util.indexing.roots.kind.SdkOrigin; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.progress.ConcurrentTasksProgressManager; import com.intellij.util.progress.SubTaskProgressIndicator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.VisibleForTesting; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; public final class UnindexedFilesUpdater extends DumbModeTask { private static final Logger LOG = Logger.getInstance(UnindexedFilesUpdater.class); private static final int DEFAULT_MAX_INDEXER_THREADS = 4; public enum TestMode { PUSHING, PUSHING_AND_SCANNING } @SuppressWarnings("StaticNonFinalField") @VisibleForTesting public static volatile TestMode ourTestMode; public static final ExecutorService GLOBAL_INDEXING_EXECUTOR = AppExecutorUtil.createBoundedApplicationPoolExecutor( "Indexing", getMaxNumberOfIndexingThreads() ); private static final @NotNull Key<Boolean> CONTENT_SCANNED = Key.create("CONTENT_SCANNED"); private static final @NotNull Key<UnindexedFilesUpdater> RUNNING_TASK = Key.create("RUNNING_INDEX_UPDATER_TASK"); private static final Object ourLastRunningTaskLock = new Object(); private final FileBasedIndexImpl myIndex = (FileBasedIndexImpl)FileBasedIndex.getInstance(); private final Project myProject; private final boolean myStartSuspended; private final boolean myRunExtensionsForFilesMarkedAsIndexed; private final PushedFilePropertiesUpdater myPusher; public UnindexedFilesUpdater(@NotNull Project project, boolean startSuspended, boolean runExtensionsForFilesMarkedAsIndexed) { super(project); myProject = project; myStartSuspended = startSuspended; myRunExtensionsForFilesMarkedAsIndexed = runExtensionsForFilesMarkedAsIndexed; myPusher = PushedFilePropertiesUpdater.getInstance(myProject); myProject.putUserData(CONTENT_SCANNED, null); synchronized (ourLastRunningTaskLock) { UnindexedFilesUpdater runningTask = myProject.getUserData(RUNNING_TASK); if (runningTask != null) { DumbService.getInstance(project).cancelTask(runningTask); } myProject.putUserData(RUNNING_TASK, this); } } @Override public void dispose() { synchronized (ourLastRunningTaskLock) { UnindexedFilesUpdater lastRunningTask = myProject.getUserData(RUNNING_TASK); if (lastRunningTask == this) { myProject.putUserData(RUNNING_TASK, null); } } } public UnindexedFilesUpdater(@NotNull Project project) { // If we haven't succeeded to fully scan the project content yet, then we must keep trying to run // file based index extensions for all project files until at least one of UnindexedFilesUpdater-s finishes without cancellation. // This is important, for example, for shared indexes: all files must be associated with their locally available shared index chunks. this(project, false, !isProjectContentFullyScanned(project)); } private void updateUnindexedFiles(@NotNull ProjectIndexingHistory projectIndexingHistory, @NotNull ProgressIndicator indicator) { if (!IndexInfrastructure.hasIndices()) return; LOG.info("Started"); ProgressSuspender suspender = ProgressSuspender.getSuspender(indicator); if (suspender != null) { listenToProgressSuspenderForSuspendedTimeDiagnostic(suspender, projectIndexingHistory); } if (myStartSuspended) { if (suspender == null) { throw new IllegalStateException("Indexing progress indicator must be suspendable!"); } if (!suspender.isSuspended()) { suspender.suspendProcess(IndexingBundle.message("progress.indexing.started.as.suspended")); } } indicator.setIndeterminate(true); indicator.setText(IndexingBundle.message("progress.indexing.scanning")); boolean trackResponsiveness = !ApplicationManager.getApplication().isUnitTestMode(); PerformanceWatcher.Snapshot snapshot = PerformanceWatcher.takeSnapshot(); Instant pushPropertiesStart = Instant.now(); try { myPusher.pushAllPropertiesNow(); } finally { projectIndexingHistory.getTimes().setPushPropertiesDuration(Duration.between(pushPropertiesStart, Instant.now())); } if (trackResponsiveness) { LOG.info(snapshot.getLogResponsivenessSinceCreationMessage("Pushing properties")); } myIndex.clearIndicesIfNecessary(); snapshot = PerformanceWatcher.takeSnapshot(); Instant scanFilesStart = Instant.now(); List<IndexableFilesIterator> orderedProviders; Map<IndexableFilesIterator, List<VirtualFile>> providerToFiles; try { orderedProviders = getOrderedProviders(); providerToFiles = collectIndexableFilesConcurrently(myProject, indicator, orderedProviders, projectIndexingHistory); myProject.putUserData(CONTENT_SCANNED, true); } finally { projectIndexingHistory.getTimes().setScanFilesDuration(Duration.between(scanFilesStart, Instant.now())); } logScanningCompletedStage(projectIndexingHistory); if (trackResponsiveness) { LOG.info(snapshot.getLogResponsivenessSinceCreationMessage("Scanning completed")); } if (!ApplicationManager.getApplication().isUnitTestMode()) { // full VFS refresh makes sense only after it's loaded, i.e. after scanning files to index is finished scheduleInitialVfsRefresh(); } int totalFiles = providerToFiles.values().stream().mapToInt(it -> it.size()).sum(); if (totalFiles == 0 || SystemProperties.getBooleanProperty("idea.indexes.pretendNoFiles", false)) { return; } snapshot = PerformanceWatcher.takeSnapshot(); ProgressIndicator poweredIndicator = PoweredProgressIndicator.wrap(indicator, getPowerForSmoothProgressIndicator()); poweredIndicator.setIndeterminate(false); poweredIndicator.setFraction(0); poweredIndicator.setText(IndexingBundle.message("progress.indexing.updating")); ConcurrentTasksProgressManager concurrentTasksProgressManager = new ConcurrentTasksProgressManager(poweredIndicator, totalFiles); int numberOfIndexingThreads = getNumberOfIndexingThreads(); LOG.info("Use " + numberOfIndexingThreads + " indexing " + StringUtil.pluralize("thread", numberOfIndexingThreads) + ", " + getNumberOfScanningThreads() + " scanning " + StringUtil.pluralize("thread", numberOfIndexingThreads)); IndexUpdateRunner indexUpdateRunner = new IndexUpdateRunner(myIndex, GLOBAL_INDEXING_EXECUTOR, numberOfIndexingThreads); Instant startIndexing = Instant.now(); try { for (IndexableFilesIterator provider : orderedProviders) { List<VirtualFile> providerFiles = providerToFiles.get(provider); if (providerFiles == null || providerFiles.isEmpty()) { continue; } concurrentTasksProgressManager.setText(provider.getIndexingProgressText()); SubTaskProgressIndicator subTaskIndicator = concurrentTasksProgressManager.createSubTaskIndicator(providerFiles.size()); try { IndexingJobStatistics statistics; IndexUpdateRunner.IndexingInterruptedException exception = null; try { statistics = indexUpdateRunner.indexFiles(myProject, provider.getDebugName(), providerFiles, subTaskIndicator); } catch (IndexUpdateRunner.IndexingInterruptedException e) { exception = e; statistics = e.myStatistics; } try { projectIndexingHistory.addProviderStatistics(statistics); } catch (Exception e) { LOG.error("Failed to add indexing statistics for " + provider.getDebugName(), e); } if (exception != null) { ExceptionUtil.rethrow(exception.getCause()); } } finally { subTaskIndicator.finished(); } } } finally { projectIndexingHistory.getTimes().setIndexingDuration(Duration.between(startIndexing, Instant.now())); } if (trackResponsiveness) { LOG.info(snapshot.getLogResponsivenessSinceCreationMessage("Unindexed files update")); } myIndex.dumpIndexStatistics(); } private static void logScanningCompletedStage(ProjectIndexingHistory projectIndexingHistory) { List<JsonScanningStatistics> statistics = projectIndexingHistory.getScanningStatistics(); int numberOfScannedFiles = statistics.stream().mapToInt(s -> s.getNumberOfScannedFiles()).sum(); int numberOfFilesForIndexing = statistics.stream().mapToInt(s -> s.getNumberOfFilesForIndexing()).sum(); LOG.info("Scanning completed. Number of scanned files: " + numberOfScannedFiles + "; " + "Number of files for indexing: " + numberOfFilesForIndexing); } private void listenToProgressSuspenderForSuspendedTimeDiagnostic(@NotNull ProgressSuspender suspender, @NotNull ProjectIndexingHistory projectIndexingHistory) { MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(this); connection.subscribe(ProgressSuspender.TOPIC, new ProgressSuspender.SuspenderListener() { private volatile Instant suspensionStart = null; @Override public void suspendedStatusChanged(@NotNull ProgressSuspender changedSuspender) { if (suspender == changedSuspender) { if (suspender.isSuspended()) { suspensionStart = Instant.now(); } else { Instant now = Instant.now(); Instant start = suspensionStart; suspensionStart = null; if (start != null && start.compareTo(now) < 0) { Duration thisDuration = Duration.between(start, now); Duration currentTotalDuration = projectIndexingHistory.getTimes().getSuspendedDuration(); Duration newTotalSuspendedDuration = currentTotalDuration.plus(thisDuration); projectIndexingHistory.getTimes().setSuspendedDuration(newTotalSuspendedDuration); } } } } }); } static boolean isProjectContentFullyScanned(@NotNull Project project) { return Boolean.TRUE.equals(project.getUserData(CONTENT_SCANNED)); } /** * Returns providers of files. Since LAB-22 (Smart Dumb Mode) is not implemented yet, the order of the providers is not strictly specified. * For shared indexes it is a good idea to index JDKs in the last turn (because they likely have shared index available) * so this method moves all SDK providers to the end. */ @NotNull private List<IndexableFilesIterator> getOrderedProviders() { List<IndexableFilesIterator> originalOrderedProviders = myIndex.getOrderedIndexableFilesProviders(myProject); List<IndexableFilesIterator> orderedProviders = new ArrayList<>(); originalOrderedProviders.stream() .filter(p -> !(p.getOrigin() instanceof SdkOrigin)) .collect(Collectors.toCollection(() -> orderedProviders)); originalOrderedProviders.stream() .filter(p -> p.getOrigin() instanceof SdkOrigin) .collect(Collectors.toCollection(() -> orderedProviders)); return orderedProviders; } @NotNull private Map<IndexableFilesIterator, List<VirtualFile>> collectIndexableFilesConcurrently( @NotNull Project project, @NotNull ProgressIndicator indicator, @NotNull List<IndexableFilesIterator> providers, @NotNull ProjectIndexingHistory projectIndexingHistory ) { if (providers.isEmpty()) { return Collections.emptyMap(); } List<IndexableFileScanner.ScanSession> sessions = ContainerUtil.map(IndexableFileScanner.EP_NAME.getExtensionList(), scanner -> scanner.startSession(project)); UnindexedFilesFinder unindexedFileFinder = new UnindexedFilesFinder(project, myIndex, myRunExtensionsForFilesMarkedAsIndexed); Map<IndexableFilesIterator, List<VirtualFile>> providerToFiles = new IdentityHashMap<>(); IndexableFilesDeduplicateFilter indexableFilesDeduplicateFilter = IndexableFilesDeduplicateFilter.create(); indicator.setText(IndexingBundle.message("progress.indexing.scanning")); indicator.setIndeterminate(false); indicator.setFraction(0); ConcurrentTasksProgressManager concurrentTasksProgressManager = new ConcurrentTasksProgressManager(indicator, providers.size()); List<Runnable> tasks = ContainerUtil.map(providers, provider -> { SubTaskProgressIndicator subTaskIndicator = concurrentTasksProgressManager.createSubTaskIndicator(1); List<VirtualFile> files = new ArrayList<>(); ScanningStatistics scanningStatistics = new ScanningStatistics(provider.getDebugName()); providerToFiles.put(provider, files); List<IndexableFileScanner.@NotNull IndexableFileVisitor> fileScannerVisitors = ContainerUtil.mapNotNull(sessions, s -> s.createVisitor(provider.getOrigin())); IndexableFilesDeduplicateFilter thisProviderDeduplicateFilter = IndexableFilesDeduplicateFilter.createDelegatingTo(indexableFilesDeduplicateFilter); ContentIterator collectingIterator = fileOrDir -> { if (subTaskIndicator.isCanceled()) { return false; } PushedFilePropertiesUpdaterImpl.applyScannersToFile(fileOrDir, fileScannerVisitors); UnindexedFileStatus status; long statusTime = System.nanoTime(); try { status = ourTestMode == TestMode.PUSHING ? null : unindexedFileFinder.getFileStatus(fileOrDir); } finally { statusTime = System.nanoTime() - statusTime; } if (status != null) { if (status.getShouldIndex() && ourTestMode == null) { files.add(fileOrDir); } scanningStatistics.addStatus(fileOrDir, status, statusTime, project); } return true; }; return () -> { subTaskIndicator.setText(provider.getRootsScanningProgressText()); try { provider.iterateFiles(project, collectingIterator, thisProviderDeduplicateFilter); } finally { scanningStatistics.setNumberOfSkippedFiles(thisProviderDeduplicateFilter.getNumberOfSkippedFiles()); synchronized (projectIndexingHistory) { projectIndexingHistory.addScanningStatistics(scanningStatistics); } subTaskIndicator.finished(); } }; }); PushedFilePropertiesUpdaterImpl.invokeConcurrentlyIfPossible(tasks); return providerToFiles; } private void scheduleInitialVfsRefresh() { ProjectRootManagerEx.getInstanceEx(myProject).markRootsForRefresh(); Application app = ApplicationManager.getApplication(); if (!app.isCommandLine() || CoreProgressManager.shouldRunHeadlessTasksSynchronously()) { long sessionId = VirtualFileManager.getInstance().asyncRefresh(null); MessageBusConnection connection = app.getMessageBus().connect(); connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosed(@NotNull Project project) { if (project == myProject) { RefreshQueue.getInstance().cancelSession(sessionId); connection.disconnect(); } } }); } else { ApplicationManager.getApplication().invokeAndWait(() -> VirtualFileManager.getInstance().syncRefresh()); } } private static double getPowerForSmoothProgressIndicator() { String rawValue = Registry.stringValue("indexing.progress.indicator.power"); if ("-".equals(rawValue)) { return 1.0; } try { return Double.parseDouble(rawValue); } catch (NumberFormatException e) { return 1.0; } } @Override public void performInDumbMode(@NotNull ProgressIndicator indicator) { ProjectIndexingHistory projectIndexingHistory = new ProjectIndexingHistory(myProject); myIndex.filesUpdateStarted(myProject); try { updateUnindexedFiles(projectIndexingHistory, indicator); } catch (Throwable e) { projectIndexingHistory.getTimes().setWasInterrupted(true); if (e instanceof ControlFlowException) { LOG.info("Unindexed files update canceled"); } throw e; } finally { myIndex.filesUpdateFinished(myProject); projectIndexingHistory.getTimes().setUpdatingEnd(ZonedDateTime.now(ZoneOffset.UTC)); IndexDiagnosticDumper.INSTANCE.dumpProjectIndexingHistoryIfNecessary(projectIndexingHistory); } } /** * Returns the best number of threads to be used for indexing at this moment. * It may change during execution of the IDE depending on other activities' load. */ public static int getNumberOfIndexingThreads() { int threadCount = Registry.intValue("caches.indexerThreadsCount"); if (threadCount <= 0) { int coresToLeaveForOtherActivity = ApplicationManager.getApplication().isCommandLine() ? 0 : 1; threadCount = Math.max(1, Math.min(Runtime.getRuntime().availableProcessors() - coresToLeaveForOtherActivity, DEFAULT_MAX_INDEXER_THREADS)); } return threadCount; } /** * Returns the maximum number of threads to be used for indexing during this execution of the IDE. */ public static int getMaxNumberOfIndexingThreads() { // Change of the registry option requires IDE restart. int threadCount = Registry.intValue("caches.indexerThreadsCount"); return threadCount <= 0 ? DEFAULT_MAX_INDEXER_THREADS : threadCount; } /** * Scanning activity can be scaled well across number of threads, so we're trying to use all available resources to do it faster. */ public static int getNumberOfScanningThreads() { int scanningThreadCount = Registry.intValue("caches.scanningThreadsCount"); if (scanningThreadCount > 0) return scanningThreadCount; int coresToLeaveForOtherActivity = ApplicationManager.getApplication().isCommandLine() ? 0 : 1; return Math.max(Runtime.getRuntime().availableProcessors() - coresToLeaveForOtherActivity, getNumberOfIndexingThreads()); } }
Indexing diagnostics: shorten log message. GitOrigin-RevId: fc3da9efe9e8bcc1de7c780c37dec4424791b914
platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesUpdater.java
Indexing diagnostics: shorten log message.
<ide><path>latform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesUpdater.java <ide> catch (Throwable e) { <ide> projectIndexingHistory.getTimes().setWasInterrupted(true); <ide> if (e instanceof ControlFlowException) { <del> LOG.info("Unindexed files update canceled"); <add> LOG.info("Cancelled"); <ide> } <ide> throw e; <ide> }
Java
bsd-2-clause
2dc43df1177532a54eb5a76634945549808fc04d
0
Auxx/grilledui,Auxx/grilledui
package com.grilledmonkey.examples.tabactivityexample; import android.app.ActionBar; import android.app.ActionBar.TabListener; import android.support.v4.app.FragmentManager; import com.grilledmonkey.grilledui.TabActivity; import com.grilledmonkey.grilledui.adapters.SectionAdapter; /** * This example shows the basic usage of {@link TabActivity} with GrilledUI library * referencing and using provided layouts. GrilledUI layouts can only be used * when referencing GrilledUI in source form. Built-in layouts can not be used * with pre-compiled library in JAR form. * <p/> * Each tab layout and logic is put inside fragments * ({@link DummySectionFragment} in this example). This simple example can be * used as a base to many simple apps with minimal navigation requirements. * You can put your logic inside fragments and completely forget about * activity. * * @author Aux * */ public class MainActivity extends TabActivity { /** * Default SectionAdapter is empty, meaning without any tabs. Override * {@code createSectionAdapter()} method to populate tabs. Remember to pass * {@link ActionBar} and {@link TabListener} to {@link SectionAdapter} * constructor. * <p/> * P.S. You may use method chaining, because {@code add()} returns current * SectionAdapter instance. */ @Override public SectionAdapter createSectionAdapter(FragmentManager fm) { // Create new SectionAdapter, bind it to action bar and make current // activity a handler to all tab events. SectionAdapter adapter = new SectionAdapter(fm, getActionBar(), this); // Add two tabs. adapter.add(new DummySectionFragment(), "First tab"); adapter.add(new DummySectionFragment(), "Second tab"); // Chaining example // adapter.add(new DummySectionFragment(), "First tab").add(new DummySectionFragment(), "Second tab"); // Return populated adapter. return(adapter); } }
examples/TabActivityExample/src/com/grilledmonkey/examples/tabactivityexample/MainActivity.java
package com.grilledmonkey.examples.tabactivityexample; import android.app.ActionBar; import android.app.ActionBar.TabListener; import android.support.v4.app.FragmentManager; import com.grilledmonkey.grilledui.TabActivity; import com.grilledmonkey.grilledui.adapters.SectionAdapter; /** * This example shows the basic usage of TabActivity with GrilledUI library * referencing and using provided layouts. GrilledUI layouts can only be used * when referencing GrilledUI in source form. Built-in layouts can not be used * with pre-compiled library in JAR form. * <p/> * Each tab layout and logic is put inside fragments * ({@link DummySectionFragment} in this example). This simple example can be * used as a base to many simple apps with minimal navigation requirements. * You can put your logic inside fragments and completely forget about * activity. * * @author Aux * */ public class MainActivity extends TabActivity { /** * Default SectionAdapter is empty, meaning without any tabs. Override * {@code createSectionAdapter()} method to populate tabs. Remember to pass * {@link ActionBar} and {@link TabListener} to {@link SectionAdapter} * constructor. * <p/> * P.S. You may use method chaining, because {@code add()} returns current * SectionAdapter instance. */ @Override public SectionAdapter createSectionAdapter(FragmentManager fm) { // Create new SectionAdapter, bind it to action bar and make current // activity a handler to all tab events. SectionAdapter adapter = new SectionAdapter(fm, getActionBar(), this); // Add two tabs. adapter.add(new DummySectionFragment(), "First tab"); adapter.add(new DummySectionFragment(), "Second tab"); // Chaining example // adapter.add(new DummySectionFragment(), "First tab").add(new DummySectionFragment(), "Second tab"); // Return populated adapter. return(adapter); } }
Fixed JavaDoc
examples/TabActivityExample/src/com/grilledmonkey/examples/tabactivityexample/MainActivity.java
Fixed JavaDoc
<ide><path>xamples/TabActivityExample/src/com/grilledmonkey/examples/tabactivityexample/MainActivity.java <ide> import com.grilledmonkey.grilledui.adapters.SectionAdapter; <ide> <ide> /** <del> * This example shows the basic usage of TabActivity with GrilledUI library <add> * This example shows the basic usage of {@link TabActivity} with GrilledUI library <ide> * referencing and using provided layouts. GrilledUI layouts can only be used <ide> * when referencing GrilledUI in source form. Built-in layouts can not be used <ide> * with pre-compiled library in JAR form.
JavaScript
mit
308f9bc867b29a050a0a64b2f70ca1e54e72eafc
0
RJFreund/OpenDSA,RJFreund/OpenDSA,hosamshahin/OpenDSA,RJFreund/OpenDSA,RJFreund/OpenDSA,hosamshahin/OpenDSA,hosamshahin/OpenDSA,hosamshahin/OpenDSA,RJFreund/OpenDSA,hosamshahin/OpenDSA,RJFreund/OpenDSA,hosamshahin/OpenDSA,hosamshahin/OpenDSA,RJFreund/OpenDSA,hosamshahin/OpenDSA,hosamshahin/OpenDSA,RJFreund/OpenDSA
/* global graphUtils */ (function ($) { "use strict"; var exercise, graph, settings = new JSAV.utils.Settings($(".jsavsettings")), jsav = new JSAV($('.avcontainer'), {settings: settings}); jsav.recorded(); function init() { // create the graph if (graph) { graph.clear(); } graph = jsav.ds.graph({ width: 400, height: 400, layout: "automatic", directed: false }); graphUtils.generate(graph, {weighted: true}); // Randomly generate the graph with weights graph.layout(); // mark the 'A' node graph.nodes()[0].addClass("marked"); jsav.displayInit(); return graph; } function fixState(modelGraph) { var graphEdges = graph.edges(), modelEdges = modelGraph.edges(); // compare the edges between exercise and model for (var i = 0; i < graphEdges.length; i++) { var edge = graphEdges[i], modelEdge = modelEdges[i]; if (modelEdge.hasClass("marked") && !edge.hasClass("marked")) { // mark the edge that is marked in the model, but not in the exercise markEdge(edge); break; } } } function model(modeljsav) { var i, graphNodes = graph.nodes(), graphEdges = graph.edges(); // create the model var modelGraph = modeljsav.ds.graph({ width: 400, height: 400, layout: "automatic", directed: false }); // copy nodes from graph for (i = 0; i < graphNodes.length; i++) { modelGraph.addNode(graphNodes[i].value()); } // copy edges from graph var modelNodes = modelGraph.nodes(); for (i = 0; i < graphEdges.length; i++) { var startIndex = graphNodes.indexOf(graphEdges[i].start()), endIndex = graphNodes.indexOf(graphEdges[i].end()), startNode = modelNodes[startIndex], endNode = modelNodes[endIndex], weight = graphEdges[i].weight(); modelGraph.addEdge(startNode, endNode, {weight: weight}); } var distanceMatrixValues = []; for (i = 0; i < graphNodes.length; i++) { distanceMatrixValues.push([graphNodes[i].value(), "∞", "-"]); } distanceMatrixValues[0][1] = 0; var distances = modeljsav.ds.matrix(distanceMatrixValues, { style: "table", center: false }); distances.element.css({ position: "absolute", top: 0, left: 10 }); // Mark the 'A' node modelNodes[0].addClass("marked"); modelGraph.layout(); modeljsav.displayInit(); // start the algorithm dijkstra(modelNodes, distances, modeljsav); modeljsav.umsg("Shortest paths from A."); // hide all edges that are not part of the spanning tree var modelEdges = modelGraph.edges(); for (i = 0; i < modelGraph.edges().length; i++) { if (!modelEdges[i].hasClass("marked")) { modelEdges[i].hide(); } } // call the layout function for the new graph modelGraph.layout(); modeljsav.step(); return modelGraph; } function markEdge(edge, av) { edge.addClass("marked"); edge.start().addClass("marked"); edge.end().addClass("marked"); if (av) { av.gradeableStep(); } else { exercise.gradeableStep(); } } function dijkstra(nodes, distances, av) { // returns the distance given a node index function getDistance(index) { var dist = parseInt(distances.value(index, 1), 10); if (isNaN(dist)) { dist = 99999; } return dist; } // returns the node index given the node's value function getIndex(value) { return value.charCodeAt(0) - "A".charCodeAt(0); } while (true) { var min = 100000, node, prev, neighbors, nodeIndex = -1; // find node closest to the minimum spanning tree for (var i = 0; i < nodes.length; i++) { if (!distances.hasClass(i, true, "unused")) { var dist = getDistance(i); if (dist < min) { min = dist; nodeIndex = i; } } } node = nodes[nodeIndex]; if (!node) { break; } distances.addClass(nodeIndex, true, "unused"); if (nodeIndex === 0) { av.umsg("Start by selecting node A"); } else { av.umsg("Select " + node.value() + ", since it has the shortest distance from A."); } av.step(); // get previous node if any prev = nodes[getIndex(distances.value(nodeIndex, 2))]; if (prev) { av.umsg("Add edge (" + prev.value() + ", " + node.value() + ") to the path tree."); markEdge(prev.edgeTo(node), av); } // update distances for neighbors neighbors = node.neighbors(); while (neighbors.hasNext()) { var neighbor = neighbors.next(), neighborIndex = getIndex(neighbor.value()), d = getDistance(neighborIndex), dThroughNode = getDistance(nodeIndex) + node.edgeTo(neighbor).weight(); if (!distances.hasClass(neighborIndex, true, "unused") && d > dThroughNode) { distances.value(neighborIndex, 1, dThroughNode); distances.value(neighborIndex, 2, node.value()); } } av.umsg( "Update " + node.value() + "'s neighbors distances. " + "For updated nodes, set the parent node to " + node.value() ); av.step(); } } // Process About button: Pop up a message with an Alert function about() { window.alert("Dijkstra's Algorithm Proficiency Exercise\nWritten by --\nCreated as part of the OpenDSA hypertextbook project\nFor more information, see http://algoviz.org/OpenDSA\nSource and development history available at\nhttps://github.com/cashaffer/OpenDSA\nCompiled with JSAV library version " + JSAV.version()); } exercise = jsav.exercise(model, init, { compare: { class: "marked" }, controls: $('.jsavexercisecontrols'), fix: fixState }); exercise.reset(); $(".jsavcontainer").on("click", ".jsavedge", function () { var edge = $(this).data("edge"); if (!edge.hasClass("marked")) { markEdge(edge); } }); $(".jsavcontainer").on("click", ".jsavnode", function () { window.alert("Please, click on the edges, not the nodes."); }); $("#about").click(about); }(jQuery));
AV/Development/DijkstraPE.js
/* global graphUtils */ (function ($) { "use strict"; var exercise, graph, settings = new JSAV.utils.Settings($(".jsavsettings")), jsav = new JSAV($('.avcontainer'), {settings: settings}); jsav.recorded(); function init() { // create the graph if (graph) { graph.clear(); } graph = jsav.ds.graph({ width: 400, height: 400, layout: "automatic", directed: false }); graphUtils.generate(graph, {weighted: true}); // Randomly generate the graph with weights graph.layout(); // mark the 'A' node graph.nodes()[0].addClass("marked"); jsav.displayInit(); return graph; } function fixState(modelGraph) { var graphEdges = graph.edges(), modelEdges = modelGraph.edges(); // compare the edges between exercise and model for (var i = 0; i < graphEdges.length; i++) { var edge = graphEdges[i], modelEdge = modelEdges[i]; if (modelEdge.hasClass("marked") && !edge.hasClass("marked")) { // mark the edge that is marked in the model, but not in the exercise markEdge(edge); break; } } } function model(modeljsav) { var i, graphNodes = graph.nodes(), graphEdges = graph.edges(); // create the model var modelGraph = modeljsav.ds.graph({ width: 400, height: 400, layout: "automatic", directed: false }); // copy nodes from graph for (i = 0; i < graphNodes.length; i++) { modelGraph.addNode(graphNodes[i].value()); } // copy edges from graph var modelNodes = modelGraph.nodes(); for (i = 0; i < graphEdges.length; i++) { var startIndex = graphNodes.indexOf(graphEdges[i].start()), endIndex = graphNodes.indexOf(graphEdges[i].end()), startNode = modelNodes[startIndex], endNode = modelNodes[endIndex], weight = graphEdges[i].weight(); modelGraph.addEdge(startNode, endNode, {weight: weight}); } var distanceMatrixValues = []; for (i = 0; i < graphNodes.length; i++) { distanceMatrixValues.push([graphNodes[i].value(), "∞", "-"]); } distanceMatrixValues[0][1] = 0; var distances = modeljsav.ds.matrix(distanceMatrixValues, { style: "table", center: false }); distances.element.css({ position: "absolute", top: 0, left: 10 }); // Mark the 'A' node modelNodes[0].addClass("marked"); modelGraph.layout(); modeljsav.displayInit(); // start the algorithm prim(modelNodes, distances, modeljsav); modeljsav.umsg("Shortest paths from A."); // hide all edges that are not part of the spanning tree var modelEdges = modelGraph.edges(); for (i = 0; i < modelGraph.edges().length; i++) { if (!modelEdges[i].hasClass("marked")) { modelEdges[i].hide(); } } // call the layout function for the new graph modelGraph.layout(); modeljsav.step(); return modelGraph; } function markEdge(edge, av) { edge.addClass("marked"); edge.start().addClass("marked"); edge.end().addClass("marked"); if (av) { av.gradeableStep(); } else { exercise.gradeableStep(); } } function prim(nodes, distances, av) { // returns the distance given a node index function getDistance(index) { var dist = parseInt(distances.value(index, 1), 10); if (isNaN(dist)) { dist = 99999; } return dist; } // returns the node index given the node's value function getIndex(value) { return value.charCodeAt(0) - "A".charCodeAt(0); } while (true) { var min = 100000, node, prev, neighbors, nodeIndex = -1; // find node closest to the minimum spanning tree for (var i = 0; i < nodes.length; i++) { if (!distances.hasClass(i, true, "unused")) { var dist = getDistance(i); if (dist < min) { min = dist; nodeIndex = i; } } } node = nodes[nodeIndex]; if (!node) { break; } distances.addClass(nodeIndex, true, "unused"); if (nodeIndex === 0) { av.umsg("Start by selecting node A"); } else { av.umsg("Select " + node.value() + ", since it has the shortest distance from A."); } av.step(); // get previous node if any prev = nodes[getIndex(distances.value(nodeIndex, 2))]; if (prev) { av.umsg("Add edge (" + prev.value() + ", " + node.value() + ") to the path tree."); markEdge(prev.edgeTo(node), av); } // update distances for neighbors neighbors = node.neighbors(); while (neighbors.hasNext()) { var neighbor = neighbors.next(), neighborIndex = getIndex(neighbor.value()), d = getDistance(neighborIndex), dThroughNode = getDistance(nodeIndex) + node.edgeTo(neighbor).weight(); if (!distances.hasClass(neighborIndex, true, "unused") && d > dThroughNode) { distances.value(neighborIndex, 1, dThroughNode); distances.value(neighborIndex, 2, node.value()); } } av.umsg( "Update " + node.value() + "'s neighbors distances. " + "For updated nodes, set the parent node to " + node.value() ); av.step(); } } // Process About button: Pop up a message with an Alert function about() { window.alert("Dijkstra's Algorithm Proficiency Exercise\nWritten by --\nCreated as part of the OpenDSA hypertextbook project\nFor more information, see http://algoviz.org/OpenDSA\nSource and development history available at\nhttps://github.com/cashaffer/OpenDSA\nCompiled with JSAV library version " + JSAV.version()); } exercise = jsav.exercise(model, init, { compare: { class: "marked" }, controls: $('.jsavexercisecontrols'), fix: fixState }); exercise.reset(); $(".jsavcontainer").on("click", ".jsavedge", function () { var edge = $(this).data("edge"); if (!edge.hasClass("marked")) { markEdge(edge); } }); $(".jsavcontainer").on("click", ".jsavnode", function () { window.alert("Please, click on the edges, not the nodes."); }); $("#about").click(about); }(jQuery));
Minor refactoring for DijkstraPE
AV/Development/DijkstraPE.js
Minor refactoring for DijkstraPE
<ide><path>V/Development/DijkstraPE.js <ide> modeljsav.displayInit(); <ide> <ide> // start the algorithm <del> prim(modelNodes, distances, modeljsav); <add> dijkstra(modelNodes, distances, modeljsav); <ide> <ide> modeljsav.umsg("Shortest paths from A."); <ide> // hide all edges that are not part of the spanning tree <ide> } <ide> } <ide> <del> function prim(nodes, distances, av) { <add> function dijkstra(nodes, distances, av) { <ide> // returns the distance given a node index <ide> function getDistance(index) { <ide> var dist = parseInt(distances.value(index, 1), 10);
Java
apache-2.0
73043783c3ef8099785389ff1afedfadd51e64f6
0
missioncommand/emp3-android,missioncommand/emp3-android
package mil.emp3.core.utils; import android.util.Log; import android.util.SparseArray; import org.cmapi.primitives.GeoFillStyle; import org.cmapi.primitives.GeoLabelStyle; import org.cmapi.primitives.GeoPosition; import org.cmapi.primitives.GeoStrokeStyle; import org.cmapi.primitives.IGeoAltitudeMode; import org.cmapi.primitives.IGeoBounds; import org.cmapi.primitives.IGeoColor; import org.cmapi.primitives.IGeoFillStyle; import org.cmapi.primitives.IGeoLabelStyle; import org.cmapi.primitives.IGeoMilSymbol; import org.cmapi.primitives.IGeoPosition; import org.cmapi.primitives.IGeoStrokeStyle; import java.util.ArrayList; import java.util.List; import armyc2.c2sd.graphics2d.Point2D; import armyc2.c2sd.renderer.utilities.MilStdAttributes; import armyc2.c2sd.renderer.utilities.ModifiersTG; import armyc2.c2sd.renderer.utilities.ModifiersUnits; import armyc2.c2sd.renderer.utilities.RendererSettings; import armyc2.c2sd.renderer.utilities.ShapeInfo; import armyc2.c2sd.renderer.utilities.SymbolUtilities; import mil.emp3.api.MilStdSymbol; import mil.emp3.api.Path; import mil.emp3.api.Polygon; import mil.emp3.api.Text; import mil.emp3.api.enums.FontSizeModifierEnum; import mil.emp3.api.enums.MilStdLabelSettingEnum; import mil.emp3.api.interfaces.ICamera; import mil.emp3.api.interfaces.IEmpBoundingArea; import mil.emp3.api.interfaces.IFeature; import mil.emp3.api.interfaces.core.IStorageManager; import mil.emp3.api.utils.EmpGeoColor; import mil.emp3.api.utils.FontUtilities; import mil.emp3.api.utils.MilStdUtilities; import mil.emp3.core.utils.milstd2525.icons.BitmapCacheFactory; import mil.emp3.core.utils.milstd2525.icons.IBitmapCache; import mil.emp3.mapengine.interfaces.IEmpImageInfo; import mil.emp3.mapengine.interfaces.IMapInstance; import mil.emp3.mapengine.interfaces.IMilStdRenderer; import sec.web.render.SECWebRenderer; /** * * This class implements the rendering of the MilStd features. */ public class MilStdRenderer implements IMilStdRenderer { private static final String TAG = MilStdRenderer.class.getSimpleName(); public static final String METOC_PRESSURE_INSTABILITY_LINE = "WA-DPXIL---L---"; public static final String METOC_PRESSURE_SHEAR_LINE = "WA-DPXSH---L---"; public static final String METOC_BOUNDED_AREAS_OF_WEATHER_LIQUID_PRECIPITATION_NON_CONVECTIVE_CONTINUOUS_OR_INTERMITTENT = "WA-DBALPC---A--"; public static final String METOC_ATMOSPHERIC_BOUNDED_AREAS_OF_WEATHER_THUNDERSTORMS = "WA-DBAT-----A--"; private final static int DEFAULT_STROKE_WIDTH = 3; private IStorageManager storageManager; private static String sRendererCacheDir = null; private int getMemoryClass = 0; private static java.util.Set<IGeoMilSymbol.Modifier> oRequiredLabels = new java.util.HashSet<>(); private static java.util.Set<IGeoMilSymbol.Modifier> oCommonLabels = new java.util.HashSet<>(); private static IBitmapCache oBitmapCache = null; private boolean initialized; private void initCheck() { if (!initialized) { init(); initialized = true; } } public void init() { Log.d(TAG, "init"); // These modifiers, if provided in the MilStd feature, must be shown // along with the icon. They are the only modifiers displayed when the label setting is REQUIRED. oRequiredLabels.add(IGeoMilSymbol.Modifier.EQUIPMENT_TYPE); oRequiredLabels.add(IGeoMilSymbol.Modifier.SIGNATURE_EQUIPMENT); oRequiredLabels.add(IGeoMilSymbol.Modifier.OFFSET_INDICATOR); oRequiredLabels.add(IGeoMilSymbol.Modifier.SPECIAL_C2_HEADQUARTERS); oRequiredLabels.add(IGeoMilSymbol.Modifier.FEINT_DUMMY_INDICATOR); oRequiredLabels.add(IGeoMilSymbol.Modifier.INSTALLATION); // These modifiers, if provided in the MilStd feature, are to be displayed with the icon // when the label setting is COMMON. oCommonLabels.addAll(oRequiredLabels); oCommonLabels.add(IGeoMilSymbol.Modifier.ADDITIONAL_INFO_1); oCommonLabels.add(IGeoMilSymbol.Modifier.ADDITIONAL_INFO_2); oCommonLabels.add(IGeoMilSymbol.Modifier.ADDITIONAL_INFO_3); oCommonLabels.add(IGeoMilSymbol.Modifier.HIGHER_FORMATION); oCommonLabels.add(IGeoMilSymbol.Modifier.UNIQUE_DESIGNATOR_1); oCommonLabels.add(IGeoMilSymbol.Modifier.UNIQUE_DESIGNATOR_2); oBitmapCache = BitmapCacheFactory.instance().getBitMapCache(MilStdRenderer.sRendererCacheDir, getMemoryClass); } @Override public String getBitmapCacheName() { if(null == oBitmapCache) { throw new IllegalStateException("BitmapCache is not yet initialized"); } Log.i(TAG, "getBitmapCacheName " + oBitmapCache.getClass().getSimpleName()); return oBitmapCache.getClass().getSimpleName(); } public void setRendererCacheDir(String sCacheDir, int getMemoryClass) { if (sRendererCacheDir == null) { sRendererCacheDir = sCacheDir; this.getMemoryClass = getMemoryClass; init(); } } @Override public void setStorageManager(IStorageManager storageManager) { this.storageManager = storageManager; } /** * This method returns the list of modifiers provided in the symbol that match the modifiers * listed in the label settings. * @param mapInstance The map instance making the call. * @param symbol the feature. * @return */ @Override public SparseArray<String> getTGModifiers(IMapInstance mapInstance, MilStdSymbol symbol) { initCheck(); String UniqueDesignator1 = null; MilStdLabelSettingEnum eLabelSetting = storageManager.getMilStdLabels(mapInstance); SparseArray<String> oArray = new SparseArray<>(); java.util.HashMap<IGeoMilSymbol.Modifier, String> geoModifiers = symbol.getModifiers(); /* java.util.Set<IGeoMilSymbol.Modifier> oLabels = null; if (eLabelSetting != null) { switch (eLabelSetting) { case REQUIRED_LABELS: oLabels = MilStdRenderer.oRequiredLabels; break; case COMMON_LABELS: oLabels = MilStdRenderer.oCommonLabels; break; } } */ if ((geoModifiers != null) && !geoModifiers.isEmpty()) { java.util.Set<IGeoMilSymbol.Modifier> oModifierList = geoModifiers.keySet(); for (IGeoMilSymbol.Modifier eModifier: oModifierList) { /* if ((oLabels != null) && !oLabels.contains(eModifier)) { // Its not on the list. continue; } */ switch (eModifier) { case SYMBOL_ICON: oArray.put(ModifiersTG.A_SYMBOL_ICON, geoModifiers.get(eModifier)); break; case ECHELON: oArray.put(ModifiersTG.B_ECHELON, geoModifiers.get(eModifier)); break; case QUANTITY: oArray.put(ModifiersTG.C_QUANTITY, geoModifiers.get(eModifier)); break; case TASK_FORCE_INDICATOR: break; case FRAME_SHAPE_MODIFIER: break; case REDUCED_OR_REINFORCED: break; case STAFF_COMMENTS: break; case ADDITIONAL_INFO_1: oArray.put(ModifiersTG.H_ADDITIONAL_INFO_1, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_2: oArray.put(ModifiersTG.H1_ADDITIONAL_INFO_2, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_3: oArray.put(ModifiersTG.H2_ADDITIONAL_INFO_3, geoModifiers.get(eModifier)); break; case EVALUATION_RATING: break; case COMBAT_EFFECTIVENESS: break; case SIGNATURE_EQUIPMENT: break; case HIGHER_FORMATION: break; case HOSTILE: oArray.put(ModifiersTG.N_HOSTILE, geoModifiers.get(eModifier)); break; case IFF_SIF: break; case DIRECTION_OF_MOVEMENT: oArray.put(ModifiersTG.Q_DIRECTION_OF_MOVEMENT, geoModifiers.get(eModifier)); break; case MOBILITY_INDICATOR: break; case SIGINT_MOBILITY_INDICATOR: break; case OFFSET_INDICATOR: break; case UNIQUE_DESIGNATOR_1: UniqueDesignator1 = geoModifiers.get(eModifier); oArray.put(ModifiersTG.T_UNIQUE_DESIGNATION_1, UniqueDesignator1); break; case UNIQUE_DESIGNATOR_2: oArray.put(ModifiersTG.T1_UNIQUE_DESIGNATION_2, geoModifiers.get(eModifier)); break; case EQUIPMENT_TYPE: oArray.put(ModifiersTG.V_EQUIP_TYPE, geoModifiers.get(eModifier)); break; case DATE_TIME_GROUP: oArray.put(ModifiersTG.W_DTG_1, geoModifiers.get(eModifier)); break; case DATE_TIME_GROUP_2: oArray.put(ModifiersTG.W1_DTG_2, geoModifiers.get(eModifier)); break; case ALTITUDE_DEPTH: oArray.put(ModifiersTG.X_ALTITUDE_DEPTH, geoModifiers.get(eModifier)); break; case LOCATION: oArray.put(ModifiersTG.Y_LOCATION, geoModifiers.get(eModifier)); break; case SPEED: break; case SPECIAL_C2_HEADQUARTERS: break; case FEINT_DUMMY_INDICATOR: break; case INSTALLATION: break; case PLATFORM_TYPE: break; case EQUIPMENT_TEARDOWN_TIME: break; case COMMON_IDENTIFIER: break; case AUXILIARY_EQUIPMENT_INDICATOR: break; case AREA_OF_UNCERTAINTY: break; case DEAD_RECKONING: break; case SPEED_LEADER: break; case PAIRING_LINE: break; case OPERATIONAL_CONDITION: break; case DISTANCE: oArray.put(ModifiersTG.AM_DISTANCE, geoModifiers.get(eModifier)); break; case AZIMUTH: oArray.put(ModifiersTG.AN_AZIMUTH, geoModifiers.get(eModifier)); break; case ENGAGEMENT_BAR: break; case COUNTRY_CODE: break; case SONAR_CLASSIFICATION_CONFIDENCE: break; } } } if ((symbol.getName() != null) && !symbol.getName().isEmpty()) { if (eLabelSetting != null) { switch (eLabelSetting) { case REQUIRED_LABELS: break; case COMMON_LABELS: case ALL_LABELS: if ((UniqueDesignator1 == null) || UniqueDesignator1.isEmpty() || !UniqueDesignator1.toUpperCase().equals(symbol.getName().toUpperCase())) { oArray.put(ModifiersUnits.CN_CPOF_NAME_LABEL, symbol.getName()); } break; } } } return oArray; } /** * This method returns the list of modifiers provided in the symbol that match the modifiers * listed in the label settings. * @param mapInstance The map instance making the call. * @param symbol the feature. * @return */ @Override public SparseArray<String> getUnitModifiers(IMapInstance mapInstance, MilStdSymbol symbol) { initCheck(); if (symbol.isTacticalGraphic()) { return this.getTGModifiers(mapInstance, symbol); } String UniqueDesignator1 = null; SparseArray<String> oArray = new SparseArray<>(); MilStdLabelSettingEnum eLabelSetting = storageManager.getMilStdLabels(mapInstance); java.util.HashMap<IGeoMilSymbol.Modifier, String> geoModifiers = symbol.getModifiers(); java.util.Set<IGeoMilSymbol.Modifier> oLabels = null; if (eLabelSetting != null) { switch (eLabelSetting) { case REQUIRED_LABELS: oLabels = MilStdRenderer.oRequiredLabels; break; case COMMON_LABELS: oLabels = MilStdRenderer.oCommonLabels; break; } } if ((geoModifiers != null) && !geoModifiers.isEmpty()) { java.util.Set<IGeoMilSymbol.Modifier> oModifierList = geoModifiers.keySet(); for (IGeoMilSymbol.Modifier eModifier: oModifierList) { if ((oLabels != null) && !oLabels.contains(eModifier)) { // Its not on the list. continue; } switch (eModifier) { case SYMBOL_ICON: oArray.put(ModifiersUnits.A_SYMBOL_ICON, geoModifiers.get(eModifier)); break; case ECHELON: oArray.put(ModifiersUnits.B_ECHELON, geoModifiers.get(eModifier)); break; case QUANTITY: oArray.put(ModifiersUnits.C_QUANTITY, geoModifiers.get(eModifier)); break; case TASK_FORCE_INDICATOR: oArray.put(ModifiersUnits.D_TASK_FORCE_INDICATOR, geoModifiers.get(eModifier)); break; case FRAME_SHAPE_MODIFIER: oArray.put(ModifiersUnits.E_FRAME_SHAPE_MODIFIER, geoModifiers.get(eModifier)); break; case REDUCED_OR_REINFORCED: oArray.put(ModifiersUnits.F_REINFORCED_REDUCED, geoModifiers.get(eModifier)); break; case STAFF_COMMENTS: oArray.put(ModifiersUnits.G_STAFF_COMMENTS, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_1: oArray.put(ModifiersUnits.H_ADDITIONAL_INFO_1, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_2: oArray.put(ModifiersUnits.H1_ADDITIONAL_INFO_2, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_3: oArray.put(ModifiersUnits.H2_ADDITIONAL_INFO_3, geoModifiers.get(eModifier)); break; case EVALUATION_RATING: oArray.put(ModifiersUnits.J_EVALUATION_RATING, geoModifiers.get(eModifier)); break; case COMBAT_EFFECTIVENESS: oArray.put(ModifiersUnits.K_COMBAT_EFFECTIVENESS, geoModifiers.get(eModifier)); break; case SIGNATURE_EQUIPMENT: oArray.put(ModifiersUnits.L_SIGNATURE_EQUIP, geoModifiers.get(eModifier)); break; case HIGHER_FORMATION: oArray.put(ModifiersUnits.M_HIGHER_FORMATION, geoModifiers.get(eModifier)); break; case HOSTILE: oArray.put(ModifiersUnits.N_HOSTILE, geoModifiers.get(eModifier)); break; case IFF_SIF: oArray.put(ModifiersUnits.P_IFF_SIF, geoModifiers.get(eModifier)); break; case DIRECTION_OF_MOVEMENT: oArray.put(ModifiersUnits.Q_DIRECTION_OF_MOVEMENT, geoModifiers.get(eModifier)); break; case MOBILITY_INDICATOR: oArray.put(ModifiersUnits.R_MOBILITY_INDICATOR, geoModifiers.get(eModifier)); break; case SIGINT_MOBILITY_INDICATOR: oArray.put(ModifiersUnits.R2_SIGNIT_MOBILITY_INDICATOR, geoModifiers.get(eModifier)); break; case OFFSET_INDICATOR: oArray.put(ModifiersUnits.S_HQ_STAFF_OR_OFFSET_INDICATOR, geoModifiers.get(eModifier)); break; case UNIQUE_DESIGNATOR_1: UniqueDesignator1 = geoModifiers.get(eModifier); oArray.put(ModifiersUnits.T_UNIQUE_DESIGNATION_1, UniqueDesignator1); break; case UNIQUE_DESIGNATOR_2: oArray.put(ModifiersUnits.T1_UNIQUE_DESIGNATION_2, geoModifiers.get(eModifier)); break; case EQUIPMENT_TYPE: oArray.put(ModifiersUnits.V_EQUIP_TYPE, geoModifiers.get(eModifier)); break; case DATE_TIME_GROUP: oArray.put(ModifiersUnits.W_DTG_1, geoModifiers.get(eModifier)); break; case DATE_TIME_GROUP_2: oArray.put(ModifiersUnits.W1_DTG_2, geoModifiers.get(eModifier)); break; case ALTITUDE_DEPTH: oArray.put(ModifiersUnits.X_ALTITUDE_DEPTH, geoModifiers.get(eModifier)); break; case LOCATION: oArray.put(ModifiersUnits.Y_LOCATION, geoModifiers.get(eModifier)); break; case SPEED: oArray.put(ModifiersUnits.Z_SPEED, geoModifiers.get(eModifier)); break; case SPECIAL_C2_HEADQUARTERS: oArray.put(ModifiersUnits.AA_SPECIAL_C2_HQ, geoModifiers.get(eModifier)); break; case FEINT_DUMMY_INDICATOR: oArray.put(ModifiersUnits.AB_FEINT_DUMMY_INDICATOR, geoModifiers.get(eModifier)); break; case INSTALLATION: oArray.put(ModifiersUnits.AC_INSTALLATION, geoModifiers.get(eModifier)); break; case PLATFORM_TYPE: oArray.put(ModifiersUnits.AD_PLATFORM_TYPE, geoModifiers.get(eModifier)); break; case EQUIPMENT_TEARDOWN_TIME: oArray.put(ModifiersUnits.AE_EQUIPMENT_TEARDOWN_TIME, geoModifiers.get(eModifier)); break; case COMMON_IDENTIFIER: oArray.put(ModifiersUnits.AF_COMMON_IDENTIFIER, geoModifiers.get(eModifier)); break; case AUXILIARY_EQUIPMENT_INDICATOR: oArray.put(ModifiersUnits.AG_AUX_EQUIP_INDICATOR, geoModifiers.get(eModifier)); break; case AREA_OF_UNCERTAINTY: oArray.put(ModifiersUnits.AH_AREA_OF_UNCERTAINTY, geoModifiers.get(eModifier)); break; case DEAD_RECKONING: oArray.put(ModifiersUnits.AI_DEAD_RECKONING_TRAILER, geoModifiers.get(eModifier)); break; case SPEED_LEADER: oArray.put(ModifiersUnits.AJ_SPEED_LEADER, geoModifiers.get(eModifier)); break; case PAIRING_LINE: oArray.put(ModifiersUnits.AK_PAIRING_LINE, geoModifiers.get(eModifier)); break; case OPERATIONAL_CONDITION: oArray.put(ModifiersUnits.AL_OPERATIONAL_CONDITION, geoModifiers.get(eModifier)); break; case DISTANCE: break; case AZIMUTH: break; case ENGAGEMENT_BAR: oArray.put(ModifiersUnits.AO_ENGAGEMENT_BAR, geoModifiers.get(eModifier)); break; case COUNTRY_CODE: oArray.put(ModifiersUnits.CC_COUNTRY_CODE, geoModifiers.get(eModifier)); break; case SONAR_CLASSIFICATION_CONFIDENCE: oArray.put(ModifiersUnits.SCC_SONAR_CLASSIFICATION_CONFIDENCE, geoModifiers.get(eModifier)); break; } } } if ((symbol.getName() != null) && !symbol.getName().isEmpty()) { if (eLabelSetting != null) { switch (eLabelSetting) { case REQUIRED_LABELS: break; case COMMON_LABELS: case ALL_LABELS: if ((UniqueDesignator1 == null) || UniqueDesignator1.isEmpty() || !UniqueDesignator1.toUpperCase().equals(symbol.getName().toUpperCase())) { oArray.put(ModifiersUnits.CN_CPOF_NAME_LABEL, symbol.getName()); } break; } } } return oArray; } @Override public SparseArray<String> getAttributes(IMapInstance mapInstance, IFeature feature, boolean selected) { initCheck(); SparseArray<String> oArray = new SparseArray<>(); int iIconSize = storageManager.getIconPixelSize(mapInstance); IGeoFillStyle oFillStyle = feature.getFillStyle(); IGeoStrokeStyle oStrokeStyle = feature.getStrokeStyle(); IGeoLabelStyle labelStyle = feature.getLabelStyle(); IGeoColor strokeColor = null; IGeoColor textColor = null; boolean isMilStd = (feature instanceof MilStdSymbol); if (isMilStd) { oArray.put(MilStdAttributes.SymbologyStandard, "" + geoMilStdVersionToRendererVersion(((MilStdSymbol) feature).getSymbolStandard())); } oArray.put(MilStdAttributes.PixelSize, "" + iIconSize); oArray.put(MilStdAttributes.KeepUnitRatio, "true"); oArray.put(MilStdAttributes.UseDashArray, "true"); if (selected) { strokeColor = storageManager.getSelectedStrokeStyle(mapInstance).getStrokeColor(); textColor = storageManager.getSelectedLabelStyle(mapInstance).getColor(); } else { if (oStrokeStyle != null) { strokeColor = oStrokeStyle.getStrokeColor(); } if (labelStyle != null) { textColor = labelStyle.getColor(); } } if (oFillStyle != null) { oArray.put(MilStdAttributes.FillColor, "#" + ColorUtils.colorToString(oFillStyle.getFillColor())); } if (oStrokeStyle != null) { oArray.put(MilStdAttributes.LineColor, "#" + ColorUtils.colorToString(oStrokeStyle.getStrokeColor())); oArray.put(MilStdAttributes.LineWidth, "" + (int) oStrokeStyle.getStrokeWidth()); } if (strokeColor != null) { oArray.put(MilStdAttributes.LineColor, "#" + ColorUtils.colorToString(strokeColor)); } if (textColor != null) { oArray.put(MilStdAttributes.TextColor, "#" + ColorUtils.colorToString(textColor)); // There is currently no way to change the font. } if (isMilStd && !((MilStdSymbol) feature).isSinglePoint()) { oArray.put(MilStdAttributes.FontSize, "" + FontUtilities.getTextPixelSize(labelStyle, FontSizeModifierEnum.NORMAL)); } return oArray; } @Override public double getFarDistanceThreshold(IMapInstance mapInstance) { initCheck(); return storageManager.getFarDistanceThreshold(mapInstance); } @Override public double getMidDistanceThreshold(IMapInstance mapInstance) { initCheck(); return storageManager.getMidDistanceThreshold(mapInstance); } private String convertToStringPosition(List<IGeoPosition> posList) { StringBuilder Str = new StringBuilder(""); for (IGeoPosition pos: posList) { if (Str.length() > 0) { Str.append(" "); } Str.append(pos.getLongitude()); Str.append(","); Str.append(pos.getLatitude()); Str.append(","); Str.append(pos.getAltitude()); } return Str.toString(); } private List<List<IGeoPosition>> convertListOfPointListsToListOfPositionLists(ArrayList<ArrayList<Point2D>> listOfPointList) { IGeoPosition position; List<IGeoPosition> positionList; List<List<IGeoPosition>> listOfPosList = new ArrayList<>(); if (listOfPointList != null) { // Convert the point lists into position lists. for (ArrayList<armyc2.c2sd.graphics2d.Point2D> pointList : listOfPointList) { positionList = new ArrayList<>(); listOfPosList.add(positionList); for (armyc2.c2sd.graphics2d.Point2D point : pointList) { position = new GeoPosition(); // Y is latitude and X is longitude. position.setLatitude(point.getY()); position.setLongitude(point.getX()); position.setAltitude(0); positionList.add(position); } } } return listOfPosList; } private void renderShapeParser(List<IFeature> featureList, IMapInstance mapInstance, armyc2.c2sd.renderer.utilities.MilStdSymbol renderSymbol, IFeature renderFeature, boolean selected) { IFeature feature; IGeoColor geoLineColor; IGeoColor geoFillColor; armyc2.c2sd.renderer.utilities.Color fillColor; armyc2.c2sd.renderer.utilities.Color lineColor; IGeoStrokeStyle renderStrokeStyle = renderFeature.getStrokeStyle(); //IGeoFillStyle symbolFillStyle = renderFeature.getFillStyle(); IGeoLabelStyle symbolTextStyle = renderFeature.getLabelStyle(); IGeoStrokeStyle currentStrokeStyle; IGeoFillStyle currentFillStyle; IGeoLabelStyle currentTextStyle; IGeoAltitudeMode.AltitudeMode altitudeMode = renderFeature.getAltitudeMode(); ArrayList<ShapeInfo> shapeInfoList = renderSymbol.getSymbolShapes(); ArrayList<ShapeInfo> modifierShapeInfoList = renderSymbol.getModifierShapes(); // Process the list of shapes. for(ShapeInfo shapeInfo: shapeInfoList) { currentStrokeStyle = null; currentFillStyle = null; lineColor = shapeInfo.getLineColor(); if (lineColor != null) { currentStrokeStyle = new GeoStrokeStyle(); currentStrokeStyle.setStrokeWidth((renderStrokeStyle == null)? 3: renderStrokeStyle.getStrokeWidth()); geoLineColor = new EmpGeoColor((double) lineColor.getAlpha() / 255.0, lineColor.getRed(), lineColor.getGreen(), lineColor.getBlue()); currentStrokeStyle.setStrokeColor(geoLineColor); } if (selected) { if (null == currentStrokeStyle) { currentStrokeStyle = storageManager.getSelectedStrokeStyle(mapInstance); } else { currentStrokeStyle.setStrokeColor(storageManager.getSelectedStrokeStyle(mapInstance).getStrokeColor()); } } armyc2.c2sd.graphics2d.BasicStroke basicStroke = (armyc2.c2sd.graphics2d.BasicStroke) shapeInfo.getStroke(); if (renderFeature instanceof MilStdSymbol) { MilStdSymbol symbol = (MilStdSymbol) renderFeature; if ((null != currentStrokeStyle) && (basicStroke != null) && (basicStroke.getDashArray() != null)) { currentStrokeStyle.setStipplingPattern(this.getTGStipplePattern(symbol.getBasicSymbol())); currentStrokeStyle.setStipplingFactor(this.getTGStippleFactor(symbol.getBasicSymbol(), (int) currentStrokeStyle.getStrokeWidth())); } } fillColor = shapeInfo.getFillColor(); if (fillColor != null) { geoFillColor = new EmpGeoColor((double) fillColor.getAlpha() / 255.0, fillColor.getRed(), fillColor.getGreen(), fillColor.getBlue()); currentFillStyle = new GeoFillStyle(); currentFillStyle.setFillColor(geoFillColor); } switch (shapeInfo.getShapeType()) { case ShapeInfo.SHAPE_TYPE_POLYLINE: { List<List<IGeoPosition>> listOfPosList = this.convertListOfPointListsToListOfPositionLists(shapeInfo.getPolylines()); if (currentFillStyle != null) { // We create the polygon feature if it has a fill style. for (List<IGeoPosition> posList : listOfPosList) { feature = new Polygon(posList); feature.setStrokeStyle(currentStrokeStyle); feature.setFillStyle(currentFillStyle); feature.setAltitudeMode(altitudeMode); featureList.add(feature); } } else { // We create a path feature if it does not have a fill style. for (List<IGeoPosition> posList: listOfPosList) { feature = new Path(posList); feature.setStrokeStyle(currentStrokeStyle); feature.setAltitudeMode(altitudeMode); featureList.add(feature); } } break; } case ShapeInfo.SHAPE_TYPE_FILL: { List<List<IGeoPosition>> listOfPosList = this.convertListOfPointListsToListOfPositionLists(shapeInfo.getPolylines()); //if ((currentStrokeStyle != null) || (currentFillStyle != null)) { if (currentStrokeStyle != null) { // We create the feature if it has at least one style. for (List<IGeoPosition> posList: listOfPosList) { feature = new Path(posList); //new Polygon(posList); feature.setStrokeStyle(currentStrokeStyle); //feature.setFillStyle(currentFillStyle); feature.setAltitudeMode(altitudeMode); featureList.add(feature); } } break; } default: Log.i(TAG, "Unhandled Shape type " + shapeInfo.getShapeType()); break; } } // All modifier text are the same color. armyc2.c2sd.renderer.utilities.Color renderTextColor = renderSymbol.getTextColor(); IGeoColor textColor = new EmpGeoColor(renderTextColor.getAlpha(), renderTextColor.getRed(), renderTextColor.getGreen(), renderTextColor.getBlue()); // Process the list of shapes. for(ShapeInfo shapeInfo: modifierShapeInfoList) { switch (shapeInfo.getShapeType()) { case ShapeInfo.SHAPE_TYPE_MODIFIER: { Log.i(TAG, "Shape Type M<odifier."); break; } case ShapeInfo.SHAPE_TYPE_MODIFIER_FILL: { Text textFeature; armyc2.c2sd.graphics2d.Point2D point2D = shapeInfo.getModifierStringPosition(); IGeoPosition textPosition = new GeoPosition(); textFeature = new Text(shapeInfo.getModifierString()); textPosition.setAltitude(0); textPosition.setLatitude(point2D.getY()); textPosition.setLongitude(point2D.getX()); textFeature.setPosition(textPosition); textFeature.setAltitudeMode(altitudeMode); currentTextStyle = new GeoLabelStyle(); if ((null == symbolTextStyle) || (null == symbolTextStyle.getColor())) { currentTextStyle.setColor(textColor); currentTextStyle.setSize(FontUtilities.DEFAULT_FONT_POINT_SIZE); } else { currentTextStyle.setColor(symbolTextStyle.getColor()); currentTextStyle.setSize(symbolTextStyle.getSize()); } if (selected) { if (null == currentTextStyle) { currentTextStyle = storageManager.getSelectedLabelStyle(mapInstance); } else { currentTextStyle.setColor(storageManager.getSelectedLabelStyle(mapInstance).getColor()); } } currentTextStyle.setFontFamily(RendererSettings.getInstance().getMPModifierFontName()); switch (shapeInfo.getTextJustify()) { case ShapeInfo.justify_left: currentTextStyle.setJustification(IGeoLabelStyle.Justification.LEFT); break; case ShapeInfo.justify_right: currentTextStyle.setJustification(IGeoLabelStyle.Justification.RIGHT); break; case ShapeInfo.justify_center: default: currentTextStyle.setJustification(IGeoLabelStyle.Justification.CENTER); break; } textFeature.setLabelStyle(currentTextStyle); textFeature.setRotationAngle(shapeInfo.getModifierStringAngle()); featureList.add(textFeature); //Log.i(TAG, "Shape Type Modifier Fill." + shapeInfo.getModifierString() + " at " + point2D.getY() + "/" + point2D.getX()); break; } default: Log.i(TAG, "Unhandled Shape type " + shapeInfo.getShapeType()); break; } } } private void renderTacticalGraphic(List<IFeature> featureList, IMapInstance mapInstance, MilStdSymbol symbol, boolean selected) { ICamera camera = mapInstance.getCamera(); IGeoBounds bounds = storageManager.getBounds(storageManager.getMapMapping(mapInstance).getClientMap()); if ((camera == null) || (bounds == null)) { return; } // Prep the parameters in the type the renderer requires them. int milstdVersion = MilStdUtilities.geoMilStdVersionToRendererVersion(symbol.getSymbolStandard()); armyc2.c2sd.renderer.utilities.SymbolDef symbolDefinition = armyc2.c2sd.renderer.utilities.SymbolDefTable.getInstance().getSymbolDef(symbol.getBasicSymbol(), milstdVersion); if (symbol.getPositions().size() < symbolDefinition.getMinPoints()) { // There is not enough positions. return; } String coordinateStr = this.convertToStringPosition(symbol.getPositions()); Log.d(TAG, "Symbol Code " + symbol.getSymbolCode() + " coordinateStr " + coordinateStr); String boundingBoxStr; if(bounds instanceof IEmpBoundingArea) { boundingBoxStr = bounds.toString(); } else { boundingBoxStr = bounds.getWest() + "," + bounds.getSouth() + "," + bounds.getEast() + "," + bounds.getNorth(); } Log.d(TAG, "bounds " + boundingBoxStr); double scale = camera.getAltitude() * 6.36; SparseArray<String> modifiers = this.getTGModifiers(mapInstance, symbol); SparseArray<String> attributes = this.getAttributes(mapInstance, symbol, selected); String altitudeModeStr = MilStdUtilities.geoAltitudeModeToString(symbol.getAltitudeMode()); armyc2.c2sd.renderer.utilities.MilStdSymbol renderSymbol = SECWebRenderer.RenderMultiPointAsMilStdSymbol( symbol.getGeoId().toString(), symbol.getName(), symbol.getDescription(), symbol.getSymbolCode(), coordinateStr, altitudeModeStr, scale, boundingBoxStr, modifiers, attributes, milstdVersion); Log.d(TAG, "After RenderMultiPointAsMilStdSymbol renderSymbolgetSymbolShapes().size() " + renderSymbol.getSymbolShapes().size()); // Retrieve the list of shapes. this.renderShapeParser(featureList, mapInstance, renderSymbol, symbol, selected); } @Override public List<IFeature> getTGRenderableShapes(IMapInstance mapInstance, MilStdSymbol symbol, boolean selected) { initCheck(); List<IFeature> oList = new ArrayList<>(); String basicSC = SymbolUtilities.getBasicSymbolID(symbol.getSymbolCode()); if (SymbolUtilities.isTacticalGraphic(basicSC)) { this.renderTacticalGraphic(oList, mapInstance, symbol, selected); } return oList; } @Override public IEmpImageInfo getMilStdIcon(String sSymbolCode, SparseArray oModifiers, SparseArray oAttr) { initCheck(); return MilStdRenderer.oBitmapCache.getImageInfo(sSymbolCode, oModifiers, oAttr); } /** * This method converts a IGeoMilSymbol.SymbolStandard enumerated value to a * MilStd Renderer symbol version value. * @param eStandard see IGeoMilSymbol.SymbolStandard. * @return an integer value indicating the standard version. */ private int geoMilStdVersionToRendererVersion(IGeoMilSymbol.SymbolStandard eStandard) { int iVersion = RendererSettings.Symbology_2525Bch2_USAS_13_14; switch (eStandard) { case MIL_STD_2525C: iVersion = RendererSettings.Symbology_2525C; break; case MIL_STD_2525B : iVersion = RendererSettings.Symbology_2525Bch2_USAS_13_14; break; } return iVersion; } @Override public double getSelectedIconScale(IMapInstance mapInstance) { return storageManager.getSelectedIconScale(mapInstance); } private int getTGStippleFactor(String basicSymbolCode, int strokeWidth) { int factor = 0; if (strokeWidth < 1) { strokeWidth = 1; } switch (basicSymbolCode) { case METOC_PRESSURE_INSTABILITY_LINE: case METOC_PRESSURE_SHEAR_LINE: factor = 2; break; case METOC_BOUNDED_AREAS_OF_WEATHER_LIQUID_PRECIPITATION_NON_CONVECTIVE_CONTINUOUS_OR_INTERMITTENT: case METOC_ATMOSPHERIC_BOUNDED_AREAS_OF_WEATHER_THUNDERSTORMS: factor = 3; break; default: // Normal dashes. factor = 3; break; } return factor; } /** * This method is called if the MilStd renderer indicates that the graphic requires a line stippling. * Specific symbols require specific stippling patterns. * @param basicSymbolCode * @return */ private short getTGStipplePattern(String basicSymbolCode) { short pattern = 0; switch (basicSymbolCode) { case METOC_PRESSURE_INSTABILITY_LINE: pattern = (short) 0xDFF6; break; case METOC_PRESSURE_SHEAR_LINE: case METOC_BOUNDED_AREAS_OF_WEATHER_LIQUID_PRECIPITATION_NON_CONVECTIVE_CONTINUOUS_OR_INTERMITTENT: case METOC_ATMOSPHERIC_BOUNDED_AREAS_OF_WEATHER_THUNDERSTORMS: pattern = (short) 0xFFF6; break; default: // Normal dashes. pattern = (short) 0xEEEE; break; } return pattern; } @Override public List<IFeature> getFeatureRenderableShapes(IMapInstance mapInstance, IFeature feature, boolean selected) { Log.i(TAG, "start getFeatureRenderableShapes "); initCheck(); String symbolCode = ""; List<IFeature> oList = new ArrayList<>(); ICamera camera = mapInstance.getCamera(); IGeoBounds bounds = storageManager.getBounds(storageManager.getMapMapping(mapInstance).getClientMap()); if ((camera == null) || (bounds == null)) { return oList; } String coordinateStr = this.convertToStringPosition(feature.getPositions()); String boundingBoxStr; if(bounds instanceof IEmpBoundingArea) { boundingBoxStr = bounds.toString(); } else { boundingBoxStr = bounds.getWest() + "," + bounds.getSouth() + "," + bounds.getEast() + "," + bounds.getNorth(); } Log.i(TAG, "coordinateStr " + coordinateStr); Log.i(TAG, "boundingBoxStr " + boundingBoxStr); double scale = camera.getAltitude() * 6.36; String altitudeModeStr = MilStdUtilities.geoAltitudeModeToString(feature.getAltitudeMode()); SparseArray<String> modifiers = new SparseArray<>(); SparseArray<String> attributes; if (feature instanceof mil.emp3.api.Circle) { mil.emp3.api.Circle circleFeature = (mil.emp3.api.Circle) feature; symbolCode = "PBS_CIRCLE-----"; modifiers.put(ModifiersTG.AM_DISTANCE, "" + circleFeature.getRadius()); attributes = this.getAttributes(mapInstance, feature, selected); } else if (feature instanceof mil.emp3.api.Ellipse) { mil.emp3.api.Ellipse ellipseFeature = (mil.emp3.api.Ellipse) feature; symbolCode = "PBS_ELLIPSE----"; modifiers.put(ModifiersTG.AM_DISTANCE, ellipseFeature.getSemiMinor() + "," + ellipseFeature.getSemiMajor()); modifiers.put(ModifiersTG.AN_AZIMUTH, ellipseFeature.getAzimuth() + ""); attributes = this.getAttributes(mapInstance, feature, selected); } else if (feature instanceof mil.emp3.api.Rectangle) { mil.emp3.api.Rectangle rectangleFeature = (mil.emp3.api.Rectangle) feature; symbolCode = "PBS_RECTANGLE--"; modifiers.put(ModifiersTG.AM_DISTANCE, rectangleFeature.getWidth() + "," + rectangleFeature.getHeight()); modifiers.put(ModifiersTG.AN_AZIMUTH, rectangleFeature.getAzimuth() + ""); attributes = this.getAttributes(mapInstance, feature, selected); } else if (feature instanceof mil.emp3.api.Square) { mil.emp3.api.Square squareFeature = (mil.emp3.api.Square) feature; symbolCode = "PBS_SQUARE-----"; modifiers.put(ModifiersTG.AM_DISTANCE, squareFeature.getWidth() + ""); modifiers.put(ModifiersTG.AN_AZIMUTH, squareFeature.getAzimuth() + ""); attributes = this.getAttributes(mapInstance, feature, selected); } else { return oList; } Log.i(TAG, "Symbol Code " + symbolCode); for(int i = 0; i < attributes.size(); i++) { int key = attributes.keyAt(i); // get the object by the key. Object obj = attributes.get(key); Log.i(TAG, "Attribute " + key + " " + obj.toString()); } for(int i = 0; i < modifiers.size(); i++) { int key = modifiers.keyAt(i); // get the object by the key. Object obj = modifiers.get(key); Log.i(TAG, "Modifiers " + key + " " + obj.toString()); } armyc2.c2sd.renderer.utilities.MilStdSymbol renderSymbol = SECWebRenderer.RenderMultiPointAsMilStdSymbol( feature.getGeoId().toString(), feature.getName(), feature.getDescription(), symbolCode, coordinateStr, altitudeModeStr, scale, boundingBoxStr, modifiers, attributes, 1); // Retrieve the list of shapes. Log.i(TAG, "start renderBasicShapeParser "); this.renderBasicShapeParser(oList, mapInstance, renderSymbol, feature, selected); Log.i(TAG, "end getFeatureRenderableShapes "); return oList; } /** * * @param featureList - This is the output feature list that will be displayed on the map * @param mapInstance - Underlying mapInstance * @param renderSymbol - This is the value returned by mission command render-er. * @param renderFeature - This is the Feature created by the application that needs to be rendered * @param selected - Is the feature in a selected state? */ private void renderBasicShapeParser(List<IFeature> featureList, IMapInstance mapInstance, armyc2.c2sd.renderer.utilities.MilStdSymbol renderSymbol, IFeature renderFeature, boolean selected) { // // The mission command render-er will return two shapes in response to a request to render a // Circle, Ellipse, Square or a Rectangle. One shape will be POLYLINE and other will be FILL. // We will pick up the right shape based on the FillStyle specified by the application in the // 'renderFeature'. This logic is dependent on fillStyle being null by default in basic shapes. // The constructor of basic shapes ensures this. // int shapeTypeToUse = ShapeInfo.SHAPE_TYPE_FILL; if(null == renderFeature.getFillStyle()) { shapeTypeToUse = ShapeInfo.SHAPE_TYPE_POLYLINE; } for(ShapeInfo shapeInfo: renderSymbol.getSymbolShapes()) { if(shapeInfo.getShapeType() != shapeTypeToUse) { continue; } // // If line color is not specified by the application then we want to use whatever default was returned by // the renderer. We also need to override with 'selected' stroke color if feature is in selected state. // IGeoStrokeStyle currentStrokeStyle = renderFeature.getStrokeStyle(); if(selected) { if(null == currentStrokeStyle) { currentStrokeStyle = storageManager.getSelectedStrokeStyle(mapInstance); } else { currentStrokeStyle.setStrokeColor(storageManager.getSelectedStrokeStyle(mapInstance).getStrokeColor()); } } if((null == currentStrokeStyle) || (null == currentStrokeStyle.getStrokeColor())) { // Get the line/stroke color from the renderer. if(null != shapeInfo.getLineColor()) { EmpGeoColor rendererStrokeColor = new EmpGeoColor((double) shapeInfo.getLineColor().getAlpha() / 255.0, shapeInfo.getLineColor().getRed(), shapeInfo.getLineColor().getGreen(), shapeInfo.getLineColor().getBlue()); if(null == currentStrokeStyle) { currentStrokeStyle = new GeoStrokeStyle(); currentStrokeStyle.setStrokeWidth(DEFAULT_STROKE_WIDTH); } currentStrokeStyle.setStrokeColor(rendererStrokeColor); } } // // If fill color is not specified by the application then we want to use whatever default was returned by // the renderer. // IGeoFillStyle currentFillStyle = renderFeature.getFillStyle(); if((null == currentFillStyle) || (null == currentFillStyle.getFillColor())) { // Get the fill color from the renderer. if(null != shapeInfo.getFillColor()) { EmpGeoColor rendererFillColor = new EmpGeoColor((double) shapeInfo.getFillColor().getAlpha() / 255.0, shapeInfo.getFillColor().getRed(), shapeInfo.getFillColor().getGreen(), shapeInfo.getFillColor().getBlue()); if(null == currentFillStyle) { currentFillStyle = new GeoFillStyle(); } currentFillStyle.setFillColor(rendererFillColor); } } switch (shapeInfo.getShapeType()) { case ShapeInfo.SHAPE_TYPE_POLYLINE: { List<List<IGeoPosition>> listOfPosList = this.convertListOfPointListsToListOfPositionLists(shapeInfo.getPolylines()); for (List<IGeoPosition> posList : listOfPosList) { IFeature feature = new Path(posList); feature.setStrokeStyle(currentStrokeStyle); feature.setAltitudeMode(renderFeature.getAltitudeMode()); featureList.add(feature); } break; } case ShapeInfo.SHAPE_TYPE_FILL: { List<List<IGeoPosition>> listOfPosList = this.convertListOfPointListsToListOfPositionLists(shapeInfo.getPolylines()); for (List<IGeoPosition> posList : listOfPosList) { IFeature feature = new Polygon(posList); feature.setStrokeStyle(currentStrokeStyle); feature.setFillStyle(currentFillStyle); feature.setAltitudeMode(renderFeature.getAltitudeMode()); featureList.add(feature); } break; } default: Log.e(TAG, "Unhandled Shape type " + shapeInfo.getShapeType()); break; } } } }
sdk/sdk-core/aar/src/main/java/mil/emp3/core/utils/MilStdRenderer.java
package mil.emp3.core.utils; import android.util.Log; import android.util.SparseArray; import org.cmapi.primitives.GeoFillStyle; import org.cmapi.primitives.GeoLabelStyle; import org.cmapi.primitives.GeoPosition; import org.cmapi.primitives.GeoStrokeStyle; import org.cmapi.primitives.IGeoAltitudeMode; import org.cmapi.primitives.IGeoBounds; import org.cmapi.primitives.IGeoColor; import org.cmapi.primitives.IGeoFillStyle; import org.cmapi.primitives.IGeoLabelStyle; import org.cmapi.primitives.IGeoMilSymbol; import org.cmapi.primitives.IGeoPosition; import org.cmapi.primitives.IGeoStrokeStyle; import java.util.ArrayList; import java.util.List; import armyc2.c2sd.graphics2d.Point2D; import armyc2.c2sd.renderer.utilities.MilStdAttributes; import armyc2.c2sd.renderer.utilities.ModifiersTG; import armyc2.c2sd.renderer.utilities.ModifiersUnits; import armyc2.c2sd.renderer.utilities.RendererSettings; import armyc2.c2sd.renderer.utilities.ShapeInfo; import armyc2.c2sd.renderer.utilities.SymbolUtilities; import mil.emp3.api.MilStdSymbol; import mil.emp3.api.Path; import mil.emp3.api.Polygon; import mil.emp3.api.Text; import mil.emp3.api.enums.FontSizeModifierEnum; import mil.emp3.api.enums.MilStdLabelSettingEnum; import mil.emp3.api.interfaces.ICamera; import mil.emp3.api.interfaces.IEmpBoundingArea; import mil.emp3.api.interfaces.IFeature; import mil.emp3.api.interfaces.core.IStorageManager; import mil.emp3.api.utils.EmpGeoColor; import mil.emp3.api.utils.FontUtilities; import mil.emp3.api.utils.MilStdUtilities; import mil.emp3.core.utils.milstd2525.icons.BitmapCacheFactory; import mil.emp3.core.utils.milstd2525.icons.IBitmapCache; import mil.emp3.mapengine.interfaces.IEmpImageInfo; import mil.emp3.mapengine.interfaces.IMapInstance; import mil.emp3.mapengine.interfaces.IMilStdRenderer; import sec.web.render.SECWebRenderer; /** * * This class implements the rendering of the MilStd features. */ public class MilStdRenderer implements IMilStdRenderer { private static final String TAG = MilStdRenderer.class.getSimpleName(); public static final String METOC_PRESSURE_INSTABILITY_LINE = "WA-DPXIL---L---"; public static final String METOC_PRESSURE_SHEAR_LINE = "WA-DPXSH---L---"; public static final String METOC_BOUNDED_AREAS_OF_WEATHER_LIQUID_PRECIPITATION_NON_CONVECTIVE_CONTINUOUS_OR_INTERMITTENT = "WA-DBALPC---A--"; public static final String METOC_ATMOSPHERIC_BOUNDED_AREAS_OF_WEATHER_THUNDERSTORMS = "WA-DBAT-----A--"; private final static int DEFAULT_STROKE_WIDTH = 3; private IStorageManager storageManager; private static String sRendererCacheDir = null; private int getMemoryClass = 0; private static java.util.Set<IGeoMilSymbol.Modifier> oRequiredLabels = new java.util.HashSet<>(); private static java.util.Set<IGeoMilSymbol.Modifier> oCommonLabels = new java.util.HashSet<>(); private static IBitmapCache oBitmapCache = null; private boolean initialized; private void initCheck() { if (!initialized) { init(); initialized = true; } } public void init() { Log.d(TAG, "init"); // These modifiers, if provided in the MilStd feature, must be shown // along with the icon. They are the only modifiers displayed when the label setting is REQUIRED. oRequiredLabels.add(IGeoMilSymbol.Modifier.EQUIPMENT_TYPE); oRequiredLabels.add(IGeoMilSymbol.Modifier.SIGNATURE_EQUIPMENT); oRequiredLabels.add(IGeoMilSymbol.Modifier.OFFSET_INDICATOR); oRequiredLabels.add(IGeoMilSymbol.Modifier.SPECIAL_C2_HEADQUARTERS); oRequiredLabels.add(IGeoMilSymbol.Modifier.FEINT_DUMMY_INDICATOR); oRequiredLabels.add(IGeoMilSymbol.Modifier.INSTALLATION); // These modifiers, if provided in the MilStd feature, are to be displayed with the icon // when the label setting is COMMON. oCommonLabels.addAll(oRequiredLabels); oCommonLabels.add(IGeoMilSymbol.Modifier.ADDITIONAL_INFO_1); oCommonLabels.add(IGeoMilSymbol.Modifier.ADDITIONAL_INFO_2); oCommonLabels.add(IGeoMilSymbol.Modifier.ADDITIONAL_INFO_3); oCommonLabels.add(IGeoMilSymbol.Modifier.HIGHER_FORMATION); oCommonLabels.add(IGeoMilSymbol.Modifier.UNIQUE_DESIGNATOR_1); oCommonLabels.add(IGeoMilSymbol.Modifier.UNIQUE_DESIGNATOR_2); oBitmapCache = BitmapCacheFactory.instance().getBitMapCache(MilStdRenderer.sRendererCacheDir, getMemoryClass); } @Override public String getBitmapCacheName() { if(null == oBitmapCache) { throw new IllegalStateException("BitmapCache is not yet initialized"); } Log.i(TAG, "getBitmapCacheName " + oBitmapCache.getClass().getSimpleName()); return oBitmapCache.getClass().getSimpleName(); } public void setRendererCacheDir(String sCacheDir, int getMemoryClass) { if (sRendererCacheDir == null) { sRendererCacheDir = sCacheDir; this.getMemoryClass = getMemoryClass; init(); } } @Override public void setStorageManager(IStorageManager storageManager) { this.storageManager = storageManager; } /** * This method returns the list of modifiers provided in the symbol that match the modifiers * listed in the label settings. * @param mapInstance The map instance making the call. * @param symbol the feature. * @return */ @Override public SparseArray<String> getTGModifiers(IMapInstance mapInstance, MilStdSymbol symbol) { initCheck(); String UniqueDesignator1 = null; MilStdLabelSettingEnum eLabelSetting = storageManager.getMilStdLabels(mapInstance); SparseArray<String> oArray = new SparseArray<>(); java.util.HashMap<IGeoMilSymbol.Modifier, String> geoModifiers = symbol.getModifiers(); /* java.util.Set<IGeoMilSymbol.Modifier> oLabels = null; if (eLabelSetting != null) { switch (eLabelSetting) { case REQUIRED_LABELS: oLabels = MilStdRenderer.oRequiredLabels; break; case COMMON_LABELS: oLabels = MilStdRenderer.oCommonLabels; break; } } */ if ((geoModifiers != null) && !geoModifiers.isEmpty()) { java.util.Set<IGeoMilSymbol.Modifier> oModifierList = geoModifiers.keySet(); for (IGeoMilSymbol.Modifier eModifier: oModifierList) { /* if ((oLabels != null) && !oLabels.contains(eModifier)) { // Its not on the list. continue; } */ switch (eModifier) { case SYMBOL_ICON: oArray.put(ModifiersTG.A_SYMBOL_ICON, geoModifiers.get(eModifier)); break; case ECHELON: oArray.put(ModifiersTG.B_ECHELON, geoModifiers.get(eModifier)); break; case QUANTITY: oArray.put(ModifiersTG.C_QUANTITY, geoModifiers.get(eModifier)); break; case TASK_FORCE_INDICATOR: break; case FRAME_SHAPE_MODIFIER: break; case REDUCED_OR_REINFORCED: break; case STAFF_COMMENTS: break; case ADDITIONAL_INFO_1: oArray.put(ModifiersTG.H_ADDITIONAL_INFO_1, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_2: oArray.put(ModifiersTG.H1_ADDITIONAL_INFO_2, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_3: oArray.put(ModifiersTG.H2_ADDITIONAL_INFO_3, geoModifiers.get(eModifier)); break; case EVALUATION_RATING: break; case COMBAT_EFFECTIVENESS: break; case SIGNATURE_EQUIPMENT: break; case HIGHER_FORMATION: break; case HOSTILE: oArray.put(ModifiersTG.N_HOSTILE, geoModifiers.get(eModifier)); break; case IFF_SIF: break; case DIRECTION_OF_MOVEMENT: oArray.put(ModifiersTG.Q_DIRECTION_OF_MOVEMENT, geoModifiers.get(eModifier)); break; case MOBILITY_INDICATOR: break; case SIGINT_MOBILITY_INDICATOR: break; case OFFSET_INDICATOR: break; case UNIQUE_DESIGNATOR_1: UniqueDesignator1 = geoModifiers.get(eModifier); oArray.put(ModifiersTG.T_UNIQUE_DESIGNATION_1, UniqueDesignator1); break; case UNIQUE_DESIGNATOR_2: oArray.put(ModifiersTG.T1_UNIQUE_DESIGNATION_2, geoModifiers.get(eModifier)); break; case EQUIPMENT_TYPE: oArray.put(ModifiersTG.V_EQUIP_TYPE, geoModifiers.get(eModifier)); break; case DATE_TIME_GROUP: oArray.put(ModifiersTG.W_DTG_1, geoModifiers.get(eModifier)); break; case DATE_TIME_GROUP_2: oArray.put(ModifiersTG.W1_DTG_2, geoModifiers.get(eModifier)); break; case ALTITUDE_DEPTH: oArray.put(ModifiersTG.X_ALTITUDE_DEPTH, geoModifiers.get(eModifier)); break; case LOCATION: oArray.put(ModifiersTG.Y_LOCATION, geoModifiers.get(eModifier)); break; case SPEED: break; case SPECIAL_C2_HEADQUARTERS: break; case FEINT_DUMMY_INDICATOR: break; case INSTALLATION: break; case PLATFORM_TYPE: break; case EQUIPMENT_TEARDOWN_TIME: break; case COMMON_IDENTIFIER: break; case AUXILIARY_EQUIPMENT_INDICATOR: break; case AREA_OF_UNCERTAINTY: break; case DEAD_RECKONING: break; case SPEED_LEADER: break; case PAIRING_LINE: break; case OPERATIONAL_CONDITION: break; case DISTANCE: oArray.put(ModifiersTG.AM_DISTANCE, geoModifiers.get(eModifier)); break; case AZIMUTH: oArray.put(ModifiersTG.AN_AZIMUTH, geoModifiers.get(eModifier)); break; case ENGAGEMENT_BAR: break; case COUNTRY_CODE: break; case SONAR_CLASSIFICATION_CONFIDENCE: break; } } } if ((symbol.getName() != null) && !symbol.getName().isEmpty()) { if (eLabelSetting != null) { switch (eLabelSetting) { case REQUIRED_LABELS: break; case COMMON_LABELS: case ALL_LABELS: if ((UniqueDesignator1 == null) || UniqueDesignator1.isEmpty() || !UniqueDesignator1.toUpperCase().equals(symbol.getName().toUpperCase())) { oArray.put(ModifiersUnits.CN_CPOF_NAME_LABEL, symbol.getName()); } break; } } } return oArray; } /** * This method returns the list of modifiers provided in the symbol that match the modifiers * listed in the label settings. * @param mapInstance The map instance making the call. * @param symbol the feature. * @return */ @Override public SparseArray<String> getUnitModifiers(IMapInstance mapInstance, MilStdSymbol symbol) { initCheck(); if (symbol.isTacticalGraphic()) { return this.getTGModifiers(mapInstance, symbol); } String UniqueDesignator1 = null; SparseArray<String> oArray = new SparseArray<>(); MilStdLabelSettingEnum eLabelSetting = storageManager.getMilStdLabels(mapInstance); java.util.HashMap<IGeoMilSymbol.Modifier, String> geoModifiers = symbol.getModifiers(); java.util.Set<IGeoMilSymbol.Modifier> oLabels = null; if (eLabelSetting != null) { switch (eLabelSetting) { case REQUIRED_LABELS: oLabels = MilStdRenderer.oRequiredLabels; break; case COMMON_LABELS: oLabels = MilStdRenderer.oCommonLabels; break; } } if ((geoModifiers != null) && !geoModifiers.isEmpty()) { java.util.Set<IGeoMilSymbol.Modifier> oModifierList = geoModifiers.keySet(); for (IGeoMilSymbol.Modifier eModifier: oModifierList) { if ((oLabels != null) && !oLabels.contains(eModifier)) { // Its not on the list. continue; } switch (eModifier) { case SYMBOL_ICON: oArray.put(ModifiersUnits.A_SYMBOL_ICON, geoModifiers.get(eModifier)); break; case ECHELON: oArray.put(ModifiersUnits.B_ECHELON, geoModifiers.get(eModifier)); break; case QUANTITY: oArray.put(ModifiersUnits.C_QUANTITY, geoModifiers.get(eModifier)); break; case TASK_FORCE_INDICATOR: oArray.put(ModifiersUnits.D_TASK_FORCE_INDICATOR, geoModifiers.get(eModifier)); break; case FRAME_SHAPE_MODIFIER: oArray.put(ModifiersUnits.E_FRAME_SHAPE_MODIFIER, geoModifiers.get(eModifier)); break; case REDUCED_OR_REINFORCED: oArray.put(ModifiersUnits.F_REINFORCED_REDUCED, geoModifiers.get(eModifier)); break; case STAFF_COMMENTS: oArray.put(ModifiersUnits.G_STAFF_COMMENTS, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_1: oArray.put(ModifiersUnits.H_ADDITIONAL_INFO_1, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_2: oArray.put(ModifiersUnits.H1_ADDITIONAL_INFO_2, geoModifiers.get(eModifier)); break; case ADDITIONAL_INFO_3: oArray.put(ModifiersUnits.H2_ADDITIONAL_INFO_3, geoModifiers.get(eModifier)); break; case EVALUATION_RATING: oArray.put(ModifiersUnits.J_EVALUATION_RATING, geoModifiers.get(eModifier)); break; case COMBAT_EFFECTIVENESS: oArray.put(ModifiersUnits.K_COMBAT_EFFECTIVENESS, geoModifiers.get(eModifier)); break; case SIGNATURE_EQUIPMENT: oArray.put(ModifiersUnits.L_SIGNATURE_EQUIP, geoModifiers.get(eModifier)); break; case HIGHER_FORMATION: oArray.put(ModifiersUnits.M_HIGHER_FORMATION, geoModifiers.get(eModifier)); break; case HOSTILE: oArray.put(ModifiersUnits.N_HOSTILE, geoModifiers.get(eModifier)); break; case IFF_SIF: oArray.put(ModifiersUnits.P_IFF_SIF, geoModifiers.get(eModifier)); break; case DIRECTION_OF_MOVEMENT: oArray.put(ModifiersUnits.Q_DIRECTION_OF_MOVEMENT, geoModifiers.get(eModifier)); break; case MOBILITY_INDICATOR: oArray.put(ModifiersUnits.R_MOBILITY_INDICATOR, geoModifiers.get(eModifier)); break; case SIGINT_MOBILITY_INDICATOR: oArray.put(ModifiersUnits.R2_SIGNIT_MOBILITY_INDICATOR, geoModifiers.get(eModifier)); break; case OFFSET_INDICATOR: oArray.put(ModifiersUnits.S_HQ_STAFF_OR_OFFSET_INDICATOR, geoModifiers.get(eModifier)); break; case UNIQUE_DESIGNATOR_1: UniqueDesignator1 = geoModifiers.get(eModifier); oArray.put(ModifiersUnits.T_UNIQUE_DESIGNATION_1, UniqueDesignator1); break; case UNIQUE_DESIGNATOR_2: oArray.put(ModifiersUnits.T1_UNIQUE_DESIGNATION_2, geoModifiers.get(eModifier)); break; case EQUIPMENT_TYPE: oArray.put(ModifiersUnits.V_EQUIP_TYPE, geoModifiers.get(eModifier)); break; case DATE_TIME_GROUP: oArray.put(ModifiersUnits.W_DTG_1, geoModifiers.get(eModifier)); break; case DATE_TIME_GROUP_2: oArray.put(ModifiersUnits.W1_DTG_2, geoModifiers.get(eModifier)); break; case ALTITUDE_DEPTH: oArray.put(ModifiersUnits.X_ALTITUDE_DEPTH, geoModifiers.get(eModifier)); break; case LOCATION: oArray.put(ModifiersUnits.Y_LOCATION, geoModifiers.get(eModifier)); break; case SPEED: oArray.put(ModifiersUnits.Z_SPEED, geoModifiers.get(eModifier)); break; case SPECIAL_C2_HEADQUARTERS: oArray.put(ModifiersUnits.AA_SPECIAL_C2_HQ, geoModifiers.get(eModifier)); break; case FEINT_DUMMY_INDICATOR: oArray.put(ModifiersUnits.AB_FEINT_DUMMY_INDICATOR, geoModifiers.get(eModifier)); break; case INSTALLATION: oArray.put(ModifiersUnits.AC_INSTALLATION, geoModifiers.get(eModifier)); break; case PLATFORM_TYPE: oArray.put(ModifiersUnits.AD_PLATFORM_TYPE, geoModifiers.get(eModifier)); break; case EQUIPMENT_TEARDOWN_TIME: oArray.put(ModifiersUnits.AE_EQUIPMENT_TEARDOWN_TIME, geoModifiers.get(eModifier)); break; case COMMON_IDENTIFIER: oArray.put(ModifiersUnits.AF_COMMON_IDENTIFIER, geoModifiers.get(eModifier)); break; case AUXILIARY_EQUIPMENT_INDICATOR: oArray.put(ModifiersUnits.AG_AUX_EQUIP_INDICATOR, geoModifiers.get(eModifier)); break; case AREA_OF_UNCERTAINTY: oArray.put(ModifiersUnits.AH_AREA_OF_UNCERTAINTY, geoModifiers.get(eModifier)); break; case DEAD_RECKONING: oArray.put(ModifiersUnits.AI_DEAD_RECKONING_TRAILER, geoModifiers.get(eModifier)); break; case SPEED_LEADER: oArray.put(ModifiersUnits.AJ_SPEED_LEADER, geoModifiers.get(eModifier)); break; case PAIRING_LINE: oArray.put(ModifiersUnits.AK_PAIRING_LINE, geoModifiers.get(eModifier)); break; case OPERATIONAL_CONDITION: oArray.put(ModifiersUnits.AL_OPERATIONAL_CONDITION, geoModifiers.get(eModifier)); break; case DISTANCE: break; case AZIMUTH: break; case ENGAGEMENT_BAR: oArray.put(ModifiersUnits.AO_ENGAGEMENT_BAR, geoModifiers.get(eModifier)); break; case COUNTRY_CODE: oArray.put(ModifiersUnits.CC_COUNTRY_CODE, geoModifiers.get(eModifier)); break; case SONAR_CLASSIFICATION_CONFIDENCE: oArray.put(ModifiersUnits.SCC_SONAR_CLASSIFICATION_CONFIDENCE, geoModifiers.get(eModifier)); break; } } } if ((symbol.getName() != null) && !symbol.getName().isEmpty()) { if (eLabelSetting != null) { switch (eLabelSetting) { case REQUIRED_LABELS: break; case COMMON_LABELS: case ALL_LABELS: if ((UniqueDesignator1 == null) || UniqueDesignator1.isEmpty() || !UniqueDesignator1.toUpperCase().equals(symbol.getName().toUpperCase())) { oArray.put(ModifiersUnits.CN_CPOF_NAME_LABEL, symbol.getName()); } break; } } } return oArray; } @Override public SparseArray<String> getAttributes(IMapInstance mapInstance, IFeature feature, boolean selected) { initCheck(); SparseArray<String> oArray = new SparseArray<>(); int iIconSize = storageManager.getIconPixelSize(mapInstance); IGeoFillStyle oFillStyle = feature.getFillStyle(); IGeoStrokeStyle oStrokeStyle = feature.getStrokeStyle(); IGeoLabelStyle labelStyle = feature.getLabelStyle(); IGeoColor strokeColor = null; IGeoColor textColor = null; boolean isMilStd = (feature instanceof MilStdSymbol); if (isMilStd) { oArray.put(MilStdAttributes.SymbologyStandard, "" + geoMilStdVersionToRendererVersion(((MilStdSymbol) feature).getSymbolStandard())); } oArray.put(MilStdAttributes.PixelSize, "" + iIconSize); oArray.put(MilStdAttributes.KeepUnitRatio, "true"); oArray.put(MilStdAttributes.UseDashArray, "true"); if (selected) { strokeColor = storageManager.getSelectedStrokeStyle(mapInstance).getStrokeColor(); textColor = storageManager.getSelectedLabelStyle(mapInstance).getColor(); } else { if (oStrokeStyle != null) { strokeColor = oStrokeStyle.getStrokeColor(); } if (labelStyle != null) { textColor = labelStyle.getColor(); } } if (oFillStyle != null) { oArray.put(MilStdAttributes.FillColor, "#" + ColorUtils.colorToString(oFillStyle.getFillColor())); } if (oStrokeStyle != null) { oArray.put(MilStdAttributes.LineColor, "#" + ColorUtils.colorToString(oStrokeStyle.getStrokeColor())); oArray.put(MilStdAttributes.LineWidth, "" + (int) oStrokeStyle.getStrokeWidth()); } if (strokeColor != null) { oArray.put(MilStdAttributes.LineColor, "#" + ColorUtils.colorToString(strokeColor)); } if (textColor != null) { oArray.put(MilStdAttributes.TextColor, "#" + ColorUtils.colorToString(textColor)); // There is currently no way to change the font. } if (isMilStd && !((MilStdSymbol) feature).isSinglePoint()) { oArray.put(MilStdAttributes.FontSize, "" + FontUtilities.getTextPixelSize(labelStyle, FontSizeModifierEnum.NORMAL)); } return oArray; } @Override public double getFarDistanceThreshold(IMapInstance mapInstance) { initCheck(); return storageManager.getFarDistanceThreshold(mapInstance); } @Override public double getMidDistanceThreshold(IMapInstance mapInstance) { initCheck(); return storageManager.getMidDistanceThreshold(mapInstance); } private String convertToStringPosition(List<IGeoPosition> posList) { StringBuilder Str = new StringBuilder(""); for (IGeoPosition pos: posList) { if (Str.length() > 0) { Str.append(" "); } Str.append(pos.getLongitude()); Str.append(","); Str.append(pos.getLatitude()); Str.append(","); Str.append(pos.getAltitude()); } return Str.toString(); } private List<List<IGeoPosition>> convertListOfPointListsToListOfPositionLists(ArrayList<ArrayList<Point2D>> listOfPointList) { IGeoPosition position; List<IGeoPosition> positionList; List<List<IGeoPosition>> listOfPosList = new ArrayList<>(); if (listOfPointList != null) { // Convert the point lists into position lists. for (ArrayList<armyc2.c2sd.graphics2d.Point2D> pointList : listOfPointList) { positionList = new ArrayList<>(); listOfPosList.add(positionList); for (armyc2.c2sd.graphics2d.Point2D point : pointList) { position = new GeoPosition(); // Y is latitude and X is longitude. position.setLatitude(point.getY()); position.setLongitude(point.getX()); position.setAltitude(0); positionList.add(position); } } } return listOfPosList; } private void renderShapeParser(List<IFeature> featureList, IMapInstance mapInstance, armyc2.c2sd.renderer.utilities.MilStdSymbol renderSymbol, IFeature renderFeature, boolean selected) { IFeature feature; IGeoColor geoLineColor; IGeoColor geoFillColor; armyc2.c2sd.renderer.utilities.Color fillColor; armyc2.c2sd.renderer.utilities.Color lineColor; IGeoStrokeStyle renderStrokeStyle = renderFeature.getStrokeStyle(); //IGeoFillStyle symbolFillStyle = renderFeature.getFillStyle(); IGeoLabelStyle symbolTextStyle = renderFeature.getLabelStyle(); IGeoStrokeStyle currentStrokeStyle; IGeoFillStyle currentFillStyle; IGeoLabelStyle currentTextStyle; IGeoAltitudeMode.AltitudeMode altitudeMode = renderFeature.getAltitudeMode(); ArrayList<ShapeInfo> shapeInfoList = renderSymbol.getSymbolShapes(); ArrayList<ShapeInfo> modifierShapeInfoList = renderSymbol.getModifierShapes(); // Process the list of shapes. for(ShapeInfo shapeInfo: shapeInfoList) { currentStrokeStyle = null; currentFillStyle = null; lineColor = shapeInfo.getLineColor(); if (lineColor != null) { currentStrokeStyle = new GeoStrokeStyle(); currentStrokeStyle.setStrokeWidth((renderStrokeStyle == null)? 3: renderStrokeStyle.getStrokeWidth()); geoLineColor = new EmpGeoColor((double) lineColor.getAlpha() / 255.0, lineColor.getRed(), lineColor.getGreen(), lineColor.getBlue()); currentStrokeStyle.setStrokeColor(geoLineColor); } if (selected) { if (null == currentStrokeStyle) { currentStrokeStyle = storageManager.getSelectedStrokeStyle(mapInstance); } else { currentStrokeStyle.setStrokeColor(storageManager.getSelectedStrokeStyle(mapInstance).getStrokeColor()); } } armyc2.c2sd.graphics2d.BasicStroke basicStroke = (armyc2.c2sd.graphics2d.BasicStroke) shapeInfo.getStroke(); if (renderFeature instanceof MilStdSymbol) { MilStdSymbol symbol = (MilStdSymbol) renderFeature; if ((null != currentStrokeStyle) && (basicStroke != null) && (basicStroke.getDashArray() != null)) { currentStrokeStyle.setStipplingPattern(this.getTGStipplePattern(symbol.getBasicSymbol())); currentStrokeStyle.setStipplingFactor(this.getTGStippleFactor(symbol.getBasicSymbol(), (int) currentStrokeStyle.getStrokeWidth())); } } fillColor = shapeInfo.getFillColor(); if (fillColor != null) { geoFillColor = new EmpGeoColor((double) fillColor.getAlpha() / 255.0, fillColor.getRed(), fillColor.getGreen(), fillColor.getBlue()); currentFillStyle = new GeoFillStyle(); currentFillStyle.setFillColor(geoFillColor); } switch (shapeInfo.getShapeType()) { case ShapeInfo.SHAPE_TYPE_POLYLINE: { List<List<IGeoPosition>> listOfPosList = this.convertListOfPointListsToListOfPositionLists(shapeInfo.getPolylines()); if (currentFillStyle != null) { // We create the polygon feature if it has a fill style. for (List<IGeoPosition> posList : listOfPosList) { feature = new Polygon(posList); feature.setStrokeStyle(currentStrokeStyle); feature.setFillStyle(currentFillStyle); feature.setAltitudeMode(altitudeMode); featureList.add(feature); } } else { // We create a path feature if it does not have a fill style. for (List<IGeoPosition> posList: listOfPosList) { feature = new Path(posList); feature.setStrokeStyle(currentStrokeStyle); feature.setAltitudeMode(altitudeMode); featureList.add(feature); } } break; } case ShapeInfo.SHAPE_TYPE_FILL: { List<List<IGeoPosition>> listOfPosList = this.convertListOfPointListsToListOfPositionLists(shapeInfo.getPolylines()); //if ((currentStrokeStyle != null) || (currentFillStyle != null)) { if (currentStrokeStyle != null) { // We create the feature if it has at least one style. for (List<IGeoPosition> posList: listOfPosList) { feature = new Path(posList); //new Polygon(posList); feature.setStrokeStyle(currentStrokeStyle); //feature.setFillStyle(currentFillStyle); feature.setAltitudeMode(altitudeMode); featureList.add(feature); } } break; } default: Log.i(TAG, "Unhandled Shape type " + shapeInfo.getShapeType()); break; } } // All modifier text are the same color. armyc2.c2sd.renderer.utilities.Color renderTextColor = renderSymbol.getTextColor(); IGeoColor textColor = new EmpGeoColor(renderTextColor.getAlpha(), renderTextColor.getRed(), renderTextColor.getGreen(), renderTextColor.getBlue()); // Process the list of shapes. for(ShapeInfo shapeInfo: modifierShapeInfoList) { switch (shapeInfo.getShapeType()) { case ShapeInfo.SHAPE_TYPE_MODIFIER: { Log.i(TAG, "Shape Type M<odifier."); break; } case ShapeInfo.SHAPE_TYPE_MODIFIER_FILL: { Text textFeature; armyc2.c2sd.graphics2d.Point2D point2D = shapeInfo.getModifierStringPosition(); IGeoPosition textPosition = new GeoPosition(); textFeature = new Text(shapeInfo.getModifierString()); textPosition.setAltitude(0); textPosition.setLatitude(point2D.getY()); textPosition.setLongitude(point2D.getX()); textFeature.setPosition(textPosition); textFeature.setAltitudeMode(altitudeMode); currentTextStyle = new GeoLabelStyle(); if ((null == symbolTextStyle) || (null == symbolTextStyle.getColor())) { currentTextStyle.setColor(textColor); currentTextStyle.setSize(FontUtilities.DEFAULT_FONT_POINT_SIZE); } else { currentTextStyle.setColor(symbolTextStyle.getColor()); currentTextStyle.setSize(symbolTextStyle.getSize()); } if (selected) { if (null == currentTextStyle) { currentTextStyle = storageManager.getSelectedLabelStyle(mapInstance); } else { currentTextStyle.setColor(storageManager.getSelectedLabelStyle(mapInstance).getColor()); } } currentTextStyle.setFontFamily(RendererSettings.getInstance().getMPModifierFontName()); switch (shapeInfo.getTextJustify()) { case ShapeInfo.justify_left: currentTextStyle.setJustification(IGeoLabelStyle.Justification.LEFT); break; case ShapeInfo.justify_right: currentTextStyle.setJustification(IGeoLabelStyle.Justification.RIGHT); break; case ShapeInfo.justify_center: default: currentTextStyle.setJustification(IGeoLabelStyle.Justification.CENTER); break; } textFeature.setLabelStyle(currentTextStyle); textFeature.setRotationAngle(shapeInfo.getModifierStringAngle()); featureList.add(textFeature); //Log.i(TAG, "Shape Type Modifier Fill." + shapeInfo.getModifierString() + " at " + point2D.getY() + "/" + point2D.getX()); break; } default: Log.i(TAG, "Unhandled Shape type " + shapeInfo.getShapeType()); break; } } } private void renderTacticalGraphic(List<IFeature> featureList, IMapInstance mapInstance, MilStdSymbol symbol, boolean selected) { ICamera camera = mapInstance.getCamera(); IGeoBounds bounds = storageManager.getBounds(storageManager.getMapMapping(mapInstance).getClientMap()); if ((camera == null) || (bounds == null)) { return; } // Prep the parameters in the type the renderer requires them. int milstdVersion = MilStdUtilities.geoMilStdVersionToRendererVersion(symbol.getSymbolStandard()); armyc2.c2sd.renderer.utilities.SymbolDef symbolDefinition = armyc2.c2sd.renderer.utilities.SymbolDefTable.getInstance().getSymbolDef(symbol.getBasicSymbol(), milstdVersion); if (symbol.getPositions().size() < symbolDefinition.getMinPoints()) { // There is not enough positions. return; } String coordinateStr = this.convertToStringPosition(symbol.getPositions()); Log.d(TAG, "Symbol Code " + symbol.getSymbolCode() + " coordinateStr " + coordinateStr); String boundingBoxStr; if(bounds instanceof IEmpBoundingArea) { boundingBoxStr = bounds.toString(); } else { boundingBoxStr = bounds.getWest() + "," + bounds.getSouth() + "," + bounds.getEast() + "," + bounds.getNorth(); } Log.d(TAG, "bounds " + boundingBoxStr); double scale = camera.getAltitude() * 6.36; SparseArray<String> modifiers = this.getTGModifiers(mapInstance, symbol); SparseArray<String> attributes = this.getAttributes(mapInstance, symbol, selected); String altitudeModeStr = MilStdUtilities.geoAltitudeModeToString(symbol.getAltitudeMode()); armyc2.c2sd.renderer.utilities.MilStdSymbol renderSymbol = SECWebRenderer.RenderMultiPointAsMilStdSymbol( symbol.getGeoId().toString(), symbol.getName(), symbol.getDescription(), symbol.getSymbolCode(), coordinateStr, altitudeModeStr, scale, boundingBoxStr, modifiers, attributes, milstdVersion); Log.d(TAG, "After RenderMultiPointAsMilStdSymbol renderSymbolgetSymbolShapes().size() " + renderSymbol.getSymbolShapes().size()); // Retrieve the list of shapes. this.renderShapeParser(featureList, mapInstance, renderSymbol, symbol, selected); } @Override public List<IFeature> getTGRenderableShapes(IMapInstance mapInstance, MilStdSymbol symbol, boolean selected) { initCheck(); List<IFeature> oList = new ArrayList<>(); String basicSC = SymbolUtilities.getBasicSymbolID(symbol.getSymbolCode()); if (SymbolUtilities.isTacticalGraphic(basicSC)) { this.renderTacticalGraphic(oList, mapInstance, symbol, selected); } return oList; } @Override public IEmpImageInfo getMilStdIcon(String sSymbolCode, SparseArray oModifiers, SparseArray oAttr) { initCheck(); return MilStdRenderer.oBitmapCache.getImageInfo(sSymbolCode, oModifiers, oAttr); } /** * This method converts a IGeoMilSymbol.SymbolStandard enumerated value to a * MilStd Renderer symbol version value. * @param eStandard see IGeoMilSymbol.SymbolStandard. * @return an integer value indicating the standard version. */ private int geoMilStdVersionToRendererVersion(IGeoMilSymbol.SymbolStandard eStandard) { int iVersion = RendererSettings.Symbology_2525Bch2_USAS_13_14; switch (eStandard) { case MIL_STD_2525C: iVersion = RendererSettings.Symbology_2525C; break; case MIL_STD_2525B : iVersion = RendererSettings.Symbology_2525Bch2_USAS_13_14; break; } return iVersion; } @Override public double getSelectedIconScale(IMapInstance mapInstance) { return storageManager.getSelectedIconScale(mapInstance); } private int getTGStippleFactor(String basicSymbolCode, int strokeWidth) { int factor = 0; if (strokeWidth < 1) { strokeWidth = 1; } switch (basicSymbolCode) { case METOC_PRESSURE_INSTABILITY_LINE: case METOC_PRESSURE_SHEAR_LINE: factor = 2; break; case METOC_BOUNDED_AREAS_OF_WEATHER_LIQUID_PRECIPITATION_NON_CONVECTIVE_CONTINUOUS_OR_INTERMITTENT: case METOC_ATMOSPHERIC_BOUNDED_AREAS_OF_WEATHER_THUNDERSTORMS: factor = 3; break; default: // Normal dashes. factor = 3; break; } return factor; } /** * This method is called if the MilStd renderer indicates that the graphic requires a line stippling. * Specific symbols require specific stippling patterns. * @param basicSymbolCode * @return */ private short getTGStipplePattern(String basicSymbolCode) { short pattern = 0; switch (basicSymbolCode) { case METOC_PRESSURE_INSTABILITY_LINE: pattern = (short) 0xDFF6; break; case METOC_PRESSURE_SHEAR_LINE: case METOC_BOUNDED_AREAS_OF_WEATHER_LIQUID_PRECIPITATION_NON_CONVECTIVE_CONTINUOUS_OR_INTERMITTENT: case METOC_ATMOSPHERIC_BOUNDED_AREAS_OF_WEATHER_THUNDERSTORMS: pattern = (short) 0xFFF6; break; default: // Normal dashes. pattern = (short) 0xEEEE; break; } return pattern; } @Override public List<IFeature> getFeatureRenderableShapes(IMapInstance mapInstance, IFeature feature, boolean selected) { Log.i(TAG, "start getFeatureRenderableShapes "); initCheck(); String symbolCode = ""; List<IFeature> oList = new ArrayList<>(); ICamera camera = mapInstance.getCamera(); IGeoBounds bounds = storageManager.getBounds(storageManager.getMapMapping(mapInstance).getClientMap()); if ((camera == null) || (bounds == null)) { return oList; } String coordinateStr = this.convertToStringPosition(feature.getPositions()); String boundingBoxStr; if(bounds instanceof IEmpBoundingArea) { boundingBoxStr = bounds.toString(); } else { boundingBoxStr = bounds.getWest() + "," + bounds.getSouth() + "," + bounds.getEast() + "," + bounds.getNorth(); } Log.i(TAG, "coordinateStr " + coordinateStr); Log.i(TAG, "boundingBoxStr " + boundingBoxStr); double scale = camera.getAltitude() * 6.36; String altitudeModeStr = MilStdUtilities.geoAltitudeModeToString(feature.getAltitudeMode()); SparseArray<String> modifiers = new SparseArray<>(); SparseArray<String> attributes; if (feature instanceof mil.emp3.api.Circle) { mil.emp3.api.Circle circleFeature = (mil.emp3.api.Circle) feature; symbolCode = "PBS_CIRCLE-----"; modifiers.put(ModifiersTG.AM_DISTANCE, "" + circleFeature.getRadius()); attributes = this.getAttributes(mapInstance, feature, selected); } else if (feature instanceof mil.emp3.api.Ellipse) { mil.emp3.api.Ellipse ellipseFeature = (mil.emp3.api.Ellipse) feature; symbolCode = "PBS_ELLIPSE----"; modifiers.put(ModifiersTG.AM_DISTANCE, ellipseFeature.getSemiMinor() + "," + ellipseFeature.getSemiMajor()); modifiers.put(ModifiersTG.AN_AZIMUTH, ellipseFeature.getAzimuth() + ""); attributes = this.getAttributes(mapInstance, feature, selected); } else if (feature instanceof mil.emp3.api.Rectangle) { mil.emp3.api.Rectangle rectangleFeature = (mil.emp3.api.Rectangle) feature; symbolCode = "PBS_RECTANGLE--"; modifiers.put(ModifiersTG.AM_DISTANCE, rectangleFeature.getWidth() + "," + rectangleFeature.getHeight()); modifiers.put(ModifiersTG.AN_AZIMUTH, rectangleFeature.getAzimuth() + ""); attributes = this.getAttributes(mapInstance, feature, selected); } else if (feature instanceof mil.emp3.api.Square) { mil.emp3.api.Square squareFeature = (mil.emp3.api.Square) feature; symbolCode = "PBS_SQUARE-----"; modifiers.put(ModifiersTG.AM_DISTANCE, squareFeature.getWidth() + ""); modifiers.put(ModifiersTG.AN_AZIMUTH, squareFeature.getAzimuth() + ""); attributes = this.getAttributes(mapInstance, feature, selected); } else { return oList; } armyc2.c2sd.renderer.utilities.MilStdSymbol renderSymbol = SECWebRenderer.RenderMultiPointAsMilStdSymbol( feature.getGeoId().toString(), feature.getName(), feature.getDescription(), symbolCode, coordinateStr, altitudeModeStr, scale, boundingBoxStr, modifiers, attributes, 1); // Retrieve the list of shapes. Log.i(TAG, "start renderBasicShapeParser "); this.renderBasicShapeParser(oList, mapInstance, renderSymbol, feature, selected); Log.i(TAG, "end getFeatureRenderableShapes "); return oList; } /** * * @param featureList - This is the output feature list that will be displayed on the map * @param mapInstance - Underlying mapInstance * @param renderSymbol - This is the value returned by mission command render-er. * @param renderFeature - This is the Feature created by the application that needs to be rendered * @param selected - Is the feature in a selected state? */ private void renderBasicShapeParser(List<IFeature> featureList, IMapInstance mapInstance, armyc2.c2sd.renderer.utilities.MilStdSymbol renderSymbol, IFeature renderFeature, boolean selected) { // // The mission command render-er will return two shapes in response to a request to render a // Circle, Ellipse, Square or a Rectangle. One shape will be POLYLINE and other will be FILL. // We will pick up the right shape based on the FillStyle specified by the application in the // 'renderFeature'. This logic is dependent on fillStyle being null by default in basic shapes. // The constructor of basic shapes ensures this. // int shapeTypeToUse = ShapeInfo.SHAPE_TYPE_FILL; if(null == renderFeature.getFillStyle()) { shapeTypeToUse = ShapeInfo.SHAPE_TYPE_POLYLINE; } for(ShapeInfo shapeInfo: renderSymbol.getSymbolShapes()) { if(shapeInfo.getShapeType() != shapeTypeToUse) { continue; } // // If line color is not specified by the application then we want to use whatever default was returned by // the renderer. We also need to override with 'selected' stroke color if feature is in selected state. // IGeoStrokeStyle currentStrokeStyle = renderFeature.getStrokeStyle(); if(selected) { if(null == currentStrokeStyle) { currentStrokeStyle = storageManager.getSelectedStrokeStyle(mapInstance); } else { currentStrokeStyle.setStrokeColor(storageManager.getSelectedStrokeStyle(mapInstance).getStrokeColor()); } } if((null == currentStrokeStyle) || (null == currentStrokeStyle.getStrokeColor())) { // Get the line/stroke color from the renderer. if(null != shapeInfo.getLineColor()) { EmpGeoColor rendererStrokeColor = new EmpGeoColor((double) shapeInfo.getLineColor().getAlpha() / 255.0, shapeInfo.getLineColor().getRed(), shapeInfo.getLineColor().getGreen(), shapeInfo.getLineColor().getBlue()); if(null == currentStrokeStyle) { currentStrokeStyle = new GeoStrokeStyle(); currentStrokeStyle.setStrokeWidth(DEFAULT_STROKE_WIDTH); } currentStrokeStyle.setStrokeColor(rendererStrokeColor); } } // // If fill color is not specified by the application then we want to use whatever default was returned by // the renderer. // IGeoFillStyle currentFillStyle = renderFeature.getFillStyle(); if((null == currentFillStyle) || (null == currentFillStyle.getFillColor())) { // Get the fill color from the renderer. if(null != shapeInfo.getFillColor()) { EmpGeoColor rendererFillColor = new EmpGeoColor((double) shapeInfo.getFillColor().getAlpha() / 255.0, shapeInfo.getFillColor().getRed(), shapeInfo.getFillColor().getGreen(), shapeInfo.getFillColor().getBlue()); if(null == currentFillStyle) { currentFillStyle = new GeoFillStyle(); } currentFillStyle.setFillColor(rendererFillColor); } } switch (shapeInfo.getShapeType()) { case ShapeInfo.SHAPE_TYPE_POLYLINE: { List<List<IGeoPosition>> listOfPosList = this.convertListOfPointListsToListOfPositionLists(shapeInfo.getPolylines()); for (List<IGeoPosition> posList : listOfPosList) { IFeature feature = new Path(posList); feature.setStrokeStyle(currentStrokeStyle); feature.setAltitudeMode(renderFeature.getAltitudeMode()); featureList.add(feature); } break; } case ShapeInfo.SHAPE_TYPE_FILL: { List<List<IGeoPosition>> listOfPosList = this.convertListOfPointListsToListOfPositionLists(shapeInfo.getPolylines()); for (List<IGeoPosition> posList : listOfPosList) { IFeature feature = new Polygon(posList); feature.setStrokeStyle(currentStrokeStyle); feature.setFillStyle(currentFillStyle); feature.setAltitudeMode(renderFeature.getAltitudeMode()); featureList.add(feature); } break; } default: Log.e(TAG, "Unhandled Shape type " + shapeInfo.getShapeType()); break; } } } }
Issue-92 #comment trouble shooting.
sdk/sdk-core/aar/src/main/java/mil/emp3/core/utils/MilStdRenderer.java
Issue-92 #comment trouble shooting.
<ide><path>dk/sdk-core/aar/src/main/java/mil/emp3/core/utils/MilStdRenderer.java <ide> return oList; <ide> } <ide> <add> Log.i(TAG, "Symbol Code " + symbolCode); <add> for(int i = 0; i < attributes.size(); i++) { <add> int key = attributes.keyAt(i); <add> // get the object by the key. <add> Object obj = attributes.get(key); <add> Log.i(TAG, "Attribute " + key + " " + obj.toString()); <add> } <add> <add> for(int i = 0; i < modifiers.size(); i++) { <add> int key = modifiers.keyAt(i); <add> // get the object by the key. <add> Object obj = modifiers.get(key); <add> Log.i(TAG, "Modifiers " + key + " " + obj.toString()); <add> } <add> <ide> armyc2.c2sd.renderer.utilities.MilStdSymbol renderSymbol = SECWebRenderer.RenderMultiPointAsMilStdSymbol( <ide> feature.getGeoId().toString(), feature.getName(), feature.getDescription(), <ide> symbolCode, coordinateStr, altitudeModeStr, scale, boundingBoxStr,
Java
apache-2.0
dd3a07be17e71e3bde0db57efaf180db888e7366
0
codelibs/elasticsearch-analysis-ja,codelibs/elasticsearch-analysis-ja
package org.codelibs.elasticsearch.ja; import org.codelibs.elasticsearch.ja.analysis.IterationMarkCharFilterFactory; import org.codelibs.elasticsearch.ja.analysis.KanjiNumberFilterFactory; import org.codelibs.elasticsearch.ja.analysis.ProlongedSoundMarkCharFilterFactory; import org.codelibs.elasticsearch.ja.analysis.ReloadableKuromojiTokenizerFactory; import org.elasticsearch.index.analysis.AnalysisModule; import org.elasticsearch.plugins.AbstractPlugin; public class JaPlugin extends AbstractPlugin { @Override public String name() { return "AnalysisJaPlugin"; } @Override public String description() { return "This plugin provides analysis library for Japanese."; } public void onModule(AnalysisModule module) { module.addCharFilter("iteration_mark", IterationMarkCharFilterFactory.class); module.addCharFilter("prolonged_sound_mark", ProlongedSoundMarkCharFilterFactory.class); module.addTokenizer("reloadable_kuromoji_tokenizer", ReloadableKuromojiTokenizerFactory.class); module.addTokenizer("reloadable_kuromoji", ReloadableKuromojiTokenizerFactory.class); module.addTokenFilter("kanji_number", KanjiNumberFilterFactory.class); } }
src/main/java/org/codelibs/elasticsearch/ja/JaPlugin.java
package org.codelibs.elasticsearch.ja; import org.codelibs.elasticsearch.ja.analysis.IterationMarkCharFilterFactory; import org.codelibs.elasticsearch.ja.analysis.KanjiNumberFilterFactory; import org.codelibs.elasticsearch.ja.analysis.ProlongedSoundMarkCharFilterFactory; import org.codelibs.elasticsearch.ja.analysis.ReloadableKuromojiTokenizerFactory; import org.elasticsearch.index.analysis.AnalysisModule; import org.elasticsearch.plugins.AbstractPlugin; public class JaPlugin extends AbstractPlugin { @Override public String name() { return "Analysis Ja Plugin"; } @Override public String description() { return "This plugin provides analysis library for Japanese."; } public void onModule(AnalysisModule module) { module.addCharFilter("iteration_mark", IterationMarkCharFilterFactory.class); module.addCharFilter("prolonged_sound_mark", ProlongedSoundMarkCharFilterFactory.class); module.addTokenizer("reloadable_kuromoji_tokenizer", ReloadableKuromojiTokenizerFactory.class); module.addTokenizer("reloadable_kuromoji", ReloadableKuromojiTokenizerFactory.class); module.addTokenFilter("kanji_number", KanjiNumberFilterFactory.class); } }
change plugin name
src/main/java/org/codelibs/elasticsearch/ja/JaPlugin.java
change plugin name
<ide><path>rc/main/java/org/codelibs/elasticsearch/ja/JaPlugin.java <ide> public class JaPlugin extends AbstractPlugin { <ide> @Override <ide> public String name() { <del> return "Analysis Ja Plugin"; <add> return "AnalysisJaPlugin"; <ide> } <ide> <ide> @Override
Java
apache-2.0
88d1940df608e6d9a1d99b20050f3371c051be81
0
jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.util; import static java.util.Objects.requireNonNull; import static java.util.concurrent.ForkJoinTask.adapt; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import javolution.context.LocalContext; /** * [code] * try (final Concurrent c = new Concurrent()) { * c.execute(task1); * c.execute(task2); * } * [/code] * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @since @__version__@ * @version @__version__@ &mdash; <em>$Date: 2013-10-24 $</em> */ public final class Concurrent implements Executor, AutoCloseable { /* ************************************************************************ * Static concurrent context. * ************************************************************************/ private static final Object NULL = new Object(); private static final LocalContext.Reference<Object> FORK_JOIN_POOL = new LocalContext.Reference<Object>(new ForkJoinPool( Runtime.getRuntime().availableProcessors() )); /** * Set the thread pool to use for concurrent actions. If the given pool is * {@code null}, the command, given in the {@link #execute(Runnable)} method * is executed in the main thread. * * @param pool the thread pool to use. */ public static void setForkJoinPool(final ForkJoinPool pool) { FORK_JOIN_POOL.set(pool != null ? pool : NULL); } /** * Return the currently use thread pool. * * @return the currently used thread pool. */ public static ForkJoinPool getForkJoinPool() { final Object pool = FORK_JOIN_POOL.get(); return pool != NULL ? (ForkJoinPool)pool : null; } /* ************************************************************************ * 'Dynamic' concurrent context. * ************************************************************************/ private final int TASKS_SIZE = 15; private final ForkJoinPool _pool; private final List<ForkJoinTask<?>> _tasks = new ArrayList<>(TASKS_SIZE); private final boolean _parallel; /** * Create a new {@code Concurrent} executor <i>context</i> with the given * {@link ForkJoinPool}. * * @param pool the {@code ForkJoinPool} used for concurrent execution of the * given tasks. The {@code pool} may be {@code null} and if so, the * given tasks are executed in the main thread. */ private Concurrent(final ForkJoinPool pool) { _pool = pool; _parallel = _pool != null; } /** * Create a new {@code Concurrent} executor <i>context</i> with the * {@code ForkJoinPool} set with the {@link #setForkJoinPool(ForkJoinPool)}, * or the default pool, if no one has been set. */ public Concurrent() { this(getForkJoinPool()); } /** * Return the current <i>parallelism</i> of this {@code Concurrent} object. * * @return the current <i>parallelism</i> of this {@code Concurrent} object */ public int getParallelism() { return _pool != null ? _pool.getParallelism() : 1; } @Override public void execute(final Runnable command) { if (_parallel) { final ForkJoinTask<?> task = toForkJoinTask(command); _pool.execute(task); _tasks.add(task); } else { command.run(); } } private static ForkJoinTask<?> toForkJoinTask(final Runnable r) { return r instanceof ForkJoinTask<?> ? (ForkJoinTask<?>)r : adapt(r); } /** * Executes the given {@code runnables} in {@code n} parts. * * @param n the number of parts the given {@code runnables} are executed. * @param runnables the runnables to be executed. * @throws NullPointerException if the given runnables are {@code null}. */ public void execute(final int n, final List<? extends Runnable> runnables) { requireNonNull(runnables, "Runnables must not be null"); if (runnables.size() > 0) { final int[] parts = arrays.partition(runnables.size(), n); for (int i = 0; i < parts.length - 1; ++i) { final int part = i; execute(new Runnable() { @Override public void run() { for (int j = parts[part]; j < parts[part + 1]; ++j) { runnables.get(j).run(); } }}); } } } /** * Executes the given {@code runnables} in {@link #getParallelism()} parts. * * @param runnables the runnables to be executed. * @throws NullPointerException if the given runnables are {@code null}. */ public void execute(final List<? extends Runnable> runnables) { execute(getParallelism(), runnables); } /** * Executes the given {@code runnables} in {@code n} parts. * * @param n the number of parts the given {@code runnables} are executed. * @param runnables the runnables to be executed. * @throws NullPointerException if the given runnables are {@code null}. */ public void execute(final int n, final Runnable... runnables) { requireNonNull(runnables, "Runnables must not be null"); if (runnables.length > 0) { final int[] parts = arrays.partition(runnables.length, n); for (int i = 0; i < parts.length - 1; ++i) { final int part = i; execute(new Runnable() { @Override public void run() { for (int j = parts[part]; j < parts[part + 1]; ++j) { runnables[j].run(); } }}); } } } /** * Executes the given {@code runnables} in {@link #getParallelism()} parts. * * @param runnables the runnables to be executed. * @throws NullPointerException if the given runnables are {@code null}. */ public void execute(final Runnable... runnables) { execute(getParallelism(), runnables); } @Override public void close() { if (_parallel) { for (int i = _tasks.size(); --i >= 0;) { _tasks.get(i).join(); } } } }
org.jenetics/src/main/java/org/jenetics/util/Concurrent.java
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.util; import static java.util.Objects.requireNonNull; import static java.util.concurrent.ForkJoinTask.adapt; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import javolution.context.LocalContext; /** * [code] * try (final Concurrent c = new Concurrent()) { * c.execute(task1); * c.execute(task2); * } * [/code] * * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> * @since @__version__@ * @version @__version__@ &mdash; <em>$Date: 2013-10-08 $</em> */ public final class Concurrent implements Executor, AutoCloseable { private static final Object NULL = new Object(); private final int TASKS_SIZE = 15; private static final LocalContext.Reference<Object> FORK_JOIN_POOL = new LocalContext.Reference<Object>(new ForkJoinPool( Runtime.getRuntime().availableProcessors() )); /** * Set the thread pool to use for concurrent actions. If the given pool is * {@code null}, the command, given in the {@link #execute(Runnable)} method * is executed in the main thread. * * @param pool the thread pool to use. */ public static void setForkJoinPool(final ForkJoinPool pool) { FORK_JOIN_POOL.set(pool != null ? pool : NULL); } /** * Return the currently use thread pool. * * @return the currently used thread pool. */ public static ForkJoinPool getForkJoinPool() { final Object pool = FORK_JOIN_POOL.get(); return pool != NULL ? (ForkJoinPool)pool : null; } private final ForkJoinPool _pool; private final List<ForkJoinTask<?>> _tasks = new ArrayList<>(TASKS_SIZE); private final boolean _parallel; private Concurrent(final ForkJoinPool pool) { _pool = pool; _parallel = _pool != null; } public Concurrent() { this(getForkJoinPool()); } /** * Return the current <i>parallelism</i> of this {@code Concurrent} object. * * @return the current <i>parallelism</i> of this {@code Concurrent} object */ public int getParallelism() { return _pool != null ? _pool.getParallelism() : 1; } @Override public void execute(final Runnable command) { if (_parallel) { final ForkJoinTask<?> task = toForkJoinTask(command); _pool.execute(task); _tasks.add(task); } else { command.run(); } } private static ForkJoinTask<?> toForkJoinTask(final Runnable r) { return r instanceof ForkJoinTask<?> ? (ForkJoinTask<?>)r : adapt(r); } /** * Executes the given {@code runnables} in {@code n} parts. * * @param n the number of parts the given {@code runnables} are executed. * @param runnables the runnables to be executed. * @throws NullPointerException if the given runnables are {@code null}. */ public void execute(final int n, final List<? extends Runnable> runnables) { requireNonNull(runnables, "Runnables must not be null"); if (runnables.size() > 0) { final int[] parts = arrays.partition(runnables.size(), n); for (int i = 0; i < parts.length - 1; ++i) { final int part = i; execute(new Runnable() { @Override public void run() { for (int j = parts[part]; j < parts[part + 1]; ++j) { runnables.get(j).run(); } }}); } } } /** * Executes the given {@code runnables} in {@link #getParallelism()} parts. * * @param runnables the runnables to be executed. * @throws NullPointerException if the given runnables are {@code null}. */ public void execute(final List<? extends Runnable> runnables) { execute(getParallelism(), runnables); } /** * Executes the given {@code runnables} in {@code n} parts. * * @param n the number of parts the given {@code runnables} are executed. * @param runnables the runnables to be executed. * @throws NullPointerException if the given runnables are {@code null}. */ public void execute(final int n, final Runnable... runnables) { requireNonNull(runnables, "Runnables must not be null"); if (runnables.length > 0) { final int[] parts = arrays.partition(runnables.length, n); for (int i = 0; i < parts.length - 1; ++i) { final int part = i; execute(new Runnable() { @Override public void run() { for (int j = parts[part]; j < parts[part + 1]; ++j) { runnables[j].run(); } }}); } } } /** * Executes the given {@code runnables} in {@link #getParallelism()} parts. * * @param runnables the runnables to be executed. * @throws NullPointerException if the given runnables are {@code null}. */ public void execute(final Runnable... runnables) { execute(getParallelism(), runnables); } @Override public void close() { if (_parallel) { for (int i = _tasks.size(); --i >= 0;) { _tasks.get(i).join(); } } } }
Improve javadoc.
org.jenetics/src/main/java/org/jenetics/util/Concurrent.java
Improve javadoc.
<ide><path>rg.jenetics/src/main/java/org/jenetics/util/Concurrent.java <ide> * <ide> * @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a> <ide> * @since @__version__@ <del> * @version @__version__@ &mdash; <em>$Date: 2013-10-08 $</em> <add> * @version @__version__@ &mdash; <em>$Date: 2013-10-24 $</em> <ide> */ <ide> public final class Concurrent implements Executor, AutoCloseable { <ide> <add> /* ************************************************************************ <add> * Static concurrent context. <add> * ************************************************************************/ <add> <ide> private static final Object NULL = new Object(); <del> private final int TASKS_SIZE = 15; <ide> <ide> private static final LocalContext.Reference<Object> <ide> FORK_JOIN_POOL = new LocalContext.Reference<Object>(new ForkJoinPool( <ide> return pool != NULL ? (ForkJoinPool)pool : null; <ide> } <ide> <add> <add> /* ************************************************************************ <add> * 'Dynamic' concurrent context. <add> * ************************************************************************/ <add> <add> private final int TASKS_SIZE = 15; <add> <ide> private final ForkJoinPool _pool; <ide> private final List<ForkJoinTask<?>> _tasks = new ArrayList<>(TASKS_SIZE); <ide> private final boolean _parallel; <ide> <add> /** <add> * Create a new {@code Concurrent} executor <i>context</i> with the given <add> * {@link ForkJoinPool}. <add> * <add> * @param pool the {@code ForkJoinPool} used for concurrent execution of the <add> * given tasks. The {@code pool} may be {@code null} and if so, the <add> * given tasks are executed in the main thread. <add> */ <ide> private Concurrent(final ForkJoinPool pool) { <ide> _pool = pool; <ide> _parallel = _pool != null; <ide> } <ide> <add> /** <add> * Create a new {@code Concurrent} executor <i>context</i> with the <add> * {@code ForkJoinPool} set with the {@link #setForkJoinPool(ForkJoinPool)}, <add> * or the default pool, if no one has been set. <add> */ <ide> public Concurrent() { <ide> this(getForkJoinPool()); <ide> }
Java
mit
6bca6c62b09678c76395a1f9fa2aec323ee27483
0
SpongePowered/SpongeCommon,SpongePowered/SpongeCommon,SpongePowered/Sponge,SpongePowered/Sponge,SpongePowered/Sponge
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.entity.player; import com.flowpowered.math.vector.Vector3d; import com.mojang.authlib.GameProfile; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EnumCreatureAttribute; import net.minecraft.entity.IEntityMultiPart; import net.minecraft.entity.MultiPartEntityPart; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.PlayerCapabilities; import net.minecraft.init.Items; import net.minecraft.init.MobEffects; import net.minecraft.init.SoundEvents; import net.minecraft.inventory.Container; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.inventory.InventoryEnderChest; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.play.server.SPacketEntityVelocity; import net.minecraft.scoreboard.Scoreboard; import net.minecraft.scoreboard.Team; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; import net.minecraft.util.CooldownTracker; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.FoodStats; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.LockCode; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.spongepowered.api.Sponge; import org.spongepowered.api.event.CauseStackManager.StackFrame; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.EventContext; import org.spongepowered.api.event.cause.EventContextKeys; import org.spongepowered.api.event.cause.entity.ModifierFunction; import org.spongepowered.api.event.cause.entity.damage.DamageFunction; import org.spongepowered.api.event.cause.entity.damage.DamageModifier; import org.spongepowered.api.event.cause.entity.damage.DamageModifierTypes; import org.spongepowered.api.event.cause.entity.damage.DamageTypes; import org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource; import org.spongepowered.api.event.entity.AttackEntityEvent; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.item.inventory.Slot; import org.spongepowered.api.item.inventory.entity.PlayerInventory; import org.spongepowered.api.item.inventory.property.SlotIndex; import org.spongepowered.api.item.inventory.transaction.SlotTransaction; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.SpongeImplHooks; import org.spongepowered.common.data.manipulator.mutable.entity.SpongeHealthData; import org.spongepowered.common.data.processor.common.ExperienceHolderUtils; import org.spongepowered.common.entity.EntityUtil; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.damage.DamageEventHandler; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.phase.packet.PacketPhase; import org.spongepowered.common.interfaces.ITargetedLocation; import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayer; import org.spongepowered.common.interfaces.entity.player.IMixinInventoryPlayer; import org.spongepowered.common.interfaces.world.IMixinWorld; import org.spongepowered.common.item.inventory.util.ItemStackUtil; import org.spongepowered.common.mixin.core.entity.MixinEntityLivingBase; import org.spongepowered.common.registry.type.event.DamageSourceRegistryModule; import org.spongepowered.common.text.SpongeTexts; import org.spongepowered.common.text.serializer.LegacyTexts; import org.spongepowered.common.util.VecHelper; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import javax.annotation.Nullable; @Mixin(EntityPlayer.class) public abstract class MixinEntityPlayer extends MixinEntityLivingBase implements IMixinEntityPlayer, ITargetedLocation { private static final String WORLD_PLAY_SOUND_AT = "Lnet/minecraft/world/World;playSound(Lnet/minecraft/entity/player/EntityPlayer;DDDLnet/minecraft/util/SoundEvent;Lnet/minecraft/util/SoundCategory;FF)V"; private static final String PLAYER_COLLIDE_ENTITY = "Lnet/minecraft/entity/Entity;onCollideWithPlayer(Lnet/minecraft/entity/player/EntityPlayer;)V"; @Shadow public Container inventoryContainer; @Shadow public Container openContainer; @Shadow public int experienceLevel; @Shadow public int experienceTotal; @Shadow public float experience; @Shadow public PlayerCapabilities capabilities; @Shadow public InventoryPlayer inventory; @Shadow private BlockPos spawnPos; @Shadow private BlockPos bedLocation; @Shadow protected FoodStats foodStats; @Shadow public InventoryEnderChest enderChest; @Shadow public abstract boolean canOpen(LockCode code); @Shadow public abstract boolean isPlayerSleeping(); @Shadow public abstract boolean isSpectator(); @Shadow public abstract int xpBarCap(); @Shadow public abstract float getCooledAttackStrength(float adjustTicks); @Shadow public abstract float getAIMoveSpeed(); @Shadow public abstract void onCriticalHit(net.minecraft.entity.Entity entityHit); @Shadow public abstract void onEnchantmentCritical(net.minecraft.entity.Entity entityHit); // onEnchantmentCritical @Shadow public abstract void addExhaustion(float p_71020_1_); @Shadow public abstract void addStat(StatBase stat, int amount); @Shadow public abstract void addStat(StatBase stat); @Shadow public abstract void resetCooldown(); @Shadow public abstract void spawnSweepParticles(); //spawnSweepParticles() @Shadow public abstract void takeStat(StatBase stat); @Shadow protected abstract void destroyVanishingCursedItems(); // Filter vanishing curse enchanted items @Shadow public abstract void wakeUpPlayer(boolean immediately, boolean updateWorldFlag, boolean setSpawn); @Shadow public abstract EntityItem dropItem(boolean dropAll); @Shadow public abstract FoodStats getFoodStats(); @Shadow public abstract GameProfile getGameProfile(); @Shadow public abstract Scoreboard getWorldScoreboard(); @Shadow public abstract String getName(); @Shadow @Nullable public abstract Team getTeam(); @Shadow public abstract void addExperienceLevel(int levels); @Shadow public abstract void addScore(int scoreIn); @Shadow public abstract CooldownTracker shadow$getCooldownTracker(); @Shadow protected abstract void spawnShoulderEntities(); private boolean affectsSpawning = true; private UUID collidingEntityUuid = null; private Vector3d targetedLocation; private boolean dontRecalculateExperience; private boolean shouldRestoreInventory = false; protected final boolean isFake = SpongeImplHooks.isFakePlayer((EntityPlayer) (Object) this); @Inject(method = "<init>(Lnet/minecraft/world/World;Lcom/mojang/authlib/GameProfile;)V", at = @At("RETURN")) public void construct(World worldIn, GameProfile gameProfileIn, CallbackInfo ci) { this.targetedLocation = VecHelper.toVector3d(worldIn.getSpawnPoint()); } @Inject(method = "getDisplayName", at = @At("RETURN"), cancellable = true) public void onGetDisplayName(CallbackInfoReturnable<ITextComponent> ci) { ci.setReturnValue(LegacyTexts.parseComponent((TextComponentString) ci.getReturnValue(), SpongeTexts.COLOR_CHAR)); } @Override public int getExperienceSinceLevel() { return this.experienceTotal - ExperienceHolderUtils.xpAtLevel(this.experienceLevel); } @Override public void setExperienceSinceLevel(int experience) { this.experienceTotal = ExperienceHolderUtils.xpAtLevel(this.experienceLevel) + experience; this.experience = (float) experience / this.xpBarCap(); } /** * {@link EntityPlayer#addExperienceLevel(int)} doesn't update the total * experience. This recalculates it for plugins to properly make use of it. */ private void recalculateTotalExperience() { if (!this.dontRecalculateExperience) { int newExperienceInLevel = (int) (this.experience * this.xpBarCap()); this.experienceTotal = ExperienceHolderUtils.xpAtLevel(this.experienceLevel) + newExperienceInLevel; this.experience = (float) newExperienceInLevel / this.xpBarCap(); } } @Inject(method = "addExperienceLevel", at = @At("RETURN")) private void onAddExperienceLevels(int levels, CallbackInfo ci) { recalculateTotalExperience(); } /** * @author JBYoshi - May 17, 2017 * @reason This makes the experience updating more accurate and disables * the totalExperience recalculation above for this method, which would * otherwise have weird intermediate states. */ @Overwrite public void addExperience(int amount) { this.addScore(amount); int i = Integer.MAX_VALUE - this.experienceTotal; if (amount > i) { amount = i; } // Sponge start - completely rewritten for integer-based calculations // this.experience += (float)amount / (float)this.xpBarCap(); // for (this.experienceTotal += amount; this.experience >= 1.0F; this.experience /= (float)this.xpBarCap()) { // this.experience = (this.experience - 1.0F) * (float)this.xpBarCap(); // this.addExperienceLevel(1); // } int finalExperience = this.experienceTotal + amount; int finalLevel = ExperienceHolderUtils.getLevelForExp(finalExperience); if (finalLevel != this.experienceLevel) { this.dontRecalculateExperience = true; try { addExperienceLevel(finalLevel - this.experienceLevel); } finally { this.dontRecalculateExperience = false; } } this.experience = (float) (finalExperience - ExperienceHolderUtils.xpAtLevel(finalLevel)) / ExperienceHolderUtils.getExpBetweenLevels(finalLevel); this.experienceTotal = finalExperience; this.experienceLevel = finalLevel; // Sponge end } @Inject(method = "readEntityFromNBT", at = @At("RETURN")) private void recalculateXpOnLoad(NBTTagCompound compound, CallbackInfo ci) { // Fix the mistakes of /xp commands past. recalculateTotalExperience(); } public boolean isFlying() { return this.capabilities.isFlying; } public void setFlying(boolean flying) { this.capabilities.isFlying = flying; } /** * @author blood - May 12th, 2016 * * @reason SpongeForge requires an overwrite so we do it here instead. This handles player death events. */ @Overwrite @Override public void onDeath(DamageSource cause) { super.onDeath(cause); this.setSize(0.2F, 0.2F); this.setPosition(this.posX, this.posY, this.posZ); this.motionY = 0.10000000149011612D; if (this.getName().equals("Notch")) { this.dropItem(new ItemStack(Items.APPLE, 1), true, false); } if (!this.world.getGameRules().getBoolean("keepInventory") && !this.isSpectator()) { this.destroyVanishingCursedItems(); this.inventory.dropAllItems(); } if (cause != null) { this.motionX = (double) (-MathHelper.cos((this.attackedAtYaw + this.rotationYaw) * 0.017453292F) * 0.1F); this.motionZ = (double) (-MathHelper.sin((this.attackedAtYaw + this.rotationYaw) * 0.017453292F) * 0.1F); } else { this.motionX = this.motionZ = 0.0D; } this.addStat(StatList.DEATHS); this.takeStat(StatList.TIME_SINCE_DEATH); this.extinguish(); this.setFlag(0, false); } @Redirect(method = "onUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/EntityPlayer;isPlayerSleeping()Z")) public boolean onIsPlayerSleeping(EntityPlayer self) { if (self.isPlayerSleeping()) { if (!((IMixinWorld) this.world).isFake()) { Sponge.getCauseStackManager().pushCause(this); SpongeImpl.postEvent(SpongeEventFactory. createSleepingEventTick(Sponge.getCauseStackManager().getCurrentCause(), this.getWorld().createSnapshot(VecHelper.toVector3i(this.bedLocation)), this)); Sponge.getCauseStackManager().popCause(); } return true; } return false; } /** * @author gabizou - January 4th, 2016 * * This prevents sounds from being sent to the server by players who are vanish. */ @Redirect(method = "playSound", at = @At(value = "INVOKE", target = WORLD_PLAY_SOUND_AT)) public void playSound(World world, EntityPlayer player, double d1, double d2, double d3, SoundEvent sound, SoundCategory category, float volume, float pitch) { if (!this.isVanished()) { this.world.playSound(player, d1, d2, d3, sound, category, volume, pitch); } } @Override public boolean affectsSpawning() { return this.affectsSpawning && !this.isSpectator(); } @Override public void setAffectsSpawning(boolean affectsSpawning) { this.affectsSpawning = affectsSpawning; } @Override public Vector3d getTargetedLocation() { return this.targetedLocation; } @Override public void setTargetedLocation(@Nullable Vector3d vec) { this.targetedLocation = vec != null ? vec : VecHelper.toVector3d(this.world.getSpawnPoint()); if (!((Object) this instanceof EntityPlayerMP)) { this.world.setSpawnPoint(VecHelper.toBlockPos(this.targetedLocation)); } } /** * @author gabizou - June 13th, 2016 * @reason Reverts the method to flow through our systems, Forge patches * this to throw an ItemTossEvent, but we'll be throwing it regardless in * SpongeForge's handling. * * @param itemStackIn * @param unused * @return */ @Overwrite @Nullable public EntityItem dropItem(ItemStack itemStackIn, boolean unused) { return this.dropItem(itemStackIn, false, false); } /** * @author gabizou - June 4th, 2016 * @reason When a player drops an item, all methods flow through here instead of {@link Entity#dropItem(Item, int)} * because of the idea of {@code dropAround} and {@code traceItem}. * * @param droppedItem * @param dropAround * @param traceItem * @return */ @Nullable @Overwrite public EntityItem dropItem(ItemStack droppedItem, boolean dropAround, boolean traceItem) { if (droppedItem.isEmpty()) { return null; } else if (this.world.isRemote) { double d0 = this.posY - 0.30000001192092896D + (double) this.getEyeHeight(); EntityItem entityitem = new EntityItem(this.world, this.posX, d0, this.posZ, droppedItem); entityitem.setPickupDelay(40); if (traceItem) { entityitem.setThrower(this.getName()); } if (dropAround) { float f = this.rand.nextFloat() * 0.5F; float f1 = this.rand.nextFloat() * ((float) Math.PI * 2F); entityitem.motionX = (double) (-MathHelper.sin(f1) * f); entityitem.motionZ = (double) (MathHelper.cos(f1) * f); entityitem.motionY = 0.20000000298023224D; } else { float f2 = 0.3F; entityitem.motionX = (double) (-MathHelper.sin(this.rotationYaw * 0.017453292F) * MathHelper.cos(this.rotationPitch * 0.017453292F) * f2); entityitem.motionZ = (double) (MathHelper.cos(this.rotationYaw * 0.017453292F) * MathHelper.cos(this.rotationPitch * 0.017453292F) * f2); entityitem.motionY = (double) (-MathHelper.sin(this.rotationPitch * 0.017453292F) * f2 + 0.1F); float f3 = this.rand.nextFloat() * ((float) Math.PI * 2F); f2 = 0.02F * this.rand.nextFloat(); entityitem.motionX += Math.cos((double) f3) * (double) f2; entityitem.motionY += (double) ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.1F); entityitem.motionZ += Math.sin((double) f3) * (double) f2; } ItemStack itemstack = this.dropItemAndGetStack(entityitem); if (traceItem) { if (!itemstack.isEmpty()) { this.addStat(StatList.getDroppedObjectStats(itemstack.getItem()), droppedItem.getCount()); } this.addStat(StatList.DROP); } return entityitem; } else { return EntityUtil.playerDropItem(this, droppedItem, dropAround, traceItem); } } /** * @author gabizou - June 4th, 2016 * @reason Overwrites the original logic to simply pass through to the * PhaseTracker. * * @param entity The entity item to spawn * @return The itemstack */ @SuppressWarnings("OverwriteModifiers") // This is a MinecraftDev thing, since forge elevates the modifier to public @Overwrite @Nullable public ItemStack dropItemAndGetStack(EntityItem entity) { this.world.spawnEntity(entity); return entity.getItem(); } @Redirect(method = "collideWithPlayer", at = @At(value = "INVOKE", target = PLAYER_COLLIDE_ENTITY)) // collideWithPlayer public void onPlayerCollideEntity(net.minecraft.entity.Entity entity, EntityPlayer player) { this.collidingEntityUuid = entity.getUniqueID(); entity.onCollideWithPlayer(player); this.collidingEntityUuid = null; } @Override public UUID getCollidingEntityUuid() { return this.collidingEntityUuid; } /** * @author dualspiral - October 7th, 2016 * * @reason When setting {@link SpongeHealthData#setHealth(double)} to 0, {@link #onDeath(DamageSource)} was * not being called. This check bypasses some of the checks that prevent the superclass method being called * when the {@link DamageSourceRegistryModule#IGNORED_DAMAGE_SOURCE} is being used. */ @Inject(method = "attackEntityFrom", cancellable = true, at = @At(value = "HEAD")) public void onAttackEntityFrom(DamageSource source, float amount, CallbackInfoReturnable<Boolean> cir) { if (source == DamageSourceRegistryModule.IGNORED_DAMAGE_SOURCE) { // Taken from the original method, wake the player up if they are about to die. if (this.isPlayerSleeping() && !this.world.isRemote) { this.wakeUpPlayer(true, true, false); } // We just throw it to the superclass method so that we can potentially get the // onDeath method. cir.setReturnValue(super.attackEntityFrom(source, amount)); } } /** * @author gabizou - April 8th, 2016 * @author gabizou - April 11th, 2016 - Update for 1.9 - This enitre method was rewritten * * * @reason Rewrites the attackTargetEntityWithCurrentItem to throw an {@link AttackEntityEvent} prior * to the ensuing {@link DamageEntityEvent}. This should cover all cases where players are * attacking entities and those entities override {@link EntityLivingBase#attackEntityFrom(DamageSource, float)} * and effectively bypass our damage event hooks. * * LVT Rename Table: * float f | damage | * float f1 | enchantmentDamage | * float f2 | attackStrength | * boolean flag | isStrongAttack | * boolean flag1 | isSprintingAttack | * boolean flag2 | isCriticalAttack | Whether critical particles will spawn and of course, multiply the output damage * boolean flag3 | isSweapingAttack | Whether the player is sweaping an attack and will deal AoE damage * int i | knockbackModifier | The knockback modifier, must be set from the event after it has been thrown * float f4 | targetOriginalHealth | This is initially set as the entity original health * boolean flag4 | litEntityOnFire | This is an internal flag to where if the attack failed, the entity is no longer set on fire * int j | fireAspectModifier | Literally just to check that the weapon used has fire aspect enchantments * double d0 | distanceWalkedDelta | This checks that the distance walked delta is more than the normal walking speed to evaluate if you're making a sweaping attack * double d1 | targetMotionX | Current target entity motion x vector * double d2 | targetMotionY | Current target entity motion y vector * double d3 | targetMotionZ | Current target entity motion z vector * boolean flag5 | attackSucceeded | Whether the attack event succeeded * * @param targetEntity The target entity */ @Overwrite public void attackTargetEntityWithCurrentItem(Entity targetEntity) { // Sponge Start - Add SpongeImpl hook to override in forge as necessary if (!SpongeImplHooks.checkAttackEntity((EntityPlayer) (Object) this, targetEntity)) { return; } // Sponge End if (targetEntity.canBeAttackedWithItem()) { if (!targetEntity.hitByEntity((EntityPlayer) (Object) this)) { // Sponge Start - Prepare our event values // float damage = (float) this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getAttributeValue(); final double originalBaseDamage = this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getAttributeValue(); float damage = (float) originalBaseDamage; // Sponge End float enchantmentDamage = 0.0F; // Spogne Start - Redirect getting enchantments for our damage event handlers // if (targetEntity instanceof EntityLivingBase) { // enchantmentDamage = EnchantmentHelper.getModifierForCreature(this.getHeldItemMainhand(), ((EntityLivingBase) targetEntity).getCreatureAttribute()); // } else { // enchantmentDamage = EnchantmentHelper.getModifierForCreature(this.getHeldItemMainhand(), EnumCreatureAttribute.UNDEFINED); // } float attackStrength = this.getCooledAttackStrength(0.5F); final List<ModifierFunction<DamageModifier>> originalFunctions = new ArrayList<>(); final EnumCreatureAttribute creatureAttribute = targetEntity instanceof EntityLivingBase ? ((EntityLivingBase) targetEntity).getCreatureAttribute() : EnumCreatureAttribute.UNDEFINED; final List<DamageFunction> enchantmentModifierFunctions = DamageEventHandler.createAttackEnchantmentFunction(this.getHeldItemMainhand(), creatureAttribute, attackStrength); // This is kept for the post-damage event handling final List<DamageModifier> enchantmentModifiers = enchantmentModifierFunctions.stream().map(ModifierFunction::getModifier).collect(Collectors.toList()); enchantmentDamage = (float) enchantmentModifierFunctions.stream() .map(ModifierFunction::getFunction) .mapToDouble(function -> function.applyAsDouble(originalBaseDamage)) .sum(); originalFunctions.addAll(enchantmentModifierFunctions); // Sponge End originalFunctions.add(DamageEventHandler.provideCooldownAttackStrengthFunction((EntityPlayer) (Object) this, attackStrength)); damage = damage * (0.2F + attackStrength * attackStrength * 0.8F); enchantmentDamage = enchantmentDamage * attackStrength; this.resetCooldown(); if (damage > 0.0F || enchantmentDamage > 0.0F) { boolean isStrongAttack = attackStrength > 0.9F; boolean isSprintingAttack = false; boolean isCriticalAttack = false; boolean isSweapingAttack = false; int knockbackModifier = 0; knockbackModifier = knockbackModifier + EnchantmentHelper.getKnockbackModifier((EntityPlayer) (Object) this); if (this.isSprinting() && isStrongAttack) { // Sponge - Only play sound after the event has be thrown and not cancelled. // this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.entity_player_attack_knockback, this.getSoundCategory(), 1.0F, 1.0F); ++knockbackModifier; isSprintingAttack = true; } isCriticalAttack = isStrongAttack && this.fallDistance > 0.0F && !this.onGround && !this.isOnLadder() && !this.isInWater() && !this.isPotionActive(MobEffects.BLINDNESS) && !this.isRiding() && targetEntity instanceof EntityLivingBase; isCriticalAttack = isCriticalAttack && !this.isSprinting(); if (isCriticalAttack) { // Sponge Start - add critical attack tuple // damage *= 1.5F; // Sponge - This is handled in the event originalFunctions.add(DamageEventHandler.provideCriticalAttackTuple((EntityPlayer) (Object) this)); // Sponge End } // damage = damage + enchantmentDamage; // Sponge - We don't need this since our event will re-assign the damage to deal double distanceWalkedDelta = (double) (this.distanceWalkedModified - this.prevDistanceWalkedModified); final ItemStack heldItem = this.getHeldItem(EnumHand.MAIN_HAND); if (isStrongAttack && !isCriticalAttack && !isSprintingAttack && this.onGround && distanceWalkedDelta < (double) this.getAIMoveSpeed()) { ItemStack itemstack = heldItem; if (itemstack.getItem() instanceof ItemSword) { isSweapingAttack = true; } } // Sponge Start - Create the event and throw it final DamageSource damageSource = DamageSource.causePlayerDamage((EntityPlayer) (Object) this); final boolean isMainthread = !this.world.isRemote; if (isMainthread) { Sponge.getCauseStackManager().pushCause(damageSource); } final Cause currentCause = isMainthread ? Sponge.getCauseStackManager().getCurrentCause() : Cause.of(EventContext.empty(), damageSource); final AttackEntityEvent event = SpongeEventFactory.createAttackEntityEvent(currentCause, originalFunctions, EntityUtil.fromNative(targetEntity), knockbackModifier, originalBaseDamage); SpongeImpl.postEvent(event); if (isMainthread) { Sponge.getCauseStackManager().popCause(); } if (event.isCancelled()) { return; } damage = (float) event.getFinalOutputDamage(); // sponge - need final for later events final double attackDamage = damage; knockbackModifier = event.getKnockbackModifier(); enchantmentDamage = (float) enchantmentModifiers.stream() .mapToDouble(event::getOutputDamage) .sum(); // Sponge End float targetOriginalHealth = 0.0F; boolean litEntityOnFire = false; int fireAspectModifier = EnchantmentHelper.getFireAspectModifier((EntityPlayer) (Object) this); if (targetEntity instanceof EntityLivingBase) { targetOriginalHealth = ((EntityLivingBase) targetEntity).getHealth(); if (fireAspectModifier > 0 && !targetEntity.isBurning()) { litEntityOnFire = true; targetEntity.setFire(1); } } double targetMotionX = targetEntity.motionX; double targetMotionY = targetEntity.motionY; double targetMotionZ = targetEntity.motionZ; boolean attackSucceeded = targetEntity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) (Object) this), damage); if (attackSucceeded) { if (knockbackModifier > 0) { if (targetEntity instanceof EntityLivingBase) { ((EntityLivingBase) targetEntity).knockBack((EntityPlayer) (Object) this, (float) knockbackModifier * 0.5F, (double) MathHelper.sin(this.rotationYaw * 0.017453292F), (double) (-MathHelper.cos(this.rotationYaw * 0.017453292F))); } else { targetEntity.addVelocity((double) (-MathHelper.sin(this.rotationYaw * 0.017453292F) * (float) knockbackModifier * 0.5F), 0.1D, (double) (MathHelper.cos(this.rotationYaw * 0.017453292F) * (float) knockbackModifier * 0.5F)); } this.motionX *= 0.6D; this.motionZ *= 0.6D; this.setSprinting(false); } if (isSweapingAttack) { for (EntityLivingBase entitylivingbase : this.world.getEntitiesWithinAABB(EntityLivingBase.class, targetEntity.getEntityBoundingBox().grow(1.0D, 0.25D, 1.0D))) { if (entitylivingbase != (EntityPlayer) (Object) this && entitylivingbase != targetEntity && !this.isOnSameTeam(entitylivingbase) && this.getDistanceSq(entitylivingbase) < 9.0D) { // Sponge Start - Do a small event for these entities // entitylivingbase.knockBack(this, 0.4F, (double)MathHelper.sin(this.rotationYaw * 0.017453292F), (double)(-MathHelper.cos(this.rotationYaw * 0.017453292F))); // entitylivingbase.attackEntityFrom(DamageSource.causePlayerDamage(this), 1.0F); final EntityDamageSource sweepingAttackSource = EntityDamageSource.builder().entity(this).type(DamageTypes.SWEEPING_ATTACK).build(); try (final StackFrame frame = isMainthread ? Sponge.getCauseStackManager().pushCauseFrame() : null) { if (isMainthread) { Sponge.getCauseStackManager().pushCause(sweepingAttackSource); } final ItemStackSnapshot heldSnapshot = ItemStackUtil.snapshotOf(heldItem); if (isMainthread) { Sponge.getCauseStackManager().addContext(EventContextKeys.WEAPON, heldSnapshot); } final DamageFunction sweapingFunction = DamageFunction.of(DamageModifier.builder() .cause(Cause.of(EventContext.empty(), heldSnapshot)) .item(heldSnapshot) .type(DamageModifierTypes.SWEEPING) .build(), (incoming) -> EnchantmentHelper.getSweepingDamageRatio((EntityPlayer) (Object) this) * attackDamage); final List<DamageFunction> sweapingFunctions = new ArrayList<>(); sweapingFunctions.add(sweapingFunction); AttackEntityEvent sweepingAttackEvent = SpongeEventFactory.createAttackEntityEvent( currentCause, sweapingFunctions, EntityUtil.fromNative(entitylivingbase), 1, 1.0D); SpongeImpl.postEvent(sweepingAttackEvent); if (!sweepingAttackEvent.isCancelled()) { entitylivingbase .knockBack((EntityPlayer) (Object) this, sweepingAttackEvent.getKnockbackModifier() * 0.4F, (double) MathHelper.sin(this.rotationYaw * 0.017453292F), (double) (-MathHelper.cos(this.rotationYaw * 0.017453292F))); entitylivingbase.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) (Object) this), (float) sweepingAttackEvent.getFinalOutputDamage()); } } // Sponge End } } this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_SWEEP, this.getSoundCategory(), 1.0F, 1.0F); this.spawnSweepParticles(); } if (targetEntity instanceof EntityPlayerMP && targetEntity.velocityChanged) { ((EntityPlayerMP) targetEntity).connection.sendPacket(new SPacketEntityVelocity(targetEntity)); targetEntity.velocityChanged = false; targetEntity.motionX = targetMotionX; targetEntity.motionY = targetMotionY; targetEntity.motionZ = targetMotionZ; } if (isCriticalAttack) { this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_CRIT, this.getSoundCategory(), 1.0F, 1.0F); this.onCriticalHit(targetEntity); } if (!isCriticalAttack && !isSweapingAttack) { if (isStrongAttack) { this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_STRONG, this.getSoundCategory(), 1.0F, 1.0F); } else { this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_WEAK , this.getSoundCategory(), 1.0F, 1.0F); } } if (enchantmentDamage > 0.0F) { this.onEnchantmentCritical(targetEntity); } this.setLastAttackedEntity(targetEntity); if (targetEntity instanceof EntityLivingBase) { EnchantmentHelper.applyThornEnchantments((EntityLivingBase) targetEntity, (EntityPlayer) (Object) this); } EnchantmentHelper.applyArthropodEnchantments((EntityPlayer) (Object) this, targetEntity); ItemStack itemstack1 = this.getHeldItemMainhand(); Entity entity = targetEntity; if (targetEntity instanceof MultiPartEntityPart) { IEntityMultiPart ientitymultipart = ((MultiPartEntityPart) targetEntity).parent; if (ientitymultipart instanceof EntityLivingBase) { entity = (EntityLivingBase) ientitymultipart; } } if(!itemstack1.isEmpty() && targetEntity instanceof EntityLivingBase) { itemstack1.hitEntity((EntityLivingBase)targetEntity, (EntityPlayer) (Object) this); if(itemstack1.isEmpty()) { this.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY); } } if (targetEntity instanceof EntityLivingBase) { float f5 = targetOriginalHealth - ((EntityLivingBase) targetEntity).getHealth(); this.addStat(StatList.DAMAGE_DEALT, Math.round(f5 * 10.0F)); if (fireAspectModifier > 0) { targetEntity.setFire(fireAspectModifier * 4); } if (this.world instanceof WorldServer && f5 > 2.0F) { int k = (int) ((double) f5 * 0.5D); ((WorldServer) this.world).spawnParticle(EnumParticleTypes.DAMAGE_INDICATOR, targetEntity.posX, targetEntity.posY + (double) (targetEntity.height * 0.5F), targetEntity.posZ, k, 0.1D, 0.0D, 0.1D, 0.2D, new int[0]); } } this.addExhaustion(0.3F); } else { this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_NODAMAGE, this.getSoundCategory(), 1.0F, 1.0F); if (litEntityOnFire) { targetEntity.extinguish(); } } } } } } @Inject(method = "setItemStackToSlot", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/NonNullList;set(ILjava/lang/Object;)Ljava/lang/Object;")) private void onSetItemStackToSlot(EntityEquipmentSlot slotIn, ItemStack stack, CallbackInfo ci) { if (((IMixinInventoryPlayer) this.inventory).capturesTransactions()) { if (slotIn == EntityEquipmentSlot.MAINHAND) { ItemStack orig = this.inventory.mainInventory.get(this.inventory.currentItem); Slot slot = ((PlayerInventory) this.inventory).getMain().getHotbar().getSlot(SlotIndex.of(this.inventory.currentItem)).get(); ((IMixinInventoryPlayer) this.inventory).getCapturedTransactions().add(new SlotTransaction(slot, ItemStackUtil.snapshotOf(orig), ItemStackUtil.snapshotOf(stack))); } else if (slotIn == EntityEquipmentSlot.OFFHAND) { ItemStack orig = this.inventory.offHandInventory.get(0); Slot slot = ((PlayerInventory) this.inventory).getOffhand(); ((IMixinInventoryPlayer) this.inventory).getCapturedTransactions().add(new SlotTransaction(slot, ItemStackUtil.snapshotOf(orig), ItemStackUtil.snapshotOf(stack))); } else if (slotIn.getSlotType() == EntityEquipmentSlot.Type.ARMOR) { ItemStack orig = this.inventory.armorInventory.get(slotIn.getIndex()); Slot slot = ((PlayerInventory) this.inventory).getEquipment().getSlot(SlotIndex.of(slotIn.getIndex())).get(); ((IMixinInventoryPlayer) this.inventory).getCapturedTransactions().add(new SlotTransaction(slot, ItemStackUtil.snapshotOf(orig), ItemStackUtil.snapshotOf(stack))); } } } @Redirect(method = "setDead", at = @At(value = "INVOKE", ordinal = 1, target = "Lnet/minecraft/inventory/Container;onContainerClosed(Lnet/minecraft/entity/player/EntityPlayer;)V")) private void onOnContainerClosed(Container container, EntityPlayer player) { try (PhaseContext<?> ctx = PacketPhase.General.CLOSE_WINDOW.createPhaseContext() .source(player) .packetPlayer(player instanceof EntityPlayerMP ? ((EntityPlayerMP) player) : null) .openContainer(container) // intentionally missing the lastCursor to not double throw close event .buildAndSwitch(); StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(player); ItemStackSnapshot cursor = ItemStackUtil.snapshotOf(this.inventory.getItemStack()); container.onContainerClosed(player); SpongeCommonEventFactory.callInteractInventoryCloseEvent(this.openContainer, (EntityPlayerMP) (Object) this, cursor, ItemStackSnapshot.NONE, false); } } @Override public void shouldRestoreInventory(boolean restore) { this.shouldRestoreInventory = restore; } @Override public boolean shouldRestoreInventory() { return this.shouldRestoreInventory; } }
src/main/java/org/spongepowered/common/mixin/core/entity/player/MixinEntityPlayer.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.entity.player; import com.flowpowered.math.vector.Vector3d; import com.mojang.authlib.GameProfile; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EnumCreatureAttribute; import net.minecraft.entity.IEntityMultiPart; import net.minecraft.entity.MultiPartEntityPart; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.PlayerCapabilities; import net.minecraft.init.Items; import net.minecraft.init.MobEffects; import net.minecraft.init.SoundEvents; import net.minecraft.inventory.Container; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.inventory.InventoryEnderChest; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.play.server.SPacketEntityVelocity; import net.minecraft.scoreboard.Scoreboard; import net.minecraft.scoreboard.Team; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; import net.minecraft.util.CooldownTracker; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.FoodStats; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.LockCode; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.spongepowered.api.Sponge; import org.spongepowered.api.event.CauseStackManager.StackFrame; import org.spongepowered.api.event.SpongeEventFactory; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.cause.EventContext; import org.spongepowered.api.event.cause.EventContextKeys; import org.spongepowered.api.event.cause.entity.ModifierFunction; import org.spongepowered.api.event.cause.entity.damage.DamageFunction; import org.spongepowered.api.event.cause.entity.damage.DamageModifier; import org.spongepowered.api.event.cause.entity.damage.DamageModifierTypes; import org.spongepowered.api.event.cause.entity.damage.DamageTypes; import org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource; import org.spongepowered.api.event.entity.AttackEntityEvent; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.item.inventory.Slot; import org.spongepowered.api.item.inventory.entity.PlayerInventory; import org.spongepowered.api.item.inventory.property.SlotIndex; import org.spongepowered.api.item.inventory.transaction.SlotTransaction; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.SpongeImplHooks; import org.spongepowered.common.data.manipulator.mutable.entity.SpongeHealthData; import org.spongepowered.common.data.processor.common.ExperienceHolderUtils; import org.spongepowered.common.entity.EntityUtil; import org.spongepowered.common.event.damage.DamageEventHandler; import org.spongepowered.common.interfaces.ITargetedLocation; import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayer; import org.spongepowered.common.interfaces.entity.player.IMixinInventoryPlayer; import org.spongepowered.common.interfaces.world.IMixinWorld; import org.spongepowered.common.item.inventory.util.ItemStackUtil; import org.spongepowered.common.mixin.core.entity.MixinEntityLivingBase; import org.spongepowered.common.registry.type.event.DamageSourceRegistryModule; import org.spongepowered.common.text.SpongeTexts; import org.spongepowered.common.text.serializer.LegacyTexts; import org.spongepowered.common.util.VecHelper; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import javax.annotation.Nullable; @Mixin(EntityPlayer.class) public abstract class MixinEntityPlayer extends MixinEntityLivingBase implements IMixinEntityPlayer, ITargetedLocation { private static final String WORLD_PLAY_SOUND_AT = "Lnet/minecraft/world/World;playSound(Lnet/minecraft/entity/player/EntityPlayer;DDDLnet/minecraft/util/SoundEvent;Lnet/minecraft/util/SoundCategory;FF)V"; private static final String PLAYER_COLLIDE_ENTITY = "Lnet/minecraft/entity/Entity;onCollideWithPlayer(Lnet/minecraft/entity/player/EntityPlayer;)V"; @Shadow public Container inventoryContainer; @Shadow public Container openContainer; @Shadow public int experienceLevel; @Shadow public int experienceTotal; @Shadow public float experience; @Shadow public PlayerCapabilities capabilities; @Shadow public InventoryPlayer inventory; @Shadow private BlockPos spawnPos; @Shadow private BlockPos bedLocation; @Shadow protected FoodStats foodStats; @Shadow public InventoryEnderChest enderChest; @Shadow public abstract boolean canOpen(LockCode code); @Shadow public abstract boolean isPlayerSleeping(); @Shadow public abstract boolean isSpectator(); @Shadow public abstract int xpBarCap(); @Shadow public abstract float getCooledAttackStrength(float adjustTicks); @Shadow public abstract float getAIMoveSpeed(); @Shadow public abstract void onCriticalHit(net.minecraft.entity.Entity entityHit); @Shadow public abstract void onEnchantmentCritical(net.minecraft.entity.Entity entityHit); // onEnchantmentCritical @Shadow public abstract void addExhaustion(float p_71020_1_); @Shadow public abstract void addStat(StatBase stat, int amount); @Shadow public abstract void addStat(StatBase stat); @Shadow public abstract void resetCooldown(); @Shadow public abstract void spawnSweepParticles(); //spawnSweepParticles() @Shadow public abstract void takeStat(StatBase stat); @Shadow protected abstract void destroyVanishingCursedItems(); // Filter vanishing curse enchanted items @Shadow public abstract void wakeUpPlayer(boolean immediately, boolean updateWorldFlag, boolean setSpawn); @Shadow public abstract EntityItem dropItem(boolean dropAll); @Shadow public abstract FoodStats getFoodStats(); @Shadow public abstract GameProfile getGameProfile(); @Shadow public abstract Scoreboard getWorldScoreboard(); @Shadow public abstract String getName(); @Shadow @Nullable public abstract Team getTeam(); @Shadow public abstract void addExperienceLevel(int levels); @Shadow public abstract void addScore(int scoreIn); @Shadow public abstract CooldownTracker shadow$getCooldownTracker(); @Shadow protected abstract void spawnShoulderEntities(); private boolean affectsSpawning = true; private UUID collidingEntityUuid = null; private Vector3d targetedLocation; private boolean dontRecalculateExperience; private boolean shouldRestoreInventory = false; protected final boolean isFake = SpongeImplHooks.isFakePlayer((EntityPlayer) (Object) this); @Inject(method = "<init>(Lnet/minecraft/world/World;Lcom/mojang/authlib/GameProfile;)V", at = @At("RETURN")) public void construct(World worldIn, GameProfile gameProfileIn, CallbackInfo ci) { this.targetedLocation = VecHelper.toVector3d(worldIn.getSpawnPoint()); } @Inject(method = "getDisplayName", at = @At("RETURN"), cancellable = true) public void onGetDisplayName(CallbackInfoReturnable<ITextComponent> ci) { ci.setReturnValue(LegacyTexts.parseComponent((TextComponentString) ci.getReturnValue(), SpongeTexts.COLOR_CHAR)); } @Override public int getExperienceSinceLevel() { return this.experienceTotal - ExperienceHolderUtils.xpAtLevel(this.experienceLevel); } @Override public void setExperienceSinceLevel(int experience) { this.experienceTotal = ExperienceHolderUtils.xpAtLevel(this.experienceLevel) + experience; this.experience = (float) experience / this.xpBarCap(); } /** * {@link EntityPlayer#addExperienceLevel(int)} doesn't update the total * experience. This recalculates it for plugins to properly make use of it. */ private void recalculateTotalExperience() { if (!this.dontRecalculateExperience) { int newExperienceInLevel = (int) (this.experience * this.xpBarCap()); this.experienceTotal = ExperienceHolderUtils.xpAtLevel(this.experienceLevel) + newExperienceInLevel; this.experience = (float) newExperienceInLevel / this.xpBarCap(); } } @Inject(method = "addExperienceLevel", at = @At("RETURN")) private void onAddExperienceLevels(int levels, CallbackInfo ci) { recalculateTotalExperience(); } /** * @author JBYoshi - May 17, 2017 * @reason This makes the experience updating more accurate and disables * the totalExperience recalculation above for this method, which would * otherwise have weird intermediate states. */ @Overwrite public void addExperience(int amount) { this.addScore(amount); int i = Integer.MAX_VALUE - this.experienceTotal; if (amount > i) { amount = i; } // Sponge start - completely rewritten for integer-based calculations // this.experience += (float)amount / (float)this.xpBarCap(); // for (this.experienceTotal += amount; this.experience >= 1.0F; this.experience /= (float)this.xpBarCap()) { // this.experience = (this.experience - 1.0F) * (float)this.xpBarCap(); // this.addExperienceLevel(1); // } int finalExperience = this.experienceTotal + amount; int finalLevel = ExperienceHolderUtils.getLevelForExp(finalExperience); if (finalLevel != this.experienceLevel) { this.dontRecalculateExperience = true; try { addExperienceLevel(finalLevel - this.experienceLevel); } finally { this.dontRecalculateExperience = false; } } this.experience = (float) (finalExperience - ExperienceHolderUtils.xpAtLevel(finalLevel)) / ExperienceHolderUtils.getExpBetweenLevels(finalLevel); this.experienceTotal = finalExperience; this.experienceLevel = finalLevel; // Sponge end } @Inject(method = "readEntityFromNBT", at = @At("RETURN")) private void recalculateXpOnLoad(NBTTagCompound compound, CallbackInfo ci) { // Fix the mistakes of /xp commands past. recalculateTotalExperience(); } public boolean isFlying() { return this.capabilities.isFlying; } public void setFlying(boolean flying) { this.capabilities.isFlying = flying; } /** * @author blood - May 12th, 2016 * * @reason SpongeForge requires an overwrite so we do it here instead. This handles player death events. */ @Overwrite @Override public void onDeath(DamageSource cause) { super.onDeath(cause); this.setSize(0.2F, 0.2F); this.setPosition(this.posX, this.posY, this.posZ); this.motionY = 0.10000000149011612D; if (this.getName().equals("Notch")) { this.dropItem(new ItemStack(Items.APPLE, 1), true, false); } if (!this.world.getGameRules().getBoolean("keepInventory") && !this.isSpectator()) { this.destroyVanishingCursedItems(); this.inventory.dropAllItems(); } if (cause != null) { this.motionX = (double) (-MathHelper.cos((this.attackedAtYaw + this.rotationYaw) * 0.017453292F) * 0.1F); this.motionZ = (double) (-MathHelper.sin((this.attackedAtYaw + this.rotationYaw) * 0.017453292F) * 0.1F); } else { this.motionX = this.motionZ = 0.0D; } this.addStat(StatList.DEATHS); this.takeStat(StatList.TIME_SINCE_DEATH); this.extinguish(); this.setFlag(0, false); } @Redirect(method = "onUpdate", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/EntityPlayer;isPlayerSleeping()Z")) public boolean onIsPlayerSleeping(EntityPlayer self) { if (self.isPlayerSleeping()) { if (!((IMixinWorld) this.world).isFake()) { Sponge.getCauseStackManager().pushCause(this); SpongeImpl.postEvent(SpongeEventFactory. createSleepingEventTick(Sponge.getCauseStackManager().getCurrentCause(), this.getWorld().createSnapshot(VecHelper.toVector3i(this.bedLocation)), this)); Sponge.getCauseStackManager().popCause(); } return true; } return false; } /** * @author gabizou - January 4th, 2016 * * This prevents sounds from being sent to the server by players who are vanish. */ @Redirect(method = "playSound", at = @At(value = "INVOKE", target = WORLD_PLAY_SOUND_AT)) public void playSound(World world, EntityPlayer player, double d1, double d2, double d3, SoundEvent sound, SoundCategory category, float volume, float pitch) { if (!this.isVanished()) { this.world.playSound(player, d1, d2, d3, sound, category, volume, pitch); } } @Override public boolean affectsSpawning() { return this.affectsSpawning && !this.isSpectator(); } @Override public void setAffectsSpawning(boolean affectsSpawning) { this.affectsSpawning = affectsSpawning; } @Override public Vector3d getTargetedLocation() { return this.targetedLocation; } @Override public void setTargetedLocation(@Nullable Vector3d vec) { this.targetedLocation = vec != null ? vec : VecHelper.toVector3d(this.world.getSpawnPoint()); if (!((Object) this instanceof EntityPlayerMP)) { this.world.setSpawnPoint(VecHelper.toBlockPos(this.targetedLocation)); } } /** * @author gabizou - June 13th, 2016 * @reason Reverts the method to flow through our systems, Forge patches * this to throw an ItemTossEvent, but we'll be throwing it regardless in * SpongeForge's handling. * * @param itemStackIn * @param unused * @return */ @Overwrite @Nullable public EntityItem dropItem(ItemStack itemStackIn, boolean unused) { return this.dropItem(itemStackIn, false, false); } /** * @author gabizou - June 4th, 2016 * @reason When a player drops an item, all methods flow through here instead of {@link Entity#dropItem(Item, int)} * because of the idea of {@code dropAround} and {@code traceItem}. * * @param droppedItem * @param dropAround * @param traceItem * @return */ @Nullable @Overwrite public EntityItem dropItem(ItemStack droppedItem, boolean dropAround, boolean traceItem) { if (droppedItem.isEmpty()) { return null; } else if (this.world.isRemote) { double d0 = this.posY - 0.30000001192092896D + (double) this.getEyeHeight(); EntityItem entityitem = new EntityItem(this.world, this.posX, d0, this.posZ, droppedItem); entityitem.setPickupDelay(40); if (traceItem) { entityitem.setThrower(this.getName()); } if (dropAround) { float f = this.rand.nextFloat() * 0.5F; float f1 = this.rand.nextFloat() * ((float) Math.PI * 2F); entityitem.motionX = (double) (-MathHelper.sin(f1) * f); entityitem.motionZ = (double) (MathHelper.cos(f1) * f); entityitem.motionY = 0.20000000298023224D; } else { float f2 = 0.3F; entityitem.motionX = (double) (-MathHelper.sin(this.rotationYaw * 0.017453292F) * MathHelper.cos(this.rotationPitch * 0.017453292F) * f2); entityitem.motionZ = (double) (MathHelper.cos(this.rotationYaw * 0.017453292F) * MathHelper.cos(this.rotationPitch * 0.017453292F) * f2); entityitem.motionY = (double) (-MathHelper.sin(this.rotationPitch * 0.017453292F) * f2 + 0.1F); float f3 = this.rand.nextFloat() * ((float) Math.PI * 2F); f2 = 0.02F * this.rand.nextFloat(); entityitem.motionX += Math.cos((double) f3) * (double) f2; entityitem.motionY += (double) ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.1F); entityitem.motionZ += Math.sin((double) f3) * (double) f2; } ItemStack itemstack = this.dropItemAndGetStack(entityitem); if (traceItem) { if (!itemstack.isEmpty()) { this.addStat(StatList.getDroppedObjectStats(itemstack.getItem()), droppedItem.getCount()); } this.addStat(StatList.DROP); } return entityitem; } else { return EntityUtil.playerDropItem(this, droppedItem, dropAround, traceItem); } } /** * @author gabizou - June 4th, 2016 * @reason Overwrites the original logic to simply pass through to the * PhaseTracker. * * @param entity The entity item to spawn * @return The itemstack */ @SuppressWarnings("OverwriteModifiers") // This is a MinecraftDev thing, since forge elevates the modifier to public @Overwrite @Nullable public ItemStack dropItemAndGetStack(EntityItem entity) { this.world.spawnEntity(entity); return entity.getItem(); } @Redirect(method = "collideWithPlayer", at = @At(value = "INVOKE", target = PLAYER_COLLIDE_ENTITY)) // collideWithPlayer public void onPlayerCollideEntity(net.minecraft.entity.Entity entity, EntityPlayer player) { this.collidingEntityUuid = entity.getUniqueID(); entity.onCollideWithPlayer(player); this.collidingEntityUuid = null; } @Override public UUID getCollidingEntityUuid() { return this.collidingEntityUuid; } /** * @author dualspiral - October 7th, 2016 * * @reason When setting {@link SpongeHealthData#setHealth(double)} to 0, {@link #onDeath(DamageSource)} was * not being called. This check bypasses some of the checks that prevent the superclass method being called * when the {@link DamageSourceRegistryModule#IGNORED_DAMAGE_SOURCE} is being used. */ @Inject(method = "attackEntityFrom", cancellable = true, at = @At(value = "HEAD")) public void onAttackEntityFrom(DamageSource source, float amount, CallbackInfoReturnable<Boolean> cir) { if (source == DamageSourceRegistryModule.IGNORED_DAMAGE_SOURCE) { // Taken from the original method, wake the player up if they are about to die. if (this.isPlayerSleeping() && !this.world.isRemote) { this.wakeUpPlayer(true, true, false); } // We just throw it to the superclass method so that we can potentially get the // onDeath method. cir.setReturnValue(super.attackEntityFrom(source, amount)); } } /** * @author gabizou - April 8th, 2016 * @author gabizou - April 11th, 2016 - Update for 1.9 - This enitre method was rewritten * * * @reason Rewrites the attackTargetEntityWithCurrentItem to throw an {@link AttackEntityEvent} prior * to the ensuing {@link DamageEntityEvent}. This should cover all cases where players are * attacking entities and those entities override {@link EntityLivingBase#attackEntityFrom(DamageSource, float)} * and effectively bypass our damage event hooks. * * LVT Rename Table: * float f | damage | * float f1 | enchantmentDamage | * float f2 | attackStrength | * boolean flag | isStrongAttack | * boolean flag1 | isSprintingAttack | * boolean flag2 | isCriticalAttack | Whether critical particles will spawn and of course, multiply the output damage * boolean flag3 | isSweapingAttack | Whether the player is sweaping an attack and will deal AoE damage * int i | knockbackModifier | The knockback modifier, must be set from the event after it has been thrown * float f4 | targetOriginalHealth | This is initially set as the entity original health * boolean flag4 | litEntityOnFire | This is an internal flag to where if the attack failed, the entity is no longer set on fire * int j | fireAspectModifier | Literally just to check that the weapon used has fire aspect enchantments * double d0 | distanceWalkedDelta | This checks that the distance walked delta is more than the normal walking speed to evaluate if you're making a sweaping attack * double d1 | targetMotionX | Current target entity motion x vector * double d2 | targetMotionY | Current target entity motion y vector * double d3 | targetMotionZ | Current target entity motion z vector * boolean flag5 | attackSucceeded | Whether the attack event succeeded * * @param targetEntity The target entity */ @Overwrite public void attackTargetEntityWithCurrentItem(Entity targetEntity) { // Sponge Start - Add SpongeImpl hook to override in forge as necessary if (!SpongeImplHooks.checkAttackEntity((EntityPlayer) (Object) this, targetEntity)) { return; } // Sponge End if (targetEntity.canBeAttackedWithItem()) { if (!targetEntity.hitByEntity((EntityPlayer) (Object) this)) { // Sponge Start - Prepare our event values // float damage = (float) this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getAttributeValue(); final double originalBaseDamage = this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getAttributeValue(); float damage = (float) originalBaseDamage; // Sponge End float enchantmentDamage = 0.0F; // Spogne Start - Redirect getting enchantments for our damage event handlers // if (targetEntity instanceof EntityLivingBase) { // enchantmentDamage = EnchantmentHelper.getModifierForCreature(this.getHeldItemMainhand(), ((EntityLivingBase) targetEntity).getCreatureAttribute()); // } else { // enchantmentDamage = EnchantmentHelper.getModifierForCreature(this.getHeldItemMainhand(), EnumCreatureAttribute.UNDEFINED); // } float attackStrength = this.getCooledAttackStrength(0.5F); final List<ModifierFunction<DamageModifier>> originalFunctions = new ArrayList<>(); final EnumCreatureAttribute creatureAttribute = targetEntity instanceof EntityLivingBase ? ((EntityLivingBase) targetEntity).getCreatureAttribute() : EnumCreatureAttribute.UNDEFINED; final List<DamageFunction> enchantmentModifierFunctions = DamageEventHandler.createAttackEnchantmentFunction(this.getHeldItemMainhand(), creatureAttribute, attackStrength); // This is kept for the post-damage event handling final List<DamageModifier> enchantmentModifiers = enchantmentModifierFunctions.stream().map(ModifierFunction::getModifier).collect(Collectors.toList()); enchantmentDamage = (float) enchantmentModifierFunctions.stream() .map(ModifierFunction::getFunction) .mapToDouble(function -> function.applyAsDouble(originalBaseDamage)) .sum(); originalFunctions.addAll(enchantmentModifierFunctions); // Sponge End originalFunctions.add(DamageEventHandler.provideCooldownAttackStrengthFunction((EntityPlayer) (Object) this, attackStrength)); damage = damage * (0.2F + attackStrength * attackStrength * 0.8F); enchantmentDamage = enchantmentDamage * attackStrength; this.resetCooldown(); if (damage > 0.0F || enchantmentDamage > 0.0F) { boolean isStrongAttack = attackStrength > 0.9F; boolean isSprintingAttack = false; boolean isCriticalAttack = false; boolean isSweapingAttack = false; int knockbackModifier = 0; knockbackModifier = knockbackModifier + EnchantmentHelper.getKnockbackModifier((EntityPlayer) (Object) this); if (this.isSprinting() && isStrongAttack) { // Sponge - Only play sound after the event has be thrown and not cancelled. // this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.entity_player_attack_knockback, this.getSoundCategory(), 1.0F, 1.0F); ++knockbackModifier; isSprintingAttack = true; } isCriticalAttack = isStrongAttack && this.fallDistance > 0.0F && !this.onGround && !this.isOnLadder() && !this.isInWater() && !this.isPotionActive(MobEffects.BLINDNESS) && !this.isRiding() && targetEntity instanceof EntityLivingBase; isCriticalAttack = isCriticalAttack && !this.isSprinting(); if (isCriticalAttack) { // Sponge Start - add critical attack tuple // damage *= 1.5F; // Sponge - This is handled in the event originalFunctions.add(DamageEventHandler.provideCriticalAttackTuple((EntityPlayer) (Object) this)); // Sponge End } // damage = damage + enchantmentDamage; // Sponge - We don't need this since our event will re-assign the damage to deal double distanceWalkedDelta = (double) (this.distanceWalkedModified - this.prevDistanceWalkedModified); final ItemStack heldItem = this.getHeldItem(EnumHand.MAIN_HAND); if (isStrongAttack && !isCriticalAttack && !isSprintingAttack && this.onGround && distanceWalkedDelta < (double) this.getAIMoveSpeed()) { ItemStack itemstack = heldItem; if (itemstack.getItem() instanceof ItemSword) { isSweapingAttack = true; } } // Sponge Start - Create the event and throw it final DamageSource damageSource = DamageSource.causePlayerDamage((EntityPlayer) (Object) this); final boolean isMainthread = !this.world.isRemote; if (isMainthread) { Sponge.getCauseStackManager().pushCause(damageSource); } final Cause currentCause = isMainthread ? Sponge.getCauseStackManager().getCurrentCause() : Cause.of(EventContext.empty(), damageSource); final AttackEntityEvent event = SpongeEventFactory.createAttackEntityEvent(currentCause, originalFunctions, EntityUtil.fromNative(targetEntity), knockbackModifier, originalBaseDamage); SpongeImpl.postEvent(event); if (isMainthread) { Sponge.getCauseStackManager().popCause(); } if (event.isCancelled()) { return; } damage = (float) event.getFinalOutputDamage(); // sponge - need final for later events final double attackDamage = damage; knockbackModifier = event.getKnockbackModifier(); enchantmentDamage = (float) enchantmentModifiers.stream() .mapToDouble(event::getOutputDamage) .sum(); // Sponge End float targetOriginalHealth = 0.0F; boolean litEntityOnFire = false; int fireAspectModifier = EnchantmentHelper.getFireAspectModifier((EntityPlayer) (Object) this); if (targetEntity instanceof EntityLivingBase) { targetOriginalHealth = ((EntityLivingBase) targetEntity).getHealth(); if (fireAspectModifier > 0 && !targetEntity.isBurning()) { litEntityOnFire = true; targetEntity.setFire(1); } } double targetMotionX = targetEntity.motionX; double targetMotionY = targetEntity.motionY; double targetMotionZ = targetEntity.motionZ; boolean attackSucceeded = targetEntity.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) (Object) this), damage); if (attackSucceeded) { if (knockbackModifier > 0) { if (targetEntity instanceof EntityLivingBase) { ((EntityLivingBase) targetEntity).knockBack((EntityPlayer) (Object) this, (float) knockbackModifier * 0.5F, (double) MathHelper.sin(this.rotationYaw * 0.017453292F), (double) (-MathHelper.cos(this.rotationYaw * 0.017453292F))); } else { targetEntity.addVelocity((double) (-MathHelper.sin(this.rotationYaw * 0.017453292F) * (float) knockbackModifier * 0.5F), 0.1D, (double) (MathHelper.cos(this.rotationYaw * 0.017453292F) * (float) knockbackModifier * 0.5F)); } this.motionX *= 0.6D; this.motionZ *= 0.6D; this.setSprinting(false); } if (isSweapingAttack) { for (EntityLivingBase entitylivingbase : this.world.getEntitiesWithinAABB(EntityLivingBase.class, targetEntity.getEntityBoundingBox().grow(1.0D, 0.25D, 1.0D))) { if (entitylivingbase != (EntityPlayer) (Object) this && entitylivingbase != targetEntity && !this.isOnSameTeam(entitylivingbase) && this.getDistanceSq(entitylivingbase) < 9.0D) { // Sponge Start - Do a small event for these entities // entitylivingbase.knockBack(this, 0.4F, (double)MathHelper.sin(this.rotationYaw * 0.017453292F), (double)(-MathHelper.cos(this.rotationYaw * 0.017453292F))); // entitylivingbase.attackEntityFrom(DamageSource.causePlayerDamage(this), 1.0F); final EntityDamageSource sweepingAttackSource = EntityDamageSource.builder().entity(this).type(DamageTypes.SWEEPING_ATTACK).build(); try (final StackFrame frame = isMainthread ? Sponge.getCauseStackManager().pushCauseFrame() : null) { if (isMainthread) { Sponge.getCauseStackManager().pushCause(sweepingAttackSource); } final ItemStackSnapshot heldSnapshot = ItemStackUtil.snapshotOf(heldItem); if (isMainthread) { Sponge.getCauseStackManager().addContext(EventContextKeys.WEAPON, heldSnapshot); } final DamageFunction sweapingFunction = DamageFunction.of(DamageModifier.builder() .cause(Cause.of(EventContext.empty(), heldSnapshot)) .item(heldSnapshot) .type(DamageModifierTypes.SWEEPING) .build(), (incoming) -> EnchantmentHelper.getSweepingDamageRatio((EntityPlayer) (Object) this) * attackDamage); final List<DamageFunction> sweapingFunctions = new ArrayList<>(); sweapingFunctions.add(sweapingFunction); AttackEntityEvent sweepingAttackEvent = SpongeEventFactory.createAttackEntityEvent( currentCause, sweapingFunctions, EntityUtil.fromNative(entitylivingbase), 1, 1.0D); SpongeImpl.postEvent(sweepingAttackEvent); if (!sweepingAttackEvent.isCancelled()) { entitylivingbase .knockBack((EntityPlayer) (Object) this, sweepingAttackEvent.getKnockbackModifier() * 0.4F, (double) MathHelper.sin(this.rotationYaw * 0.017453292F), (double) (-MathHelper.cos(this.rotationYaw * 0.017453292F))); entitylivingbase.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) (Object) this), (float) sweepingAttackEvent.getFinalOutputDamage()); } } // Sponge End } } this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_SWEEP, this.getSoundCategory(), 1.0F, 1.0F); this.spawnSweepParticles(); } if (targetEntity instanceof EntityPlayerMP && targetEntity.velocityChanged) { ((EntityPlayerMP) targetEntity).connection.sendPacket(new SPacketEntityVelocity(targetEntity)); targetEntity.velocityChanged = false; targetEntity.motionX = targetMotionX; targetEntity.motionY = targetMotionY; targetEntity.motionZ = targetMotionZ; } if (isCriticalAttack) { this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_CRIT, this.getSoundCategory(), 1.0F, 1.0F); this.onCriticalHit(targetEntity); } if (!isCriticalAttack && !isSweapingAttack) { if (isStrongAttack) { this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_STRONG, this.getSoundCategory(), 1.0F, 1.0F); } else { this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_WEAK , this.getSoundCategory(), 1.0F, 1.0F); } } if (enchantmentDamage > 0.0F) { this.onEnchantmentCritical(targetEntity); } this.setLastAttackedEntity(targetEntity); if (targetEntity instanceof EntityLivingBase) { EnchantmentHelper.applyThornEnchantments((EntityLivingBase) targetEntity, (EntityPlayer) (Object) this); } EnchantmentHelper.applyArthropodEnchantments((EntityPlayer) (Object) this, targetEntity); ItemStack itemstack1 = this.getHeldItemMainhand(); Entity entity = targetEntity; if (targetEntity instanceof MultiPartEntityPart) { IEntityMultiPart ientitymultipart = ((MultiPartEntityPart) targetEntity).parent; if (ientitymultipart instanceof EntityLivingBase) { entity = (EntityLivingBase) ientitymultipart; } } if(!itemstack1.isEmpty() && targetEntity instanceof EntityLivingBase) { itemstack1.hitEntity((EntityLivingBase)targetEntity, (EntityPlayer) (Object) this); if(itemstack1.isEmpty()) { this.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY); } } if (targetEntity instanceof EntityLivingBase) { float f5 = targetOriginalHealth - ((EntityLivingBase) targetEntity).getHealth(); this.addStat(StatList.DAMAGE_DEALT, Math.round(f5 * 10.0F)); if (fireAspectModifier > 0) { targetEntity.setFire(fireAspectModifier * 4); } if (this.world instanceof WorldServer && f5 > 2.0F) { int k = (int) ((double) f5 * 0.5D); ((WorldServer) this.world).spawnParticle(EnumParticleTypes.DAMAGE_INDICATOR, targetEntity.posX, targetEntity.posY + (double) (targetEntity.height * 0.5F), targetEntity.posZ, k, 0.1D, 0.0D, 0.1D, 0.2D, new int[0]); } } this.addExhaustion(0.3F); } else { this.world.playSound((EntityPlayer) null, this.posX, this.posY, this.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_NODAMAGE, this.getSoundCategory(), 1.0F, 1.0F); if (litEntityOnFire) { targetEntity.extinguish(); } } } } } } @Inject(method = "setItemStackToSlot", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/NonNullList;set(ILjava/lang/Object;)Ljava/lang/Object;")) private void onSetItemStackToSlot(EntityEquipmentSlot slotIn, ItemStack stack, CallbackInfo ci) { if (((IMixinInventoryPlayer) this.inventory).capturesTransactions()) { if (slotIn == EntityEquipmentSlot.MAINHAND) { ItemStack orig = this.inventory.mainInventory.get(this.inventory.currentItem); Slot slot = ((PlayerInventory) this.inventory).getMain().getHotbar().getSlot(SlotIndex.of(this.inventory.currentItem)).get(); ((IMixinInventoryPlayer) this.inventory).getCapturedTransactions().add(new SlotTransaction(slot, ItemStackUtil.snapshotOf(orig), ItemStackUtil.snapshotOf(stack))); } else if (slotIn == EntityEquipmentSlot.OFFHAND) { ItemStack orig = this.inventory.offHandInventory.get(0); Slot slot = ((PlayerInventory) this.inventory).getOffhand(); ((IMixinInventoryPlayer) this.inventory).getCapturedTransactions().add(new SlotTransaction(slot, ItemStackUtil.snapshotOf(orig), ItemStackUtil.snapshotOf(stack))); } else if (slotIn.getSlotType() == EntityEquipmentSlot.Type.ARMOR) { ItemStack orig = this.inventory.armorInventory.get(slotIn.getIndex()); Slot slot = ((PlayerInventory) this.inventory).getEquipment().getSlot(SlotIndex.of(slotIn.getIndex())).get(); ((IMixinInventoryPlayer) this.inventory).getCapturedTransactions().add(new SlotTransaction(slot, ItemStackUtil.snapshotOf(orig), ItemStackUtil.snapshotOf(stack))); } } } @Override public void shouldRestoreInventory(boolean restore) { this.shouldRestoreInventory = restore; } @Override public boolean shouldRestoreInventory() { return this.shouldRestoreInventory; } }
fire Inventory Close on death (and quit) #1813
src/main/java/org/spongepowered/common/mixin/core/entity/player/MixinEntityPlayer.java
fire Inventory Close on death (and quit) #1813
<ide><path>rc/main/java/org/spongepowered/common/mixin/core/entity/player/MixinEntityPlayer.java <ide> import org.spongepowered.common.data.manipulator.mutable.entity.SpongeHealthData; <ide> import org.spongepowered.common.data.processor.common.ExperienceHolderUtils; <ide> import org.spongepowered.common.entity.EntityUtil; <add>import org.spongepowered.common.event.SpongeCommonEventFactory; <ide> import org.spongepowered.common.event.damage.DamageEventHandler; <add>import org.spongepowered.common.event.tracking.PhaseContext; <add>import org.spongepowered.common.event.tracking.phase.packet.PacketPhase; <ide> import org.spongepowered.common.interfaces.ITargetedLocation; <ide> import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayer; <ide> import org.spongepowered.common.interfaces.entity.player.IMixinInventoryPlayer; <ide> } <ide> } <ide> <add> @Redirect(method = "setDead", at = @At(value = "INVOKE", ordinal = 1, target = "Lnet/minecraft/inventory/Container;onContainerClosed(Lnet/minecraft/entity/player/EntityPlayer;)V")) <add> private void onOnContainerClosed(Container container, EntityPlayer player) { <add> try (PhaseContext<?> ctx = PacketPhase.General.CLOSE_WINDOW.createPhaseContext() <add> .source(player) <add> .packetPlayer(player instanceof EntityPlayerMP ? ((EntityPlayerMP) player) : null) <add> .openContainer(container) <add> // intentionally missing the lastCursor to not double throw close event <add> .buildAndSwitch(); <add> StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { <add> frame.pushCause(player); <add> ItemStackSnapshot cursor = ItemStackUtil.snapshotOf(this.inventory.getItemStack()); <add> container.onContainerClosed(player); <add> SpongeCommonEventFactory.callInteractInventoryCloseEvent(this.openContainer, (EntityPlayerMP) (Object) this, cursor, ItemStackSnapshot.NONE, false); <add> } <add> } <add> <ide> @Override <ide> public void shouldRestoreInventory(boolean restore) { <ide> this.shouldRestoreInventory = restore;
Java
apache-2.0
1d6fd2b6a6748d8442c544286c3ac56d5e2d2bf4
0
Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces
/******************************************************************************* * * Copyright (c) 2012 GigaSpaces Technologies Ltd. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.openspaces.admin.internal.space; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openspaces.admin.Admin; import org.openspaces.admin.AdminException; import org.openspaces.admin.StatisticsMonitor; import org.openspaces.admin.internal.admin.InternalAdmin; import org.openspaces.admin.internal.space.events.DefaultReplicationStatusChangedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceInstanceAddedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceInstanceRemovedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceInstanceStatisticsChangedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceModeChangedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceStatisticsChangedEventManager; import org.openspaces.admin.internal.space.events.InternalReplicationStatusChangedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceInstanceAddedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceInstanceRemovedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceInstanceStatisticsChangedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceModeChangedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceStatisticsChangedEventManager; import org.openspaces.admin.internal.support.NetworkExceptionHelper; import org.openspaces.admin.pu.DeploymentStatus; import org.openspaces.admin.pu.ProcessingUnit; import org.openspaces.admin.space.ReplicationStatus; import org.openspaces.admin.space.ReplicationTarget; import org.openspaces.admin.space.ReplicationTargetType; import org.openspaces.admin.space.Space; import org.openspaces.admin.space.SpaceInstance; import org.openspaces.admin.space.SpaceInstanceStatistics; import org.openspaces.admin.space.SpacePartition; import org.openspaces.admin.space.SpaceReplicationManager; import org.openspaces.admin.space.SpaceRuntimeDetails; import org.openspaces.admin.space.SpaceStatistics; import org.openspaces.admin.space.Spaces; import org.openspaces.admin.space.events.ReplicationStatusChangedEventManager; import org.openspaces.admin.space.events.SpaceInstanceAddedEventListener; import org.openspaces.admin.space.events.SpaceInstanceAddedEventManager; import org.openspaces.admin.space.events.SpaceInstanceLifecycleEventListener; import org.openspaces.admin.space.events.SpaceInstanceRemovedEventManager; import org.openspaces.admin.space.events.SpaceInstanceStatisticsChangedEventManager; import org.openspaces.admin.space.events.SpaceModeChangedEvent; import org.openspaces.admin.space.events.SpaceModeChangedEventListener; import org.openspaces.admin.space.events.SpaceModeChangedEventManager; import org.openspaces.admin.space.events.SpaceStatisticsChangedEvent; import org.openspaces.admin.space.events.SpaceStatisticsChangedEventManager; import org.openspaces.core.GigaSpace; import org.openspaces.core.GigaSpaceConfigurer; import com.gigaspaces.cluster.activeelection.InactiveSpaceException; import com.gigaspaces.cluster.activeelection.SpaceMode; import com.gigaspaces.internal.client.spaceproxy.ISpaceProxy; import com.gigaspaces.internal.cluster.node.impl.gateway.GatewayPolicy; import com.gigaspaces.internal.version.PlatformLogicalVersion; import com.j_spaces.core.IJSpace; import com.j_spaces.core.ISpaceState; import com.j_spaces.core.admin.IRemoteJSpaceAdmin; import com.j_spaces.core.admin.RuntimeHolder; import com.j_spaces.core.exception.SpaceUnavailableException; import com.j_spaces.core.exception.internal.InterruptedSpaceException; import com.j_spaces.core.filters.ReplicationStatistics; import com.j_spaces.core.filters.ReplicationStatistics.OutgoingChannel; import com.j_spaces.core.filters.StatisticsHolder; import com.j_spaces.kernel.JSpaceUtilities; import com.j_spaces.kernel.SizeConcurrentHashMap; /** * @author kimchy */ public class DefaultSpace implements InternalSpace { private static final Log logger = LogFactory.getLog(DefaultSpace.class); private final InternalAdmin admin; private final InternalSpaces spaces; private final String uid; private final String name; private volatile IJSpace space; private volatile GigaSpace gigaSpace; private final Map<String, SpaceInstance> spaceInstancesByUID = new SizeConcurrentHashMap<String, SpaceInstance>(); private final Map<String, SpaceInstance> spaceInstancesByMemberName = new ConcurrentHashMap<String, SpaceInstance>(); private final Map<Integer, SpacePartition> spacePartitions = new SizeConcurrentHashMap<Integer, SpacePartition>(); private final Map<String, Future> scheduledRuntimeFetchers = new ConcurrentHashMap<String, Future>(); private final InternalSpaceInstanceAddedEventManager spaceInstanceAddedEventManager; private final InternalSpaceInstanceRemovedEventManager spaceInstanceRemovedEventManager; private final InternalSpaceModeChangedEventManager spaceModeChangedEventManager; private final InternalReplicationStatusChangedEventManager replicationStatusChangedEventManager; private final InternalSpaceStatisticsChangedEventManager statisticsChangedEventManager; private final InternalSpaceInstanceStatisticsChangedEventManager instanceStatisticsChangedEventManager; private volatile long statisticsInterval = StatisticsMonitor.DEFAULT_MONITOR_INTERVAL; private volatile int statisticsHistorySize = StatisticsMonitor.DEFAULT_HISTORY_SIZE; private long lastStatisticsTimestamp = 0; private long lastPrimariesStatisticsTimestamp = 0; private long lastBackupsStatisticsTimestamp = 0; private SpaceStatistics lastStatistics; private SpaceStatistics lastPrimariesStatistics; private SpaceStatistics lastBackupStatistics; private final SpaceRuntimeDetails spaceRuntimeDetails; private final SpaceReplicationManager spaceReplicationManager; private Future scheduledStatisticsMonitor; private int scheduledStatisticsRefCount = 0; public DefaultSpace(InternalSpaces spaces, String uid, String name) { this.spaces = spaces; this.admin = (InternalAdmin) spaces.getAdmin(); this.uid = uid; this.name = name; this.spaceInstanceAddedEventManager = new DefaultSpaceInstanceAddedEventManager(admin, this); this.spaceInstanceRemovedEventManager = new DefaultSpaceInstanceRemovedEventManager(admin); this.spaceModeChangedEventManager = new DefaultSpaceModeChangedEventManager(this, admin); this.replicationStatusChangedEventManager = new DefaultReplicationStatusChangedEventManager(admin); this.statisticsChangedEventManager = new DefaultSpaceStatisticsChangedEventManager(admin); this.instanceStatisticsChangedEventManager = new DefaultSpaceInstanceStatisticsChangedEventManager(admin); this.spaceRuntimeDetails = new DefaultSpaceRuntimeDetails(this); this.spaceReplicationManager = new DefaultSpaceReplicationManager(this); } public Spaces getSpaces() { return this.spaces; } public String getUid() { return this.uid; } public String getName() { return this.name; } public synchronized void setStatisticsInterval(long interval, TimeUnit timeUnit) { statisticsInterval = timeUnit.toMillis(interval); if (isMonitoring()) { rescheduleStatisticsMonitor(); } for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { spaceInstance.setStatisticsInterval(interval, timeUnit); } } public void setStatisticsHistorySize(int historySize) { statisticsHistorySize = historySize; for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { spaceInstance.setStatisticsHistorySize(historySize); } } public synchronized void startStatisticsMonitor() { rescheduleStatisticsMonitor(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { spaceInstance.startStatisticsMonitor(); } } public synchronized void stopStatisticsMonitor() { stopScheduledStatisticsMonitor(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { spaceInstance.stopStatisticsMonitor(); } } private void stopScheduledStatisticsMonitor() { if (scheduledStatisticsRefCount!=0 && --scheduledStatisticsRefCount > 0) return; if (scheduledStatisticsMonitor != null) { scheduledStatisticsMonitor.cancel(false); scheduledStatisticsMonitor = null; } } public synchronized boolean isMonitoring() { return scheduledStatisticsMonitor != null; } private void rescheduleStatisticsMonitor() { if (scheduledStatisticsRefCount++ > 0) return; if (scheduledStatisticsMonitor != null) { scheduledStatisticsMonitor.cancel(false); } scheduledStatisticsMonitor = admin.scheduleWithFixedDelay(new Runnable() { public void run() { SpaceStatistics stats = getStatistics(); SpaceStatisticsChangedEvent event = new SpaceStatisticsChangedEvent(DefaultSpace.this, stats); statisticsChangedEventManager.spaceStatisticsChanged(event); ((InternalSpaceStatisticsChangedEventManager) spaces.getSpaceStatisticsChanged()).spaceStatisticsChanged(event); } }, 0, statisticsInterval, TimeUnit.MILLISECONDS); } private int numberOfInstances = -1; public int getNumberOfInstances() { if (numberOfInstances != -1) { return numberOfInstances; } numberOfInstances = doWithInstance(new InstanceCallback<Integer>() { public Integer doWithinstance(InternalSpaceInstance spaceInstance) { return spaceInstance.getNumberOfInstances(); } }, -1); return numberOfInstances; } private int numberOfBackups = -1; public int getNumberOfBackups() { if (numberOfBackups != -1) { return numberOfBackups; } numberOfBackups = doWithInstance(new InstanceCallback<Integer>() { public Integer doWithinstance(InternalSpaceInstance spaceInstance) { return spaceInstance.getNumberOfBackups(); } }, -1); return numberOfBackups; } public int getTotalNumberOfInstances() { return getNumberOfInstances() * (getNumberOfBackups() + 1); } public SpaceInstance[] getInstances() { return spaceInstancesByUID.values().toArray(new SpaceInstance[0]); } public Iterator<SpaceInstance> iterator() { return Collections.unmodifiableCollection(spaceInstancesByUID.values()).iterator(); } public SpacePartition[] getPartitions() { return spacePartitions.values().toArray(new SpacePartition[0]); } public SpacePartition getPartition(int partitionId) { return spacePartitions.get(partitionId); } public SpaceModeChangedEventManager getSpaceModeChanged() { return this.spaceModeChangedEventManager; } public ReplicationStatusChangedEventManager getReplicationStatusChanged() { return this.replicationStatusChangedEventManager; } public SpaceStatisticsChangedEventManager getStatisticsChanged() { return this.statisticsChangedEventManager; } public SpaceInstanceStatisticsChangedEventManager getInstanceStatisticsChanged() { return this.instanceStatisticsChangedEventManager; } public synchronized SpaceStatistics getStatistics() { long currentTime = System.currentTimeMillis(); if ((currentTime - lastStatisticsTimestamp) < statisticsInterval) { return lastStatistics; } lastStatisticsTimestamp = currentTime; List<SpaceInstanceStatistics> stats = new ArrayList<SpaceInstanceStatistics>(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { stats.add(spaceInstance.getStatistics()); } lastStatistics = new DefaultSpaceStatistics(stats.toArray(new SpaceInstanceStatistics[stats.size()]), lastStatistics, statisticsHistorySize); return lastStatistics; } public synchronized SpaceStatistics getPrimariesStatistics() { long currentTime = System.currentTimeMillis(); if ((currentTime - lastPrimariesStatisticsTimestamp) < statisticsInterval) { return lastPrimariesStatistics; } lastPrimariesStatisticsTimestamp = currentTime; List<SpaceInstanceStatistics> stats = new ArrayList<SpaceInstanceStatistics>(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { if (spaceInstance.getMode() == SpaceMode.PRIMARY) { stats.add(spaceInstance.getStatistics()); } } lastPrimariesStatistics = new DefaultSpaceStatistics(stats.toArray(new SpaceInstanceStatistics[stats.size()]), lastPrimariesStatistics, statisticsHistorySize); return lastPrimariesStatistics; } public synchronized SpaceStatistics getBackupsStatistics() { long currentTime = System.currentTimeMillis(); if ((currentTime - lastBackupsStatisticsTimestamp) < statisticsInterval) { return lastStatistics; } lastBackupsStatisticsTimestamp = currentTime; List<SpaceInstanceStatistics> stats = new ArrayList<SpaceInstanceStatistics>(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { if (spaceInstance.getMode() == SpaceMode.BACKUP) { stats.add(spaceInstance.getStatistics()); } } lastBackupStatistics = new DefaultSpaceStatistics(stats.toArray(new SpaceInstanceStatistics[stats.size()]), lastBackupStatistics, statisticsHistorySize); return lastBackupStatistics; } public SpaceRuntimeDetails getRuntimeDetails() { return spaceRuntimeDetails; } @Override public SpaceReplicationManager getReplicationManager() { return spaceReplicationManager; } public void addInstance(final SpaceInstance spaceInstance) { assertStateChangesPermitted(); InternalSpaceInstance internalSpaceInstance = (InternalSpaceInstance) spaceInstance; // the first addition (which we make sure is added before the space becomes visible) will // cause the partition to initialize if (spaceInstancesByUID.isEmpty()) { // guess if its a partition (with no backup) since we can't tell if its replicated or just partitioned if (internalSpaceInstance.getClusterSchema() != null && internalSpaceInstance.getClusterSchema().contains("partition")) { for (int i = 0; i < internalSpaceInstance.getNumberOfInstances(); i++) { spacePartitions.put(i, new DefaultSpacePartition(this, i)); } } else { if (internalSpaceInstance.getNumberOfBackups() == 0) { // single partition (replicated?) when there is no backup spacePartitions.put(0, new DefaultSpacePartition(this, 0)); } else { for (int i = 0; i < internalSpaceInstance.getNumberOfInstances(); i++) { spacePartitions.put(i, new DefaultSpacePartition(this, i)); } } } } SpaceInstance existing = spaceInstancesByUID.put(spaceInstance.getUid(), spaceInstance); String fullSpaceName = JSpaceUtilities.createFullSpaceName(spaceInstance.getSpaceUrl().getContainerName(), spaceInstance.getSpaceUrl().getSpaceName()); spaceInstancesByMemberName.put(fullSpaceName, spaceInstance); InternalSpacePartition spacePartition = getPartition(internalSpaceInstance); internalSpaceInstance.setPartition(spacePartition); spacePartition.addSpaceInstance(spaceInstance); if (existing == null) { spaceInstanceAddedEventManager.spaceInstanceAdded(spaceInstance); ((InternalSpaceInstanceAddedEventManager) spaces.getSpaceInstanceAdded()).spaceInstanceAdded(spaceInstance); } spaceInstance.setStatisticsInterval(statisticsInterval, TimeUnit.MILLISECONDS); spaceInstance.setStatisticsHistorySize(statisticsHistorySize); if (isMonitoring()) { admin.raiseEvent(this, new Runnable() { public void run() { spaceInstance.startStatisticsMonitor(); } }); } // start the scheduler Future fetcher = scheduledRuntimeFetchers.get(spaceInstance.getUid()); if (fetcher == null) { fetcher = admin.scheduleWithFixedDelay(new ScheduledRuntimeFetcher(spaceInstance), admin.getScheduledSpaceMonitorInterval(), admin.getScheduledSpaceMonitorInterval(), TimeUnit.MILLISECONDS); scheduledRuntimeFetchers.put(spaceInstance.getUid(), fetcher); } } public InternalSpaceInstance removeInstance(String uid) { assertStateChangesPermitted(); InternalSpaceInstance spaceInstance = (InternalSpaceInstance) spaceInstancesByUID.remove(uid); if (spaceInstance != null) { spaceInstance.stopStatisticsMonitor(); getPartition(spaceInstance).removeSpaceInstance(uid); String fullSpaceName = JSpaceUtilities.createFullSpaceName(spaceInstance.getSpaceUrl().getContainerName(), spaceInstance.getSpaceUrl().getSpaceName()); spaceInstancesByMemberName.remove(fullSpaceName); spaceInstanceRemovedEventManager.spaceInstanceRemoved(spaceInstance); ((InternalSpaceInstanceRemovedEventManager) spaces.getSpaceInstanceRemoved()).spaceInstanceRemoved(spaceInstance); Future fetcher = scheduledRuntimeFetchers.remove(uid); if (fetcher != null) { fetcher.cancel(true); } } return spaceInstance; } private InternalSpacePartition getPartition(InternalSpaceInstance spaceInstance) { if (spaceInstance.getClusterSchema() != null && spaceInstance.getClusterSchema().contains("partition")) { return (InternalSpacePartition) spacePartitions.get(spaceInstance.getInstanceId() - 1); } else { if (spaceInstance.getNumberOfBackups() == 0) { return (InternalSpacePartition) spacePartitions.get(0); } else { return (InternalSpacePartition) spacePartitions.get(spaceInstance.getInstanceId() - 1); } } } // no need to sync since it is synced on Admin public void refreshScheduledSpaceMonitors() { for (Future fetcher : scheduledRuntimeFetchers.values()) { fetcher.cancel(false); } for (SpaceInstance spaceInstance : this) { Future fetcher = admin.scheduleWithFixedDelay(new ScheduledRuntimeFetcher(spaceInstance), admin.getScheduledSpaceMonitorInterval(), admin.getScheduledSpaceMonitorInterval(), TimeUnit.MILLISECONDS); scheduledRuntimeFetchers.put(spaceInstance.getUid(), fetcher); } } public int getSize() { return spaceInstancesByUID.size(); } public boolean isEmpty() { return spaceInstancesByUID.size() == 0; } public IJSpace getIJSpace() { if (space == null) { SpaceInstance firstInstance = null; for (SpaceInstance instance : spaceInstancesByUID.values()) { firstInstance = instance; break; } if (firstInstance == null) { if (logger.isDebugEnabled()) { logger.debug("Space " + getName() + " cannot create IJSpace since it has no instances"); } return null; } try { space = ((ISpaceProxy) ((InternalSpaceInstance) firstInstance).getIJSpace()).getClusteredSpace(); if (space.isSecured()) { ((ISpaceProxy)space).login(admin.getUserDetails()); } } catch (AdminException e) { throw e; } catch (Exception e) { throw new AdminException("Failed to fetch space", e); } } return space; } public GigaSpace getGigaSpace() { if (gigaSpace == null) { IJSpace ijSpace = getIJSpace(); if (ijSpace == null) { throw new AdminException("Cannot create GigaSpace object since no space instance is discovered"); } this.gigaSpace = new GigaSpaceConfigurer(ijSpace).clustered(true).gigaSpace(); } return this.gigaSpace; } public boolean waitFor(int numberOfSpaceInstances) { return waitFor(numberOfSpaceInstances, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit()); } public boolean waitFor(int numberOfSpaceInstances, long timeout, TimeUnit timeUnit) { final CountDownLatch latch = new CountDownLatch(numberOfSpaceInstances); SpaceInstanceAddedEventListener added = new SpaceInstanceAddedEventListener() { public void spaceInstanceAdded(SpaceInstance spaceInstance) { latch.countDown(); } }; getSpaceInstanceAdded().add(added); try { return latch.await(timeout, timeUnit); } catch (InterruptedException e) { return false; } finally { getSpaceInstanceAdded().remove(added); } } public boolean waitFor(int numberOfSpaceInstances, SpaceMode spaceMode) { return waitFor(numberOfSpaceInstances, spaceMode, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit()); } public boolean waitFor(int numberOfSpaceInstances, final SpaceMode spaceMode, long timeout, TimeUnit timeUnit) { final CountDownLatch latch = new CountDownLatch(numberOfSpaceInstances); SpaceModeChangedEventListener modeChanged = new SpaceModeChangedEventListener() { public void spaceModeChanged(SpaceModeChangedEvent event) { if (event.getNewMode() == spaceMode) { latch.countDown(); } } }; getSpaceModeChanged().add(modeChanged); boolean result; try { result = latch.await(timeout, timeUnit); } catch (InterruptedException e) { return false; } finally { getSpaceModeChanged().remove(modeChanged); } if (result) { // double check again int sum = 0; for (SpaceInstance spaceInstance : this) { if (spaceInstance.getMode() == spaceMode) { sum++; } } if (sum < numberOfSpaceInstances) { return waitFor(numberOfSpaceInstances, spaceMode, timeout, timeUnit); } } return result; } public SpaceInstance[] getSpaceInstances() { return getInstances(); } public SpaceInstanceAddedEventManager getSpaceInstanceAdded() { return this.spaceInstanceAddedEventManager; } public SpaceInstanceRemovedEventManager getSpaceInstanceRemoved() { return this.spaceInstanceRemovedEventManager; } public void addLifecycleListener(SpaceInstanceLifecycleEventListener eventListener) { spaceInstanceAddedEventManager.add(eventListener); spaceInstanceRemovedEventManager.add(eventListener); } public void removeLifecycleListener(SpaceInstanceLifecycleEventListener eventListener) { spaceInstanceAddedEventManager.remove(eventListener); spaceInstanceRemovedEventManager.remove(eventListener); } public Admin getAdmin() { return this.admin; } private <T> T doWithInstance(InstanceCallback<T> callback, T naValue) { for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { return callback.doWithinstance((InternalSpaceInstance) spaceInstance); } return naValue; } private static interface InstanceCallback<T> { T doWithinstance(InternalSpaceInstance spaceInstance); } private class ScheduledRuntimeFetcher implements Runnable { private final InternalSpaceInstance spaceInstance; private ScheduledRuntimeFetcher(SpaceInstance spaceInstance) { this.spaceInstance = (InternalSpaceInstance) spaceInstance; } public void run() { try { final RuntimeHolder runtimeHolder = spaceInstance.getRuntimeHolder(); final StatisticsHolder statisticsHolder = spaceInstance.getStatisticsHolder(); final ReplicationStatistics replicationStatistics = (statisticsHolder == null) ? null : statisticsHolder.getReplicationStatistics(); if (runtimeHolder.getSpaceState() != null && (runtimeHolder.getSpaceState() == ISpaceState.STOPPED || runtimeHolder.getSpaceState() == ISpaceState.STARTING)) { // we don't want to update the space mode to until the space state is STARTED // The space instance starts as STOPPED then changes to STARTING and only after recovery is complete it's state STARTED if (logger.isTraceEnabled()) { logger.trace("Ignoring runtimeHolder of space:" + spaceInstance.getSpaceName() + " serviceID:" + spaceInstance.getServiceID() + " state="+runtimeHolder.getSpaceState()); } return; } DefaultSpace.this.admin.scheduleNonBlockingStateChange(new Runnable() { public void run() { spaceInstance.setMode(runtimeHolder.getSpaceMode()); if (spaceInstance.getPlatformLogicalVersion().greaterOrEquals(PlatformLogicalVersion.v8_0_5)) { if (replicationStatistics != null) { final List<OutgoingChannel> channels = replicationStatistics.getOutgoingReplication().getChannels(); ReplicationTarget[] replicationTargets = new ReplicationTarget[channels.size()]; int index = 0; for (OutgoingChannel outgoingChannel : channels) { ReplicationTargetType replicationTargetType; switch (outgoingChannel.getReplicationMode()) { case MIRROR: replicationTargetType = ReplicationTargetType.MIRROR_SERVICE; break; case GATEWAY: replicationTargetType = ReplicationTargetType.GATEWAY; break; case LOCAL_VIEW: replicationTargetType = ReplicationTargetType.LOCAL_VIEW; break; case DURABLE_NOTIFICATION: replicationTargetType = ReplicationTargetType.DURABLE_NOTIFICATION; break; case ACTIVE_SPACE: case BACKUP_SPACE: replicationTargetType = ReplicationTargetType.SPACE_INSTANCE; break; default: throw new IllegalArgumentException("Unexpected replication mode: " + outgoingChannel.getReplicationMode()); } ReplicationStatus replicationStatus; switch (outgoingChannel.getChannelState()) { case ACTIVE: replicationStatus = ReplicationStatus.ACTIVE; break; case CONNECTED: case DISCONNECTED: replicationStatus = ReplicationStatus.DISCONNECTED; break; default: throw new IllegalArgumentException("Unexpected channel state: " + outgoingChannel.getChannelState()); } SpaceInstance targetSpaceInstance = spaceInstancesByMemberName.get(outgoingChannel.getTargetMemberName()); if (targetSpaceInstance == null && replicationTargetType == ReplicationTargetType.MIRROR_SERVICE) { String mirrorServiceName = outgoingChannel.getTargetMemberName().split(":")[1]; Space mirrorServiceSpace = spaceInstance.getAdmin().getSpaces().getSpaceByName(mirrorServiceName); if (mirrorServiceSpace != null) { SpaceInstance[] instances = mirrorServiceSpace.getInstances(); if (instances.length > 0) { SpaceInstance mirrorInstance = instances[0]; if (mirrorInstance != null && mirrorInstance.getSpaceUrl().getSchema().equals("mirror")) { //note: don't cache it in spaceInstanceByMemberName map since we don't get a removal event on this instance targetSpaceInstance = mirrorInstance; } } } } replicationTargets[index++] = new ReplicationTarget((InternalSpaceInstance) targetSpaceInstance, replicationStatus, outgoingChannel.getTargetMemberName(), replicationTargetType); } spaceInstance.setReplicationTargets(replicationTargets); } } else { // Fall back to old path if (runtimeHolder.getReplicationStatus() != null) { Object[] memberNames = (Object[]) runtimeHolder.getReplicationStatus()[0]; int[] replicationStatus = (int[]) runtimeHolder.getReplicationStatus()[1]; ReplicationTarget[] replicationTargets = new ReplicationTarget[memberNames.length]; for (int i = 0; i < memberNames.length; i++) { if (memberNames[i] == null) { continue; } SpaceInstance targetSpaceInstance = spaceInstancesByMemberName.get(memberNames[i]); ReplicationTargetType replicationTargetType = ReplicationTargetType.SPACE_INSTANCE; //Check if target is a gateway, so we cannot locate a target space instance for it if (((String)memberNames[i]).startsWith(GatewayPolicy.GATEWAY_NAME_PREFIX)){ replicationTargetType = ReplicationTargetType.GATEWAY; }else { /* * If mirror-service is one of the replication target names, find its SpaceInstance. */ if (targetSpaceInstance == null) { //we don't know the name of the mirror-service space (it can be any name that is different from the cluster name) if (!((String)memberNames[i]).endsWith(":"+name)) { String mirrorServiceName = ((String)memberNames[i]).split(":")[1]; Space mirrorServiceSpace = spaceInstance.getAdmin().getSpaces().getSpaceByName(mirrorServiceName); if (mirrorServiceSpace != null) { SpaceInstance mirrorInstance = mirrorServiceSpace.getInstances()[0]; if (mirrorInstance != null && mirrorInstance.getSpaceUrl().getSchema().equals("mirror")) { //note: don't cache it in spaceInstanceByMemberName map since we don't get a removal event on this instance targetSpaceInstance = mirrorInstance; replicationTargetType = ReplicationTargetType.MIRROR_SERVICE; } } else { replicationTargetType = ReplicationTargetType.MIRROR_SERVICE; //we guess this is a mirror (since 8.0.1) } } }else { if (targetSpaceInstance != null && targetSpaceInstance.getSpaceUrl().getSchema().equals("mirror")) { replicationTargetType = ReplicationTargetType.MIRROR_SERVICE; } } } ReplicationStatus replStatus = null; switch (replicationStatus[i]) { case IRemoteJSpaceAdmin.REPLICATION_STATUS_ACTIVE: replStatus = ReplicationStatus.ACTIVE; break; case IRemoteJSpaceAdmin.REPLICATION_STATUS_DISCONNECTED: replStatus = ReplicationStatus.DISCONNECTED; break; case IRemoteJSpaceAdmin.REPLICATION_STATUS_DISABLED: replStatus = ReplicationStatus.DISABLED; break; } replicationTargets[i] = new ReplicationTarget((InternalSpaceInstance) targetSpaceInstance, replStatus, (String)memberNames[i], replicationTargetType); } spaceInstance.setReplicationTargets(replicationTargets); } } }}); } catch (SpaceUnavailableException e) { // space is going shutdown or abort process } catch (InactiveSpaceException e) { // ignore this (maybe we should add it as a state to a Space instance?) } catch (InterruptedSpaceException e) { ProcessingUnit pu = admin.getProcessingUnits().getProcessingUnit(name); if (pu == null || pu.getStatus() == DeploymentStatus.UNDEPLOYED) { logger.debug("Failed to get runtime information", e); } else { logger.warn("Failed to get runtime information", e); } } catch (Exception e) { if (NetworkExceptionHelper.isConnectOrCloseException(e)) { logger.debug("Failed to get runtime information", e); } else { logger.warn("Failed to get runtime information", e); } } } } private void assertStateChangesPermitted() { admin.assertStateChangesPermitted(); } }
src/main/src/org/openspaces/admin/internal/space/DefaultSpace.java
/******************************************************************************* * * Copyright (c) 2012 GigaSpaces Technologies Ltd. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.openspaces.admin.internal.space; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openspaces.admin.Admin; import org.openspaces.admin.AdminException; import org.openspaces.admin.StatisticsMonitor; import org.openspaces.admin.internal.admin.InternalAdmin; import org.openspaces.admin.internal.space.events.DefaultReplicationStatusChangedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceInstanceAddedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceInstanceRemovedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceInstanceStatisticsChangedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceModeChangedEventManager; import org.openspaces.admin.internal.space.events.DefaultSpaceStatisticsChangedEventManager; import org.openspaces.admin.internal.space.events.InternalReplicationStatusChangedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceInstanceAddedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceInstanceRemovedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceInstanceStatisticsChangedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceModeChangedEventManager; import org.openspaces.admin.internal.space.events.InternalSpaceStatisticsChangedEventManager; import org.openspaces.admin.internal.support.NetworkExceptionHelper; import org.openspaces.admin.pu.DeploymentStatus; import org.openspaces.admin.pu.ProcessingUnit; import org.openspaces.admin.space.ReplicationStatus; import org.openspaces.admin.space.ReplicationTarget; import org.openspaces.admin.space.ReplicationTargetType; import org.openspaces.admin.space.Space; import org.openspaces.admin.space.SpaceInstance; import org.openspaces.admin.space.SpaceInstanceStatistics; import org.openspaces.admin.space.SpacePartition; import org.openspaces.admin.space.SpaceReplicationManager; import org.openspaces.admin.space.SpaceRuntimeDetails; import org.openspaces.admin.space.SpaceStatistics; import org.openspaces.admin.space.Spaces; import org.openspaces.admin.space.events.ReplicationStatusChangedEventManager; import org.openspaces.admin.space.events.SpaceInstanceAddedEventListener; import org.openspaces.admin.space.events.SpaceInstanceAddedEventManager; import org.openspaces.admin.space.events.SpaceInstanceLifecycleEventListener; import org.openspaces.admin.space.events.SpaceInstanceRemovedEventManager; import org.openspaces.admin.space.events.SpaceInstanceStatisticsChangedEventManager; import org.openspaces.admin.space.events.SpaceModeChangedEvent; import org.openspaces.admin.space.events.SpaceModeChangedEventListener; import org.openspaces.admin.space.events.SpaceModeChangedEventManager; import org.openspaces.admin.space.events.SpaceStatisticsChangedEvent; import org.openspaces.admin.space.events.SpaceStatisticsChangedEventManager; import org.openspaces.core.GigaSpace; import org.openspaces.core.GigaSpaceConfigurer; import com.gigaspaces.cluster.activeelection.InactiveSpaceException; import com.gigaspaces.cluster.activeelection.SpaceMode; import com.gigaspaces.internal.client.spaceproxy.ISpaceProxy; import com.gigaspaces.internal.cluster.node.impl.gateway.GatewayPolicy; import com.gigaspaces.internal.version.PlatformLogicalVersion; import com.j_spaces.core.IJSpace; import com.j_spaces.core.ISpaceState; import com.j_spaces.core.admin.IRemoteJSpaceAdmin; import com.j_spaces.core.admin.RuntimeHolder; import com.j_spaces.core.exception.SpaceUnavailableException; import com.j_spaces.core.exception.internal.InterruptedSpaceException; import com.j_spaces.core.filters.ReplicationStatistics; import com.j_spaces.core.filters.ReplicationStatistics.OutgoingChannel; import com.j_spaces.core.filters.StatisticsHolder; import com.j_spaces.kernel.JSpaceUtilities; import com.j_spaces.kernel.SizeConcurrentHashMap; /** * @author kimchy */ public class DefaultSpace implements InternalSpace { private static final Log logger = LogFactory.getLog(DefaultSpace.class); private final InternalAdmin admin; private final InternalSpaces spaces; private final String uid; private final String name; private volatile IJSpace space; private volatile GigaSpace gigaSpace; private final Map<String, SpaceInstance> spaceInstancesByUID = new SizeConcurrentHashMap<String, SpaceInstance>(); private final Map<String, SpaceInstance> spaceInstancesByMemberName = new ConcurrentHashMap<String, SpaceInstance>(); private final Map<Integer, SpacePartition> spacePartitions = new SizeConcurrentHashMap<Integer, SpacePartition>(); private final Map<String, Future> scheduledRuntimeFetchers = new ConcurrentHashMap<String, Future>(); private final InternalSpaceInstanceAddedEventManager spaceInstanceAddedEventManager; private final InternalSpaceInstanceRemovedEventManager spaceInstanceRemovedEventManager; private final InternalSpaceModeChangedEventManager spaceModeChangedEventManager; private final InternalReplicationStatusChangedEventManager replicationStatusChangedEventManager; private final InternalSpaceStatisticsChangedEventManager statisticsChangedEventManager; private final InternalSpaceInstanceStatisticsChangedEventManager instanceStatisticsChangedEventManager; private volatile long statisticsInterval = StatisticsMonitor.DEFAULT_MONITOR_INTERVAL; private volatile int statisticsHistorySize = StatisticsMonitor.DEFAULT_HISTORY_SIZE; private long lastStatisticsTimestamp = 0; private long lastPrimariesStatisticsTimestamp = 0; private long lastBackupsStatisticsTimestamp = 0; private SpaceStatistics lastStatistics; private SpaceStatistics lastPrimariesStatistics; private SpaceStatistics lastBackupStatistics; private final SpaceRuntimeDetails spaceRuntimeDetails; private final SpaceReplicationManager spaceReplicationManager; private Future scheduledStatisticsMonitor; private int scheduledStatisticsRefCount = 0; public DefaultSpace(InternalSpaces spaces, String uid, String name) { this.spaces = spaces; this.admin = (InternalAdmin) spaces.getAdmin(); this.uid = uid; this.name = name; this.spaceInstanceAddedEventManager = new DefaultSpaceInstanceAddedEventManager(admin, this); this.spaceInstanceRemovedEventManager = new DefaultSpaceInstanceRemovedEventManager(admin); this.spaceModeChangedEventManager = new DefaultSpaceModeChangedEventManager(this, admin); this.replicationStatusChangedEventManager = new DefaultReplicationStatusChangedEventManager(admin); this.statisticsChangedEventManager = new DefaultSpaceStatisticsChangedEventManager(admin); this.instanceStatisticsChangedEventManager = new DefaultSpaceInstanceStatisticsChangedEventManager(admin); this.spaceRuntimeDetails = new DefaultSpaceRuntimeDetails(this); this.spaceReplicationManager = new DefaultSpaceReplicationManager(this); } public Spaces getSpaces() { return this.spaces; } public String getUid() { return this.uid; } public String getName() { return this.name; } public synchronized void setStatisticsInterval(long interval, TimeUnit timeUnit) { statisticsInterval = timeUnit.toMillis(interval); if (isMonitoring()) { rescheduleStatisticsMonitor(); } for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { spaceInstance.setStatisticsInterval(interval, timeUnit); } } public void setStatisticsHistorySize(int historySize) { statisticsHistorySize = historySize; for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { spaceInstance.setStatisticsHistorySize(historySize); } } public synchronized void startStatisticsMonitor() { rescheduleStatisticsMonitor(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { spaceInstance.startStatisticsMonitor(); } } public synchronized void stopStatisticsMonitor() { stopScheduledStatisticsMonitor(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { spaceInstance.stopStatisticsMonitor(); } } private void stopScheduledStatisticsMonitor() { if (scheduledStatisticsRefCount!=0 && --scheduledStatisticsRefCount > 0) return; if (scheduledStatisticsMonitor != null) { scheduledStatisticsMonitor.cancel(false); scheduledStatisticsMonitor = null; } } public synchronized boolean isMonitoring() { return scheduledStatisticsMonitor != null; } private void rescheduleStatisticsMonitor() { if (scheduledStatisticsRefCount++ > 0) return; if (scheduledStatisticsMonitor != null) { scheduledStatisticsMonitor.cancel(false); } scheduledStatisticsMonitor = admin.scheduleWithFixedDelay(new Runnable() { public void run() { SpaceStatistics stats = getStatistics(); SpaceStatisticsChangedEvent event = new SpaceStatisticsChangedEvent(DefaultSpace.this, stats); statisticsChangedEventManager.spaceStatisticsChanged(event); ((InternalSpaceStatisticsChangedEventManager) spaces.getSpaceStatisticsChanged()).spaceStatisticsChanged(event); } }, 0, statisticsInterval, TimeUnit.MILLISECONDS); } private int numberOfInstances = -1; public int getNumberOfInstances() { if (numberOfInstances != -1) { return numberOfInstances; } numberOfInstances = doWithInstance(new InstanceCallback<Integer>() { public Integer doWithinstance(InternalSpaceInstance spaceInstance) { return spaceInstance.getNumberOfInstances(); } }, -1); return numberOfInstances; } private int numberOfBackups = -1; public int getNumberOfBackups() { if (numberOfBackups != -1) { return numberOfBackups; } numberOfBackups = doWithInstance(new InstanceCallback<Integer>() { public Integer doWithinstance(InternalSpaceInstance spaceInstance) { return spaceInstance.getNumberOfBackups(); } }, -1); return numberOfBackups; } public int getTotalNumberOfInstances() { return getNumberOfInstances() * (getNumberOfBackups() + 1); } public SpaceInstance[] getInstances() { return spaceInstancesByUID.values().toArray(new SpaceInstance[0]); } public Iterator<SpaceInstance> iterator() { return Collections.unmodifiableCollection(spaceInstancesByUID.values()).iterator(); } public SpacePartition[] getPartitions() { return spacePartitions.values().toArray(new SpacePartition[0]); } public SpacePartition getPartition(int partitionId) { return spacePartitions.get(partitionId); } public SpaceModeChangedEventManager getSpaceModeChanged() { return this.spaceModeChangedEventManager; } public ReplicationStatusChangedEventManager getReplicationStatusChanged() { return this.replicationStatusChangedEventManager; } public SpaceStatisticsChangedEventManager getStatisticsChanged() { return this.statisticsChangedEventManager; } public SpaceInstanceStatisticsChangedEventManager getInstanceStatisticsChanged() { return this.instanceStatisticsChangedEventManager; } public synchronized SpaceStatistics getStatistics() { long currentTime = System.currentTimeMillis(); if ((currentTime - lastStatisticsTimestamp) < statisticsInterval) { return lastStatistics; } lastStatisticsTimestamp = currentTime; List<SpaceInstanceStatistics> stats = new ArrayList<SpaceInstanceStatistics>(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { stats.add(spaceInstance.getStatistics()); } lastStatistics = new DefaultSpaceStatistics(stats.toArray(new SpaceInstanceStatistics[stats.size()]), lastStatistics, statisticsHistorySize); return lastStatistics; } public synchronized SpaceStatistics getPrimariesStatistics() { long currentTime = System.currentTimeMillis(); if ((currentTime - lastPrimariesStatisticsTimestamp) < statisticsInterval) { return lastPrimariesStatistics; } lastPrimariesStatisticsTimestamp = currentTime; List<SpaceInstanceStatistics> stats = new ArrayList<SpaceInstanceStatistics>(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { if (spaceInstance.getMode() == SpaceMode.PRIMARY) { stats.add(spaceInstance.getStatistics()); } } lastPrimariesStatistics = new DefaultSpaceStatistics(stats.toArray(new SpaceInstanceStatistics[stats.size()]), lastPrimariesStatistics, statisticsHistorySize); return lastPrimariesStatistics; } public synchronized SpaceStatistics getBackupsStatistics() { long currentTime = System.currentTimeMillis(); if ((currentTime - lastBackupsStatisticsTimestamp) < statisticsInterval) { return lastStatistics; } lastBackupsStatisticsTimestamp = currentTime; List<SpaceInstanceStatistics> stats = new ArrayList<SpaceInstanceStatistics>(); for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { if (spaceInstance.getMode() == SpaceMode.BACKUP) { stats.add(spaceInstance.getStatistics()); } } lastBackupStatistics = new DefaultSpaceStatistics(stats.toArray(new SpaceInstanceStatistics[stats.size()]), lastBackupStatistics, statisticsHistorySize); return lastBackupStatistics; } public SpaceRuntimeDetails getRuntimeDetails() { return spaceRuntimeDetails; } @Override public SpaceReplicationManager getReplicationManager() { return spaceReplicationManager; } public void addInstance(final SpaceInstance spaceInstance) { assertStateChangesPermitted(); InternalSpaceInstance internalSpaceInstance = (InternalSpaceInstance) spaceInstance; // the first addition (which we make sure is added before the space becomes visible) will // cause the partition to initialize if (spaceInstancesByUID.isEmpty()) { // guess if its a partition (with no backup) since we can't tell if its replicated or just partitioned if (internalSpaceInstance.getClusterSchema() != null && internalSpaceInstance.getClusterSchema().contains("partition")) { for (int i = 0; i < internalSpaceInstance.getNumberOfInstances(); i++) { spacePartitions.put(i, new DefaultSpacePartition(this, i)); } } else { if (internalSpaceInstance.getNumberOfBackups() == 0) { // single partition (replicated?) when there is no backup spacePartitions.put(0, new DefaultSpacePartition(this, 0)); } else { for (int i = 0; i < internalSpaceInstance.getNumberOfInstances(); i++) { spacePartitions.put(i, new DefaultSpacePartition(this, i)); } } } } SpaceInstance existing = spaceInstancesByUID.put(spaceInstance.getUid(), spaceInstance); String fullSpaceName = JSpaceUtilities.createFullSpaceName(spaceInstance.getSpaceUrl().getContainerName(), spaceInstance.getSpaceUrl().getSpaceName()); spaceInstancesByMemberName.put(fullSpaceName, spaceInstance); InternalSpacePartition spacePartition = getPartition(internalSpaceInstance); internalSpaceInstance.setPartition(spacePartition); spacePartition.addSpaceInstance(spaceInstance); if (existing == null) { spaceInstanceAddedEventManager.spaceInstanceAdded(spaceInstance); ((InternalSpaceInstanceAddedEventManager) spaces.getSpaceInstanceAdded()).spaceInstanceAdded(spaceInstance); } spaceInstance.setStatisticsInterval(statisticsInterval, TimeUnit.MILLISECONDS); spaceInstance.setStatisticsHistorySize(statisticsHistorySize); if (isMonitoring()) { admin.raiseEvent(this, new Runnable() { public void run() { spaceInstance.startStatisticsMonitor(); } }); } // start the scheduler Future fetcher = scheduledRuntimeFetchers.get(spaceInstance.getUid()); if (fetcher == null) { fetcher = admin.scheduleWithFixedDelay(new ScheduledRuntimeFetcher(spaceInstance), admin.getScheduledSpaceMonitorInterval(), admin.getScheduledSpaceMonitorInterval(), TimeUnit.MILLISECONDS); scheduledRuntimeFetchers.put(spaceInstance.getUid(), fetcher); } } public InternalSpaceInstance removeInstance(String uid) { assertStateChangesPermitted(); InternalSpaceInstance spaceInstance = (InternalSpaceInstance) spaceInstancesByUID.remove(uid); if (spaceInstance != null) { spaceInstance.stopStatisticsMonitor(); getPartition(spaceInstance).removeSpaceInstance(uid); String fullSpaceName = JSpaceUtilities.createFullSpaceName(spaceInstance.getSpaceUrl().getContainerName(), spaceInstance.getSpaceUrl().getSpaceName()); spaceInstancesByMemberName.remove(fullSpaceName); spaceInstanceRemovedEventManager.spaceInstanceRemoved(spaceInstance); ((InternalSpaceInstanceRemovedEventManager) spaces.getSpaceInstanceRemoved()).spaceInstanceRemoved(spaceInstance); Future fetcher = scheduledRuntimeFetchers.get(uid); if (fetcher != null) { fetcher.cancel(true); } } return spaceInstance; } private InternalSpacePartition getPartition(InternalSpaceInstance spaceInstance) { if (spaceInstance.getClusterSchema() != null && spaceInstance.getClusterSchema().contains("partition")) { return (InternalSpacePartition) spacePartitions.get(spaceInstance.getInstanceId() - 1); } else { if (spaceInstance.getNumberOfBackups() == 0) { return (InternalSpacePartition) spacePartitions.get(0); } else { return (InternalSpacePartition) spacePartitions.get(spaceInstance.getInstanceId() - 1); } } } // no need to sync since it is synced on Admin public void refreshScheduledSpaceMonitors() { for (Future fetcher : scheduledRuntimeFetchers.values()) { fetcher.cancel(false); } for (SpaceInstance spaceInstance : this) { Future fetcher = admin.scheduleWithFixedDelay(new ScheduledRuntimeFetcher(spaceInstance), admin.getScheduledSpaceMonitorInterval(), admin.getScheduledSpaceMonitorInterval(), TimeUnit.MILLISECONDS); scheduledRuntimeFetchers.put(spaceInstance.getUid(), fetcher); } } public int getSize() { return spaceInstancesByUID.size(); } public boolean isEmpty() { return spaceInstancesByUID.size() == 0; } public IJSpace getIJSpace() { if (space == null) { SpaceInstance firstInstance = null; for (SpaceInstance instance : spaceInstancesByUID.values()) { firstInstance = instance; break; } if (firstInstance == null) { if (logger.isDebugEnabled()) { logger.debug("Space " + getName() + " cannot create IJSpace since it has no instances"); } return null; } try { space = ((ISpaceProxy) ((InternalSpaceInstance) firstInstance).getIJSpace()).getClusteredSpace(); if (space.isSecured()) { ((ISpaceProxy)space).login(admin.getUserDetails()); } } catch (AdminException e) { throw e; } catch (Exception e) { throw new AdminException("Failed to fetch space", e); } } return space; } public GigaSpace getGigaSpace() { if (gigaSpace == null) { IJSpace ijSpace = getIJSpace(); if (ijSpace == null) { throw new AdminException("Cannot create GigaSpace object since no space instance is discovered"); } this.gigaSpace = new GigaSpaceConfigurer(ijSpace).clustered(true).gigaSpace(); } return this.gigaSpace; } public boolean waitFor(int numberOfSpaceInstances) { return waitFor(numberOfSpaceInstances, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit()); } public boolean waitFor(int numberOfSpaceInstances, long timeout, TimeUnit timeUnit) { final CountDownLatch latch = new CountDownLatch(numberOfSpaceInstances); SpaceInstanceAddedEventListener added = new SpaceInstanceAddedEventListener() { public void spaceInstanceAdded(SpaceInstance spaceInstance) { latch.countDown(); } }; getSpaceInstanceAdded().add(added); try { return latch.await(timeout, timeUnit); } catch (InterruptedException e) { return false; } finally { getSpaceInstanceAdded().remove(added); } } public boolean waitFor(int numberOfSpaceInstances, SpaceMode spaceMode) { return waitFor(numberOfSpaceInstances, spaceMode, admin.getDefaultTimeout(), admin.getDefaultTimeoutTimeUnit()); } public boolean waitFor(int numberOfSpaceInstances, final SpaceMode spaceMode, long timeout, TimeUnit timeUnit) { final CountDownLatch latch = new CountDownLatch(numberOfSpaceInstances); SpaceModeChangedEventListener modeChanged = new SpaceModeChangedEventListener() { public void spaceModeChanged(SpaceModeChangedEvent event) { if (event.getNewMode() == spaceMode) { latch.countDown(); } } }; getSpaceModeChanged().add(modeChanged); boolean result; try { result = latch.await(timeout, timeUnit); } catch (InterruptedException e) { return false; } finally { getSpaceModeChanged().remove(modeChanged); } if (result) { // double check again int sum = 0; for (SpaceInstance spaceInstance : this) { if (spaceInstance.getMode() == spaceMode) { sum++; } } if (sum < numberOfSpaceInstances) { return waitFor(numberOfSpaceInstances, spaceMode, timeout, timeUnit); } } return result; } public SpaceInstance[] getSpaceInstances() { return getInstances(); } public SpaceInstanceAddedEventManager getSpaceInstanceAdded() { return this.spaceInstanceAddedEventManager; } public SpaceInstanceRemovedEventManager getSpaceInstanceRemoved() { return this.spaceInstanceRemovedEventManager; } public void addLifecycleListener(SpaceInstanceLifecycleEventListener eventListener) { spaceInstanceAddedEventManager.add(eventListener); spaceInstanceRemovedEventManager.add(eventListener); } public void removeLifecycleListener(SpaceInstanceLifecycleEventListener eventListener) { spaceInstanceAddedEventManager.remove(eventListener); spaceInstanceRemovedEventManager.remove(eventListener); } public Admin getAdmin() { return this.admin; } private <T> T doWithInstance(InstanceCallback<T> callback, T naValue) { for (SpaceInstance spaceInstance : spaceInstancesByUID.values()) { return callback.doWithinstance((InternalSpaceInstance) spaceInstance); } return naValue; } private static interface InstanceCallback<T> { T doWithinstance(InternalSpaceInstance spaceInstance); } private class ScheduledRuntimeFetcher implements Runnable { private final InternalSpaceInstance spaceInstance; private ScheduledRuntimeFetcher(SpaceInstance spaceInstance) { this.spaceInstance = (InternalSpaceInstance) spaceInstance; } public void run() { try { final RuntimeHolder runtimeHolder = spaceInstance.getRuntimeHolder(); final StatisticsHolder statisticsHolder = spaceInstance.getStatisticsHolder(); final ReplicationStatistics replicationStatistics = (statisticsHolder == null) ? null : statisticsHolder.getReplicationStatistics(); if (runtimeHolder.getSpaceState() != null && (runtimeHolder.getSpaceState() == ISpaceState.STOPPED || runtimeHolder.getSpaceState() == ISpaceState.STARTING)) { // we don't want to update the space mode to until the space state is STARTED // The space instance starts as STOPPED then changes to STARTING and only after recovery is complete it's state STARTED if (logger.isTraceEnabled()) { logger.trace("Ignoring runtimeHolder of space:" + spaceInstance.getSpaceName() + " serviceID:" + spaceInstance.getServiceID() + " state="+runtimeHolder.getSpaceState()); } return; } DefaultSpace.this.admin.scheduleNonBlockingStateChange(new Runnable() { public void run() { spaceInstance.setMode(runtimeHolder.getSpaceMode()); if (spaceInstance.getPlatformLogicalVersion().greaterOrEquals(PlatformLogicalVersion.v8_0_5)) { if (replicationStatistics != null) { final List<OutgoingChannel> channels = replicationStatistics.getOutgoingReplication().getChannels(); ReplicationTarget[] replicationTargets = new ReplicationTarget[channels.size()]; int index = 0; for (OutgoingChannel outgoingChannel : channels) { ReplicationTargetType replicationTargetType; switch (outgoingChannel.getReplicationMode()) { case MIRROR: replicationTargetType = ReplicationTargetType.MIRROR_SERVICE; break; case GATEWAY: replicationTargetType = ReplicationTargetType.GATEWAY; break; case LOCAL_VIEW: replicationTargetType = ReplicationTargetType.LOCAL_VIEW; break; case DURABLE_NOTIFICATION: replicationTargetType = ReplicationTargetType.DURABLE_NOTIFICATION; break; case ACTIVE_SPACE: case BACKUP_SPACE: replicationTargetType = ReplicationTargetType.SPACE_INSTANCE; break; default: throw new IllegalArgumentException("Unexpected replication mode: " + outgoingChannel.getReplicationMode()); } ReplicationStatus replicationStatus; switch (outgoingChannel.getChannelState()) { case ACTIVE: replicationStatus = ReplicationStatus.ACTIVE; break; case CONNECTED: case DISCONNECTED: replicationStatus = ReplicationStatus.DISCONNECTED; break; default: throw new IllegalArgumentException("Unexpected channel state: " + outgoingChannel.getChannelState()); } SpaceInstance targetSpaceInstance = spaceInstancesByMemberName.get(outgoingChannel.getTargetMemberName()); if (targetSpaceInstance == null && replicationTargetType == ReplicationTargetType.MIRROR_SERVICE) { String mirrorServiceName = outgoingChannel.getTargetMemberName().split(":")[1]; Space mirrorServiceSpace = spaceInstance.getAdmin().getSpaces().getSpaceByName(mirrorServiceName); if (mirrorServiceSpace != null) { SpaceInstance[] instances = mirrorServiceSpace.getInstances(); if (instances.length > 0) { SpaceInstance mirrorInstance = instances[0]; if (mirrorInstance != null && mirrorInstance.getSpaceUrl().getSchema().equals("mirror")) { //note: don't cache it in spaceInstanceByMemberName map since we don't get a removal event on this instance targetSpaceInstance = mirrorInstance; } } } } replicationTargets[index++] = new ReplicationTarget((InternalSpaceInstance) targetSpaceInstance, replicationStatus, outgoingChannel.getTargetMemberName(), replicationTargetType); } spaceInstance.setReplicationTargets(replicationTargets); } } else { // Fall back to old path if (runtimeHolder.getReplicationStatus() != null) { Object[] memberNames = (Object[]) runtimeHolder.getReplicationStatus()[0]; int[] replicationStatus = (int[]) runtimeHolder.getReplicationStatus()[1]; ReplicationTarget[] replicationTargets = new ReplicationTarget[memberNames.length]; for (int i = 0; i < memberNames.length; i++) { if (memberNames[i] == null) { continue; } SpaceInstance targetSpaceInstance = spaceInstancesByMemberName.get(memberNames[i]); ReplicationTargetType replicationTargetType = ReplicationTargetType.SPACE_INSTANCE; //Check if target is a gateway, so we cannot locate a target space instance for it if (((String)memberNames[i]).startsWith(GatewayPolicy.GATEWAY_NAME_PREFIX)){ replicationTargetType = ReplicationTargetType.GATEWAY; }else { /* * If mirror-service is one of the replication target names, find its SpaceInstance. */ if (targetSpaceInstance == null) { //we don't know the name of the mirror-service space (it can be any name that is different from the cluster name) if (!((String)memberNames[i]).endsWith(":"+name)) { String mirrorServiceName = ((String)memberNames[i]).split(":")[1]; Space mirrorServiceSpace = spaceInstance.getAdmin().getSpaces().getSpaceByName(mirrorServiceName); if (mirrorServiceSpace != null) { SpaceInstance mirrorInstance = mirrorServiceSpace.getInstances()[0]; if (mirrorInstance != null && mirrorInstance.getSpaceUrl().getSchema().equals("mirror")) { //note: don't cache it in spaceInstanceByMemberName map since we don't get a removal event on this instance targetSpaceInstance = mirrorInstance; replicationTargetType = ReplicationTargetType.MIRROR_SERVICE; } } else { replicationTargetType = ReplicationTargetType.MIRROR_SERVICE; //we guess this is a mirror (since 8.0.1) } } }else { if (targetSpaceInstance != null && targetSpaceInstance.getSpaceUrl().getSchema().equals("mirror")) { replicationTargetType = ReplicationTargetType.MIRROR_SERVICE; } } } ReplicationStatus replStatus = null; switch (replicationStatus[i]) { case IRemoteJSpaceAdmin.REPLICATION_STATUS_ACTIVE: replStatus = ReplicationStatus.ACTIVE; break; case IRemoteJSpaceAdmin.REPLICATION_STATUS_DISCONNECTED: replStatus = ReplicationStatus.DISCONNECTED; break; case IRemoteJSpaceAdmin.REPLICATION_STATUS_DISABLED: replStatus = ReplicationStatus.DISABLED; break; } replicationTargets[i] = new ReplicationTarget((InternalSpaceInstance) targetSpaceInstance, replStatus, (String)memberNames[i], replicationTargetType); } spaceInstance.setReplicationTargets(replicationTargets); } } }}); } catch (SpaceUnavailableException e) { // space is going shutdown or abort process } catch (InactiveSpaceException e) { // ignore this (maybe we should add it as a state to a Space instance?) } catch (InterruptedSpaceException e) { ProcessingUnit pu = admin.getProcessingUnits().getProcessingUnit(name); if (pu == null || pu.getStatus() == DeploymentStatus.UNDEPLOYED) { logger.debug("Failed to get runtime information", e); } else { logger.warn("Failed to get runtime information", e); } } catch (Exception e) { if (NetworkExceptionHelper.isConnectOrCloseException(e)) { logger.debug("Failed to get runtime information", e); } else { logger.warn("Failed to get runtime information", e); } } } } private void assertStateChangesPermitted() { admin.assertStateChangesPermitted(); } }
GS-10441: Admin that recovers from network disconnection fails to fetch processing unit Space instance details. DefaultSpace.addInstance schedules a ScheduledRuntimeFetcher to fetch SpaceInstance details (SpaceMode, etc.) DefaultSpace.removeInstance cancels the future ScheduledRuntimeFetcher. But, it does not remove it from the map. When addInstance is called with the space instance that was discovered and disconnected, a new fetcher is started only if it is not in already in the map. Fix: remove it from the map so that next time it will be created. svn path=/xap/trunk/openspaces/; revision=123557 Former-commit-id: b564831a02684bde491191d4b0e2eac870170db1
src/main/src/org/openspaces/admin/internal/space/DefaultSpace.java
GS-10441: Admin that recovers from network disconnection fails to fetch processing unit Space instance details.
<ide><path>rc/main/src/org/openspaces/admin/internal/space/DefaultSpace.java <ide> spaceInstancesByMemberName.remove(fullSpaceName); <ide> spaceInstanceRemovedEventManager.spaceInstanceRemoved(spaceInstance); <ide> ((InternalSpaceInstanceRemovedEventManager) spaces.getSpaceInstanceRemoved()).spaceInstanceRemoved(spaceInstance); <del> Future fetcher = scheduledRuntimeFetchers.get(uid); <add> Future fetcher = scheduledRuntimeFetchers.remove(uid); <ide> if (fetcher != null) { <ide> fetcher.cancel(true); <ide> }
Java
mit
6423dc3639ee9826865027dc1235f6d849172c8a
0
sormuras/bach,sormuras/bach
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.sormuras.bach.task; import de.sormuras.bach.Bach; import de.sormuras.bach.Call; import de.sormuras.bach.Log; import de.sormuras.bach.project.Folder; import de.sormuras.bach.project.Realm; import de.sormuras.bach.project.Unit; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReference; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.ServiceLoader; import java.util.spi.ToolProvider; import java.util.stream.StreamSupport; class Tester { private final Bach bach; private final Realm realm; private final Log log; private final Folder folder; Tester(Bach bach, Realm realm) { this.bach = bach; this.realm = realm; this.log = bach.getLog(); this.folder = bach.getProject().folder(); } void test(Iterable<Unit> units) { log.debug("Launching all tests in realm " + realm); for (var unit : units) { log.debug("Testing %s...", unit); test(unit); } } private void test(Unit unit) { var modulePath = new ArrayList<Path>(); modulePath.add(bach.getProject().modularJar(unit)); // test module first modulePath.addAll(realm.modulePaths()); // compile dependencies next, like "main"... modulePath.add(folder.modules(realm.name())); // same realm last, like "test"... var layer = layer(modulePath, unit.name()); var errors = new StringBuilder(); errors.append(run(layer, "test(" + unit.name() + ")")); errors.append(run(layer, "junit", "--select-module", unit.name())); if (errors.toString().replace('0', ' ').isBlank()) { return; } throw new AssertionError("Test run failed! // " + errors); } private ModuleLayer layer(List<Path> modulePath, String module) { var finder = ModuleFinder.of(modulePath.toArray(Path[]::new)); var roots = List.of(module); if (bach.isVerbose()) { log.debug("Module path:"); for (var element : modulePath) { log.debug(" -> %s", element); } log.debug("Finder finds module(s):"); finder.findAll().stream() .sorted(Comparator.comparing(ModuleReference::descriptor)) .forEach(reference -> log.debug(" -> %s", reference)); log.debug("Root module(s):"); for (var root : roots) { log.debug(" -> %s", root); } } var boot = ModuleLayer.boot(); var configuration = boot.configuration().resolveAndBind(ModuleFinder.ofSystem(), finder, roots); var loader = ClassLoader.getPlatformClassLoader(); var controller = ModuleLayer.defineModulesWithOneLoader(configuration, List.of(boot), loader); return controller.layer(); } private int run(ModuleLayer layer, String name, String... args) { var serviceLoader = ServiceLoader.load(layer, ToolProvider.class); return StreamSupport.stream(serviceLoader.spliterator(), false) .filter(provider -> provider.name().equals(name)) .mapToInt(tool -> Math.abs(run(tool, args))) .sum(); } private int run(ToolProvider tool, String... args) { var toolLoader = tool.getClass().getClassLoader(); var currentThread = Thread.currentThread(); var currentContextLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(toolLoader); try { var parent = toolLoader; while (parent != null) { parent.setDefaultAssertionStatus(true); parent = parent.getParent(); } return bach.run(tool, new Call(tool.name(), args)); } finally { currentThread.setContextClassLoader(currentContextLoader); } } }
src/de.sormuras.bach/main/java/de/sormuras/bach/task/Tester.java
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.sormuras.bach.task; import de.sormuras.bach.Bach; import de.sormuras.bach.Call; import de.sormuras.bach.Log; import de.sormuras.bach.project.Folder; import de.sormuras.bach.project.Realm; import de.sormuras.bach.project.Unit; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReference; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.ServiceLoader; import java.util.spi.ToolProvider; import java.util.stream.StreamSupport; class Tester { private final Bach bach; private final Realm realm; private final Log log; private final Folder folder; Tester(Bach bach, Realm realm) { this.bach = bach; this.realm = realm; this.log = bach.getLog(); this.folder = bach.getProject().folder(); } void test(Iterable<Unit> units) { log.debug("Launching all tests in realm " + realm); for (var unit : units) { log.debug("Testing %s...", unit); test(unit); } } private void test(Unit unit) { var modulePath = new ArrayList<Path>(); modulePath.add(bach.getProject().modularJar(unit)); // test module first modulePath.addAll(realm.modulePaths()); // compile dependencies next, like "main"... modulePath.add(folder.modules(realm.name())); // same realm last, like "test"... var layer = layer(modulePath, unit.name()); var errors = new StringBuilder(); errors.append(run(layer, "test(" + unit.name() + ")")); errors.append(run(layer, "junit", "--select-module", unit.name())); if (errors.toString().replace('0', ' ').isBlank()) { return; } throw new AssertionError("Test run failed! // " + errors); } private ModuleLayer layer(List<Path> modulePath, String module) { var finder = ModuleFinder.of(modulePath.toArray(Path[]::new)); var roots = List.of(module); if (bach.isVerbose()) { log.debug("Module path:"); for (var element : modulePath) { log.debug(" -> %s", element); } log.debug("Finder finds module(s):"); finder.findAll().stream() .sorted(Comparator.comparing(ModuleReference::descriptor)) .forEach(reference -> log.debug(" -> %s", reference)); log.debug("Root module(s):"); for (var root : roots) { log.debug(" -> %s", root); } } var boot = ModuleLayer.boot(); var configuration = boot.configuration().resolveAndBind(finder, ModuleFinder.ofSystem(), roots); var loader = ClassLoader.getPlatformClassLoader(); var controller = ModuleLayer.defineModulesWithOneLoader(configuration, List.of(boot), loader); return controller.layer(); } private int run(ModuleLayer layer, String name, String... args) { var serviceLoader = ServiceLoader.load(layer, ToolProvider.class); return StreamSupport.stream(serviceLoader.spliterator(), false) .filter(provider -> provider.name().equals(name)) .mapToInt(tool -> Math.abs(run(tool, args))) .sum(); } private int run(ToolProvider tool, String... args) { var toolLoader = tool.getClass().getClassLoader(); var currentThread = Thread.currentThread(); var currentContextLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(toolLoader); try { var parent = toolLoader; while (parent != null) { parent.setDefaultAssertionStatus(true); parent = parent.getParent(); } return bach.run(tool, new Call(tool.name(), args)); } finally { currentThread.setContextClassLoader(currentContextLoader); } } }
Let system modules be located before custom modules
src/de.sormuras.bach/main/java/de/sormuras/bach/task/Tester.java
Let system modules be located before custom modules
<ide><path>rc/de.sormuras.bach/main/java/de/sormuras/bach/task/Tester.java <ide> } <ide> } <ide> var boot = ModuleLayer.boot(); <del> var configuration = boot.configuration().resolveAndBind(finder, ModuleFinder.ofSystem(), roots); <add> var configuration = boot.configuration().resolveAndBind(ModuleFinder.ofSystem(), finder, roots); <ide> var loader = ClassLoader.getPlatformClassLoader(); <ide> var controller = ModuleLayer.defineModulesWithOneLoader(configuration, List.of(boot), loader); <ide> return controller.layer();
Java
apache-2.0
ca7e3d54eb9563da76b018184bfb9e1009dbd9e9
0
apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.airavata.helix.workflow; import org.apache.airavata.helix.core.AbstractTask; import org.apache.airavata.helix.core.OutPort; import org.apache.airavata.helix.core.util.TaskUtil; import org.apache.airavata.helix.task.api.annotation.TaskDef; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.task.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * TODO: Class level comments please * * @author dimuthu * @since 1.0.0-SNAPSHOT */ public class WorkflowOperator { private final static Logger logger = LoggerFactory.getLogger(WorkflowOperator.class); private static final String WORKFLOW_PREFIX = "Workflow_of_process_"; private static final long WORKFLOW_EXPIRY_TIME = 1 * 1000; private static final long TASK_EXPIRY_TIME = 24 * 60 * 60 * 1000; private TaskDriver taskDriver; private HelixManager helixManager; public WorkflowOperator(String helixClusterName, String instanceName, String zkConnectionString) throws Exception { helixManager = HelixManagerFactory.getZKHelixManager(helixClusterName, instanceName, InstanceType.SPECTATOR, zkConnectionString); helixManager.connect(); Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { if (helixManager != null && helixManager.isConnected()) { helixManager.disconnect(); } } } ); taskDriver = new TaskDriver(helixManager); } public void disconnect() { if (helixManager != null && helixManager.isConnected()) { helixManager.disconnect(); } } public synchronized String launchWorkflow(String processId, List<AbstractTask> tasks, boolean globalParticipant, boolean monitor) throws Exception { String workflowName = WORKFLOW_PREFIX + processId; logger.info("Launching workflow " + workflowName + " for process " + processId); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName).setExpiry(0); for (int i = 0; i < tasks.size(); i++) { AbstractTask data = tasks.get(i); String taskType = data.getClass().getAnnotation(TaskDef.class).name(); TaskConfig.Builder taskBuilder = new TaskConfig.Builder().setTaskId("Task_" + data.getTaskId()) .setCommand(taskType); Map<String, String> paramMap = org.apache.airavata.helix.core.util.TaskUtil.serializeTaskData(data); paramMap.forEach(taskBuilder::addConfig); List<TaskConfig> taskBuilds = new ArrayList<>(); taskBuilds.add(taskBuilder.build()); JobConfig.Builder job = new JobConfig.Builder() .addTaskConfigs(taskBuilds) .setFailureThreshold(0) .setExpiry(WORKFLOW_EXPIRY_TIME) .setTimeoutPerTask(TASK_EXPIRY_TIME) .setNumConcurrentTasksPerInstance(20) .setMaxAttemptsPerTask(data.getRetryCount()); if (!globalParticipant) { job.setInstanceGroupTag(taskType); } workflowBuilder.addJob((data.getTaskId()), job); List<OutPort> outPorts = TaskUtil.getOutPortsOfTask(data); outPorts.forEach(outPort -> { if (outPort != null) { workflowBuilder.addParentChildDependency(data.getTaskId(), outPort.getNextJobId()); } }); } WorkflowConfig.Builder config = new WorkflowConfig.Builder().setFailureThreshold(0); workflowBuilder.setWorkflowConfig(config.build()); workflowBuilder.setExpiry(WORKFLOW_EXPIRY_TIME); Workflow workflow = workflowBuilder.build(); taskDriver.start(workflow); //TODO : Do we need to monitor workflow status? If so how do we do it in a scalable manner? For example, // if the hfac that monitors a particular workflow, got killed due to some reason, who is taking the responsibility if (monitor) { TaskState taskState = pollForWorkflowCompletion(workflow.getName(), 3600000); logger.info("Workflow " + workflowName + " for process " + processId + " finished with state " + taskState.name()); } return workflowName; } public synchronized TaskState pollForWorkflowCompletion(String workflowName, long timeout) throws InterruptedException { return taskDriver.pollForWorkflowState(workflowName, timeout, TaskState.COMPLETED, TaskState.FAILED, TaskState.STOPPED, TaskState.ABORTED); } public TaskState getWorkflowState(String workflow) { return taskDriver.getWorkflowContext(workflow).getWorkflowState(); } }
modules/airavata-helix/workflow-impl/src/main/java/org/apache/airavata/helix/workflow/WorkflowOperator.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.airavata.helix.workflow; import org.apache.airavata.helix.core.AbstractTask; import org.apache.airavata.helix.core.OutPort; import org.apache.airavata.helix.core.util.TaskUtil; import org.apache.airavata.helix.task.api.annotation.TaskDef; import org.apache.helix.HelixManager; import org.apache.helix.HelixManagerFactory; import org.apache.helix.InstanceType; import org.apache.helix.task.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * TODO: Class level comments please * * @author dimuthu * @since 1.0.0-SNAPSHOT */ public class WorkflowOperator { private final static Logger logger = LoggerFactory.getLogger(WorkflowOperator.class); private static final String WORKFLOW_PREFIX = "Workflow_of_process_"; private static final long WORKFLOW_EXPIRY_TIME = 1 * 1000; private TaskDriver taskDriver; private HelixManager helixManager; public WorkflowOperator(String helixClusterName, String instanceName, String zkConnectionString) throws Exception { helixManager = HelixManagerFactory.getZKHelixManager(helixClusterName, instanceName, InstanceType.SPECTATOR, zkConnectionString); helixManager.connect(); Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { if (helixManager != null && helixManager.isConnected()) { helixManager.disconnect(); } } } ); taskDriver = new TaskDriver(helixManager); } public void disconnect() { if (helixManager != null && helixManager.isConnected()) { helixManager.disconnect(); } } public synchronized String launchWorkflow(String processId, List<AbstractTask> tasks, boolean globalParticipant, boolean monitor) throws Exception { String workflowName = WORKFLOW_PREFIX + processId; logger.info("Launching workflow " + workflowName + " for process " + processId); Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName).setExpiry(0); for (int i = 0; i < tasks.size(); i++) { AbstractTask data = tasks.get(i); String taskType = data.getClass().getAnnotation(TaskDef.class).name(); TaskConfig.Builder taskBuilder = new TaskConfig.Builder().setTaskId("Task_" + data.getTaskId()) .setCommand(taskType); Map<String, String> paramMap = org.apache.airavata.helix.core.util.TaskUtil.serializeTaskData(data); paramMap.forEach(taskBuilder::addConfig); List<TaskConfig> taskBuilds = new ArrayList<>(); taskBuilds.add(taskBuilder.build()); JobConfig.Builder job = new JobConfig.Builder() .addTaskConfigs(taskBuilds) .setFailureThreshold(0) .setExpiry(WORKFLOW_EXPIRY_TIME) .setNumConcurrentTasksPerInstance(20) .setMaxAttemptsPerTask(data.getRetryCount()); if (!globalParticipant) { job.setInstanceGroupTag(taskType); } workflowBuilder.addJob((data.getTaskId()), job); List<OutPort> outPorts = TaskUtil.getOutPortsOfTask(data); outPorts.forEach(outPort -> { if (outPort != null) { workflowBuilder.addParentChildDependency(data.getTaskId(), outPort.getNextJobId()); } }); } WorkflowConfig.Builder config = new WorkflowConfig.Builder().setFailureThreshold(0); workflowBuilder.setWorkflowConfig(config.build()); workflowBuilder.setExpiry(WORKFLOW_EXPIRY_TIME); Workflow workflow = workflowBuilder.build(); taskDriver.start(workflow); //TODO : Do we need to monitor workflow status? If so how do we do it in a scalable manner? For example, // if the hfac that monitors a particular workflow, got killed due to some reason, who is taking the responsibility if (monitor) { TaskState taskState = pollForWorkflowCompletion(workflow.getName(), 3600000); logger.info("Workflow " + workflowName + " for process " + processId + " finished with state " + taskState.name()); } return workflowName; } public synchronized TaskState pollForWorkflowCompletion(String workflowName, long timeout) throws InterruptedException { return taskDriver.pollForWorkflowState(workflowName, timeout, TaskState.COMPLETED, TaskState.FAILED, TaskState.STOPPED, TaskState.ABORTED); } public TaskState getWorkflowState(String workflow) { return taskDriver.getWorkflowContext(workflow).getWorkflowState(); } }
Setting the task expiry to 24 hours
modules/airavata-helix/workflow-impl/src/main/java/org/apache/airavata/helix/workflow/WorkflowOperator.java
Setting the task expiry to 24 hours
<ide><path>odules/airavata-helix/workflow-impl/src/main/java/org/apache/airavata/helix/workflow/WorkflowOperator.java <ide> <ide> private static final String WORKFLOW_PREFIX = "Workflow_of_process_"; <ide> private static final long WORKFLOW_EXPIRY_TIME = 1 * 1000; <add> private static final long TASK_EXPIRY_TIME = 24 * 60 * 60 * 1000; <ide> private TaskDriver taskDriver; <ide> private HelixManager helixManager; <ide> <ide> .addTaskConfigs(taskBuilds) <ide> .setFailureThreshold(0) <ide> .setExpiry(WORKFLOW_EXPIRY_TIME) <add> .setTimeoutPerTask(TASK_EXPIRY_TIME) <ide> .setNumConcurrentTasksPerInstance(20) <ide> .setMaxAttemptsPerTask(data.getRetryCount()); <ide>
Java
apache-2.0
60337599198722629caa3e193c19dc2f201747af
0
fivesmallq/web-data-extractor,fivesmallq/web-data-extractor
package im.nll.data.extractor.impl; import com.google.common.base.Charsets; import com.google.common.io.Resources; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; /** * @author <a href="mailto:[email protected]">fivesmallq</a> * @version Revision: 1.0 * @date 15/12/30 下午3:42 */ public class StringRangeExtractorTest { private String html; StringRangeExtractor stringRangeExtractor; @Before public void setUp() throws Exception { try { html = Resources.toString(Resources.getResource("list.html"), Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } } @Test public void testExtract() throws Exception { String demoHtml = "<td>www.baidu.com</td>"; stringRangeExtractor = new StringRangeExtractor("<td>", "</td>"); String result = stringRangeExtractor.extract(demoHtml); Assert.assertEquals(result, "www.baidu.com"); stringRangeExtractor = new StringRangeExtractor("x", "xx"); result = stringRangeExtractor.extract(demoHtml); Assert.assertEquals(result, ""); stringRangeExtractor = new StringRangeExtractor("<td>", "</td>", "true"); result = stringRangeExtractor.extract(demoHtml); Assert.assertEquals(result, "<td>www.baidu.com</td>"); stringRangeExtractor = new StringRangeExtractor("<td>", "</td>", "false"); result = stringRangeExtractor.extract(demoHtml); Assert.assertEquals(result, "www.baidu.com"); } @Test public void testExtractList() throws Exception { stringRangeExtractor = new StringRangeExtractor("<tr class=\"item\">", "</tr>", "true"); List<String> stringList = stringRangeExtractor.extractList(html); Assert.assertNotNull(stringList); Assert.assertEquals(stringList.size(), 3); Assert.assertEquals("<tr class=\"item\">\n" + " <td class=\"type\">dynamic</td>\n" + " <td class=\"name\">Python</td>\n" + " <td class=\"url\">>https://www.python.org</td>\n" + " </tr>", stringList.get(2)); stringRangeExtractor = new StringRangeExtractor("<tr class=\"item\">", "</tr>", "false"); stringList = stringRangeExtractor.extractList(html); Assert.assertNotNull(stringList); Assert.assertEquals(stringList.size(), 3); Assert.assertEquals("\n" + " <td class=\"type\">dynamic</td>\n" + " <td class=\"name\">Python</td>\n" + " <td class=\"url\">>https://www.python.org</td>\n" + " ", stringList.get(2)); } }
src/test/java/im/nll/data/extractor/impl/StringRangeExtractorTest.java
package im.nll.data.extractor.impl; import com.google.common.base.Charsets; import com.google.common.io.Resources; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; /** * @author <a href="mailto:[email protected]">fivesmallq</a> * @version Revision: 1.0 * @date 15/12/30 下午3:42 */ public class StringRangeExtractorTest { private String html; StringRangeExtractor stringRangeExtractor; @Before public void setUp() throws Exception { try { html = Resources.toString(Resources.getResource("list2.html"), Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } } @Test public void testExtract() throws Exception { String demoHtml = "<td>www.baidu.com</td>"; stringRangeExtractor = new StringRangeExtractor("<td>", "</td>"); String result = stringRangeExtractor.extract(demoHtml); Assert.assertEquals(result, "www.baidu.com"); stringRangeExtractor = new StringRangeExtractor("x", "xx"); result = stringRangeExtractor.extract(demoHtml); Assert.assertEquals(result, ""); stringRangeExtractor = new StringRangeExtractor("<td>", "</td>", "true"); result = stringRangeExtractor.extract(demoHtml); Assert.assertEquals(result, "<td>www.baidu.com</td>"); stringRangeExtractor = new StringRangeExtractor("<td>", "</td>", "false"); result = stringRangeExtractor.extract(demoHtml); Assert.assertEquals(result, "www.baidu.com"); } @Test public void testExtractList() throws Exception { stringRangeExtractor = new StringRangeExtractor("<td style", "</td>", "true"); List<String> stringList = stringRangeExtractor.extractList(html); Assert.assertNotNull(stringList); Assert.assertEquals(stringList.size(), 5); Assert.assertEquals(stringList.get(3), "<td style=\"text-align:center;\">4</td>"); stringRangeExtractor = new StringRangeExtractor("<td style", "</td>", "false"); stringList = stringRangeExtractor.extractList(html); Assert.assertNotNull(stringList); Assert.assertEquals(stringList.size(), 5); Assert.assertEquals(stringList.get(3), "=\"text-align:center;\">4"); } }
fix String Range test
src/test/java/im/nll/data/extractor/impl/StringRangeExtractorTest.java
fix String Range test
<ide><path>rc/test/java/im/nll/data/extractor/impl/StringRangeExtractorTest.java <ide> @Before <ide> public void setUp() throws Exception { <ide> try { <del> html = Resources.toString(Resources.getResource("list2.html"), Charsets.UTF_8); <add> html = Resources.toString(Resources.getResource("list.html"), Charsets.UTF_8); <ide> } catch (IOException e) { <ide> e.printStackTrace(); <ide> } <ide> <ide> @Test <ide> public void testExtractList() throws Exception { <del> stringRangeExtractor = new StringRangeExtractor("<td style", "</td>", "true"); <add> stringRangeExtractor = new StringRangeExtractor("<tr class=\"item\">", "</tr>", "true"); <ide> List<String> stringList = stringRangeExtractor.extractList(html); <ide> Assert.assertNotNull(stringList); <del> Assert.assertEquals(stringList.size(), 5); <del> Assert.assertEquals(stringList.get(3), "<td style=\"text-align:center;\">4</td>"); <del> stringRangeExtractor = new StringRangeExtractor("<td style", "</td>", "false"); <add> Assert.assertEquals(stringList.size(), 3); <add> Assert.assertEquals("<tr class=\"item\">\n" + <add> " <td class=\"type\">dynamic</td>\n" + <add> " <td class=\"name\">Python</td>\n" + <add> " <td class=\"url\">>https://www.python.org</td>\n" + <add> " </tr>", stringList.get(2)); <add> stringRangeExtractor = new StringRangeExtractor("<tr class=\"item\">", "</tr>", "false"); <ide> stringList = stringRangeExtractor.extractList(html); <ide> Assert.assertNotNull(stringList); <del> Assert.assertEquals(stringList.size(), 5); <del> Assert.assertEquals(stringList.get(3), "=\"text-align:center;\">4"); <add> Assert.assertEquals(stringList.size(), 3); <add> Assert.assertEquals("\n" + <add> " <td class=\"type\">dynamic</td>\n" + <add> " <td class=\"name\">Python</td>\n" + <add> " <td class=\"url\">>https://www.python.org</td>\n" + <add> " ", stringList.get(2)); <ide> <ide> } <ide> }
Java
apache-2.0
e3ccfffd3e43504bff5044918d6abc0d4e37d5c6
0
jjj117/airavata,dogless/airavata,anujbhan/airavata,machristie/airavata,jjj117/airavata,machristie/airavata,jjj117/airavata,glahiru/airavata,anujbhan/airavata,gouravshenoy/airavata,jjj117/airavata,jjj117/airavata,anujbhan/airavata,gouravshenoy/airavata,glahiru/airavata,apache/airavata,anujbhan/airavata,machristie/airavata,machristie/airavata,apache/airavata,hasinitg/airavata,gouravshenoy/airavata,hasinitg/airavata,gouravshenoy/airavata,glahiru/airavata,gouravshenoy/airavata,apache/airavata,jjj117/airavata,hasinitg/airavata,anujbhan/airavata,apache/airavata,machristie/airavata,gouravshenoy/airavata,gouravshenoy/airavata,anujbhan/airavata,hasinitg/airavata,glahiru/airavata,apache/airavata,dogless/airavata,dogless/airavata,anujbhan/airavata,dogless/airavata,apache/airavata,hasinitg/airavata,glahiru/airavata,machristie/airavata,machristie/airavata,apache/airavata,dogless/airavata,dogless/airavata,hasinitg/airavata,apache/airavata
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.registry.api.impl; import org.apache.airavata.common.registry.api.exception.RegistryException; import org.apache.airavata.common.registry.api.impl.JCRRegistry; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.commons.gfac.wsdl.WSDLConstants; import org.apache.airavata.commons.gfac.wsdl.WSDLGenerator; import org.apache.airavata.registry.api.Axis2Registry; import org.apache.airavata.registry.api.DataRegistry; import org.apache.airavata.registry.api.WorkflowExecution; import org.apache.airavata.registry.api.WorkflowExecutionStatus; import org.apache.airavata.registry.api.WorkflowExecutionStatus.ExecutionStatus; import org.apache.airavata.registry.api.exception.DeploymentDescriptionRetrieveException; import org.apache.airavata.registry.api.exception.HostDescriptionRetrieveException; import org.apache.airavata.registry.api.exception.ServiceDescriptionRetrieveException; import org.apache.airavata.registry.api.workflow.WorkflowIOData; import org.apache.airavata.registry.api.workflow.WorkflowServiceIOData; import org.apache.airavata.schemas.gfac.MethodType; import org.apache.airavata.schemas.gfac.PortTypeType; import org.apache.airavata.schemas.gfac.ServiceType; import org.apache.airavata.schemas.gfac.ServiceType.ServiceName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.*; import javax.xml.namespace.QName; import java.net.URI; import java.sql.Timestamp; import java.util.*; import java.util.regex.Pattern; public class AiravataJCRRegistry extends JCRRegistry implements Axis2Registry, DataRegistry { private static final String OUTPUT_NODE_NAME = "OUTPUTS"; private static final String SERVICE_NODE_NAME = "SERVICE_HOST"; private static final String GFAC_INSTANCE_DATA = "GFAC_INSTANCE_DATA"; private static final String DEPLOY_NODE_NAME = "APP_HOST"; private static final String HOST_NODE_NAME = "GFAC_HOST"; private static final String XML_PROPERTY_NAME = "XML"; private static final String WSDL_PROPERTY_NAME = "WSDL"; private static final String GFAC_URL_PROPERTY_NAME = "GFAC_URL_LIST"; private static final String LINK_NAME = "LINK"; private static final String PROPERTY_WORKFLOW_NAME = "workflowName"; private static final String PROPERTY_WORKFLOW_IO_CONTENT = "content"; public static final String WORKFLOWS = "WORKFLOWS"; public static final String PUBLIC = "PUBLIC"; public static final String REGISTRY_TYPE_WORKFLOW = "workflow"; public static final int GFAC_URL_UPDATE_INTERVAL = 1000 * 60 * 60 * 3; public static final String WORKFLOW_DATA = "experiments"; public static final String INPUT = "Input"; public static final String OUTPUT = "Output"; public static final String RESULT = "Result"; public static final String WORKFLOW_STATUS_PROPERTY = "Status"; public static final String WORKFLOW_STATUS_TIME_PROPERTY = "Status_Time"; public static final String WORKFLOW_METADATA_PROPERTY = "Metadata"; public static final String WORKFLOW_USER_PROPERTY = "User"; private static Logger log = LoggerFactory.getLogger(AiravataJCRRegistry.class); public AiravataJCRRegistry(URI repositoryURI, String className, String user, String pass, Map<String, String> map) throws RepositoryException { super(repositoryURI, className, user, pass, map); } private Node getServiceNode(Session session) throws RepositoryException { return getOrAddNode(getRootNode(session), SERVICE_NODE_NAME); } private Node getDeploymentNode(Session session) throws RepositoryException { return getOrAddNode(getRootNode(session), DEPLOY_NODE_NAME); } private Node getHostNode(Session session) throws RepositoryException { return getOrAddNode(getRootNode(session), HOST_NODE_NAME); } // public List<HostDescription> getServiceLocation(String serviceId) { // Session session = null; // ArrayList<HostDescription> result = new ArrayList<HostDescription>(); // try { // session = getSession(); // Node node = getServiceNode(session); // Node serviceNode = node.getNode(serviceId); // if (serviceNode.hasProperty(LINK_NAME)) { // Property prop = serviceNode.getProperty(LINK_NAME); // Value[] vals = prop.getValues(); // for (Value val : vals) { // Node host = session.getNodeByIdentifier(val.getString()); // Property hostProp = host.getProperty(XML_PROPERTY_NAME); // result.add(HostDescription.fromXML(hostProp.getString())); // } // } // } catch (Exception e) { // System.out.println(e); // e.printStackTrace(); // // TODO propagate // } finally { // closeSession(session); // } // return result; // } public void deleteServiceDescription(String serviceId) throws ServiceDescriptionRetrieveException { Session session = null; try { session = getSession(); Node serviceNode = getServiceNode(session); Node node = serviceNode.getNode(serviceId); if (node != null) { node.remove(); session.save(); // triggerObservers(this); } } catch (Exception e) { throw new ServiceDescriptionRetrieveException(e); } finally { closeSession(session); } } public ServiceDescription getServiceDescription(String serviceId) throws ServiceDescriptionRetrieveException { Session session = null; ServiceDescription result = null; try { session = getSession(); Node serviceNode = getServiceNode(session); Node node = serviceNode.getNode(serviceId); Property prop = node.getProperty(XML_PROPERTY_NAME); result = ServiceDescription.fromXML(prop.getString()); } catch (Exception e) { throw new ServiceDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public ApplicationDeploymentDescription getDeploymentDescription(String serviceId, String hostId) throws RegistryException { Session session = null; ApplicationDeploymentDescription result = null; try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceId); Node hostNode = serviceNode.getNode(hostId); List<Node> childNodes = getChildNodes(hostNode); for (Node app:childNodes) { Property prop = app.getProperty(XML_PROPERTY_NAME); result = ApplicationDeploymentDescription.fromXML(prop.getString()); break; } } catch (PathNotFoundException e) { return null; } catch (Exception e) { log.error("Cannot get Deployment Description", e); throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public void deleteHostDescription(String hostId) throws RegistryException { Session session = null; try { session = getSession(); Node hostNode = getHostNode(session); Node node = hostNode.getNode(hostId); if (node != null) { node.remove(); session.save(); // triggerObservers(this); } } catch (Exception e) { throw new HostDescriptionRetrieveException(e); } finally { closeSession(session); } } public ServiceDescription getServiceDesc(String serviceId) throws ServiceDescriptionRetrieveException { Session session = null; ServiceDescription result = null; try { session = getSession(); Node serviceNode = getServiceNode(session); Node node = serviceNode.getNode(serviceId); Property prop = node.getProperty(XML_PROPERTY_NAME); result = ServiceDescription.fromXML(prop.getString()); } catch (PathNotFoundException e) { return null; } catch (Exception e) { throw new ServiceDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public HostDescription getHostDescription(String hostId) throws RegistryException { Session session = null; HostDescription result = null; try { session = getSession(); Node hostNode = getHostNode(session); Node node = hostNode.getNode(hostId); if (node != null) { result = getHostDescriptor(node); } } catch (PathNotFoundException e) { return null; } catch (Exception e) { log.debug(e.getMessage()); e.printStackTrace(); throw new HostDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } private HostDescription getHostDescriptor(Node node) throws RegistryException { HostDescription result; try { Property prop = node.getProperty(XML_PROPERTY_NAME); result = HostDescription.fromXML(prop.getString()); } catch (Exception e) { throw new HostDescriptionRetrieveException(e); } return result; } public String saveHostDescription(HostDescription host) throws RegistryException{ Session session = null; String result = null; try { session = getSession(); Node hostNode = getHostNode(session); Node node = getOrAddNode(hostNode, host.getType().getHostName()); node.setProperty(XML_PROPERTY_NAME, host.toXML()); session.save(); result = node.getIdentifier(); // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving host description!!!", e); } finally { closeSession(session); } return result; } public String saveServiceDescription(ServiceDescription service) throws RegistryException{ Session session = null; String result = null; try { session = getSession(); Node serviceNode = getServiceNode(session); Node node = getOrAddNode(serviceNode, service.getType().getName()); node.setProperty(XML_PROPERTY_NAME, service.toXML()); session.save(); result = node.getIdentifier(); // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving service description!!!", e); } finally { closeSession(session); } return result; } public String saveDeploymentDescription(String serviceId, String hostId, ApplicationDeploymentDescription app) throws RegistryException { Session session = null; String result = null; try { session = getSession(); Node deployNode = getDeploymentNode(session); Node serviceNode = getOrAddNode(deployNode, serviceId); Node hostNode = getOrAddNode(serviceNode, hostId); Node appName = getOrAddNode(hostNode, app.getType().getApplicationName().getStringValue()); appName.setProperty(XML_PROPERTY_NAME, app.toXML()); session.save(); result = appName.getIdentifier(); // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving deployment description!!!", e); } finally { closeSession(session); } return result; } public boolean deployServiceOnHost(String serviceId, String hostId)throws RegistryException { Session session = null; try { session = getSession(); Node serviceRoot = getServiceNode(session); Node hostRoot = getHostNode(session); Node serviceNode = serviceRoot.getNode(serviceId); Node hostNode = hostRoot.getNode(hostId); if (!serviceNode.hasProperty(LINK_NAME)) { serviceNode.setProperty(LINK_NAME, new String[] { hostNode.getIdentifier() }); } else { Property prop = serviceNode.getProperty(LINK_NAME); Value[] vals = prop.getValues(); ArrayList<String> s = new ArrayList<String>(); for (Value val : vals) { s.add(val.getString()); } if (s.contains(hostNode.getIdentifier())) { return false; } s.add(hostNode.getIdentifier()); serviceNode.setProperty(LINK_NAME, s.toArray(new String[0])); } session.save(); return true; } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving service on host!!!", e); } finally { closeSession(session); } } public List<ServiceDescription> searchServiceDescription(String nameRegEx) throws RegistryException { Session session = null; ArrayList<ServiceDescription> result = new ArrayList<ServiceDescription>(); try { session = getSession(); Node node = getServiceNode(session); List<Node> childNodes = getChildNodes(node); for (Node service:childNodes) { if (nameRegEx.equals("") || service.getName().matches(nameRegEx)) { Property prop = service.getProperty(XML_PROPERTY_NAME); result.add(ServiceDescription.fromXML(prop.getString())); } } } catch (Exception e) { throw new ServiceDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public List<HostDescription> searchHostDescription(String nameRegEx) throws RegistryException { Session session = null; List<HostDescription> result = new ArrayList<HostDescription>(); try { session = getSession(); Node node = getHostNode(session); List<Node> childNodes = getChildNodes(node); for (Node host:childNodes) { if (host != null && host.getName().matches(nameRegEx)) { HostDescription hostDescriptor = getHostDescriptor(host); result.add(hostDescriptor); } } } catch (Exception e) { throw new HostDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public Map<ApplicationDeploymentDescription, String> searchDeploymentDescription() throws RegistryException { Session session = null; Map<ApplicationDeploymentDescription, String> result = new HashMap<ApplicationDeploymentDescription, String>(); try { session = getSession(); Node deploymentNode = getDeploymentNode(session); List<Node> childNodes = getChildNodes(deploymentNode); for (Node serviceNode:childNodes) { List<Node> childNodes2 = getChildNodes(serviceNode); for (Node hostNode:childNodes2) { List<Node> childNodes3 = getChildNodes(hostNode); for (Node app:childNodes3) { Property prop = app.getProperty(XML_PROPERTY_NAME); result.put(ApplicationDeploymentDescription.fromXML(prop.getString()), serviceNode.getName() + "$" + hostNode.getName()); } } } } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public void deleteDeploymentDescription(String serviceName, String hostName, String applicationName) throws RegistryException { Session session = null; try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceName); Node hostNode = serviceNode.getNode(hostName); hostNode.remove(); session.save(); } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } } public List<ApplicationDeploymentDescription> searchDeploymentDescription(String serviceName, String hostName, String applicationName) throws RegistryException { Session session = null; List<ApplicationDeploymentDescription> result = new ArrayList<ApplicationDeploymentDescription>(); try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceName); Node hostNode = serviceNode.getNode(hostName); List<Node> childNodes = getChildNodes(hostNode); for (Node app:childNodes) { Property prop = app.getProperty(XML_PROPERTY_NAME); ApplicationDeploymentDescription appDesc = ApplicationDeploymentDescription.fromXML(prop.getString()); if (appDesc.getType().getApplicationName().getStringValue().matches(applicationName)) { result.add(appDesc); } } } catch (PathNotFoundException e) { return result; } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public Map<HostDescription,List<ApplicationDeploymentDescription>> searchDeploymentDescription(String serviceName) throws RegistryException{ Session session = null; Map<HostDescription,List<ApplicationDeploymentDescription>> result = new HashMap<HostDescription,List<ApplicationDeploymentDescription>>(); try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceName); List<Node> childNodes = getChildNodes(serviceNode); for (Node hostNode:childNodes) { HostDescription hostDescriptor = getHostDescription(hostNode.getName()); List<Node> childNodes2 = getChildNodes(hostNode); for (Node app:childNodes2) { result.put(hostDescriptor, new ArrayList<ApplicationDeploymentDescription>()); Property prop = app.getProperty(XML_PROPERTY_NAME); result.get(hostDescriptor).add(ApplicationDeploymentDescription.fromXML(prop.getString())); } } }catch (PathNotFoundException e){ return result; } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public List<ApplicationDeploymentDescription> searchDeploymentDescription(String serviceName, String hostName) throws RegistryException { Session session = null; List<ApplicationDeploymentDescription> result = new ArrayList<ApplicationDeploymentDescription>(); try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceName); Node hostNode = serviceNode.getNode(hostName); List<Node> childNodes = getChildNodes(hostNode); for (Node app:childNodes) { Property prop = app.getProperty(XML_PROPERTY_NAME); result.add(ApplicationDeploymentDescription.fromXML(prop.getString())); } } catch (PathNotFoundException e) { return result; } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } // public String saveWSDL(ServiceDescription service, String WSDL) { // Session session = null; // String result = null; // try { // session = getSession(); // Node serviceNode = getServiceNode(session); // Node node = getOrAddNode(serviceNode, service.getId()); // node.setProperty(WSDL_PROPERTY_NAME, WSDL); // session.save(); // // result = node.getIdentifier(); // triggerObservers(this); // } catch (Exception e) { // System.out.println(e); // e.printStackTrace(); // // TODO propagate // } finally { // closeSession(session); // } // return result; // } // // public String saveWSDL(ServiceDescription service) { // return saveWSDL(service, WebServiceUtil.generateWSDL(service)); // } public String getWSDL(String serviceName) throws Exception { ServiceDescription serviceDescription = getServiceDescription(serviceName); if (serviceDescription != null) { return getWSDL(serviceDescription); } throw new ServiceDescriptionRetrieveException(new Exception("No service description from the name " + serviceName)); } public String getWSDL(ServiceDescription service) throws Exception{ try { ServiceType type = service.getType().addNewService(); ServiceName name = type.addNewServiceName(); name.setStringValue(service.getType().getName()); name.setTargetNamespace("http://schemas.airavata.apache.org/gfac/type"); PortTypeType portType = service.getType().addNewPortType(); MethodType methodType = portType.addNewMethod(); methodType.setMethodName("invoke"); WSDLGenerator generator = new WSDLGenerator(); Hashtable table = generator.generateWSDL(null, null, null, service.getType(), true); return (String) table.get(WSDLConstants.AWSDL); } catch (Exception e) { throw new RuntimeException(e); } } public boolean saveGFacDescriptor(String gfacURL) throws RegistryException{ java.util.Date today = Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime(); Timestamp timestamp = new Timestamp(today.getTime()); Session session = null; try { URI uri = new URI(gfacURL); String propertyName = uri.getHost() + "-" + uri.getPort(); session = getSession(); Node gfacDataNode = getOrAddNode(getRootNode(session), GFAC_INSTANCE_DATA); try { Property prop = gfacDataNode.getProperty(propertyName); prop.setValue(gfacURL + ";" + timestamp.getTime()); session.save(); } catch (PathNotFoundException e) { gfacDataNode.setProperty(propertyName, gfacURL + ";" + timestamp.getTime()); session.save(); } // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving GFac Descriptor to the registry!!!", e); } finally { closeSession(session); } return true; } public boolean deleteGFacDescriptor(String gfacURL) throws RegistryException{ Session session = null; try { URI uri = new URI(gfacURL); String propertyName = uri.getHost() + "-" + uri.getPort(); session = getSession(); Node gfacDataNode = getOrAddNode(getRootNode(session), GFAC_INSTANCE_DATA); Property prop = gfacDataNode.getProperty(propertyName); if (prop != null) { prop.setValue((String) null); session.save(); // triggerObservers(this); } } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while deleting GFac Descriptions from registry!!!",e); } finally { closeSession(session); } return true; } public List<String> getGFacDescriptorList() throws RegistryException{ Session session = null; List<String> urlList = new ArrayList<String>(); java.util.Date today = Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime(); Timestamp timestamp = new Timestamp(today.getTime()); try { session = getSession(); Node gfacNode = getOrAddNode(getRootNode(session), GFAC_INSTANCE_DATA); PropertyIterator propertyIterator = gfacNode.getProperties(); while (propertyIterator.hasNext()) { Property property = propertyIterator.nextProperty(); if (!"nt:unstructured".equals(property.getString())) { String x = property.getString(); Timestamp setTime = new Timestamp(new Long(property.getString().split(";")[1])); if (GFAC_URL_UPDATE_INTERVAL > (timestamp.getTime() - setTime.getTime())) { urlList.add(property.getString().split(";")[0]); } } } } catch (RepositoryException e) { throw new RegistryException("Error while retrieving GFac Descriptor list!!!", e); } return urlList; } public String saveOutput(String workflowId, List<ActualParameter> parameters) throws RegistryException{ Session session = null; String result = null; try { session = getSession(); Node outputNode = getOrAddNode(getRootNode(session), OUTPUT_NODE_NAME); Node node = getOrAddNode(outputNode, workflowId); for (int i = 0; i < parameters.size(); i++) { node.setProperty(String.valueOf(i), parameters.get(i).toXML()); } session.save(); result = node.getIdentifier(); // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving workflow output to the registry!!!", e); } finally { closeSession(session); } return result; } public List<ActualParameter> loadOutput(String workflowId) throws RegistryException{ Session session = null; ArrayList<ActualParameter> result = new ArrayList<ActualParameter>(); try { session = getSession(); Node outputNode = getOrAddNode(getRootNode(session), OUTPUT_NODE_NAME); Node node = outputNode.getNode(workflowId); PropertyIterator it = node.getProperties(); while (it.hasNext()) { Property prop = (Property) it.next(); result.add(ActualParameter.fromXML(prop.getString())); } } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while loading workflow output from registry!!!", e); } finally { closeSession(session); } return result; } public Map<QName, Node> getWorkflows(String userName) throws RegistryException{ Session session = null; Map<QName, Node> workflowList = new HashMap<QName, Node>(); try { session = getSession(); Node workflowListNode = getOrAddNode(getOrAddNode(getRootNode(session), WORKFLOWS), PUBLIC); List<Node> childNodes = getChildNodes(workflowListNode); for (Node nextNode:childNodes) { workflowList.put(new QName(nextNode.getName()), nextNode); } workflowListNode = getOrAddNode(getOrAddNode(getRootNode(session), WORKFLOWS), userName); childNodes = getChildNodes(workflowListNode); for (Node nextNode:childNodes) { workflowList.put(new QName(nextNode.getName()), nextNode); } } catch (Exception e) { throw new RegistryException("Error while retrieving workflows from registry!!!",e); } return workflowList; } public Node getWorkflow(QName templateID, String userName) throws RegistryException{ Session session = null; Node result = null; try { session = getSession(); Node workflowListNode = getOrAddNode(getOrAddNode(getRootNode(session), WORKFLOWS), userName); result = getOrAddNode(workflowListNode, templateID.getLocalPart()); } catch (Exception e) { throw new RegistryException("Error while retrieving workflow from registry!!!", e); } return result; } public boolean saveWorkflow(QName ResourceID, String workflowName, String resourceDesc, String workflowAsaString, String owner, boolean isMakePublic) throws RegistryException{ Session session = null; try { session = getSession(); Node workflowListNode = getOrAddNode(getRootNode(session), WORKFLOWS); Node workflowNode = null; if (isMakePublic) { workflowNode = getOrAddNode(getOrAddNode(workflowListNode, PUBLIC), workflowName); } else { workflowNode = getOrAddNode(getOrAddNode(workflowListNode, owner), workflowName); } workflowNode.setProperty("workflow", workflowAsaString); workflowNode.setProperty("Prefix", ResourceID.getPrefix()); workflowNode.setProperty("LocalPart", ResourceID.getLocalPart()); workflowNode.setProperty("NamespaceURI", ResourceID.getNamespaceURI()); workflowNode.setProperty("public", isMakePublic); workflowNode.setProperty("Description", resourceDesc); workflowNode.setProperty("Type", REGISTRY_TYPE_WORKFLOW); session.save(); // triggerObservers(this); } catch (Exception e) { throw new RegistryException("Error while saving workflow to the registry!!!", e); } finally { closeSession(session); return true; } } public boolean deleteWorkflow(QName resourceID, String userName) throws RegistryException{ Session session = null; try { session = getSession(); Node workflowListNode = getOrAddNode(getOrAddNode(getRootNode(session), WORKFLOWS), userName); Node result = getOrAddNode(workflowListNode, resourceID.getLocalPart()); if (result != null) { result.remove(); session.save(); // triggerObservers(this); } } catch (Exception e) { throw new RegistryException("Error while deleting workflow from registry!!!", e); } finally { closeSession(session); } return false; } public boolean saveWorkflowExecutionServiceInput(WorkflowServiceIOData workflowInputData) throws RegistryException{ return saveWorkflowIO(workflowInputData, INPUT); } public boolean saveWorkflowExecutionServiceOutput(WorkflowServiceIOData workflowOutputData) throws RegistryException{ return saveWorkflowIO(workflowOutputData, OUTPUT); } private boolean saveWorkflowIO(WorkflowServiceIOData workflowOutputData, String type) throws RegistryException{ Session session = null; boolean isSaved = true; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(workflowOutputData.getExperimentId(),session); workflowDataNode.setProperty(PROPERTY_WORKFLOW_NAME, workflowOutputData.getWorkflowName()); workflowDataNode = getOrAddNode(getOrAddNode(workflowDataNode, workflowOutputData.getNodeId()), type); workflowDataNode.setProperty(PROPERTY_WORKFLOW_IO_CONTENT, workflowOutputData.getValue()); session.save(); } catch (Exception e) { isSaved = false; throw new RegistryException("Error while saving workflow execution service data!!!", e); } finally { closeSession(session); } return isSaved; } public List<WorkflowServiceIOData> searchWorkflowExecutionServiceInput(String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx) throws RegistryException{ return searchWorkflowIO(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx, INPUT); } public List<WorkflowServiceIOData> searchWorkflowExecutionServiceOutput(String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx) throws RegistryException{ return searchWorkflowIO(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx, OUTPUT); } private List<WorkflowServiceIOData> searchWorkflowIO(String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx, String type) throws RegistryException{ List<WorkflowServiceIOData> workflowIODataList = new ArrayList<WorkflowServiceIOData>(); Session session = null; try { session = getSession(); Node experimentsNode = getWorkflowDataNode(session); List<Node> childNodes = getChildNodes(experimentsNode); for (Node experimentNode:childNodes) { if (experimentIdRegEx != null && !experimentNode.getName().matches(experimentIdRegEx)) { continue; } List<Node> childNodes2 = getChildNodes(experimentNode); for (Node workflowNode:childNodes2) { String workflowName = null; if (workflowNode.hasProperty(PROPERTY_WORKFLOW_NAME)) { workflowName = workflowNode.getProperty( PROPERTY_WORKFLOW_NAME).getString(); if (workflowNameRegEx != null && !workflowName.matches(workflowNameRegEx)) { continue; } } List<Node> childNodes3 = getChildNodes(workflowNode); for (Node serviceNode:childNodes3) { if (nodeNameRegEx != null && !serviceNode.getName().matches(nodeNameRegEx)) { continue; } Node ioNode = getOrAddNode(serviceNode, type); if (ioNode.hasProperty(PROPERTY_WORKFLOW_IO_CONTENT)) { WorkflowServiceIOData workflowIOData = new WorkflowServiceIOData(); workflowIOData.setExperimentId(experimentNode .getName()); workflowIOData .setWorkflowId(workflowNode.getName()); workflowIOData.setWorkflowName(workflowName); workflowIOData.setNodeId(serviceNode.getName()); workflowIOData.setValue(ioNode.getProperty( PROPERTY_WORKFLOW_IO_CONTENT).getString()); workflowIODataList.add(workflowIOData); } } } } } catch (Exception e) { throw new RegistryException("Error while retrieving workflow execution service data!!!",e); } finally { closeSession(session); } return workflowIODataList; } public boolean saveWorkflowExecutionStatus(String experimentId,WorkflowExecutionStatus status)throws RegistryException{ Session session = null; boolean isSaved = true; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); workflowDataNode.setProperty(WORKFLOW_STATUS_PROPERTY,status.getExecutionStatus().name()); Date time = status.getStatusUpdateTime(); if (time==null){ time=Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime(); } //TODO is saving the datetime following format ok? workflowDataNode.setProperty(WORKFLOW_STATUS_TIME_PROPERTY,time.getTime()); session.save(); } catch (Exception e) { isSaved = false; e.printStackTrace(); } finally { closeSession(session); } return isSaved; } public WorkflowExecutionStatus getWorkflowExecutionStatus(String experimentId)throws RegistryException{ Session session = null; WorkflowExecutionStatus property = null; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); ExecutionStatus status = null; if (workflowDataNode.hasProperty(WORKFLOW_STATUS_PROPERTY)) { status = ExecutionStatus.valueOf(workflowDataNode.getProperty( WORKFLOW_STATUS_PROPERTY).getString()); } Date date = null; if (workflowDataNode.hasProperty(WORKFLOW_STATUS_TIME_PROPERTY)) { Property prop = workflowDataNode .getProperty(WORKFLOW_STATUS_TIME_PROPERTY); date = null; if (prop != null) { Long dateMiliseconds = prop.getLong(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(dateMiliseconds); date = cal.getTime(); } } property=new WorkflowExecutionStatus(status, date); session.save(); } catch (Exception e) { throw new RegistryException("Error while retrieving workflow execution status!!!", e); } finally { closeSession(session); } return property; } private Node getWorkflowExperimentDataNode(String experimentId, Session session) throws RepositoryException { return getOrAddNode(getOrAddNode(getWorkflowDataNode(session), experimentId),experimentId); } private Node getWorkflowDataNode(Session session) throws RepositoryException { return getOrAddNode(getRootNode(session), WORKFLOW_DATA); } public boolean saveWorkflowExecutionOutput(String experimentId,String outputNodeName,String output) throws RegistryException{ Session session=null; try { session = getSession(); Node resultNode = getWorkflowExperimentResultNode(experimentId, session); resultNode.setProperty(outputNodeName, output); session.save(); } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return true; } public WorkflowIOData getWorkflowExecutionOutput(String experimentId,String outputNodeName) throws RegistryException{ Session session=null; try { session = getSession(); Node resultNode = getWorkflowExperimentResultNode(experimentId, session); Property outputProperty = resultNode.getProperty(outputNodeName); if (outputProperty==null){ return null; } return new WorkflowIOData(outputNodeName,outputProperty.getString()); } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } } public String[] getWorkflowExecutionOutputNames(String experimentId) throws RegistryException{ Session session=null; List<String> outputNames=new ArrayList<String>(); try { session = getSession(); Node resultNode = getWorkflowExperimentResultNode(experimentId, session); PropertyIterator properties = resultNode.getProperties(); for (;properties.hasNext();) { Property nextProperty = properties.nextProperty(); if(!"jcr:primaryType".equals(nextProperty.getName())){ outputNames.add(nextProperty.getName()); } } } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return outputNames.toArray(new String[]{}); } private Node getWorkflowExperimentResultNode(String experimentId, Session session) throws RepositoryException { Node workflowExperimentDataNode = getWorkflowExperimentDataNode(experimentId, session); Node resultNode = getOrAddNode(workflowExperimentDataNode,RESULT); return resultNode; } private List<String> getMatchingExperimentIds(String regex,Session session)throws RepositoryException{ Node orAddNode = getWorkflowDataNode(session); List<String> matchList = new ArrayList<String>(); Pattern compile = Pattern.compile(regex); List<Node> childNodes = getChildNodes(orAddNode); for (Node node:childNodes) { String name = node.getName(); if(compile.matcher(name).find()){ matchList.add(name); } } return matchList; } public Map<String, WorkflowExecutionStatus> getWorkflowExecutionStatusWithRegex(String regex) throws RegistryException { Session session=null; Map<String,WorkflowExecutionStatus> workflowStatusMap = new HashMap<String, WorkflowExecutionStatus>(); try { session = getSession(); List<String> matchingExperimentIds = getMatchingExperimentIds(regex, session); for(String experimentId:matchingExperimentIds){ WorkflowExecutionStatus workflowStatus = getWorkflowExecutionStatus(experimentId); workflowStatusMap.put(experimentId,workflowStatus); } } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return workflowStatusMap; } public Map<String, WorkflowIOData> getWorkflowExecutionOutputWithRegex(String regex, String outputName) throws RegistryException { Session session=null; Map<String,WorkflowIOData> workflowStatusMap = new HashMap<String, WorkflowIOData>(); try { session = getSession(); List<String> matchingExperimentIds = getMatchingExperimentIds(regex, session); for(String experimentId:matchingExperimentIds){ WorkflowIOData workflowOutputData = getWorkflowExecutionOutput(experimentId,outputName); workflowStatusMap.put(experimentId,workflowOutputData); } } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return workflowStatusMap; } public Map<String, String[]> getWorkflowExecutionOutputNamesWithRegex(String regex) throws RegistryException { Session session = null; Map<String,String[]> workflowStatusMap = new HashMap<String, String[]>(); try { session = getSession(); List<String> matchingExperimentIds = getMatchingExperimentIds(regex, session); for(String experimentId:matchingExperimentIds){ String[] workflowOutputData = getWorkflowExecutionOutputNames(experimentId); workflowStatusMap.put(experimentId,workflowOutputData); } } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return workflowStatusMap; } public boolean saveWorkflowExecutionUser(String experimentId, String user) throws RegistryException { Session session = null; boolean isSaved = true; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); workflowDataNode.setProperty(WORKFLOW_USER_PROPERTY,user); session.save(); } catch (Exception e) { isSaved = false; e.printStackTrace(); } finally { closeSession(session); } return isSaved; } public boolean saveWorkflowExecutionOutput(String experimentId,WorkflowIOData data) throws RegistryException { return saveWorkflowExecutionOutput(experimentId, data.getNodeId(), data.getValue()); } public String getWorkflowExecutionUser(String experimentId) throws RegistryException { Session session = null; String property = null; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); if (workflowDataNode.hasProperty(WORKFLOW_USER_PROPERTY)) { property = workflowDataNode.getProperty(WORKFLOW_USER_PROPERTY) .getString(); } session.save(); } catch (Exception e) { e.printStackTrace(); } finally { closeSession(session); } return property; } public WorkflowExecution getWorkflowExecution(String experimentId) throws RegistryException { WorkflowExecution workflowExecution = new WorkflowExecutionImpl(); workflowExecution.setExperimentId(experimentId); workflowExecution.setExecutionStatus(getWorkflowExecutionStatus(experimentId)); workflowExecution.setUser(getWorkflowExecutionUser(experimentId)); workflowExecution.setMetadata(getWorkflowExecutionMetadata(experimentId)); workflowExecution.setOutput(getWorkflowExecutionOutput(experimentId)); workflowExecution.setServiceInput(searchWorkflowExecutionServiceInput(experimentId,".*",".*")); workflowExecution.setServiceOutput(searchWorkflowExecutionServiceOutput(experimentId,".*",".*")); return workflowExecution; } public List<WorkflowIOData> getWorkflowExecutionOutput(String experimentId) throws RegistryException { List<WorkflowIOData> result=new ArrayList<WorkflowIOData>(); String[] workflowExecutionOutputNames = getWorkflowExecutionOutputNames(experimentId); for (String workflowExecutionOutputName : workflowExecutionOutputNames) { result.add(getWorkflowExecutionOutput(experimentId, workflowExecutionOutputName)); } return result; } public List<String> getWorkflowExecutionIdByUser(String user) throws RegistryException { Session session = null; List<String> ids=new ArrayList<String>(); try { session = getSession(); List<String> matchingExperimentIds = getMatchingExperimentIds(".*", session); for (String id : matchingExperimentIds) { if (user.equals(getWorkflowExecutionUser(id))){ ids.add(id); } } } catch (RepositoryException e) { throw new RegistryException("Error in retrieving Execution Ids for the user '"+user+"'",e); }finally{ closeSession(session); } return ids; } public List<WorkflowExecution> getWorkflowExecutionByUser(String user) throws RegistryException { return getWorkflowExecution(user,-1,-1); } private List<WorkflowExecution> getWorkflowExecution(String user, int startLimit, int endLimit) throws RegistryException { List<WorkflowExecution> executions=new ArrayList<WorkflowExecution>(); List<String> workflowExecutionIdByUser = getWorkflowExecutionIdByUser(user); int count=0; for (String id : workflowExecutionIdByUser) { if ((startLimit==-1 && endLimit==-1) || (startLimit==-1 && count<endLimit) || (startLimit<=count && endLimit==-1) || (startLimit<=count && count<endLimit)){ executions.add(getWorkflowExecution(id)); } count++; } return executions; } public List<WorkflowExecution> getWorkflowExecutionByUser(String user, int pageSize, int pageNo) throws RegistryException { return getWorkflowExecutionByUser(user,pageSize*pageNo,pageSize*(pageNo+1)); } public String getWorkflowExecutionMetadata(String experimentId) throws RegistryException { Session session = null; String property = null; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); if (workflowDataNode.hasProperty(WORKFLOW_METADATA_PROPERTY)) { property = workflowDataNode.getProperty( WORKFLOW_METADATA_PROPERTY).getString(); } session.save(); } catch (Exception e) { throw new RegistryException("Error while retrieving workflow metadata!!!", e); } finally { closeSession(session); } return property; } public boolean saveWorkflowExecutionMetadata(String experimentId, String metadata) throws RegistryException { Session session = null; boolean isSaved = true; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); workflowDataNode.setProperty(WORKFLOW_METADATA_PROPERTY,metadata); session.save(); } catch (Exception e) { isSaved = false; e.printStackTrace(); } finally { closeSession(session); } return isSaved; } public boolean saveWorkflowExecutionStatus(String experimentId, ExecutionStatus status) throws RegistryException { return saveWorkflowExecutionStatus(experimentId,new WorkflowExecutionStatus(status)); } }
modules/commons/registry-api/src/main/java/org/apache/airavata/registry/api/impl/AiravataJCRRegistry.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.registry.api.impl; import org.apache.airavata.common.registry.api.exception.RegistryException; import org.apache.airavata.common.registry.api.impl.JCRRegistry; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.commons.gfac.wsdl.WSDLConstants; import org.apache.airavata.commons.gfac.wsdl.WSDLGenerator; import org.apache.airavata.registry.api.Axis2Registry; import org.apache.airavata.registry.api.DataRegistry; import org.apache.airavata.registry.api.WorkflowExecution; import org.apache.airavata.registry.api.WorkflowExecutionStatus; import org.apache.airavata.registry.api.WorkflowExecutionStatus.ExecutionStatus; import org.apache.airavata.registry.api.exception.DeploymentDescriptionRetrieveException; import org.apache.airavata.registry.api.exception.HostDescriptionRetrieveException; import org.apache.airavata.registry.api.exception.ServiceDescriptionRetrieveException; import org.apache.airavata.registry.api.workflow.WorkflowIOData; import org.apache.airavata.registry.api.workflow.WorkflowServiceIOData; import org.apache.airavata.schemas.gfac.MethodType; import org.apache.airavata.schemas.gfac.PortTypeType; import org.apache.airavata.schemas.gfac.ServiceType; import org.apache.airavata.schemas.gfac.ServiceType.ServiceName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.*; import javax.xml.namespace.QName; import java.net.URI; import java.sql.Timestamp; import java.util.*; import java.util.regex.Pattern; public class AiravataJCRRegistry extends JCRRegistry implements Axis2Registry, DataRegistry { private static final String OUTPUT_NODE_NAME = "OUTPUTS"; private static final String SERVICE_NODE_NAME = "SERVICE_HOST"; private static final String GFAC_INSTANCE_DATA = "GFAC_INSTANCE_DATA"; private static final String DEPLOY_NODE_NAME = "APP_HOST"; private static final String HOST_NODE_NAME = "GFAC_HOST"; private static final String XML_PROPERTY_NAME = "XML"; private static final String WSDL_PROPERTY_NAME = "WSDL"; private static final String GFAC_URL_PROPERTY_NAME = "GFAC_URL_LIST"; private static final String LINK_NAME = "LINK"; private static final String PROPERTY_WORKFLOW_NAME = "workflowName"; private static final String PROPERTY_WORKFLOW_IO_CONTENT = "content"; public static final String WORKFLOWS = "WORKFLOWS"; public static final String PUBLIC = "PUBLIC"; public static final String REGISTRY_TYPE_WORKFLOW = "workflow"; public static final int GFAC_URL_UPDATE_INTERVAL = 1000 * 60 * 60 * 3; public static final String WORKFLOW_DATA = "experiments"; public static final String INPUT = "Input"; public static final String OUTPUT = "Output"; public static final String RESULT = "Result"; public static final String WORKFLOW_STATUS_PROPERTY = "Status"; public static final String WORKFLOW_STATUS_TIME_PROPERTY = "Status_Time"; public static final String WORKFLOW_METADATA_PROPERTY = "Metadata"; public static final String WORKFLOW_USER_PROPERTY = "User"; private static Logger log = LoggerFactory.getLogger(AiravataJCRRegistry.class); public AiravataJCRRegistry(URI repositoryURI, String className, String user, String pass, Map<String, String> map) throws RepositoryException { super(repositoryURI, className, user, pass, map); } private Node getServiceNode(Session session) throws RepositoryException { return getOrAddNode(getRootNode(session), SERVICE_NODE_NAME); } private Node getDeploymentNode(Session session) throws RepositoryException { return getOrAddNode(getRootNode(session), DEPLOY_NODE_NAME); } private Node getHostNode(Session session) throws RepositoryException { return getOrAddNode(getRootNode(session), HOST_NODE_NAME); } // public List<HostDescription> getServiceLocation(String serviceId) { // Session session = null; // ArrayList<HostDescription> result = new ArrayList<HostDescription>(); // try { // session = getSession(); // Node node = getServiceNode(session); // Node serviceNode = node.getNode(serviceId); // if (serviceNode.hasProperty(LINK_NAME)) { // Property prop = serviceNode.getProperty(LINK_NAME); // Value[] vals = prop.getValues(); // for (Value val : vals) { // Node host = session.getNodeByIdentifier(val.getString()); // Property hostProp = host.getProperty(XML_PROPERTY_NAME); // result.add(HostDescription.fromXML(hostProp.getString())); // } // } // } catch (Exception e) { // System.out.println(e); // e.printStackTrace(); // // TODO propagate // } finally { // closeSession(session); // } // return result; // } public void deleteServiceDescription(String serviceId) throws ServiceDescriptionRetrieveException { Session session = null; try { session = getSession(); Node serviceNode = getServiceNode(session); Node node = serviceNode.getNode(serviceId); if (node != null) { node.remove(); session.save(); // triggerObservers(this); } } catch (Exception e) { throw new ServiceDescriptionRetrieveException(e); } finally { closeSession(session); } } public ServiceDescription getServiceDescription(String serviceId) throws ServiceDescriptionRetrieveException { Session session = null; ServiceDescription result = null; try { session = getSession(); Node serviceNode = getServiceNode(session); Node node = serviceNode.getNode(serviceId); Property prop = node.getProperty(XML_PROPERTY_NAME); result = ServiceDescription.fromXML(prop.getString()); } catch (Exception e) { throw new ServiceDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public ApplicationDeploymentDescription getDeploymentDescription(String serviceId, String hostId) throws RegistryException { Session session = null; ApplicationDeploymentDescription result = null; try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceId); Node hostNode = serviceNode.getNode(hostId); List<Node> childNodes = getChildNodes(hostNode); for (Node app:childNodes) { Property prop = app.getProperty(XML_PROPERTY_NAME); result = ApplicationDeploymentDescription.fromXML(prop.getString()); break; } } catch (PathNotFoundException e) { return null; } catch (Exception e) { log.error("Cannot get Deployment Description", e); throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public void deleteHostDescription(String hostId) throws RegistryException { Session session = null; try { session = getSession(); Node hostNode = getHostNode(session); Node node = hostNode.getNode(hostId); if (node != null) { node.remove(); session.save(); // triggerObservers(this); } } catch (Exception e) { throw new HostDescriptionRetrieveException(e); } finally { closeSession(session); } } public ServiceDescription getServiceDesc(String serviceId) throws ServiceDescriptionRetrieveException { Session session = null; ServiceDescription result = null; try { session = getSession(); Node serviceNode = getServiceNode(session); Node node = serviceNode.getNode(serviceId); Property prop = node.getProperty(XML_PROPERTY_NAME); result = ServiceDescription.fromXML(prop.getString()); } catch (PathNotFoundException e) { return null; } catch (Exception e) { throw new ServiceDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public HostDescription getHostDescription(String hostId) throws RegistryException { Session session = null; HostDescription result = null; try { session = getSession(); Node hostNode = getHostNode(session); Node node = hostNode.getNode(hostId); if (node != null) { result = getHostDescriptor(node); } } catch (PathNotFoundException e) { return null; } catch (Exception e) { log.debug(e.getMessage()); e.printStackTrace(); throw new HostDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } private HostDescription getHostDescriptor(Node node) throws RegistryException { HostDescription result; try { Property prop = node.getProperty(XML_PROPERTY_NAME); result = HostDescription.fromXML(prop.getString()); } catch (Exception e) { throw new HostDescriptionRetrieveException(e); } return result; } public String saveHostDescription(HostDescription host) throws RegistryException{ Session session = null; String result = null; try { session = getSession(); Node hostNode = getHostNode(session); Node node = getOrAddNode(hostNode, host.getType().getHostName()); node.setProperty(XML_PROPERTY_NAME, host.toXML()); session.save(); result = node.getIdentifier(); // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving host description!!!", e); } finally { closeSession(session); } return result; } public String saveServiceDescription(ServiceDescription service) throws RegistryException{ Session session = null; String result = null; try { session = getSession(); Node serviceNode = getServiceNode(session); Node node = getOrAddNode(serviceNode, service.getType().getName()); node.setProperty(XML_PROPERTY_NAME, service.toXML()); session.save(); result = node.getIdentifier(); // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving service description!!!", e); } finally { closeSession(session); } return result; } public String saveDeploymentDescription(String serviceId, String hostId, ApplicationDeploymentDescription app) throws RegistryException { Session session = null; String result = null; try { session = getSession(); Node deployNode = getDeploymentNode(session); Node serviceNode = getOrAddNode(deployNode, serviceId); Node hostNode = getOrAddNode(serviceNode, hostId); Node appName = getOrAddNode(hostNode, app.getType().getApplicationName().getStringValue()); appName.setProperty(XML_PROPERTY_NAME, app.toXML()); session.save(); result = appName.getIdentifier(); // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving deployment description!!!", e); } finally { closeSession(session); } return result; } public boolean deployServiceOnHost(String serviceId, String hostId)throws RegistryException { Session session = null; try { session = getSession(); Node serviceRoot = getServiceNode(session); Node hostRoot = getHostNode(session); Node serviceNode = serviceRoot.getNode(serviceId); Node hostNode = hostRoot.getNode(hostId); if (!serviceNode.hasProperty(LINK_NAME)) { serviceNode.setProperty(LINK_NAME, new String[] { hostNode.getIdentifier() }); } else { Property prop = serviceNode.getProperty(LINK_NAME); Value[] vals = prop.getValues(); ArrayList<String> s = new ArrayList<String>(); for (Value val : vals) { s.add(val.getString()); } if (s.contains(hostNode.getIdentifier())) { return false; } s.add(hostNode.getIdentifier()); serviceNode.setProperty(LINK_NAME, s.toArray(new String[0])); } session.save(); return true; } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving service on host!!!", e); } finally { closeSession(session); } } public List<ServiceDescription> searchServiceDescription(String nameRegEx) throws RegistryException { Session session = null; ArrayList<ServiceDescription> result = new ArrayList<ServiceDescription>(); try { session = getSession(); Node node = getServiceNode(session); List<Node> childNodes = getChildNodes(node); for (Node service:childNodes) { if (nameRegEx.equals("") || service.getName().matches(nameRegEx)) { Property prop = service.getProperty(XML_PROPERTY_NAME); result.add(ServiceDescription.fromXML(prop.getString())); } } } catch (Exception e) { throw new ServiceDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public List<HostDescription> searchHostDescription(String nameRegEx) throws RegistryException { Session session = null; List<HostDescription> result = new ArrayList<HostDescription>(); try { session = getSession(); Node node = getHostNode(session); List<Node> childNodes = getChildNodes(node); for (Node host:childNodes) { if (host != null && host.getName().matches(nameRegEx)) { HostDescription hostDescriptor = getHostDescriptor(host); result.add(hostDescriptor); } } } catch (Exception e) { throw new HostDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public Map<ApplicationDeploymentDescription, String> searchDeploymentDescription() throws RegistryException { Session session = null; Map<ApplicationDeploymentDescription, String> result = new HashMap<ApplicationDeploymentDescription, String>(); try { session = getSession(); Node deploymentNode = getDeploymentNode(session); List<Node> childNodes = getChildNodes(deploymentNode); for (Node serviceNode:childNodes) { List<Node> childNodes2 = getChildNodes(serviceNode); for (Node hostNode:childNodes2) { List<Node> childNodes3 = getChildNodes(hostNode); for (Node app:childNodes3) { Property prop = app.getProperty(XML_PROPERTY_NAME); result.put(ApplicationDeploymentDescription.fromXML(prop.getString()), serviceNode.getName() + "$" + hostNode.getName()); } } } } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public void deleteDeploymentDescription(String serviceName, String hostName, String applicationName) throws RegistryException { Session session = null; try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceName); Node hostNode = serviceNode.getNode(hostName); hostNode.remove(); session.save(); } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } } public List<ApplicationDeploymentDescription> searchDeploymentDescription(String serviceName, String hostName, String applicationName) throws RegistryException { Session session = null; List<ApplicationDeploymentDescription> result = new ArrayList<ApplicationDeploymentDescription>(); try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceName); Node hostNode = serviceNode.getNode(hostName); List<Node> childNodes = getChildNodes(hostNode); for (Node app:childNodes) { Property prop = app.getProperty(XML_PROPERTY_NAME); ApplicationDeploymentDescription appDesc = ApplicationDeploymentDescription.fromXML(prop.getString()); if (appDesc.getType().getApplicationName().getStringValue().matches(applicationName)) { result.add(appDesc); } } } catch (PathNotFoundException e) { return result; } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public Map<HostDescription,List<ApplicationDeploymentDescription>> searchDeploymentDescription(String serviceName) throws RegistryException{ Session session = null; Map<HostDescription,List<ApplicationDeploymentDescription>> result = new HashMap<HostDescription,List<ApplicationDeploymentDescription>>(); try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceName); List<Node> childNodes = getChildNodes(serviceNode); for (Node hostNode:childNodes) { HostDescription hostDescriptor = getHostDescription(hostNode.getName()); result.put(hostDescriptor, new ArrayList<ApplicationDeploymentDescription>()); List<Node> childNodes2 = getChildNodes(hostNode); for (Node app:childNodes2) { Property prop = app.getProperty(XML_PROPERTY_NAME); result.get(hostDescriptor).add(ApplicationDeploymentDescription.fromXML(prop.getString())); } } }catch (PathNotFoundException e){ return result; } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } public List<ApplicationDeploymentDescription> searchDeploymentDescription(String serviceName, String hostName) throws RegistryException { Session session = null; List<ApplicationDeploymentDescription> result = new ArrayList<ApplicationDeploymentDescription>(); try { session = getSession(); Node deploymentNode = getDeploymentNode(session); Node serviceNode = deploymentNode.getNode(serviceName); Node hostNode = serviceNode.getNode(hostName); List<Node> childNodes = getChildNodes(hostNode); for (Node app:childNodes) { Property prop = app.getProperty(XML_PROPERTY_NAME); result.add(ApplicationDeploymentDescription.fromXML(prop.getString())); } } catch (PathNotFoundException e) { return result; } catch (Exception e) { throw new DeploymentDescriptionRetrieveException(e); } finally { closeSession(session); } return result; } // public String saveWSDL(ServiceDescription service, String WSDL) { // Session session = null; // String result = null; // try { // session = getSession(); // Node serviceNode = getServiceNode(session); // Node node = getOrAddNode(serviceNode, service.getId()); // node.setProperty(WSDL_PROPERTY_NAME, WSDL); // session.save(); // // result = node.getIdentifier(); // triggerObservers(this); // } catch (Exception e) { // System.out.println(e); // e.printStackTrace(); // // TODO propagate // } finally { // closeSession(session); // } // return result; // } // // public String saveWSDL(ServiceDescription service) { // return saveWSDL(service, WebServiceUtil.generateWSDL(service)); // } public String getWSDL(String serviceName) throws Exception { ServiceDescription serviceDescription = getServiceDescription(serviceName); if (serviceDescription != null) { return getWSDL(serviceDescription); } throw new ServiceDescriptionRetrieveException(new Exception("No service description from the name " + serviceName)); } public String getWSDL(ServiceDescription service) throws Exception{ try { ServiceType type = service.getType().addNewService(); ServiceName name = type.addNewServiceName(); name.setStringValue(service.getType().getName()); name.setTargetNamespace("http://schemas.airavata.apache.org/gfac/type"); PortTypeType portType = service.getType().addNewPortType(); MethodType methodType = portType.addNewMethod(); methodType.setMethodName("invoke"); WSDLGenerator generator = new WSDLGenerator(); Hashtable table = generator.generateWSDL(null, null, null, service.getType(), true); return (String) table.get(WSDLConstants.AWSDL); } catch (Exception e) { throw new RuntimeException(e); } } public boolean saveGFacDescriptor(String gfacURL) throws RegistryException{ java.util.Date today = Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime(); Timestamp timestamp = new Timestamp(today.getTime()); Session session = null; try { URI uri = new URI(gfacURL); String propertyName = uri.getHost() + "-" + uri.getPort(); session = getSession(); Node gfacDataNode = getOrAddNode(getRootNode(session), GFAC_INSTANCE_DATA); try { Property prop = gfacDataNode.getProperty(propertyName); prop.setValue(gfacURL + ";" + timestamp.getTime()); session.save(); } catch (PathNotFoundException e) { gfacDataNode.setProperty(propertyName, gfacURL + ";" + timestamp.getTime()); session.save(); } // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving GFac Descriptor to the registry!!!", e); } finally { closeSession(session); } return true; } public boolean deleteGFacDescriptor(String gfacURL) throws RegistryException{ Session session = null; try { URI uri = new URI(gfacURL); String propertyName = uri.getHost() + "-" + uri.getPort(); session = getSession(); Node gfacDataNode = getOrAddNode(getRootNode(session), GFAC_INSTANCE_DATA); Property prop = gfacDataNode.getProperty(propertyName); if (prop != null) { prop.setValue((String) null); session.save(); // triggerObservers(this); } } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while deleting GFac Descriptions from registry!!!",e); } finally { closeSession(session); } return true; } public List<String> getGFacDescriptorList() throws RegistryException{ Session session = null; List<String> urlList = new ArrayList<String>(); java.util.Date today = Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime(); Timestamp timestamp = new Timestamp(today.getTime()); try { session = getSession(); Node gfacNode = getOrAddNode(getRootNode(session), GFAC_INSTANCE_DATA); PropertyIterator propertyIterator = gfacNode.getProperties(); while (propertyIterator.hasNext()) { Property property = propertyIterator.nextProperty(); if (!"nt:unstructured".equals(property.getString())) { String x = property.getString(); Timestamp setTime = new Timestamp(new Long(property.getString().split(";")[1])); if (GFAC_URL_UPDATE_INTERVAL > (timestamp.getTime() - setTime.getTime())) { urlList.add(property.getString().split(";")[0]); } } } } catch (RepositoryException e) { throw new RegistryException("Error while retrieving GFac Descriptor list!!!", e); } return urlList; } public String saveOutput(String workflowId, List<ActualParameter> parameters) throws RegistryException{ Session session = null; String result = null; try { session = getSession(); Node outputNode = getOrAddNode(getRootNode(session), OUTPUT_NODE_NAME); Node node = getOrAddNode(outputNode, workflowId); for (int i = 0; i < parameters.size(); i++) { node.setProperty(String.valueOf(i), parameters.get(i).toXML()); } session.save(); result = node.getIdentifier(); // triggerObservers(this); } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while saving workflow output to the registry!!!", e); } finally { closeSession(session); } return result; } public List<ActualParameter> loadOutput(String workflowId) throws RegistryException{ Session session = null; ArrayList<ActualParameter> result = new ArrayList<ActualParameter>(); try { session = getSession(); Node outputNode = getOrAddNode(getRootNode(session), OUTPUT_NODE_NAME); Node node = outputNode.getNode(workflowId); PropertyIterator it = node.getProperties(); while (it.hasNext()) { Property prop = (Property) it.next(); result.add(ActualParameter.fromXML(prop.getString())); } } catch (Exception e) { System.out.println(e); throw new RegistryException("Error while loading workflow output from registry!!!", e); } finally { closeSession(session); } return result; } public Map<QName, Node> getWorkflows(String userName) throws RegistryException{ Session session = null; Map<QName, Node> workflowList = new HashMap<QName, Node>(); try { session = getSession(); Node workflowListNode = getOrAddNode(getOrAddNode(getRootNode(session), WORKFLOWS), PUBLIC); List<Node> childNodes = getChildNodes(workflowListNode); for (Node nextNode:childNodes) { workflowList.put(new QName(nextNode.getName()), nextNode); } workflowListNode = getOrAddNode(getOrAddNode(getRootNode(session), WORKFLOWS), userName); childNodes = getChildNodes(workflowListNode); for (Node nextNode:childNodes) { workflowList.put(new QName(nextNode.getName()), nextNode); } } catch (Exception e) { throw new RegistryException("Error while retrieving workflows from registry!!!",e); } return workflowList; } public Node getWorkflow(QName templateID, String userName) throws RegistryException{ Session session = null; Node result = null; try { session = getSession(); Node workflowListNode = getOrAddNode(getOrAddNode(getRootNode(session), WORKFLOWS), userName); result = getOrAddNode(workflowListNode, templateID.getLocalPart()); } catch (Exception e) { throw new RegistryException("Error while retrieving workflow from registry!!!", e); } return result; } public boolean saveWorkflow(QName ResourceID, String workflowName, String resourceDesc, String workflowAsaString, String owner, boolean isMakePublic) throws RegistryException{ Session session = null; try { session = getSession(); Node workflowListNode = getOrAddNode(getRootNode(session), WORKFLOWS); Node workflowNode = null; if (isMakePublic) { workflowNode = getOrAddNode(getOrAddNode(workflowListNode, PUBLIC), workflowName); } else { workflowNode = getOrAddNode(getOrAddNode(workflowListNode, owner), workflowName); } workflowNode.setProperty("workflow", workflowAsaString); workflowNode.setProperty("Prefix", ResourceID.getPrefix()); workflowNode.setProperty("LocalPart", ResourceID.getLocalPart()); workflowNode.setProperty("NamespaceURI", ResourceID.getNamespaceURI()); workflowNode.setProperty("public", isMakePublic); workflowNode.setProperty("Description", resourceDesc); workflowNode.setProperty("Type", REGISTRY_TYPE_WORKFLOW); session.save(); // triggerObservers(this); } catch (Exception e) { throw new RegistryException("Error while saving workflow to the registry!!!", e); } finally { closeSession(session); return true; } } public boolean deleteWorkflow(QName resourceID, String userName) throws RegistryException{ Session session = null; try { session = getSession(); Node workflowListNode = getOrAddNode(getOrAddNode(getRootNode(session), WORKFLOWS), userName); Node result = getOrAddNode(workflowListNode, resourceID.getLocalPart()); if (result != null) { result.remove(); session.save(); // triggerObservers(this); } } catch (Exception e) { throw new RegistryException("Error while deleting workflow from registry!!!", e); } finally { closeSession(session); } return false; } public boolean saveWorkflowExecutionServiceInput(WorkflowServiceIOData workflowInputData) throws RegistryException{ return saveWorkflowIO(workflowInputData, INPUT); } public boolean saveWorkflowExecutionServiceOutput(WorkflowServiceIOData workflowOutputData) throws RegistryException{ return saveWorkflowIO(workflowOutputData, OUTPUT); } private boolean saveWorkflowIO(WorkflowServiceIOData workflowOutputData, String type) throws RegistryException{ Session session = null; boolean isSaved = true; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(workflowOutputData.getExperimentId(),session); workflowDataNode.setProperty(PROPERTY_WORKFLOW_NAME, workflowOutputData.getWorkflowName()); workflowDataNode = getOrAddNode(getOrAddNode(workflowDataNode, workflowOutputData.getNodeId()), type); workflowDataNode.setProperty(PROPERTY_WORKFLOW_IO_CONTENT, workflowOutputData.getValue()); session.save(); } catch (Exception e) { isSaved = false; throw new RegistryException("Error while saving workflow execution service data!!!", e); } finally { closeSession(session); } return isSaved; } public List<WorkflowServiceIOData> searchWorkflowExecutionServiceInput(String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx) throws RegistryException{ return searchWorkflowIO(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx, INPUT); } public List<WorkflowServiceIOData> searchWorkflowExecutionServiceOutput(String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx) throws RegistryException{ return searchWorkflowIO(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx, OUTPUT); } private List<WorkflowServiceIOData> searchWorkflowIO(String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx, String type) throws RegistryException{ List<WorkflowServiceIOData> workflowIODataList = new ArrayList<WorkflowServiceIOData>(); Session session = null; try { session = getSession(); Node experimentsNode = getWorkflowDataNode(session); List<Node> childNodes = getChildNodes(experimentsNode); for (Node experimentNode:childNodes) { if (experimentIdRegEx != null && !experimentNode.getName().matches(experimentIdRegEx)) { continue; } List<Node> childNodes2 = getChildNodes(experimentNode); for (Node workflowNode:childNodes2) { String workflowName = null; if (workflowNode.hasProperty(PROPERTY_WORKFLOW_NAME)) { workflowName = workflowNode.getProperty( PROPERTY_WORKFLOW_NAME).getString(); if (workflowNameRegEx != null && !workflowName.matches(workflowNameRegEx)) { continue; } } List<Node> childNodes3 = getChildNodes(workflowNode); for (Node serviceNode:childNodes3) { if (nodeNameRegEx != null && !serviceNode.getName().matches(nodeNameRegEx)) { continue; } Node ioNode = getOrAddNode(serviceNode, type); if (ioNode.hasProperty(PROPERTY_WORKFLOW_IO_CONTENT)) { WorkflowServiceIOData workflowIOData = new WorkflowServiceIOData(); workflowIOData.setExperimentId(experimentNode .getName()); workflowIOData .setWorkflowId(workflowNode.getName()); workflowIOData.setWorkflowName(workflowName); workflowIOData.setNodeId(serviceNode.getName()); workflowIOData.setValue(ioNode.getProperty( PROPERTY_WORKFLOW_IO_CONTENT).getString()); workflowIODataList.add(workflowIOData); } } } } } catch (Exception e) { throw new RegistryException("Error while retrieving workflow execution service data!!!",e); } finally { closeSession(session); } return workflowIODataList; } public boolean saveWorkflowExecutionStatus(String experimentId,WorkflowExecutionStatus status)throws RegistryException{ Session session = null; boolean isSaved = true; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); workflowDataNode.setProperty(WORKFLOW_STATUS_PROPERTY,status.getExecutionStatus().name()); Date time = status.getStatusUpdateTime(); if (time==null){ time=Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime(); } //TODO is saving the datetime following format ok? workflowDataNode.setProperty(WORKFLOW_STATUS_TIME_PROPERTY,time.getTime()); session.save(); } catch (Exception e) { isSaved = false; e.printStackTrace(); } finally { closeSession(session); } return isSaved; } public WorkflowExecutionStatus getWorkflowExecutionStatus(String experimentId)throws RegistryException{ Session session = null; WorkflowExecutionStatus property = null; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); ExecutionStatus status = null; if (workflowDataNode.hasProperty(WORKFLOW_STATUS_PROPERTY)) { status = ExecutionStatus.valueOf(workflowDataNode.getProperty( WORKFLOW_STATUS_PROPERTY).getString()); } Date date = null; if (workflowDataNode.hasProperty(WORKFLOW_STATUS_TIME_PROPERTY)) { Property prop = workflowDataNode .getProperty(WORKFLOW_STATUS_TIME_PROPERTY); date = null; if (prop != null) { Long dateMiliseconds = prop.getLong(); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(dateMiliseconds); date = cal.getTime(); } } property=new WorkflowExecutionStatus(status, date); session.save(); } catch (Exception e) { throw new RegistryException("Error while retrieving workflow execution status!!!", e); } finally { closeSession(session); } return property; } private Node getWorkflowExperimentDataNode(String experimentId, Session session) throws RepositoryException { return getOrAddNode(getOrAddNode(getWorkflowDataNode(session), experimentId),experimentId); } private Node getWorkflowDataNode(Session session) throws RepositoryException { return getOrAddNode(getRootNode(session), WORKFLOW_DATA); } public boolean saveWorkflowExecutionOutput(String experimentId,String outputNodeName,String output) throws RegistryException{ Session session=null; try { session = getSession(); Node resultNode = getWorkflowExperimentResultNode(experimentId, session); resultNode.setProperty(outputNodeName, output); session.save(); } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return true; } public WorkflowIOData getWorkflowExecutionOutput(String experimentId,String outputNodeName) throws RegistryException{ Session session=null; try { session = getSession(); Node resultNode = getWorkflowExperimentResultNode(experimentId, session); Property outputProperty = resultNode.getProperty(outputNodeName); if (outputProperty==null){ return null; } return new WorkflowIOData(outputNodeName,outputProperty.getString()); } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } } public String[] getWorkflowExecutionOutputNames(String experimentId) throws RegistryException{ Session session=null; List<String> outputNames=new ArrayList<String>(); try { session = getSession(); Node resultNode = getWorkflowExperimentResultNode(experimentId, session); PropertyIterator properties = resultNode.getProperties(); for (;properties.hasNext();) { Property nextProperty = properties.nextProperty(); if(!"jcr:primaryType".equals(nextProperty.getName())){ outputNames.add(nextProperty.getName()); } } } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return outputNames.toArray(new String[]{}); } private Node getWorkflowExperimentResultNode(String experimentId, Session session) throws RepositoryException { Node workflowExperimentDataNode = getWorkflowExperimentDataNode(experimentId, session); Node resultNode = getOrAddNode(workflowExperimentDataNode,RESULT); return resultNode; } private List<String> getMatchingExperimentIds(String regex,Session session)throws RepositoryException{ Node orAddNode = getWorkflowDataNode(session); List<String> matchList = new ArrayList<String>(); Pattern compile = Pattern.compile(regex); List<Node> childNodes = getChildNodes(orAddNode); for (Node node:childNodes) { String name = node.getName(); if(compile.matcher(name).find()){ matchList.add(name); } } return matchList; } public Map<String, WorkflowExecutionStatus> getWorkflowExecutionStatusWithRegex(String regex) throws RegistryException { Session session=null; Map<String,WorkflowExecutionStatus> workflowStatusMap = new HashMap<String, WorkflowExecutionStatus>(); try { session = getSession(); List<String> matchingExperimentIds = getMatchingExperimentIds(regex, session); for(String experimentId:matchingExperimentIds){ WorkflowExecutionStatus workflowStatus = getWorkflowExecutionStatus(experimentId); workflowStatusMap.put(experimentId,workflowStatus); } } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return workflowStatusMap; } public Map<String, WorkflowIOData> getWorkflowExecutionOutputWithRegex(String regex, String outputName) throws RegistryException { Session session=null; Map<String,WorkflowIOData> workflowStatusMap = new HashMap<String, WorkflowIOData>(); try { session = getSession(); List<String> matchingExperimentIds = getMatchingExperimentIds(regex, session); for(String experimentId:matchingExperimentIds){ WorkflowIOData workflowOutputData = getWorkflowExecutionOutput(experimentId,outputName); workflowStatusMap.put(experimentId,workflowOutputData); } } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return workflowStatusMap; } public Map<String, String[]> getWorkflowExecutionOutputNamesWithRegex(String regex) throws RegistryException { Session session = null; Map<String,String[]> workflowStatusMap = new HashMap<String, String[]>(); try { session = getSession(); List<String> matchingExperimentIds = getMatchingExperimentIds(regex, session); for(String experimentId:matchingExperimentIds){ String[] workflowOutputData = getWorkflowExecutionOutputNames(experimentId); workflowStatusMap.put(experimentId,workflowOutputData); } } catch (RepositoryException e) { e.printStackTrace(); throw new RegistryException(e); }finally{ closeSession(session); } return workflowStatusMap; } public boolean saveWorkflowExecutionUser(String experimentId, String user) throws RegistryException { Session session = null; boolean isSaved = true; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); workflowDataNode.setProperty(WORKFLOW_USER_PROPERTY,user); session.save(); } catch (Exception e) { isSaved = false; e.printStackTrace(); } finally { closeSession(session); } return isSaved; } public boolean saveWorkflowExecutionOutput(String experimentId,WorkflowIOData data) throws RegistryException { return saveWorkflowExecutionOutput(experimentId, data.getNodeId(), data.getValue()); } public String getWorkflowExecutionUser(String experimentId) throws RegistryException { Session session = null; String property = null; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); if (workflowDataNode.hasProperty(WORKFLOW_USER_PROPERTY)) { property = workflowDataNode.getProperty(WORKFLOW_USER_PROPERTY) .getString(); } session.save(); } catch (Exception e) { e.printStackTrace(); } finally { closeSession(session); } return property; } public WorkflowExecution getWorkflowExecution(String experimentId) throws RegistryException { WorkflowExecution workflowExecution = new WorkflowExecutionImpl(); workflowExecution.setExperimentId(experimentId); workflowExecution.setExecutionStatus(getWorkflowExecutionStatus(experimentId)); workflowExecution.setUser(getWorkflowExecutionUser(experimentId)); workflowExecution.setMetadata(getWorkflowExecutionMetadata(experimentId)); workflowExecution.setOutput(getWorkflowExecutionOutput(experimentId)); workflowExecution.setServiceInput(searchWorkflowExecutionServiceInput(experimentId,".*",".*")); workflowExecution.setServiceOutput(searchWorkflowExecutionServiceOutput(experimentId,".*",".*")); return workflowExecution; } public List<WorkflowIOData> getWorkflowExecutionOutput(String experimentId) throws RegistryException { List<WorkflowIOData> result=new ArrayList<WorkflowIOData>(); String[] workflowExecutionOutputNames = getWorkflowExecutionOutputNames(experimentId); for (String workflowExecutionOutputName : workflowExecutionOutputNames) { result.add(getWorkflowExecutionOutput(experimentId, workflowExecutionOutputName)); } return result; } public List<String> getWorkflowExecutionIdByUser(String user) throws RegistryException { Session session = null; List<String> ids=new ArrayList<String>(); try { session = getSession(); List<String> matchingExperimentIds = getMatchingExperimentIds(".*", session); for (String id : matchingExperimentIds) { if (user.equals(getWorkflowExecutionUser(id))){ ids.add(id); } } } catch (RepositoryException e) { throw new RegistryException("Error in retrieving Execution Ids for the user '"+user+"'",e); }finally{ closeSession(session); } return ids; } public List<WorkflowExecution> getWorkflowExecutionByUser(String user) throws RegistryException { return getWorkflowExecution(user,-1,-1); } private List<WorkflowExecution> getWorkflowExecution(String user, int startLimit, int endLimit) throws RegistryException { List<WorkflowExecution> executions=new ArrayList<WorkflowExecution>(); List<String> workflowExecutionIdByUser = getWorkflowExecutionIdByUser(user); int count=0; for (String id : workflowExecutionIdByUser) { if ((startLimit==-1 && endLimit==-1) || (startLimit==-1 && count<endLimit) || (startLimit<=count && endLimit==-1) || (startLimit<=count && count<endLimit)){ executions.add(getWorkflowExecution(id)); } count++; } return executions; } public List<WorkflowExecution> getWorkflowExecutionByUser(String user, int pageSize, int pageNo) throws RegistryException { return getWorkflowExecutionByUser(user,pageSize*pageNo,pageSize*(pageNo+1)); } public String getWorkflowExecutionMetadata(String experimentId) throws RegistryException { Session session = null; String property = null; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); if (workflowDataNode.hasProperty(WORKFLOW_METADATA_PROPERTY)) { property = workflowDataNode.getProperty( WORKFLOW_METADATA_PROPERTY).getString(); } session.save(); } catch (Exception e) { throw new RegistryException("Error while retrieving workflow metadata!!!", e); } finally { closeSession(session); } return property; } public boolean saveWorkflowExecutionMetadata(String experimentId, String metadata) throws RegistryException { Session session = null; boolean isSaved = true; try { session = getSession(); Node workflowDataNode = getWorkflowExperimentDataNode(experimentId, session); workflowDataNode.setProperty(WORKFLOW_METADATA_PROPERTY,metadata); session.save(); } catch (Exception e) { isSaved = false; e.printStackTrace(); } finally { closeSession(session); } return isSaved; } public boolean saveWorkflowExecutionStatus(String experimentId, ExecutionStatus status) throws RegistryException { return saveWorkflowExecutionStatus(experimentId,new WorkflowExecutionStatus(status)); } }
we remove the undefined AppDescriptors. git-svn-id: 64c7115bac0e45f25b6ef7317621bf38f6d5f89e@1327272 13f79535-47bb-0310-9956-ffa450edef68
modules/commons/registry-api/src/main/java/org/apache/airavata/registry/api/impl/AiravataJCRRegistry.java
we remove the undefined AppDescriptors.
<ide><path>odules/commons/registry-api/src/main/java/org/apache/airavata/registry/api/impl/AiravataJCRRegistry.java <ide> List<Node> childNodes = getChildNodes(serviceNode); <ide> for (Node hostNode:childNodes) { <ide> HostDescription hostDescriptor = getHostDescription(hostNode.getName()); <del> result.put(hostDescriptor, new ArrayList<ApplicationDeploymentDescription>()); <ide> List<Node> childNodes2 = getChildNodes(hostNode); <del> for (Node app:childNodes2) { <del> Property prop = app.getProperty(XML_PROPERTY_NAME); <add> for (Node app:childNodes2) { <add> result.put(hostDescriptor, new ArrayList<ApplicationDeploymentDescription>()); <add> Property prop = app.getProperty(XML_PROPERTY_NAME); <ide> result.get(hostDescriptor).add(ApplicationDeploymentDescription.fromXML(prop.getString())); <ide> } <ide> }
Java
apache-2.0
9857b351f781b78742f65bbf7c679ce63317c477
0
ingenieux/beanstalker,ingenieux/beanstalker
package br.com.ingenieux.mojo.beanstalk.version; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.ListIterator; import java.util.regex.Pattern; import org.apache.commons.lang.builder.CompareToBuilder; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import br.com.ingenieux.mojo.beanstalk.AbstractBeanstalkMojo; import com.amazonaws.services.elasticbeanstalk.model.ApplicationVersionDescription; import com.amazonaws.services.elasticbeanstalk.model.DeleteApplicationVersionRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeApplicationVersionsRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeApplicationVersionsResult; import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentsResult; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; /** * Deletes application versions, either by count and/or by date old * * @since 0.2.2 */ @Mojo(name="clean-previous-versions") public class CleanPreviousVersionsMojo extends AbstractBeanstalkMojo { /** * Beanstalk Application Name */ @Parameter(property="beanstalk.applicationName", defaultValue="${project.artifactId}", required=true) String applicationName; /** * Delete the source bundle? */ @Parameter(property="beanstalk.deleteSourceBundle", defaultValue="false") boolean deleteSourceBundle; /** * How many versions to keep? */ @Parameter(property="beanstalk.versionsToKeep") Integer versionsToKeep; /** * How many versions to keep? */ @Parameter(property="beanstalk.daysToKeep") Integer daysToKeep; /** * Filter application version list by version label wildcard matching? */ @Parameter(property="beanstalk.keepFilter") String keepFilter; /** * Simulate deletion changing algorithm? */ @Parameter(property="beanstalk.dryRun", defaultValue="true") boolean dryRun; private int deletedVersionsCount; @Override protected Object executeInternal() throws MojoExecutionException, MojoFailureException { boolean bVersionsToKeepDefined = (null != versionsToKeep); boolean bDaysToKeepDefined = (null != daysToKeep); if (!(bVersionsToKeepDefined ^ bDaysToKeepDefined)) throw new MojoFailureException( "Declare either versionsToKeep or daysToKeep, but not both nor none!"); DescribeApplicationVersionsRequest describeApplicationVersionsRequest = new DescribeApplicationVersionsRequest() .withApplicationName(applicationName); DescribeApplicationVersionsResult appVersions = getService() .describeApplicationVersions(describeApplicationVersionsRequest); DescribeEnvironmentsResult environments = getService() .describeEnvironments(); List<ApplicationVersionDescription> appVersionList = new ArrayList<ApplicationVersionDescription>( appVersions.getApplicationVersions()); deletedVersionsCount = 0; for (EnvironmentDescription d : environments.getEnvironments()) { boolean bActiveEnvironment = (d.getStatus().equals("Running") || d.getStatus().equals("Launching") || d.getStatus() .equals("Ready")); for (ListIterator<ApplicationVersionDescription> appVersionIterator = appVersionList .listIterator(); appVersionIterator.hasNext();) { ApplicationVersionDescription appVersion = appVersionIterator .next(); boolean bMatchesVersion = appVersion.getVersionLabel().equals( d.getVersionLabel()); if (bActiveEnvironment && bMatchesVersion) { getLog().info( "VersionLabel " + appVersion.getVersionLabel() + " is bound to environment " + d.getEnvironmentName() + " - Skipping it"); appVersionIterator.remove(); } } } filterAppVersionListByVersionLabelPattern(appVersionList, keepFilter); Collections.sort(appVersionList, new Comparator<ApplicationVersionDescription>() { @Override public int compare(ApplicationVersionDescription o1, ApplicationVersionDescription o2) { return new CompareToBuilder().append( o1.getDateUpdated(), o2.getDateUpdated()) .toComparison(); } }); if (bDaysToKeepDefined) { Date now = new Date(); for (ApplicationVersionDescription d : appVersionList) { long delta = now.getTime() - d.getDateUpdated().getTime(); delta /= 1000; delta /= 86400; boolean shouldDeleteP = (delta > daysToKeep); if (getLog().isDebugEnabled()) getLog().debug( "Version " + d.getVersionLabel() + " was from " + delta + " days ago. Should we delete? " + shouldDeleteP); if (shouldDeleteP) deleteVersion(d); } } else { while (appVersionList.size() > versionsToKeep) deleteVersion(appVersionList.remove(0)); } getLog().info( "Deleted " + deletedVersionsCount + " versions."); return null; } void deleteVersion(ApplicationVersionDescription versionToRemove) { getLog().info( "Must delete version: " + versionToRemove.getVersionLabel()); DeleteApplicationVersionRequest req = new DeleteApplicationVersionRequest() .withApplicationName(versionToRemove.getApplicationName())// .withDeleteSourceBundle(deleteSourceBundle)// .withVersionLabel(versionToRemove.getVersionLabel()); if (!dryRun) { getService().deleteApplicationVersion(req); deletedVersionsCount++; } } void filterAppVersionListByVersionLabelPattern(List<ApplicationVersionDescription> appVersionList, String patternString) { if (patternString == null) return; getLog().info( "Filtering versions with pattern : " + patternString); Pattern p = Pattern.compile(patternString); for (ListIterator<ApplicationVersionDescription> appVersionIterator = appVersionList .listIterator(); appVersionIterator.hasNext();) { if (!p.matcher(appVersionIterator .next() .getVersionLabel()) .matches()) appVersionIterator.remove(); } } }
beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/version/CleanPreviousVersionsMojo.java
package br.com.ingenieux.mojo.beanstalk.version; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.ListIterator; import org.apache.commons.lang.builder.CompareToBuilder; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import br.com.ingenieux.mojo.beanstalk.AbstractBeanstalkMojo; import com.amazonaws.services.elasticbeanstalk.model.ApplicationVersionDescription; import com.amazonaws.services.elasticbeanstalk.model.DeleteApplicationVersionRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeApplicationVersionsRequest; import com.amazonaws.services.elasticbeanstalk.model.DescribeApplicationVersionsResult; import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentsResult; import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription; /** * Deletes application versions, either by count and/or by date old * * @since 0.2.2 */ @Mojo(name="clean-previous-versions") public class CleanPreviousVersionsMojo extends AbstractBeanstalkMojo { /** * Beanstalk Application Name */ @Parameter(property="beanstalk.applicationName", defaultValue="${project.artifactId}", required=true) String applicationName; /** * Delete the source bundle? */ @Parameter(property="beanstalk.deleteSourceBundle", defaultValue="false") boolean deleteSourceBundle; /** * How many versions to keep? */ @Parameter(property="beanstalk.versionsToKeep") Integer versionsToKeep; /** * How many versions to keep? */ @Parameter(property="beanstalk.daysToKeep") Integer daysToKeep; /** * Simulate deletion changing algorithm? */ @Parameter(property="beanstalk.dryRun", defaultValue="true") boolean dryRun; private int deletedVersionsCount; @Override protected Object executeInternal() throws MojoExecutionException, MojoFailureException { boolean bVersionsToKeepDefined = (null != versionsToKeep); boolean bDaysToKeepDefined = (null != daysToKeep); if (!(bVersionsToKeepDefined ^ bDaysToKeepDefined)) throw new MojoFailureException( "Declare either versionsToKeep or daysToKeep, but not both nor none!"); DescribeApplicationVersionsRequest describeApplicationVersionsRequest = new DescribeApplicationVersionsRequest() .withApplicationName(applicationName); DescribeApplicationVersionsResult appVersions = getService() .describeApplicationVersions(describeApplicationVersionsRequest); DescribeEnvironmentsResult environments = getService() .describeEnvironments(); List<ApplicationVersionDescription> appVersionList = new ArrayList<ApplicationVersionDescription>( appVersions.getApplicationVersions()); deletedVersionsCount = 0; for (EnvironmentDescription d : environments.getEnvironments()) { boolean bActiveEnvironment = (d.getStatus().equals("Running") || d.getStatus().equals("Launching") || d.getStatus() .equals("Ready")); for (ListIterator<ApplicationVersionDescription> appVersionIterator = appVersionList .listIterator(); appVersionIterator.hasNext();) { ApplicationVersionDescription appVersion = appVersionIterator .next(); boolean bMatchesVersion = appVersion.getVersionLabel().equals( d.getVersionLabel()); if (bActiveEnvironment && bMatchesVersion) { getLog().info( "VersionLabel " + appVersion.getVersionLabel() + " is bound to environment " + d.getEnvironmentName() + " - Skipping it"); appVersionIterator.remove(); } } } Collections.sort(appVersionList, new Comparator<ApplicationVersionDescription>() { @Override public int compare(ApplicationVersionDescription o1, ApplicationVersionDescription o2) { return new CompareToBuilder().append( o1.getDateUpdated(), o2.getDateUpdated()) .toComparison(); } }); if (bDaysToKeepDefined) { Date now = new Date(); for (ApplicationVersionDescription d : appVersionList) { long delta = now.getTime() - d.getDateUpdated().getTime(); delta /= 1000; delta /= 86400; boolean shouldDeleteP = (delta > daysToKeep); if (getLog().isDebugEnabled()) getLog().debug( "Version " + d.getVersionLabel() + " was from " + delta + " days ago. Should we delete? " + shouldDeleteP); if (shouldDeleteP) deleteVersion(d); } } else { while (appVersionList.size() > versionsToKeep) deleteVersion(appVersionList.remove(0)); } getLog().info( "Deleted " + deletedVersionsCount + " versions."); return null; } void deleteVersion(ApplicationVersionDescription versionToRemove) { getLog().info( "Must delete version: " + versionToRemove.getVersionLabel()); DeleteApplicationVersionRequest req = new DeleteApplicationVersionRequest() .withApplicationName(versionToRemove.getApplicationName())// .withDeleteSourceBundle(deleteSourceBundle)// .withVersionLabel(versionToRemove.getVersionLabel()); if (!dryRun) { getService().deleteApplicationVersion(req); deletedVersionsCount++; } } }
clean-previous-versions : add filtering of app versions to delete with versionLabel pattern
beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/version/CleanPreviousVersionsMojo.java
clean-previous-versions : add filtering of app versions to delete with versionLabel pattern
<ide><path>eanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/version/CleanPreviousVersionsMojo.java <ide> import java.util.Date; <ide> import java.util.List; <ide> import java.util.ListIterator; <add>import java.util.regex.Pattern; <ide> <ide> import org.apache.commons.lang.builder.CompareToBuilder; <ide> import org.apache.maven.plugin.MojoExecutionException; <ide> @Parameter(property="beanstalk.daysToKeep") <ide> Integer daysToKeep; <ide> <add> /** <add> * Filter application version list by version label wildcard matching? <add> */ <add> @Parameter(property="beanstalk.keepFilter") <add> String keepFilter; <add> <ide> /** <ide> * Simulate deletion changing algorithm? <ide> */ <ide> } <ide> } <ide> } <add> <add> filterAppVersionListByVersionLabelPattern(appVersionList, keepFilter); <ide> <ide> Collections.sort(appVersionList, <ide> new Comparator<ApplicationVersionDescription>() { <ide> deletedVersionsCount++; <ide> } <ide> } <add> <add> void filterAppVersionListByVersionLabelPattern(List<ApplicationVersionDescription> appVersionList, String patternString) { <add> if (patternString == null) <add> return; <add> <add> getLog().info( <add> "Filtering versions with pattern : " + patternString); <add> <add> Pattern p = Pattern.compile(patternString); <add> for (ListIterator<ApplicationVersionDescription> appVersionIterator = appVersionList <add> .listIterator(); appVersionIterator.hasNext();) { <add> <add> if (!p.matcher(appVersionIterator <add> .next() <add> .getVersionLabel()) <add> .matches()) <add> appVersionIterator.remove(); <add> } <add> } <ide> }
Java
apache-2.0
a89692f4f09cf432c0b6414acb091580cc7bef60
0
daradurvs/ignite,ilantukh/ignite,NSAmelchev/ignite,ascherbakoff/ignite,ascherbakoff/ignite,apache/ignite,nizhikov/ignite,daradurvs/ignite,chandresh-pancholi/ignite,shroman/ignite,samaitra/ignite,ptupitsyn/ignite,apache/ignite,chandresh-pancholi/ignite,apache/ignite,ptupitsyn/ignite,nizhikov/ignite,andrey-kuznetsov/ignite,apache/ignite,SomeFire/ignite,nizhikov/ignite,SomeFire/ignite,shroman/ignite,samaitra/ignite,SomeFire/ignite,NSAmelchev/ignite,NSAmelchev/ignite,BiryukovVA/ignite,shroman/ignite,ascherbakoff/ignite,samaitra/ignite,samaitra/ignite,NSAmelchev/ignite,shroman/ignite,BiryukovVA/ignite,SomeFire/ignite,apache/ignite,nizhikov/ignite,ascherbakoff/ignite,samaitra/ignite,ptupitsyn/ignite,apache/ignite,ascherbakoff/ignite,BiryukovVA/ignite,ilantukh/ignite,samaitra/ignite,ilantukh/ignite,apache/ignite,BiryukovVA/ignite,daradurvs/ignite,nizhikov/ignite,xtern/ignite,ilantukh/ignite,samaitra/ignite,xtern/ignite,ilantukh/ignite,ascherbakoff/ignite,andrey-kuznetsov/ignite,BiryukovVA/ignite,NSAmelchev/ignite,NSAmelchev/ignite,daradurvs/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,shroman/ignite,andrey-kuznetsov/ignite,ilantukh/ignite,samaitra/ignite,xtern/ignite,andrey-kuznetsov/ignite,nizhikov/ignite,apache/ignite,shroman/ignite,daradurvs/ignite,ascherbakoff/ignite,shroman/ignite,ptupitsyn/ignite,SomeFire/ignite,samaitra/ignite,BiryukovVA/ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,BiryukovVA/ignite,apache/ignite,xtern/ignite,SomeFire/ignite,daradurvs/ignite,BiryukovVA/ignite,andrey-kuznetsov/ignite,SomeFire/ignite,andrey-kuznetsov/ignite,nizhikov/ignite,andrey-kuznetsov/ignite,nizhikov/ignite,ptupitsyn/ignite,xtern/ignite,xtern/ignite,chandresh-pancholi/ignite,chandresh-pancholi/ignite,nizhikov/ignite,ptupitsyn/ignite,ilantukh/ignite,andrey-kuznetsov/ignite,chandresh-pancholi/ignite,shroman/ignite,xtern/ignite,BiryukovVA/ignite,ascherbakoff/ignite,NSAmelchev/ignite,SomeFire/ignite,BiryukovVA/ignite,daradurvs/ignite,SomeFire/ignite,ilantukh/ignite,NSAmelchev/ignite,daradurvs/ignite,samaitra/ignite,xtern/ignite,ptupitsyn/ignite,ptupitsyn/ignite,ascherbakoff/ignite,NSAmelchev/ignite,xtern/ignite,SomeFire/ignite,daradurvs/ignite,shroman/ignite,ilantukh/ignite,ilantukh/ignite,ptupitsyn/ignite,andrey-kuznetsov/ignite,shroman/ignite,daradurvs/ignite,chandresh-pancholi/ignite,chandresh-pancholi/ignite
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.jdbc.thin; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.cache.query.annotations.QuerySqlField; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.IgniteInterruptedCheckedException; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteInClosure; import org.apache.ignite.testframework.GridTestUtils; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test to check various transactional scenarios. */ @RunWith(JUnit4.class) public abstract class JdbcThinTransactionsAbstractComplexSelfTest extends JdbcThinAbstractSelfTest { /** Client node index. */ static final int CLI_IDX = 1; /** * Closure to perform ordinary delete after repeatable read. */ private final IgniteInClosure<Connection> afterReadDel = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }; /** * Closure to perform fast delete after repeatable read. */ private final IgniteInClosure<Connection> afterReadFastDel = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }; /** * Closure to perform ordinary update after repeatable read. */ private final IgniteInClosure<Connection> afterReadUpdate = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person set firstname = 'Joe' where firstname = 'John'"); } }; /** * Closure to perform ordinary delete and rollback after repeatable read. */ private final IgniteInClosure<Connection> afterReadDelAndRollback = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); rollback(conn); } }; /** * Closure to perform fast delete after repeatable read. */ private final IgniteInClosure<Connection> afterReadFastDelAndRollback = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); rollback(conn); } }; /** * Closure to perform ordinary update and rollback after repeatable read. */ private final IgniteInClosure<Connection> afterReadUpdateAndRollback = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person set firstname = 'Joe' where firstname = 'John'"); rollback(conn); } }; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String testIgniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(testIgniteInstanceName); CacheConfiguration<Integer, Person> ccfg = new CacheConfiguration<>("Person"); ccfg.setIndexedTypes(Integer.class, Person.class); ccfg.getQueryEntities().iterator().next().setKeyFieldName("id"); ccfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT); ccfg.setCacheMode(CacheMode.PARTITIONED); cfg.setCacheConfiguration(ccfg); // Let the node with index 1 be client node. cfg.setClientMode(F.eq(testIgniteInstanceName, getTestIgniteInstanceName(CLI_IDX))); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); execute("ALTER TABLE \"Person\".person add if not exists cityid int"); execute("ALTER TABLE \"Person\".person add if not exists companyid int"); execute("CREATE TABLE City (id int primary key, name varchar, population int) WITH " + "\"atomicity=transactional_snapshot,template=partitioned,backups=3,cache_name=City\""); execute("CREATE TABLE Company (id int, \"cityid\" int, name varchar, primary key (id, \"cityid\")) WITH " + "\"atomicity=transactional_snapshot,template=partitioned,backups=1,wrap_value=false,affinity_key=cityid," + "cache_name=Company\""); execute("CREATE TABLE Product (id int primary key, name varchar, companyid int) WITH " + "\"atomicity=transactional_snapshot,template=partitioned,backups=2,cache_name=Product\""); execute("CREATE INDEX IF NOT EXISTS prodidx ON Product(companyid)"); execute("CREATE INDEX IF NOT EXISTS persidx ON \"Person\".person(cityid)"); insertPerson(1, "John", "Smith", 1, 1); insertPerson(2, "Mike", "Johns", 1, 2); insertPerson(3, "Sam", "Jules", 2, 2); insertPerson(4, "Alex", "Pope", 2, 3); insertPerson(5, "Peter", "Williams", 2, 3); insertCity(1, "Los Angeles", 5000); insertCity(2, "Seattle", 1500); insertCity(3, "New York", 12000); insertCity(4, "Cupertino", 400); insertCompany(1, "Microsoft", 2); insertCompany(2, "Google", 3); insertCompany(3, "Facebook", 1); insertCompany(4, "Uber", 1); insertCompany(5, "Apple", 4); insertProduct(1, "Search", 2); insertProduct(2, "Windows", 1); insertProduct(3, "Mac", 5); awaitPartitionMapExchange(); } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); startGrid(0); startGrid(1); startGrid(2); startGrid(3); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { stopAllGrids(); super.afterTestsStopped(); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { execute("DELETE FROM \"Person\".Person"); execute("DROP TABLE City"); execute("DROP TABLE Company"); execute("DROP TABLE Product"); super.afterTest(); } /** * */ @Test public void testSingleDmlStatement() throws SQLException { insertPerson(6, "John", "Doe", 2, 2); assertEquals(Collections.singletonList(l(6, "John", "Doe", 2, 2)), execute("SELECT * FROM \"Person\".Person where id = 6")); } /** * */ @Test public void testMultipleDmlStatements() throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertPerson(conn, 6, "John", "Doe", 2, 2); // https://issues.apache.org/jira/browse/IGNITE-6938 - we can only see results of // UPDATE of what we have not inserted ourselves. execute(conn, "UPDATE \"Person\".person SET lastname = 'Jameson' where lastname = 'Jules'"); execute(conn, "DELETE FROM \"Person\".person where id = 5"); } }); assertEquals(l( l(3, "Sam", "Jameson", 2, 2), l(6, "John", "Doe", 2, 2) ), execute("SELECT * FROM \"Person\".Person where id = 3 or id >= 5 order by id")); } /** * */ @Test public void testBatchDmlStatements() throws SQLException { doBatchedInsert(); assertEquals(l( l(6, "John", "Doe", 2, 2), l(7, "Mary", "Lee", 1, 3) ), execute("SELECT * FROM \"Person\".Person where id > 5 order by id")); } /** * */ @Test public void testBatchDmlStatementsIntermediateFailure() throws SQLException { insertPerson(6, "John", "Doe", 2, 2); IgniteException e = (IgniteException)GridTestUtils.assertThrows(null, new Callable<Object>() { @Override public Object call() throws Exception { doBatchedInsert(); return null; } }, IgniteException.class, "Duplicate key during INSERT [key=KeyCacheObjectImpl " + "[part=6, val=6, hasValBytes=true]]"); assertTrue(e.getCause() instanceof BatchUpdateException); assertTrue(e.getCause().getMessage().contains("Duplicate key during INSERT [key=KeyCacheObjectImpl " + "[part=6, val=6, hasValBytes=true]]")); // First we insert id 7, then 6. Still, 7 is not in the cache as long as the whole batch has failed inside tx. assertEquals(Collections.emptyList(), execute("SELECT * FROM \"Person\".Person where id > 6 order by id")); } /** * */ private void doBatchedInsert() throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { try { try (PreparedStatement ps = conn.prepareStatement("INSERT INTO \"Person\".person " + "(id, firstName, lastName, cityId, companyId) values (?, ?, ?, ?, ?)")) { ps.setInt(1, 7); ps.setString(2, "Mary"); ps.setString(3, "Lee"); ps.setInt(4, 1); ps.setInt(5, 3); ps.addBatch(); ps.setInt(1, 6); ps.setString(2, "John"); ps.setString(3, "Doe"); ps.setInt(4, 2); ps.setInt(5, 2); ps.addBatch(); ps.executeBatch(); } } catch (SQLException e) { throw new IgniteException(e); } } }); } /** * */ @Test public void testInsertAndQueryMultipleCaches() throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertCity(conn, 5, "St Petersburg", 6000); insertCompany(conn, 6, "VK", 5); insertPerson(conn, 6, "Peter", "Sergeev", 5, 6); } }); try (Connection c = connect("distributedJoins=true")) { assertEquals(l(l(5, "St Petersburg", 6000, 6, 5, "VK", 6, "Peter", "Sergeev", 5, 6)), execute(c, "SELECT * FROM City left join Company on City.id = Company.\"cityid\" " + "left join \"Person\".Person p on City.id = p.cityid WHERE p.id = 6 or company.id = 6")); } } /** * */ @Test public void testColocatedJoinSelectAndInsertInTransaction() throws SQLException { // We'd like to put some Google into cities wgit checith over 1K population which don't have it yet executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { List<Integer> ids = flat(execute(conn, "SELECT distinct City.id from City left join Company c on " + "City.id = c.\"cityid\" where population >= 1000 and c.name <> 'Google' order by City.id")); assertEqualsCollections(l(1, 2), ids); int i = 5; for (int l : ids) insertCompany(conn, ++i, "Google", l); } }); assertEqualsCollections(l("Los Angeles", "Seattle", "New York"), flat(execute("SELECT City.name from City " + "left join Company c on city.id = c.\"cityid\" WHERE c.name = 'Google' order by City.id"))); } /** * */ @Test public void testDistributedJoinSelectAndInsertInTransaction() throws SQLException { try (Connection c = connect("distributedJoins=true")) { // We'd like to put some Google into cities with over 1K population which don't have it yet executeInTransaction(c, new TransactionClosure() { @Override public void apply(Connection conn) { List<?> res = flat(execute(conn, "SELECT p.id,p.name,c.id from Company c left join Product p on " + "c.id = p.companyid left join City on city.id = c.\"cityid\" WHERE c.name <> 'Microsoft' " + "and population < 1000")); assertEqualsCollections(l(3, "Mac", 5), res); insertProduct(conn, 4, (String)res.get(1), 1); } }); } try (Connection c = connect("distributedJoins=true")) { assertEqualsCollections(l("Windows", "Mac"), flat(execute(c, "SELECT p.name from Company c left join " + "Product p on c.id = p.companyid WHERE c.name = 'Microsoft' order by p.id"))); } } /** * */ @Test public void testInsertFromExpression() throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { execute(conn, "insert into city (id, name, population) values (? + 1, ?, ?)", 8, "Moscow", 15000); } }); } /** * */ @Test public void testAutoRollback() throws SQLException { try (Connection c = connect()) { begin(c); insertPerson(c, 6, "John", "Doe", 2, 2); } // Connection has not hung on close and update has not been applied. assertTrue(personCache().query(new SqlFieldsQuery("SELECT * FROM \"Person\".Person WHERE id = 6")) .getAll().isEmpty()); } /** * */ @Test public void testRepeatableReadWithConcurrentDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, null); } /** * */ @Test public void testRepeatableReadWithConcurrentFastDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, null); } /** * */ @Test public void testRepeatableReadWithConcurrentCacheRemove() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, null); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, afterReadDel); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentFastDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, afterReadDel); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentCacheRemove() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, afterReadDel); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, afterReadFastDel); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentFastDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, afterReadFastDel); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentCacheRemove() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, afterReadFastDel); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentDeleteAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, afterReadDelAndRollback); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentFastDeleteAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, afterReadDelAndRollback); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentCacheRemoveAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, afterReadDelAndRollback); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentDeleteAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, afterReadFastDelAndRollback); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentFastDeleteAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, afterReadFastDelAndRollback); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentCacheRemoveAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, afterReadFastDelAndRollback); } /** * */ @Test public void testRepeatableReadWithConcurrentUpdate() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person SET lastname = 'Fix' where firstname = 'John'"); } }, null); } /** * */ @Test public void testRepeatableReadWithConcurrentCacheReplace() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { Person p = new Person(); p.id = 1; p.firstName = "Luke"; p.lastName = "Maxwell"; personCache().replace(1, p); } }, null); } /** * */ @Test public void testRepeatableReadAndUpdateWithConcurrentUpdate() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person SET lastname = 'Fix' where firstname = 'John'"); } }, afterReadUpdate); } /** * */ @Test public void testRepeatableReadAndUpdateWithConcurrentCacheReplace() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { Person p = new Person(); p.id = 1; p.firstName = "Luke"; p.lastName = "Maxwell"; personCache().replace(1, p); } }, afterReadUpdate); } /** * */ @Test public void testRepeatableReadAndUpdateWithConcurrentUpdateAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person SET lastname = 'Fix' where firstname = 'John'"); } }, afterReadUpdateAndRollback); } /** * */ @Test public void testRepeatableReadAndUpdateWithConcurrentCacheReplaceAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { Person p = new Person(); p.id = 1; p.firstName = "Luke"; p.lastName = "Maxwell"; personCache().replace(1, p); } }, afterReadUpdateAndRollback); } /** * Perform repeatable reads and concurrent changes. * @param concurrentWriteClo Updating closure. * @param afterReadClo Closure making write changes that should also be made inside repeatable read transaction * (must yield an exception). * @throws Exception if failed. */ private void doTestRepeatableRead(final IgniteInClosure<Connection> concurrentWriteClo, final IgniteInClosure<Connection> afterReadClo) throws Exception { final CountDownLatch repeatableReadLatch = new CountDownLatch(1); final CountDownLatch initLatch = new CountDownLatch(1); final IgniteInternalFuture<?> readFut = multithreadedAsync(new Callable<Object>() { @Override public Object call() throws Exception { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { List<?> before = flat(execute(conn, "SELECT * from \"Person\".Person where id = 1")); assertEqualsCollections(l(1, "John", "Smith", 1, 1), before); initLatch.countDown(); try { U.await(repeatableReadLatch); } catch (IgniteInterruptedCheckedException e) { throw new IgniteException(e); } List<?> after = flat(execute(conn, "SELECT * from \"Person\".Person where id = 1")); assertEqualsCollections(before, after); if (afterReadClo != null) afterReadClo.apply(conn); } }); return null; } }, 1); IgniteInternalFuture<?> conModFut = multithreadedAsync(new Callable<Object>() { @Override public Object call() throws Exception { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { try { U.await(initLatch); } catch (IgniteInterruptedCheckedException e) { throw new IgniteException(e); } concurrentWriteClo.apply(conn); repeatableReadLatch.countDown(); } }); return null; } }, 1); conModFut.get(); if (afterReadClo != null) { IgniteCheckedException ex = (IgniteCheckedException)GridTestUtils.assertThrows(null, new Callable() { @Override public Object call() throws Exception { readFut.get(); return null; } }, IgniteCheckedException.class, "Cannot serialize transaction due to write conflict"); assertTrue(X.hasCause(ex, SQLException.class)); assertTrue(X.getCause(ex).getMessage().contains("Cannot serialize transaction due to write conflict")); } else readFut.get(); } /** * Create a new connection, a new transaction and run given closure in its scope. * @param clo Closure. * @throws SQLException if failed. */ private void executeInTransaction(TransactionClosure clo) throws SQLException { try (Connection conn = connect()) { executeInTransaction(conn, clo); } } /** * Create a new transaction and run given closure in its scope. * @param conn Connection. * @param clo Closure. * @throws SQLException if failed. */ private void executeInTransaction(Connection conn, TransactionClosure clo) throws SQLException { begin(conn); clo.apply(conn); commit(conn); } /** * @return Auto commit strategy for this test. */ abstract boolean autoCommit(); /** * @param c Connection to begin a transaction on. */ private void begin(Connection c) throws SQLException { if (autoCommit()) execute(c, "BEGIN"); } /** * @param c Connection to begin a transaction on. */ private void commit(Connection c) throws SQLException { if (autoCommit()) execute(c, "COMMIT"); else c.commit(); } /** * @param c Connection to rollback a transaction on. */ private void rollback(Connection c) { try { if (autoCommit()) execute(c, "ROLLBACK"); else c.rollback(); } catch (SQLException e) { throw new IgniteException(e); } } /** * @param sql Statement. * @param args Arguments. * @return Result set. * @throws SQLException if failed. */ List<List<?>> execute(String sql, Object... args) throws SQLException { try (Connection c = connect()) { c.setAutoCommit(true); return execute(c, sql, args); } } /** * @param sql Statement. * @param args Arguments. * @return Result set. * @throws RuntimeException if failed. */ protected List<List<?>> execute(Connection conn, String sql, Object... args) { try { return super.execute(conn, sql, args); } catch (SQLException e) { throw new IgniteException(e); } } /** * @return New connection to default node. * @throws SQLException if failed. */ private Connection connect() throws SQLException { return connect(null); } /** * @param params Connection parameters. * @return New connection to default node. * @throws SQLException if failed. */ private Connection connect(String params) throws SQLException { Connection c = connect(node(), params); c.setAutoCommit(false); return c; } /** * @param node Node to connect to. * @param params Connection parameters. * @return Thin JDBC connection to specified node. */ protected Connection connect(IgniteEx node, String params) { try { return super.connect(node, params); } catch (SQLException e) { throw new AssertionError(e); } } /** * @return Default node to fire queries from. */ private IgniteEx node() { return grid(nodeIndex()); } /** * @return {@link Person} cache. */ private IgniteCache<Integer, Person> personCache() { return node().cache("Person"); } /** * @return Node index to fire queries from. */ abstract int nodeIndex(); /** * @param id New person's id. * @param firstName First name. * @param lastName Second name. * @param cityId City id. * @param companyId Company id. * @throws SQLException if failed. */ private void insertPerson(final int id, final String firstName, final String lastName, final int cityId, final int companyId) throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertPerson(conn, id, firstName, lastName, cityId, companyId); } }); } /** * @param c Connection. * @param id New person's id. * @param firstName First name. * @param lastName Second name. * @param cityId City id. * @param companyId Company id. */ private void insertPerson(Connection c, int id, String firstName, String lastName, int cityId, int companyId) { execute(c, "INSERT INTO \"Person\".person (id, firstName, lastName, cityId, companyId) values (?, ?, ?, ?, ?)", id, firstName, lastName, cityId, companyId); } /** * @param id New city's id. * @param name City name. * @param population Number of people. * @throws SQLException if failed. */ private void insertCity(final int id, final String name, final int population) throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertCity(conn, id, name, population); } }); } /** * @param c Connection. * @param id New city's id. * @param name City name. * @param population Number of people. */ private void insertCity(Connection c, int id, String name, int population) { execute(c, "INSERT INTO city (id, name, population) values (?, ?, ?)", id, name, population); } /** * @param id New company's id. * @param name Company name. * @param cityId City id. * @throws SQLException if failed. */ private void insertCompany(final int id, final String name, final int cityId) throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertCompany(conn, id, name, cityId); } }); } /** * @param c Connection. * @param id New company's id. * @param name Company name. * @param cityId City id. */ private void insertCompany(Connection c, int id, String name, int cityId) { execute(c, "INSERT INTO company (id, name, \"cityid\") values (?, ?, ?)", id, name, cityId); } /** * @param id New product's id. * @param name Product name. * @param companyId Company id.. * @throws SQLException if failed. */ private void insertProduct(final int id, final String name, final int companyId) throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertProduct(conn, id, name, companyId); } }); } /** * @param c Connection. * @param id New product's id. * @param name Product name. * @param companyId Company id.. */ private void insertProduct(Connection c, int id, String name, int companyId) { execute(c, "INSERT INTO product (id, name, companyid) values (?, ?, ?)", id, name, companyId); } /** * Person class. */ private static final class Person { /** */ @QuerySqlField public int id; /** */ @QuerySqlField public String firstName; /** */ @QuerySqlField public String lastName; } /** * Closure to be executed in scope of a transaction. */ private abstract class TransactionClosure implements IgniteInClosure<Connection> { // No-op. } /** * @return List of given arguments. */ private static List<?> l(Object... args) { return F.asList(args); } /** * Flatten rows. * @param rows Rows. * @return Rows as a single list. */ @SuppressWarnings("unchecked") private static <T> List<T> flat(Collection<? extends Collection<?>> rows) { return new ArrayList<>(F.flatCollections((Collection<? extends Collection<T>>)rows)); } }
modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcThinTransactionsAbstractComplexSelfTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.jdbc.thin; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.cache.query.annotations.QuerySqlField; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.IgniteInterruptedCheckedException; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteInClosure; import org.apache.ignite.testframework.GridTestUtils; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test to check various transactional scenarios. */ @RunWith(JUnit4.class) public abstract class JdbcThinTransactionsAbstractComplexSelfTest extends JdbcThinAbstractSelfTest { /** Client node index. */ static final int CLI_IDX = 1; /** * Closure to perform ordinary delete after repeatable read. */ private final IgniteInClosure<Connection> afterReadDel = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }; /** * Closure to perform fast delete after repeatable read. */ private final IgniteInClosure<Connection> afterReadFastDel = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }; /** * Closure to perform ordinary update after repeatable read. */ private final IgniteInClosure<Connection> afterReadUpdate = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person set firstname = 'Joe' where firstname = 'John'"); } }; /** * Closure to perform ordinary delete and rollback after repeatable read. */ private final IgniteInClosure<Connection> afterReadDelAndRollback = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); rollback(conn); } }; /** * Closure to perform fast delete after repeatable read. */ private final IgniteInClosure<Connection> afterReadFastDelAndRollback = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); rollback(conn); } }; /** * Closure to perform ordinary update and rollback after repeatable read. */ private final IgniteInClosure<Connection> afterReadUpdateAndRollback = new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person set firstname = 'Joe' where firstname = 'John'"); rollback(conn); } }; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String testIgniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(testIgniteInstanceName); CacheConfiguration<Integer, Person> ccfg = new CacheConfiguration<>("Person"); ccfg.setIndexedTypes(Integer.class, Person.class); ccfg.getQueryEntities().iterator().next().setKeyFieldName("id"); ccfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT); ccfg.setCacheMode(CacheMode.PARTITIONED); cfg.setCacheConfiguration(ccfg); // Let the node with index 1 be client node. cfg.setClientMode(F.eq(testIgniteInstanceName, getTestIgniteInstanceName(CLI_IDX))); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); execute("ALTER TABLE \"Person\".person add if not exists cityid int"); execute("ALTER TABLE \"Person\".person add if not exists companyid int"); execute("CREATE TABLE City (id int primary key, name varchar, population int) WITH " + "\"atomicity=transactional_snapshot,template=partitioned,backups=3,cache_name=City\""); execute("CREATE TABLE Company (id int, \"cityid\" int, name varchar, primary key (id, \"cityid\")) WITH " + "\"atomicity=transactional_snapshot,template=partitioned,backups=1,wrap_value=false,affinity_key=cityid," + "cache_name=Company\""); execute("CREATE TABLE Product (id int primary key, name varchar, companyid int) WITH " + "\"atomicity=transactional_snapshot,template=partitioned,backups=2,cache_name=Product\""); execute("CREATE INDEX IF NOT EXISTS prodidx ON Product(companyid)"); execute("CREATE INDEX IF NOT EXISTS persidx ON \"Person\".person(cityid)"); insertPerson(1, "John", "Smith", 1, 1); insertPerson(2, "Mike", "Johns", 1, 2); insertPerson(3, "Sam", "Jules", 2, 2); insertPerson(4, "Alex", "Pope", 2, 3); insertPerson(5, "Peter", "Williams", 2, 3); insertCity(1, "Los Angeles", 5000); insertCity(2, "Seattle", 1500); insertCity(3, "New York", 12000); insertCity(4, "Cupertino", 400); insertCompany(1, "Microsoft", 2); insertCompany(2, "Google", 3); insertCompany(3, "Facebook", 1); insertCompany(4, "Uber", 1); insertCompany(5, "Apple", 4); insertProduct(1, "Search", 2); insertProduct(2, "Windows", 1); insertProduct(3, "Mac", 5); } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); startGrid(0); startGrid(1); startGrid(2); startGrid(3); } /** {@inheritDoc} */ @Override protected void afterTestsStopped() throws Exception { stopAllGrids(); super.afterTestsStopped(); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { execute("DELETE FROM \"Person\".Person"); execute("DROP TABLE City"); execute("DROP TABLE Company"); execute("DROP TABLE Product"); super.afterTest(); } /** * */ @Test public void testSingleDmlStatement() throws SQLException { insertPerson(6, "John", "Doe", 2, 2); assertEquals(Collections.singletonList(l(6, "John", "Doe", 2, 2)), execute("SELECT * FROM \"Person\".Person where id = 6")); } /** * */ @Test public void testMultipleDmlStatements() throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertPerson(conn, 6, "John", "Doe", 2, 2); // https://issues.apache.org/jira/browse/IGNITE-6938 - we can only see results of // UPDATE of what we have not inserted ourselves. execute(conn, "UPDATE \"Person\".person SET lastname = 'Jameson' where lastname = 'Jules'"); execute(conn, "DELETE FROM \"Person\".person where id = 5"); } }); assertEquals(l( l(3, "Sam", "Jameson", 2, 2), l(6, "John", "Doe", 2, 2) ), execute("SELECT * FROM \"Person\".Person where id = 3 or id >= 5 order by id")); } /** * */ @Test public void testBatchDmlStatements() throws SQLException { doBatchedInsert(); assertEquals(l( l(6, "John", "Doe", 2, 2), l(7, "Mary", "Lee", 1, 3) ), execute("SELECT * FROM \"Person\".Person where id > 5 order by id")); } /** * */ @Test public void testBatchDmlStatementsIntermediateFailure() throws SQLException { insertPerson(6, "John", "Doe", 2, 2); IgniteException e = (IgniteException)GridTestUtils.assertThrows(null, new Callable<Object>() { @Override public Object call() throws Exception { doBatchedInsert(); return null; } }, IgniteException.class, "Duplicate key during INSERT [key=KeyCacheObjectImpl " + "[part=6, val=6, hasValBytes=true]]"); assertTrue(e.getCause() instanceof BatchUpdateException); assertTrue(e.getCause().getMessage().contains("Duplicate key during INSERT [key=KeyCacheObjectImpl " + "[part=6, val=6, hasValBytes=true]]")); // First we insert id 7, then 6. Still, 7 is not in the cache as long as the whole batch has failed inside tx. assertEquals(Collections.emptyList(), execute("SELECT * FROM \"Person\".Person where id > 6 order by id")); } /** * */ private void doBatchedInsert() throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { try { try (PreparedStatement ps = conn.prepareStatement("INSERT INTO \"Person\".person " + "(id, firstName, lastName, cityId, companyId) values (?, ?, ?, ?, ?)")) { ps.setInt(1, 7); ps.setString(2, "Mary"); ps.setString(3, "Lee"); ps.setInt(4, 1); ps.setInt(5, 3); ps.addBatch(); ps.setInt(1, 6); ps.setString(2, "John"); ps.setString(3, "Doe"); ps.setInt(4, 2); ps.setInt(5, 2); ps.addBatch(); ps.executeBatch(); } } catch (SQLException e) { throw new IgniteException(e); } } }); } /** * */ @Ignore("https://issues.apache.org/jira/browse/IGNITE-10770") @Test public void testInsertAndQueryMultipleCaches() throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertCity(conn, 5, "St Petersburg", 6000); insertCompany(conn, 6, "VK", 5); insertPerson(conn, 6, "Peter", "Sergeev", 5, 6); } }); try (Connection c = connect("distributedJoins=true")) { assertEquals(l(l(5, "St Petersburg", 6000, 6, 5, "VK", 6, "Peter", "Sergeev", 5, 6)), execute(c, "SELECT * FROM City left join Company on City.id = Company.\"cityid\" " + "left join \"Person\".Person p on City.id = p.cityid WHERE p.id = 6 or company.id = 6")); } } /** * */ @Test public void testColocatedJoinSelectAndInsertInTransaction() throws SQLException { // We'd like to put some Google into cities wgit checith over 1K population which don't have it yet executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { List<Integer> ids = flat(execute(conn, "SELECT distinct City.id from City left join Company c on " + "City.id = c.\"cityid\" where population >= 1000 and c.name <> 'Google' order by City.id")); assertEqualsCollections(l(1, 2), ids); int i = 5; for (int l : ids) insertCompany(conn, ++i, "Google", l); } }); assertEqualsCollections(l("Los Angeles", "Seattle", "New York"), flat(execute("SELECT City.name from City " + "left join Company c on city.id = c.\"cityid\" WHERE c.name = 'Google' order by City.id"))); } /** * */ @Test public void testDistributedJoinSelectAndInsertInTransaction() throws SQLException { try (Connection c = connect("distributedJoins=true")) { // We'd like to put some Google into cities with over 1K population which don't have it yet executeInTransaction(c, new TransactionClosure() { @Override public void apply(Connection conn) { List<?> res = flat(execute(conn, "SELECT p.id,p.name,c.id from Company c left join Product p on " + "c.id = p.companyid left join City on city.id = c.\"cityid\" WHERE c.name <> 'Microsoft' " + "and population < 1000")); assertEqualsCollections(l(3, "Mac", 5), res); insertProduct(conn, 4, (String)res.get(1), 1); } }); } try (Connection c = connect("distributedJoins=true")) { assertEqualsCollections(l("Windows", "Mac"), flat(execute(c, "SELECT p.name from Company c left join " + "Product p on c.id = p.companyid WHERE c.name = 'Microsoft' order by p.id"))); } } /** * */ @Test public void testInsertFromExpression() throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { execute(conn, "insert into city (id, name, population) values (? + 1, ?, ?)", 8, "Moscow", 15000); } }); } /** * */ @Test public void testAutoRollback() throws SQLException { try (Connection c = connect()) { begin(c); insertPerson(c, 6, "John", "Doe", 2, 2); } // Connection has not hung on close and update has not been applied. assertTrue(personCache().query(new SqlFieldsQuery("SELECT * FROM \"Person\".Person WHERE id = 6")) .getAll().isEmpty()); } /** * */ @Test public void testRepeatableReadWithConcurrentDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, null); } /** * */ @Test public void testRepeatableReadWithConcurrentFastDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, null); } /** * */ @Test public void testRepeatableReadWithConcurrentCacheRemove() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, null); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, afterReadDel); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentFastDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, afterReadDel); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentCacheRemove() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, afterReadDel); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, afterReadFastDel); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentFastDelete() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, afterReadFastDel); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentCacheRemove() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, afterReadFastDel); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentDeleteAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, afterReadDelAndRollback); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentFastDeleteAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, afterReadDelAndRollback); } /** * */ @Test public void testRepeatableReadAndDeleteWithConcurrentCacheRemoveAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, afterReadDelAndRollback); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentDeleteAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where firstname = 'John'"); } }, afterReadFastDelAndRollback); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentFastDeleteAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "DELETE FROM \"Person\".Person where id = 1"); } }, afterReadFastDelAndRollback); } /** * */ @Test public void testRepeatableReadAndFastDeleteWithConcurrentCacheRemoveAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { personCache().remove(1); } }, afterReadFastDelAndRollback); } /** * */ @Test public void testRepeatableReadWithConcurrentUpdate() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person SET lastname = 'Fix' where firstname = 'John'"); } }, null); } /** * */ @Test public void testRepeatableReadWithConcurrentCacheReplace() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { Person p = new Person(); p.id = 1; p.firstName = "Luke"; p.lastName = "Maxwell"; personCache().replace(1, p); } }, null); } /** * */ @Test public void testRepeatableReadAndUpdateWithConcurrentUpdate() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person SET lastname = 'Fix' where firstname = 'John'"); } }, afterReadUpdate); } /** * */ @Test public void testRepeatableReadAndUpdateWithConcurrentCacheReplace() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { Person p = new Person(); p.id = 1; p.firstName = "Luke"; p.lastName = "Maxwell"; personCache().replace(1, p); } }, afterReadUpdate); } /** * */ @Test public void testRepeatableReadAndUpdateWithConcurrentUpdateAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { execute(conn, "UPDATE \"Person\".Person SET lastname = 'Fix' where firstname = 'John'"); } }, afterReadUpdateAndRollback); } /** * */ @Test public void testRepeatableReadAndUpdateWithConcurrentCacheReplaceAndRollback() throws Exception { doTestRepeatableRead(new IgniteInClosure<Connection>() { @Override public void apply(Connection conn) { Person p = new Person(); p.id = 1; p.firstName = "Luke"; p.lastName = "Maxwell"; personCache().replace(1, p); } }, afterReadUpdateAndRollback); } /** * Perform repeatable reads and concurrent changes. * @param concurrentWriteClo Updating closure. * @param afterReadClo Closure making write changes that should also be made inside repeatable read transaction * (must yield an exception). * @throws Exception if failed. */ private void doTestRepeatableRead(final IgniteInClosure<Connection> concurrentWriteClo, final IgniteInClosure<Connection> afterReadClo) throws Exception { final CountDownLatch repeatableReadLatch = new CountDownLatch(1); final CountDownLatch initLatch = new CountDownLatch(1); final IgniteInternalFuture<?> readFut = multithreadedAsync(new Callable<Object>() { @Override public Object call() throws Exception { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { List<?> before = flat(execute(conn, "SELECT * from \"Person\".Person where id = 1")); assertEqualsCollections(l(1, "John", "Smith", 1, 1), before); initLatch.countDown(); try { U.await(repeatableReadLatch); } catch (IgniteInterruptedCheckedException e) { throw new IgniteException(e); } List<?> after = flat(execute(conn, "SELECT * from \"Person\".Person where id = 1")); assertEqualsCollections(before, after); if (afterReadClo != null) afterReadClo.apply(conn); } }); return null; } }, 1); IgniteInternalFuture<?> conModFut = multithreadedAsync(new Callable<Object>() { @Override public Object call() throws Exception { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { try { U.await(initLatch); } catch (IgniteInterruptedCheckedException e) { throw new IgniteException(e); } concurrentWriteClo.apply(conn); repeatableReadLatch.countDown(); } }); return null; } }, 1); conModFut.get(); if (afterReadClo != null) { IgniteCheckedException ex = (IgniteCheckedException)GridTestUtils.assertThrows(null, new Callable() { @Override public Object call() throws Exception { readFut.get(); return null; } }, IgniteCheckedException.class, "Cannot serialize transaction due to write conflict"); assertTrue(X.hasCause(ex, SQLException.class)); assertTrue(X.getCause(ex).getMessage().contains("Cannot serialize transaction due to write conflict")); } else readFut.get(); } /** * Create a new connection, a new transaction and run given closure in its scope. * @param clo Closure. * @throws SQLException if failed. */ private void executeInTransaction(TransactionClosure clo) throws SQLException { try (Connection conn = connect()) { executeInTransaction(conn, clo); } } /** * Create a new transaction and run given closure in its scope. * @param conn Connection. * @param clo Closure. * @throws SQLException if failed. */ private void executeInTransaction(Connection conn, TransactionClosure clo) throws SQLException { begin(conn); clo.apply(conn); commit(conn); } /** * @return Auto commit strategy for this test. */ abstract boolean autoCommit(); /** * @param c Connection to begin a transaction on. */ private void begin(Connection c) throws SQLException { if (autoCommit()) execute(c, "BEGIN"); } /** * @param c Connection to begin a transaction on. */ private void commit(Connection c) throws SQLException { if (autoCommit()) execute(c, "COMMIT"); else c.commit(); } /** * @param c Connection to rollback a transaction on. */ private void rollback(Connection c) { try { if (autoCommit()) execute(c, "ROLLBACK"); else c.rollback(); } catch (SQLException e) { throw new IgniteException(e); } } /** * @param sql Statement. * @param args Arguments. * @return Result set. * @throws SQLException if failed. */ List<List<?>> execute(String sql, Object... args) throws SQLException { try (Connection c = connect()) { c.setAutoCommit(true); return execute(c, sql, args); } } /** * @param sql Statement. * @param args Arguments. * @return Result set. * @throws RuntimeException if failed. */ protected List<List<?>> execute(Connection conn, String sql, Object... args) { try { return super.execute(conn, sql, args); } catch (SQLException e) { throw new IgniteException(e); } } /** * @return New connection to default node. * @throws SQLException if failed. */ private Connection connect() throws SQLException { return connect(null); } /** * @param params Connection parameters. * @return New connection to default node. * @throws SQLException if failed. */ private Connection connect(String params) throws SQLException { Connection c = connect(node(), params); c.setAutoCommit(false); return c; } /** * @param node Node to connect to. * @param params Connection parameters. * @return Thin JDBC connection to specified node. */ protected Connection connect(IgniteEx node, String params) { try { return super.connect(node, params); } catch (SQLException e) { throw new AssertionError(e); } } /** * @return Default node to fire queries from. */ private IgniteEx node() { return grid(nodeIndex()); } /** * @return {@link Person} cache. */ private IgniteCache<Integer, Person> personCache() { return node().cache("Person"); } /** * @return Node index to fire queries from. */ abstract int nodeIndex(); /** * @param id New person's id. * @param firstName First name. * @param lastName Second name. * @param cityId City id. * @param companyId Company id. * @throws SQLException if failed. */ private void insertPerson(final int id, final String firstName, final String lastName, final int cityId, final int companyId) throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertPerson(conn, id, firstName, lastName, cityId, companyId); } }); } /** * @param c Connection. * @param id New person's id. * @param firstName First name. * @param lastName Second name. * @param cityId City id. * @param companyId Company id. */ private void insertPerson(Connection c, int id, String firstName, String lastName, int cityId, int companyId) { execute(c, "INSERT INTO \"Person\".person (id, firstName, lastName, cityId, companyId) values (?, ?, ?, ?, ?)", id, firstName, lastName, cityId, companyId); } /** * @param id New city's id. * @param name City name. * @param population Number of people. * @throws SQLException if failed. */ private void insertCity(final int id, final String name, final int population) throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertCity(conn, id, name, population); } }); } /** * @param c Connection. * @param id New city's id. * @param name City name. * @param population Number of people. */ private void insertCity(Connection c, int id, String name, int population) { execute(c, "INSERT INTO city (id, name, population) values (?, ?, ?)", id, name, population); } /** * @param id New company's id. * @param name Company name. * @param cityId City id. * @throws SQLException if failed. */ private void insertCompany(final int id, final String name, final int cityId) throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertCompany(conn, id, name, cityId); } }); } /** * @param c Connection. * @param id New company's id. * @param name Company name. * @param cityId City id. */ private void insertCompany(Connection c, int id, String name, int cityId) { execute(c, "INSERT INTO company (id, name, \"cityid\") values (?, ?, ?)", id, name, cityId); } /** * @param id New product's id. * @param name Product name. * @param companyId Company id.. * @throws SQLException if failed. */ private void insertProduct(final int id, final String name, final int companyId) throws SQLException { executeInTransaction(new TransactionClosure() { @Override public void apply(Connection conn) { insertProduct(conn, id, name, companyId); } }); } /** * @param c Connection. * @param id New product's id. * @param name Product name. * @param companyId Company id.. */ private void insertProduct(Connection c, int id, String name, int companyId) { execute(c, "INSERT INTO product (id, name, companyid) values (?, ?, ?)", id, name, companyId); } /** * Person class. */ private static final class Person { /** */ @QuerySqlField public int id; /** */ @QuerySqlField public String firstName; /** */ @QuerySqlField public String lastName; } /** * Closure to be executed in scope of a transaction. */ private abstract class TransactionClosure implements IgniteInClosure<Connection> { // No-op. } /** * @return List of given arguments. */ private static List<?> l(Object... args) { return F.asList(args); } /** * Flatten rows. * @param rows Rows. * @return Rows as a single list. */ @SuppressWarnings("unchecked") private static <T> List<T> flat(Collection<? extends Collection<?>> rows) { return new ArrayList<>(F.flatCollections((Collection<? extends Collection<T>>)rows)); } }
IGNITE-10770: Enabled JdbcThinTransactionsAbstractComplexSelfTest.testInsertAndQueryMultipleCaches. Works fine with prior PME await.
modules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcThinTransactionsAbstractComplexSelfTest.java
IGNITE-10770: Enabled JdbcThinTransactionsAbstractComplexSelfTest.testInsertAndQueryMultipleCaches. Works fine with prior PME await.
<ide><path>odules/clients/src/test/java/org/apache/ignite/jdbc/thin/JdbcThinTransactionsAbstractComplexSelfTest.java <ide> execute("CREATE INDEX IF NOT EXISTS persidx ON \"Person\".person(cityid)"); <ide> <ide> insertPerson(1, "John", "Smith", 1, 1); <del> <ide> insertPerson(2, "Mike", "Johns", 1, 2); <del> <ide> insertPerson(3, "Sam", "Jules", 2, 2); <del> <ide> insertPerson(4, "Alex", "Pope", 2, 3); <del> <ide> insertPerson(5, "Peter", "Williams", 2, 3); <ide> <ide> insertCity(1, "Los Angeles", 5000); <del> <ide> insertCity(2, "Seattle", 1500); <del> <ide> insertCity(3, "New York", 12000); <del> <ide> insertCity(4, "Cupertino", 400); <ide> <ide> insertCompany(1, "Microsoft", 2); <del> <ide> insertCompany(2, "Google", 3); <del> <ide> insertCompany(3, "Facebook", 1); <del> <ide> insertCompany(4, "Uber", 1); <del> <ide> insertCompany(5, "Apple", 4); <ide> <ide> insertProduct(1, "Search", 2); <del> <ide> insertProduct(2, "Windows", 1); <del> <ide> insertProduct(3, "Mac", 5); <add> <add> awaitPartitionMapExchange(); <ide> } <ide> <ide> /** {@inheritDoc} */ <ide> super.beforeTestsStarted(); <ide> <ide> startGrid(0); <del> <ide> startGrid(1); <del> <ide> startGrid(2); <del> <ide> startGrid(3); <ide> } <ide> <ide> /** <ide> * <ide> */ <del> @Ignore("https://issues.apache.org/jira/browse/IGNITE-10770") <ide> @Test <ide> public void testInsertAndQueryMultipleCaches() throws SQLException { <ide> executeInTransaction(new TransactionClosure() {
Java
bsd-3-clause
61ea45b7d8decfcd7f6823fb8e41d19f34a3960c
0
lutece-platform/lutece-core,lutece-platform/lutece-core,rzara/lutece-core,lutece-platform/lutece-core,rzara/lutece-core,rzara/lutece-core
/* * Copyright (c) 2002-2013, Mairie de Paris * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * License 1.0 */ package fr.paris.lutece.portal.service.content; import fr.paris.lutece.portal.service.init.LuteceInitException; import fr.paris.lutece.portal.service.message.SiteMessage; import fr.paris.lutece.portal.service.message.SiteMessageException; import fr.paris.lutece.portal.service.message.SiteMessageService; import fr.paris.lutece.portal.service.portal.PortalService; import fr.paris.lutece.portal.service.security.LuteceUser; import fr.paris.lutece.portal.service.security.SecurityService; import fr.paris.lutece.portal.service.security.UserNotSignedException; import fr.paris.lutece.portal.service.template.AppTemplateService; import fr.paris.lutece.portal.service.util.AppException; import fr.paris.lutece.portal.service.util.AppLogService; import fr.paris.lutece.portal.web.xpages.XPage; import fr.paris.lutece.portal.web.xpages.XPageApplication; import fr.paris.lutece.portal.web.xpages.XPageApplicationEntry; import fr.paris.lutece.util.html.HtmlTemplate; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * This class delivers Extra pages (xpages) to web components. An XPage is a page where the content is provided by a * specific class, but should be integrated into the portal struture and design. XPageApps are identified by a key * name. To display an XPage into the portal just call the following url :<br><code> * Portal.jsp?page=<i>keyname</i>&amp;param1=value1&amp; ...&amp;paramN=valueN </code> * * @see fr.paris.lutece.portal.web.xpages.XPage */ public class XPageAppService extends ContentService { public static final String PARAM_XPAGE_APP = "page"; private static final String CONTENT_SERVICE_NAME = "XPageAppService"; private static final String MESSAGE_ERROR_APP_BODY = "portal.util.message.errorXpageApp"; private static final String ATTRIBUTE_XPAGE = "LUTECE_XPAGE_"; private static Map<String, XPageApplicationEntry> _mapApplications = new HashMap<String, XPageApplicationEntry>( ); /** * Register an application by its entry defined in the plugin xml file * @param entry The application entry * @throws LuteceInitException If an error occured */ public static void registerXPageApplication( XPageApplicationEntry entry ) throws LuteceInitException { try { XPageApplication application = (XPageApplication) Class.forName( entry.getClassName( ) ).newInstance( ); entry.setApplication( application ); _mapApplications.put( entry.getId( ), entry ); AppLogService.info( "New XPage application registered : " + entry.getId( ) ); } catch ( ClassNotFoundException e ) { throw new LuteceInitException( "Error instantiating XPageApplication : " + entry.getId( ) + " - " + e.getCause( ), e ); } catch ( InstantiationException e ) { throw new LuteceInitException( "Error instantiating XPageApplication : " + entry.getId( ) + " - " + e.getCause( ), e ); } catch ( IllegalAccessException e ) { throw new LuteceInitException( "Error instantiating XPageApplication : " + entry.getId( ) + " - " + e.getCause( ), e ); } } /** * Returns the Content Service name * * @return The name as a String */ @Override public String getName( ) { return CONTENT_SERVICE_NAME; } /** * Analyzes request parameters to see if the request should be handled by the current Content Service * * @param request The HTTP request * @return true if this ContentService should handle this request */ @Override public boolean isInvoked( HttpServletRequest request ) { String strXPage = request.getParameter( PARAM_XPAGE_APP ); if ( ( strXPage != null ) && ( strXPage.length( ) > 0 ) ) { return true; } return false; } /** * Enable or disable the cache feature. * * @param bCache true to enable the cache, false to disable */ public void setCache( boolean bCache ) { } /** * Gets the current cache status. * * @return true if enable, otherwise false */ @Override public boolean isCacheEnable( ) { return false; } /** * Reset the cache. */ @Override public void resetCache( ) { } /** * Gets the number of item currently in the cache. * * @return the number of item currently in the cache. */ @Override public int getCacheSize( ) { return 0; } /** * Build the XPage content. * * @param request The HTTP request. * @param nMode The current mode. * @return The HTML code of the page. * @throws UserNotSignedException The User Not Signed Exception * @throws SiteMessageException occurs when a site message need to be displayed */ @Override public String getPage( HttpServletRequest request, int nMode ) throws UserNotSignedException, SiteMessageException { // Gets XPage info from the lutece.properties String strName = request.getParameter( PARAM_XPAGE_APP ); PageData data = new PageData( ); XPageApplicationEntry entry = getApplicationEntry( strName ); // TODO : Handle entry == null if ( ( entry != null ) && ( entry.isEnable( ) ) ) { XPage page = null; List<String> listRoles = entry.getRoles( ); if ( SecurityService.isAuthenticationEnable( ) && ( listRoles.size( ) > 0 ) ) { LuteceUser user = SecurityService.getInstance( ).getRegisteredUser( request ); if ( user != null ) { boolean bAutorized = false; for ( String strRole : listRoles ) { if ( SecurityService.getInstance( ).isUserInRole( request, strRole ) ) { bAutorized = true; } } if ( bAutorized ) { XPageApplication application = getXPageSessionInstance( request , entry ); page = application.getPage( request, nMode, entry.getPlugin( ) ); } else { // The user doesn't have the correct role String strAccessDeniedTemplate = SecurityService.getInstance( ).getAccessDeniedTemplate( ); HtmlTemplate tAccessDenied = AppTemplateService.getTemplate( strAccessDeniedTemplate ); page = new XPage( ); page.setContent( tAccessDenied.getHtml( ) ); } } else { throw new UserNotSignedException( ); } } else { XPageApplication application = getXPageSessionInstance( request , entry ); page = application.getPage( request, nMode, entry.getPlugin( ) ); } data.setContent( page.getContent( ) ); data.setName( page.getTitle( ) ); // set the page path. Done by addind the extra-path information to the pathLabel. String strXml = page.getXmlExtendedPathLabel( ); if ( strXml == null ) { data.setPagePath( PortalService.getXPagePathContent( page.getPathLabel( ), 0, request ) ); } else { data.setPagePath( PortalService.getXPagePathContent( page.getPathLabel( ), 0, strXml, request ) ); } } else { AppLogService.error( "The specified Xpage '" + strName + "' cannot be retrieved. Check installation of your Xpage application." ); SiteMessageService.setMessage( request, MESSAGE_ERROR_APP_BODY, SiteMessage.TYPE_ERROR ); } return PortalService.buildPageContent( data, nMode, request ); } /** * Gets Application entry by name * @param strName The application's name * @return The entry */ public static XPageApplicationEntry getApplicationEntry( String strName ) { return _mapApplications.get( strName ); } /** * Gets applications list * @return A collection of applications */ public static Collection<XPageApplicationEntry> getXPageApplicationsList( ) { return _mapApplications.values( ); } /** * Return an instance of the XPage attached to the current Http Session * @param request The HTTP request * @param entry The XPage entry * @return The XPage instance */ private static XPageApplication getXPageSessionInstance( HttpServletRequest request , XPageApplicationEntry entry ) { HttpSession session = request.getSession( true ); String strAttribute = ATTRIBUTE_XPAGE + entry.getId(); XPageApplication application = (XPageApplication) session.getAttribute( strAttribute ); if( application == null ) { application = getApplicationInstance( entry ); session.setAttribute( strAttribute, application ); AppLogService.debug( "New XPage instance of " + entry.getClassName() + " created and attached to session " + session ); } return application; } /** * Get an XPage instance * @param entry The Xpage entry * @return An instance of a given XPage */ public static XPageApplication getApplicationInstance( XPageApplicationEntry entry ) { XPageApplication application = null; try { application = (XPageApplication) Class.forName( entry.getClassName( ) ).newInstance( ); } catch ( Exception e ) { throw new AppException( "Error instantiating XPageApplication : " + entry.getId( ) + " - " + e.getCause( ), e ); } return application; } }
src/java/fr/paris/lutece/portal/service/content/XPageAppService.java
/* * Copyright (c) 2002-2013, Mairie de Paris * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * License 1.0 */ package fr.paris.lutece.portal.service.content; import fr.paris.lutece.portal.service.init.LuteceInitException; import fr.paris.lutece.portal.service.message.SiteMessage; import fr.paris.lutece.portal.service.message.SiteMessageException; import fr.paris.lutece.portal.service.message.SiteMessageService; import fr.paris.lutece.portal.service.portal.PortalService; import fr.paris.lutece.portal.service.security.LuteceUser; import fr.paris.lutece.portal.service.security.SecurityService; import fr.paris.lutece.portal.service.security.UserNotSignedException; import fr.paris.lutece.portal.service.template.AppTemplateService; import fr.paris.lutece.portal.service.util.AppLogService; import fr.paris.lutece.portal.web.xpages.XPage; import fr.paris.lutece.portal.web.xpages.XPageApplication; import fr.paris.lutece.portal.web.xpages.XPageApplicationEntry; import fr.paris.lutece.util.html.HtmlTemplate; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; /** * This class delivers Extra pages (xpages) to web components. An XPage is a page where the content is provided by a * specific class, but should be integrated into the portal struture and design. XPageApps are identified by a key * name. To display an XPage into the portal just call the following url :<br><code> * Portal.jsp?page=<i>keyname</i>&amp;param1=value1&amp; ...&amp;paramN=valueN </code> * * @see fr.paris.lutece.portal.web.xpages.XPage */ public class XPageAppService extends ContentService { public static final String PARAM_XPAGE_APP = "page"; private static final String CONTENT_SERVICE_NAME = "XPageAppService"; private static final String MESSAGE_ERROR_APP_BODY = "portal.util.message.errorXpageApp"; private static Map<String, XPageApplicationEntry> _mapApplications = new HashMap<String, XPageApplicationEntry>( ); /** * Register an application by its entry defined in the plugin xml file * @param entry The application entry * @throws LuteceInitException If an error occured */ public static void registerXPageApplication( XPageApplicationEntry entry ) throws LuteceInitException { try { XPageApplication application = (XPageApplication) Class.forName( entry.getClassName( ) ).newInstance( ); entry.setApplication( application ); _mapApplications.put( entry.getId( ), entry ); AppLogService.info( "New XPage application registered : " + entry.getId( ) ); } catch ( ClassNotFoundException e ) { throw new LuteceInitException( "Error instantiating XPageApplication : " + entry.getId( ) + " - " + e.getCause( ), e ); } catch ( InstantiationException e ) { throw new LuteceInitException( "Error instantiating XPageApplication : " + entry.getId( ) + " - " + e.getCause( ), e ); } catch ( IllegalAccessException e ) { throw new LuteceInitException( "Error instantiating XPageApplication : " + entry.getId( ) + " - " + e.getCause( ), e ); } } /** * Returns the Content Service name * * @return The name as a String */ @Override public String getName( ) { return CONTENT_SERVICE_NAME; } /** * Analyzes request parameters to see if the request should be handled by the current Content Service * * @param request The HTTP request * @return true if this ContentService should handle this request */ @Override public boolean isInvoked( HttpServletRequest request ) { String strXPage = request.getParameter( PARAM_XPAGE_APP ); if ( ( strXPage != null ) && ( strXPage.length( ) > 0 ) ) { return true; } return false; } /** * Enable or disable the cache feature. * * @param bCache true to enable the cache, false to disable */ public void setCache( boolean bCache ) { } /** * Gets the current cache status. * * @return true if enable, otherwise false */ @Override public boolean isCacheEnable( ) { return false; } /** * Reset the cache. */ @Override public void resetCache( ) { } /** * Gets the number of item currently in the cache. * * @return the number of item currently in the cache. */ @Override public int getCacheSize( ) { return 0; } /** * Build the XPage content. * * @param request The HTTP request. * @param nMode The current mode. * @return The HTML code of the page. * @throws UserNotSignedException The User Not Signed Exception * @throws SiteMessageException occurs when a site message need to be displayed */ @Override public String getPage( HttpServletRequest request, int nMode ) throws UserNotSignedException, SiteMessageException { // Gets XPage info from the lutece.properties String strName = request.getParameter( PARAM_XPAGE_APP ); PageData data = new PageData( ); XPageApplicationEntry entry = getApplicationEntry( strName ); // TODO : Handle entry == null if ( ( entry != null ) && ( entry.isEnable( ) ) ) { XPage page = null; List<String> listRoles = entry.getRoles( ); if ( SecurityService.isAuthenticationEnable( ) && ( listRoles.size( ) > 0 ) ) { LuteceUser user = SecurityService.getInstance( ).getRegisteredUser( request ); if ( user != null ) { boolean bAutorized = false; for ( String strRole : listRoles ) { if ( SecurityService.getInstance( ).isUserInRole( request, strRole ) ) { bAutorized = true; } } if ( bAutorized ) { XPageApplication application = entry.getApplication( ); page = application.getPage( request, nMode, entry.getPlugin( ) ); } else { // The user doesn't have the correct role String strAccessDeniedTemplate = SecurityService.getInstance( ).getAccessDeniedTemplate( ); HtmlTemplate tAccessDenied = AppTemplateService.getTemplate( strAccessDeniedTemplate ); page = new XPage( ); page.setContent( tAccessDenied.getHtml( ) ); } } else { throw new UserNotSignedException( ); } } else { XPageApplication application = entry.getApplication( ); page = application.getPage( request, nMode, entry.getPlugin( ) ); } data.setContent( page.getContent( ) ); data.setName( page.getTitle( ) ); // set the page path. Done by addind the extra-path information to the pathLabel. String strXml = page.getXmlExtendedPathLabel( ); if ( strXml == null ) { data.setPagePath( PortalService.getXPagePathContent( page.getPathLabel( ), 0, request ) ); } else { data.setPagePath( PortalService.getXPagePathContent( page.getPathLabel( ), 0, strXml, request ) ); } } else { AppLogService.error( "The specified Xpage '" + strName + "' cannot be retrieved. Check installation of your Xpage application." ); SiteMessageService.setMessage( request, MESSAGE_ERROR_APP_BODY, SiteMessage.TYPE_ERROR ); } return PortalService.buildPageContent( data, nMode, request ); } /** * Gets Application entry by name * @param strName The application's name * @return The entry */ public static XPageApplicationEntry getApplicationEntry( String strName ) { return _mapApplications.get( strName ); } /** * Gets applications list * @return A collection of applications */ public static Collection<XPageApplicationEntry> getXPageApplicationsList( ) { return _mapApplications.values( ); } }
LUTECE-1627 : XPage objects are now instanciated for each HttpSession git-svn-id: 890dd67775b5971c21efd90062c158582082fe1b@50775 bab10101-e421-0410-a517-8ce0973de3ef
src/java/fr/paris/lutece/portal/service/content/XPageAppService.java
LUTECE-1627 : XPage objects are now instanciated for each HttpSession
<ide><path>rc/java/fr/paris/lutece/portal/service/content/XPageAppService.java <ide> import fr.paris.lutece.portal.service.security.SecurityService; <ide> import fr.paris.lutece.portal.service.security.UserNotSignedException; <ide> import fr.paris.lutece.portal.service.template.AppTemplateService; <add>import fr.paris.lutece.portal.service.util.AppException; <ide> import fr.paris.lutece.portal.service.util.AppLogService; <ide> import fr.paris.lutece.portal.web.xpages.XPage; <ide> import fr.paris.lutece.portal.web.xpages.XPageApplication; <ide> import java.util.Map; <ide> <ide> import javax.servlet.http.HttpServletRequest; <add>import javax.servlet.http.HttpSession; <ide> <ide> <ide> /** <ide> public static final String PARAM_XPAGE_APP = "page"; <ide> private static final String CONTENT_SERVICE_NAME = "XPageAppService"; <ide> private static final String MESSAGE_ERROR_APP_BODY = "portal.util.message.errorXpageApp"; <add> private static final String ATTRIBUTE_XPAGE = "LUTECE_XPAGE_"; <add> <ide> private static Map<String, XPageApplicationEntry> _mapApplications = new HashMap<String, XPageApplicationEntry>( ); <ide> <ide> /** <ide> <ide> if ( bAutorized ) <ide> { <del> XPageApplication application = entry.getApplication( ); <add> XPageApplication application = getXPageSessionInstance( request , entry ); <ide> page = application.getPage( request, nMode, entry.getPlugin( ) ); <ide> } <ide> else <ide> } <ide> else <ide> { <del> XPageApplication application = entry.getApplication( ); <add> XPageApplication application = getXPageSessionInstance( request , entry ); <ide> page = application.getPage( request, nMode, entry.getPlugin( ) ); <ide> } <ide> <ide> { <ide> return _mapApplications.values( ); <ide> } <add> <add> /** <add> * Return an instance of the XPage attached to the current Http Session <add> * @param request The HTTP request <add> * @param entry The XPage entry <add> * @return The XPage instance <add> */ <add> private static XPageApplication getXPageSessionInstance( HttpServletRequest request , XPageApplicationEntry entry ) <add> { <add> HttpSession session = request.getSession( true ); <add> String strAttribute = ATTRIBUTE_XPAGE + entry.getId(); <add> XPageApplication application = (XPageApplication) session.getAttribute( strAttribute ); <add> if( application == null ) <add> { <add> application = getApplicationInstance( entry ); <add> session.setAttribute( strAttribute, application ); <add> AppLogService.debug( "New XPage instance of " + entry.getClassName() + " created and attached to session " + session ); <add> } <add> return application; <add> } <add> <add> /** <add> * Get an XPage instance <add> * @param entry The Xpage entry <add> * @return An instance of a given XPage <add> */ <add> public static XPageApplication getApplicationInstance( XPageApplicationEntry entry ) <add> { <add> XPageApplication application = null; <add> try <add> { <add> application = (XPageApplication) Class.forName( entry.getClassName( ) ).newInstance( ); <add> } <add> catch ( Exception e ) <add> { <add> throw new AppException( "Error instantiating XPageApplication : " + entry.getId( ) + " - " + <add> e.getCause( ), e ); <add> } <add> return application; <add> } <add> <ide> }
Java
apache-2.0
9bdae5379ad37ea10dbbb649612d771ce0f45198
0
chunlinyao/fop,apache/fop,apache/fop,chunlinyao/fop,chunlinyao/fop,apache/fop,apache/fop,apache/fop,chunlinyao/fop,chunlinyao/fop
/* * $Id$ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved. * For details on use and redistribution please refer to the * LICENSE file included with these sources. */ package org.apache.fop.image; // Java import java.io.IOException; import java.io.InputStream; import java.io.File; import java.net.URL; import java.net.MalformedURLException; import java.lang.reflect.Constructor; import java.util.Hashtable; // FOP import org.apache.fop.image.analyser.ImageReaderFactory; import org.apache.fop.image.analyser.ImageReader; import org.apache.fop.configuration.Configuration; /** * create FopImage objects (with a configuration file - not yet implemented). * @author Eric SCHAEFFER */ public class FopImageFactory { private static Hashtable m_urlMap = new Hashtable(); /** * create an FopImage objects. * @param href image URL as a String * @return a new FopImage object * @exception java.net.MalformedURLException bad URL * @exception FopImageException an error occured during construction */ public static FopImage Make(String href) throws MalformedURLException, FopImageException { /* * According to section 5.11 a <uri-specification> is: * "url(" + URI + ")" * according to 7.28.7 a <uri-specification> is: * URI * So handle both. */ // Get the absolute URL URL absoluteURL = null; InputStream imgIS = null; href = href.trim(); if(href.startsWith("url(") && (href.indexOf(")") != -1)) { href = href.substring(4, href.indexOf(")")).trim(); if(href.startsWith("'") && href.endsWith("'")) { href = href.substring(1, href.length() - 1); } else if(href.startsWith("\"") && href.endsWith("\"")) { href = href.substring(1, href.length() - 1); } } try { // try url as complete first, this can cause // a problem with relative uri's if there is an // image relative to where fop is run and relative // to the base dir of the document try { absoluteURL = new URL(href); } catch (MalformedURLException mue) { // if the href contains onl a path then file is assumed absoluteURL = new URL("file:" + href); } imgIS = absoluteURL.openStream(); } catch (MalformedURLException e_context) { throw new FopImageException("Error with image URL: " + e_context.getMessage()); } catch (Exception e) { // maybe relative URL context_url = null; String base = Configuration.getStringValue("baseDir"); if(base == null) { throw new FopImageException("Error with image URL: " + e.getMessage() + " and no base directory is specified"); } try { absoluteURL = new URL(Configuration.getStringValue("baseDir") + absoluteURL.getFile()); } catch (MalformedURLException e_context) { // pb context url throw new FopImageException("Invalid Image URL - error on relative URL : " + e_context.getMessage()); } } // check if already created FopImage imageObject = (FopImage)m_urlMap.get(absoluteURL.toString()); if (imageObject != null) return imageObject; // If not, check image type ImageReader imgReader = null; try { if (imgIS == null) { imgIS = absoluteURL.openStream(); } imgReader = ImageReaderFactory.Make(absoluteURL.toExternalForm(), imgIS); } catch (Exception e) { throw new FopImageException("Error while recovering Image Informations (" + absoluteURL.toString() + ") : " + e.getMessage()); } finally { if (imgIS != null) { try { imgIS.close(); } catch (IOException e) {} } } if (imgReader == null) throw new FopImageException("No ImageReader for this type of image (" + absoluteURL.toString() + ")"); // Associate mime-type to FopImage class String imgMimeType = imgReader.getMimeType(); String imgClassName = null; if ("image/gif".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.GifImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/jpeg".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.JpegImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/bmp".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.BmpImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/png".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.JimiImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/tga".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.JimiImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/tiff".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.JimiImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/svg+xml".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.SVGImage"; } if (imgClassName == null) throw new FopImageException("Unsupported image type (" + absoluteURL.toString() + ") : " + imgMimeType); // load the right image class // return new <FopImage implementing class> Object imageInstance = null; Class imageClass = null; try { imageClass = Class.forName(imgClassName); Class[] imageConstructorParameters = new Class[2]; imageConstructorParameters[0] = Class.forName("java.net.URL"); imageConstructorParameters[1] = Class.forName("org.apache.fop.image.analyser.ImageReader"); Constructor imageConstructor = imageClass.getDeclaredConstructor(imageConstructorParameters); Object[] initArgs = new Object[2]; initArgs[0] = absoluteURL; initArgs[1] = imgReader; imageInstance = imageConstructor.newInstance(initArgs); } catch (java.lang.reflect.InvocationTargetException ex) { Throwable t = ex.getTargetException(); String msg; if (t != null) { msg = t.getMessage(); } else { msg = ex.getMessage(); } throw new FopImageException("Error creating FopImage object (" + absoluteURL.toString() + ") : " + msg); } catch (Exception ex) { throw new FopImageException("Error creating FopImage object (" + "Error creating FopImage object (" + absoluteURL.toString() + ") : " + ex.getMessage()); } if (!(imageInstance instanceof org.apache.fop.image.FopImage)) { throw new FopImageException("Error creating FopImage object (" + absoluteURL.toString() + ") : " + "class " + imageClass.getName() + " doesn't implement org.apache.fop.image.FopImage interface"); } m_urlMap.put(absoluteURL.toString(), imageInstance); return (FopImage)imageInstance; } }
src/org/apache/fop/image/FopImageFactory.java
/* * $Id$ * Copyright (C) 2001 The Apache Software Foundation. All rights reserved. * For details on use and redistribution please refer to the * LICENSE file included with these sources. */ package org.apache.fop.image; // Java import java.io.IOException; import java.io.InputStream; import java.io.File; import java.net.URL; import java.net.MalformedURLException; import java.lang.reflect.Constructor; import java.util.Hashtable; // FOP import org.apache.fop.image.analyser.ImageReaderFactory; import org.apache.fop.image.analyser.ImageReader; import org.apache.fop.configuration.Configuration; /** * create FopImage objects (with a configuration file - not yet implemented). * @author Eric SCHAEFFER */ public class FopImageFactory { private static Hashtable m_urlMap = new Hashtable(); /** * create an FopImage objects. * @param href image URL as a String * @return a new FopImage object * @exception java.net.MalformedURLException bad URL * @exception FopImageException an error occured during construction */ public static FopImage Make(String href) throws MalformedURLException, FopImageException { /* * According to section 5.11 a <uri-specification> is: * "url(" + URI + ")" * according to 7.28.7 a <uri-specification> is: * URI * So handle both. */ // Get the absolute URL URL absoluteURL = null; InputStream imgIS = null; href = href.trim(); if(href.startsWith("url(") && (href.indexOf(")") != -1)) { href = href.substring(4, href.indexOf(")")).trim(); if(href.startsWith("'") && href.endsWith("'")) { href = href.substring(1, href.length() - 1); } else if(href.startsWith("\"") && href.endsWith("\"")) { href = href.substring(1, href.length() - 1); } } try { // try url as complete first, this can cause // a problem with relative uri's if there is an // image relative to where fop is run and relative // to the base dir of the document try { absoluteURL = new URL(href); } catch (MalformedURLException mue) { // if the href contains onl a path then file is assumed absoluteURL = new URL("file:" + href); } imgIS = absoluteURL.openStream(); } catch (MalformedURLException e_context) { throw new FopImageException("Error with image URL: " + e_context.getMessage()); } catch (Exception e) { // maybe relative URL context_url = null; try { absoluteURL = new URL(Configuration.getStringValue("baseDir") + absoluteURL.getFile()); } catch (MalformedURLException e_context) { // pb context url throw new FopImageException("Invalid Image URL - error on relative URL : " + e_context.getMessage()); } } // check if already created FopImage imageObject = (FopImage)m_urlMap.get(absoluteURL.toString()); if (imageObject != null) return imageObject; // If not, check image type ImageReader imgReader = null; try { if (imgIS == null) { imgIS = absoluteURL.openStream(); } imgReader = ImageReaderFactory.Make(absoluteURL.toExternalForm(), imgIS); } catch (Exception e) { throw new FopImageException("Error while recovering Image Informations (" + absoluteURL.toString() + ") : " + e.getMessage()); } finally { if (imgIS != null) { try { imgIS.close(); } catch (IOException e) {} } } if (imgReader == null) throw new FopImageException("No ImageReader for this type of image (" + absoluteURL.toString() + ")"); // Associate mime-type to FopImage class String imgMimeType = imgReader.getMimeType(); String imgClassName = null; if ("image/gif".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.GifImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/jpeg".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.JpegImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/bmp".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.BmpImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/png".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.JimiImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/tga".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.JimiImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/tiff".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.JimiImage"; // imgClassName = "org.apache.fop.image.JAIImage"; } else if ("image/svg+xml".equals(imgMimeType)) { imgClassName = "org.apache.fop.image.SVGImage"; } if (imgClassName == null) throw new FopImageException("Unsupported image type (" + absoluteURL.toString() + ") : " + imgMimeType); // load the right image class // return new <FopImage implementing class> Object imageInstance = null; Class imageClass = null; try { imageClass = Class.forName(imgClassName); Class[] imageConstructorParameters = new Class[2]; imageConstructorParameters[0] = Class.forName("java.net.URL"); imageConstructorParameters[1] = Class.forName("org.apache.fop.image.analyser.ImageReader"); Constructor imageConstructor = imageClass.getDeclaredConstructor(imageConstructorParameters); Object[] initArgs = new Object[2]; initArgs[0] = absoluteURL; initArgs[1] = imgReader; imageInstance = imageConstructor.newInstance(initArgs); } catch (java.lang.reflect.InvocationTargetException ex) { Throwable t = ex.getTargetException(); String msg; if (t != null) { msg = t.getMessage(); } else { msg = ex.getMessage(); } throw new FopImageException("Error creating FopImage object (" + absoluteURL.toString() + ") : " + msg); } catch (Exception ex) { throw new FopImageException("Error creating FopImage object (" + "Error creating FopImage object (" + absoluteURL.toString() + ") : " + ex.getMessage()); } if (!(imageInstance instanceof org.apache.fop.image.FopImage)) { throw new FopImageException("Error creating FopImage object (" + absoluteURL.toString() + ") : " + "class " + imageClass.getName() + " doesn't implement org.apache.fop.image.FopImage interface"); } m_urlMap.put(absoluteURL.toString(), imageInstance); return (FopImage)imageInstance; } }
throws a different error if base dir not specified git-svn-id: 102839466c3b40dd9c7e25c0a1a6d26afc40150a@194497 13f79535-47bb-0310-9956-ffa450edef68
src/org/apache/fop/image/FopImageFactory.java
throws a different error if base dir not specified
<ide><path>rc/org/apache/fop/image/FopImageFactory.java <ide> } catch (Exception e) { <ide> // maybe relative <ide> URL context_url = null; <add> String base = Configuration.getStringValue("baseDir"); <add> if(base == null) { <add> throw new FopImageException("Error with image URL: " <add> + e.getMessage() <add> + " and no base directory is specified"); <add> } <ide> try { <ide> absoluteURL = new URL(Configuration.getStringValue("baseDir") <ide> + absoluteURL.getFile());
JavaScript
mit
cd422c93393e7ea96457fbfe8d3d18129f65969f
0
watzak/gulp-babel-react-starter-kit,watzak/gulp-babel-react-starter-kit
var gulp = require('gulp'); var browserify = require('browserify'); var babelify = require('babelify'); var source = require('vinyl-source-stream'); var browserSync = require('browser-sync'); var concatCss = require('gulp-concat-css'); gulp.task('build', function () { browserify({ entries: './src/js/index.jsx', extensions: ['.jsx'], debug: true }) .transform(babelify) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./dist')) .pipe(browserSync.reload({stream:true})); }); gulp.task('copyCSS', function () { return gulp.src('./src/styles/*.css') .pipe(concatCss("bundle.css")) .pipe(gulp.dest('./dist')) .pipe(browserSync.reload({stream:true})); }); gulp.task('copyIndex', function () { gulp.src('./src/index.html') .pipe(gulp.dest('./dist')) .pipe(browserSync.reload({stream:true})); }); gulp.task('browserSync', function () { browserSync({ server: { baseDir: './dist' } }); }); gulp.task('watchFiles', function () { gulp.watch('./src/js/**/*.jsx', []); gulp.watch('./src/styles/*.css', []); gulp.watch('./src/index.html', []); }); gulp.task('default', ['build','copyIndex','copyCSS','browserSync','watchFiles']);
Gulpfile.js
var gulp = require('gulp'); var browserify = require('browserify'); var babelify = require('babelify'); var source = require('vinyl-source-stream'); var browserSync = require('browser-sync'); var concatCss = require('gulp-concat-css'); gulp.task('build', function () { browserify({ entries: './src/js/index.jsx', extensions: ['.jsx'], debug: true }) .transform(babelify) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./dist')) .pipe(browserSync.reload({stream:true})); }); gulp.task('copyCSS', function () { return gulp.src('./src/styles/*.css') .pipe(concatCss("bundle.css")) .pipe(gulp.dest('./dist')) .pipe(browserSync.reload({stream:true})); }); gulp.task('copyIndex', function () { gulp.src('./src/index.html') .pipe(gulp.dest('./dist')) .pipe(browserSync.reload({stream:true})); }); gulp.task('browserSync', function () { browserSync({ server: { baseDir: './dist' } }); }); gulp.task('watchFiles', function () { gulp.watch('./src/js/**/*.jsx', []); gulp.watch('./src/styles/*.css', []); gulp.watch('./src/js/index.jsx', []); }); gulp.task('default', ['build','copyIndex','copyCSS','browserSync','watchFiles']);
bug fixed with watching files
Gulpfile.js
bug fixed with watching files
<ide><path>ulpfile.js <ide> gulp.task('watchFiles', function () { <ide> gulp.watch('./src/js/**/*.jsx', []); <ide> gulp.watch('./src/styles/*.css', []); <del> gulp.watch('./src/js/index.jsx', []); <add> gulp.watch('./src/index.html', []); <ide> }); <ide> <ide> gulp.task('default', ['build','copyIndex','copyCSS','browserSync','watchFiles']);
JavaScript
apache-2.0
b4b6dd02235e95ea9716d4406c57316eae3950e8
0
naturalatlas/node-gdal,sbmelvin/node-gdal,infitude/node-gdal,Uli1/node-gdal,nbuchanan/node-gdal,infitude/node-gdal,not001praween001/node-gdal,not001praween001/node-gdal,jdesboeufs/node-gdal,nbuchanan/node-gdal,Uli1/node-gdal,Uli1/node-gdal,nbuchanan/node-gdal,sbmelvin/node-gdal,nbuchanan/node-gdal,Uli1/node-gdal,jwoyame/node-gdal,jwoyame/node-gdal,naturalatlas/node-gdal,infitude/node-gdal,naturalatlas/node-gdal,jdesboeufs/node-gdal,jdesboeufs/node-gdal,sbmelvin/node-gdal,jdesboeufs/node-gdal,jwoyame/node-gdal,jwoyame/node-gdal,infitude/node-gdal,not001praween001/node-gdal,not001praween001/node-gdal,naturalatlas/node-gdal,sbmelvin/node-gdal
'use strict' var gdal = require('../lib/gdal.js'); var path = require('path'); var assert = require('chai').assert; if (process.env.TARGET !== 'SHARED') { describe('Open', function() { describe('BIGTIFF', function() { var filename, ds; it('should not throw', function() { filename = path.join(__dirname,"data/sample_bigtiff.tif"); ds = gdal.open(filename); }); it('should be able to read raster size', function() { assert.equal(ds.rasterSize.x,100000); assert.equal(ds.rasterSize.y,100000); assert.equal(ds.bands.count(),1); }); }); }); };
test/open_bigtiff.test.js
'use strict' var gdal = require('../lib/gdal.js'); var path = require('path'); var assert = require('chai').assert; describe('Open', function() { describe('BIGTIFF', function() { var filename, ds; it('should not throw', function() { filename = path.join(__dirname,"data/sample_bigtiff.tif"); ds = gdal.open(filename); }); it('should be able to read raster size', function() { assert.equal(ds.rasterSize.x,100000); assert.equal(ds.rasterSize.y,100000); assert.equal(ds.bands.count(),1); }); }); });
add SHARED tag
test/open_bigtiff.test.js
add SHARED tag
<ide><path>est/open_bigtiff.test.js <ide> var path = require('path'); <ide> var assert = require('chai').assert; <ide> <del>describe('Open', function() { <del> <del> describe('BIGTIFF', function() { <del> var filename, ds; <add>if (process.env.TARGET !== 'SHARED') { <add> describe('Open', function() { <ide> <del> it('should not throw', function() { <del> filename = path.join(__dirname,"data/sample_bigtiff.tif"); <del> ds = gdal.open(filename); <del> }); <add> describe('BIGTIFF', function() { <add> var filename, ds; <ide> <del> it('should be able to read raster size', function() { <del> assert.equal(ds.rasterSize.x,100000); <del> assert.equal(ds.rasterSize.y,100000); <del> assert.equal(ds.bands.count(),1); <add> it('should not throw', function() { <add> filename = path.join(__dirname,"data/sample_bigtiff.tif"); <add> ds = gdal.open(filename); <add> }); <add> <add> it('should be able to read raster size', function() { <add> assert.equal(ds.rasterSize.x,100000); <add> assert.equal(ds.rasterSize.y,100000); <add> assert.equal(ds.bands.count(),1); <add> }); <ide> }); <ide> }); <del>}); <add>};
Java
bsd-3-clause
005810a2db7afa51c21167501611edec81235fd2
0
goreycn/FileTemplatesVariable,vkravets/FileTemplatesVariable
package org.jetbrains.idea.project.filetemplate; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.impl.DefaultProject; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.Pair; import com.intellij.util.text.UniqueNameGenerator; import org.jdom.Attribute; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Created by IntelliJ IDEA. * Author: Vladimir Kravets * E-Mail: [email protected] * Date: 2/14/14 * Time: 5:35 PM */ @State(name = "ProjectTemplateVariables", storages = { @Storage(file = StoragePathMacros.PROJECT_FILE), @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/template/", scheme = StorageScheme.DIRECTORY_BASED, stateSplitter = PerProjectTemplateManager.ProjectTemplateStateSplitter.class) } ) public class PerProjectTemplateManager extends AbstractProjectComponent implements PersistentStateComponent<Element> { private Properties projectVariables; protected PerProjectTemplateManager(Project project) { super(project); projectVariables = new Properties(); } private static final String VARIABLE_TAG = "variable"; private static final String VARIABLE_NAME_ATTR = "name"; private static final String TEMPLATE_VARIABLES = "templateVariables"; @Nullable @Override public Element getState() { Element root = new Element(TEMPLATE_VARIABLES); for (String name : projectVariables.stringPropertyNames()) { Element variable = new Element(VARIABLE_TAG); variable.setAttribute(VARIABLE_NAME_ATTR, name); variable.addContent(projectVariables.getProperty(name)); root.addContent(variable); } return root; } @Override public void loadState(Element element) { projectVariables.clear(); List<Element> elements = JDOMUtil.getChildren(element, TEMPLATE_VARIABLES); if (elements.size() > 0) { updateVariablesFromElement(elements.get(0)); } else { // Workaround for DefaultProject storage behavior // it's save information without root element, in our case without TEMPLATE_VARIABLES tag updateVariablesFromElement(element); } } private void updateVariablesFromElement(Element element) { List<Element> elements = JDOMUtil.getChildren(element, VARIABLE_TAG); for (Element variable : elements) { Attribute attribute = variable.getAttribute(VARIABLE_NAME_ATTR); if (attribute != null && attribute.getValue() != null) { projectVariables.put(attribute.getValue(), variable.getValue()); } } } public static class ProjectTemplateStateSplitter implements StateSplitter{ public ProjectTemplateStateSplitter() { } @Override public List<Pair<Element, String>> splitState(Element e) { final UniqueNameGenerator generator = new UniqueNameGenerator(); final List<Pair<Element, String>> result = new ArrayList<Pair<Element, String>>(); result.add(new Pair<Element, String>(e, generator.generateUniqueName("template_variable_settings") + ".xml")); return result; } @Override public void mergeStatesInto(Element target, Element[] elements) { for (Element element : elements) { if (element.getName().equals(TEMPLATE_VARIABLES)) { element.detach(); Element child = target.getChild(TEMPLATE_VARIABLES); if (child == null) { child = new Element(TEMPLATE_VARIABLES); target.addContent(child); } Element[] variables = JDOMUtil.getElements(element); for (Element variable : variables) { variable.detach(); child.addContent(variable); } } else { final Element[] states = JDOMUtil.getElements(element); for (Element state : states) { state.detach(); target.addContent(state); } for (Object attr : element.getAttributes()) { target.setAttribute(((Attribute)attr).clone()); } } } } } public static PerProjectTemplateManager getInstance(Project project) { return project.getComponent(PerProjectTemplateManager.class); } public Properties getProjectVariables() { return projectVariables; } }
src/org/jetbrains/idea/project/filetemplate/PerProjectTemplateManager.java
package org.jetbrains.idea.project.filetemplate; import com.intellij.openapi.components.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.Pair; import com.intellij.util.text.UniqueNameGenerator; import org.jdom.Attribute; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Created by IntelliJ IDEA. * Author: Vladimir Kravets * E-Mail: [email protected] * Date: 2/14/14 * Time: 5:35 PM */ @State(name = "ProjectTemplateVariables", storages = { @Storage(file = StoragePathMacros.PROJECT_FILE), @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/template/", scheme = StorageScheme.DIRECTORY_BASED, stateSplitter = PerProjectTemplateManager.ProjectTemplateStateSplitter.class) } ) public class PerProjectTemplateManager extends AbstractProjectComponent implements PersistentStateComponent<Element> { private Properties projectVariables; protected PerProjectTemplateManager(Project project) { super(project); projectVariables = new Properties(); } private static final String VARIABLE_TAG = "variable"; private static final String VARIABLE_NAME_ATTR = "name"; private static final String TEMPLATE_VARIABLES = "templateVariables"; @Nullable @Override public Element getState() { Element root = new Element(TEMPLATE_VARIABLES); for (String name : projectVariables.stringPropertyNames()) { Element variable = new Element(VARIABLE_TAG); variable.setAttribute(VARIABLE_NAME_ATTR, name); variable.addContent(projectVariables.getProperty(name)); root.addContent(variable); } return root; } @Override public void loadState(Element element) { projectVariables.clear(); List<Element> elements = JDOMUtil.getChildren(element, TEMPLATE_VARIABLES); if (elements.size() > 0) { elements = JDOMUtil.getChildren(elements.get(0), VARIABLE_TAG); for (Element variable : elements) { Attribute attribute = variable.getAttribute(VARIABLE_NAME_ATTR); if (attribute != null && attribute.getValue() != null) { projectVariables.put(attribute.getValue(), variable.getValue()); } } } } public static class ProjectTemplateStateSplitter implements StateSplitter{ public ProjectTemplateStateSplitter() { } @Override public List<Pair<Element, String>> splitState(Element e) { final UniqueNameGenerator generator = new UniqueNameGenerator(); final List<Pair<Element, String>> result = new ArrayList<Pair<Element, String>>(); result.add(new Pair<Element, String>(e, generator.generateUniqueName("template_variable_settings") + ".xml")); return result; } @Override public void mergeStatesInto(Element target, Element[] elements) { for (Element element : elements) { if (element.getName().equals(TEMPLATE_VARIABLES)) { element.detach(); Element child = target.getChild(TEMPLATE_VARIABLES); if (child == null) { child = new Element(TEMPLATE_VARIABLES); target.addContent(child); } Element[] variables = JDOMUtil.getElements(element); for (Element variable : variables) { variable.detach(); child.addContent(variable); } } else { final Element[] states = JDOMUtil.getElements(element); for (Element state : states) { state.detach(); target.addContent(state); } for (Object attr : element.getAttributes()) { target.setAttribute(((Attribute)attr).clone()); } } } } } public static PerProjectTemplateManager getInstance(Project project) { return project.getComponent(PerProjectTemplateManager.class); } public Properties getProjectVariables() { return projectVariables; } }
Fix issue #1 with loading Default Project settings again
src/org/jetbrains/idea/project/filetemplate/PerProjectTemplateManager.java
Fix issue #1 with loading Default Project settings again
<ide><path>rc/org/jetbrains/idea/project/filetemplate/PerProjectTemplateManager.java <ide> <ide> import com.intellij.openapi.components.*; <ide> import com.intellij.openapi.project.Project; <add>import com.intellij.openapi.project.impl.DefaultProject; <ide> import com.intellij.openapi.util.JDOMUtil; <ide> import com.intellij.openapi.util.Pair; <ide> import com.intellij.util.text.UniqueNameGenerator; <ide> projectVariables.clear(); <ide> List<Element> elements = JDOMUtil.getChildren(element, TEMPLATE_VARIABLES); <ide> if (elements.size() > 0) { <del> elements = JDOMUtil.getChildren(elements.get(0), VARIABLE_TAG); <del> for (Element variable : elements) { <del> Attribute attribute = variable.getAttribute(VARIABLE_NAME_ATTR); <del> if (attribute != null && attribute.getValue() != null) { <del> projectVariables.put(attribute.getValue(), variable.getValue()); <del> } <add> updateVariablesFromElement(elements.get(0)); <add> } else { <add> // Workaround for DefaultProject storage behavior <add> // it's save information without root element, in our case without TEMPLATE_VARIABLES tag <add> updateVariablesFromElement(element); <add> } <add> } <add> <add> private void updateVariablesFromElement(Element element) { <add> List<Element> elements = JDOMUtil.getChildren(element, VARIABLE_TAG); <add> for (Element variable : elements) { <add> Attribute attribute = variable.getAttribute(VARIABLE_NAME_ATTR); <add> if (attribute != null && attribute.getValue() != null) { <add> projectVariables.put(attribute.getValue(), variable.getValue()); <ide> } <ide> } <ide> }
Java
apache-2.0
891d0af4c8de9ae3640c9d4f873fd14597e52f94
0
daradurvs/ignite,chandresh-pancholi/ignite,apache/ignite,samaitra/ignite,nizhikov/ignite,ascherbakoff/ignite,daradurvs/ignite,daradurvs/ignite,ascherbakoff/ignite,apache/ignite,NSAmelchev/ignite,samaitra/ignite,ascherbakoff/ignite,nizhikov/ignite,chandresh-pancholi/ignite,daradurvs/ignite,SomeFire/ignite,samaitra/ignite,xtern/ignite,xtern/ignite,chandresh-pancholi/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,SomeFire/ignite,chandresh-pancholi/ignite,daradurvs/ignite,xtern/ignite,SomeFire/ignite,SomeFire/ignite,NSAmelchev/ignite,SomeFire/ignite,SomeFire/ignite,apache/ignite,nizhikov/ignite,xtern/ignite,apache/ignite,daradurvs/ignite,xtern/ignite,samaitra/ignite,samaitra/ignite,chandresh-pancholi/ignite,samaitra/ignite,SomeFire/ignite,nizhikov/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,ascherbakoff/ignite,nizhikov/ignite,nizhikov/ignite,nizhikov/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,xtern/ignite,chandresh-pancholi/ignite,ascherbakoff/ignite,daradurvs/ignite,samaitra/ignite,apache/ignite,SomeFire/ignite,SomeFire/ignite,ascherbakoff/ignite,samaitra/ignite,apache/ignite,apache/ignite,daradurvs/ignite,NSAmelchev/ignite,xtern/ignite,NSAmelchev/ignite,samaitra/ignite,daradurvs/ignite,apache/ignite,daradurvs/ignite,samaitra/ignite,nizhikov/ignite,NSAmelchev/ignite,xtern/ignite,ascherbakoff/ignite,SomeFire/ignite,NSAmelchev/ignite,NSAmelchev/ignite,apache/ignite,nizhikov/ignite,xtern/ignite
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ignite.compatibility.persistence; import java.io.File; import java.io.IOException; import java.nio.file.OpenOption; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgnitionEx; import org.apache.ignite.internal.processors.cache.GridCacheAbstractFullApiSelfTest; import org.apache.ignite.internal.processors.cache.persistence.CheckpointState; import org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager; import org.apache.ignite.internal.processors.cache.persistence.file.FileIO; import org.apache.ignite.internal.processors.cache.persistence.file.FileIODecorator; import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory; import org.apache.ignite.internal.processors.cache.persistence.file.RandomAccessFileIOFactory; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteInClosure; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.testframework.GridTestUtils; import org.jetbrains.annotations.Nullable; import org.junit.Test; /** * Tests migration of metastorage. */ public class MetaStorageCompatibilityTest extends IgnitePersistenceCompatibilityAbstractTest { /** Consistent id. */ private static final String CONSISTENT_ID_1 = "node1"; /** Consistent id. */ private static final String CONSISTENT_ID_2 = "node2"; /** Ignite version. */ private static final String IGNITE_VERSION = "2.4.0"; /** Filename of index. */ private static final String INDEX_BIN_FILE = "index.bin"; /** Filename of partition. */ private static final String PART_FILE = "part-0.bin"; /** * The zero partition hasn't full baseline information. The last changes are read from WAL. * * @throws Exception If failed. */ @Test public void testMigrationWithoutFullBaselineIntoPartition() throws Exception { try { U.delete(new File(U.defaultWorkDirectory())); startGrid(1, IGNITE_VERSION, new ConfigurationClosure(CONSISTENT_ID_1), new ActivateAndForceCheckpointClosure()); startGrid(2, IGNITE_VERSION, new ConfigurationClosure(CONSISTENT_ID_2), new NewBaselineTopologyClosure()); stopAllGrids(); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { // No-op. } } assertFalse(metastorageFileExists(INDEX_BIN_FILE)); assertFalse(metastorageFileExists(PART_FILE)); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { assertTrue(GridTestUtils.waitForCondition(() -> ig1.cluster().active(), 10_000)); } } } finally { stopAllGrids(); } } /** * Tests that BLT can be changed and persisted after metastorage migration. */ @Test public void testMigrationToNewBaselineSetNewBaselineAfterMigration() throws Exception { try { U.delete(new File(U.defaultWorkDirectory())); startGrid(1, IGNITE_VERSION, new ConfigurationClosure(CONSISTENT_ID_1), new ActivateAndStopClosure()); stopAllGrids(); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { ig0.cluster().setBaselineTopology(ig1.cluster().topologyVersion()); } } assertFalse(metastorageFileExists(INDEX_BIN_FILE)); assertFalse(metastorageFileExists(PART_FILE)); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { assertTrue(GridTestUtils.waitForCondition(() -> ig1.cluster().active(), 10_000)); } } } finally { stopAllGrids(); } } /** * */ @Test public void testMigrationWithExceptionDuringTheProcess() throws Exception { try { U.delete(new File(U.defaultWorkDirectory())); startGrid(1, IGNITE_VERSION, new ConfigurationClosure(CONSISTENT_ID_1), new ActivateAndStopClosure()); stopAllGrids(); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1, PART_FILE))) { ig0.getOrCreateCache("default-cache").put(1, 1); // trigger checkpoint on close() } assertTrue(metastorageFileExists(INDEX_BIN_FILE)); assertTrue(metastorageFileExists(PART_FILE)); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1, INDEX_BIN_FILE))) { ig0.getOrCreateCache("default-cache").put(1, 1); // trigger checkpoint on close() } assertTrue(metastorageFileExists(INDEX_BIN_FILE)); assertFalse(metastorageFileExists(PART_FILE)); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { ig0.cluster().setBaselineTopology(ig1.cluster().topologyVersion()); } } try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { assertTrue(GridTestUtils.waitForCondition(() -> ig1.cluster().active(), 10_000)); } } } finally { stopAllGrids(); } } /** * Checks that file exists. * * @param fileName File name. */ private boolean metastorageFileExists(String fileName) throws IgniteCheckedException { return new File(U.defaultWorkDirectory() + "/db/" + U.maskForFileName(CONSISTENT_ID_1) + "/metastorage/" + fileName).exists(); } /** * Updates the given ignite configuration. * * @param cfg Ignite configuration to be updated. * @param consistentId Consistent id. * @return Updated configuration. */ private static IgniteConfiguration prepareConfig(IgniteConfiguration cfg, @Nullable String consistentId) { return prepareConfig(cfg, consistentId, null); } /** * Updates the given ignite configuration. * * @param cfg Ignite configuration to be updated. * @param consistentId Consistent id. * @param failOnFileRmv Indicates that an exception should be trown when partition/index file is going to be removed. * @return Updated configuration. */ private static IgniteConfiguration prepareConfig( IgniteConfiguration cfg, @Nullable String consistentId, @Nullable String failOnFileRmv ) { cfg.setLocalHost("127.0.0.1"); TcpDiscoverySpi disco = new TcpDiscoverySpi(); disco.setIpFinder(GridCacheAbstractFullApiSelfTest.LOCAL_IP_FINDER); cfg.setDiscoverySpi(disco); cfg.setPeerClassLoadingEnabled(false); DataStorageConfiguration memCfg = new DataStorageConfiguration() .setDefaultDataRegionConfiguration( new DataRegionConfiguration() .setPersistenceEnabled(true) .setInitialSize(10L * 1024 * 1024) .setMaxSize(10L * 1024 * 1024)) .setPageSize(4096); cfg.setDataStorageConfiguration(memCfg); if (consistentId != null) { cfg.setIgniteInstanceName(consistentId); cfg.setConsistentId(consistentId); } if (failOnFileRmv != null) cfg.getDataStorageConfiguration().setFileIOFactory(new FailingFileIOFactory(failOnFileRmv)); return cfg; } /** */ private static class ConfigurationClosure implements IgniteInClosure<IgniteConfiguration> { /** Consistent id. */ private final String consistentId; /** * Creates a new instance of Configuration closure. * * @param consistentId Consistent id. */ public ConfigurationClosure(String consistentId) { this.consistentId = consistentId; } /** {@inheritDoc} */ @Override public void apply(IgniteConfiguration cfg) { prepareConfig(cfg, consistentId, null); } } /** * Post-startup close that activate the grid and force checkpoint. */ private static class ActivateAndForceCheckpointClosure implements IgniteInClosure<Ignite> { /** {@inheritDoc} */ @Override public void apply(Ignite ignite) { try { ignite.active(true); ((IgniteEx)ignite).context().cache().context().database() .wakeupForCheckpoint("force test checkpoint").get(); ((GridCacheDatabaseSharedManager)(((IgniteEx)ignite).context().cache().context().database())) .enableCheckpoints(false); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } } /** * Activates the cluster and stops it after that. */ private static class ActivateAndStopClosure implements IgniteInClosure<Ignite> { /** {@inheritDoc} */ @Override public void apply(Ignite ignite) { ignite.active(true); ignite.close(); } } /** * Disables checkpointer and sets a new baseline topology. */ private static class NewBaselineTopologyClosure implements IgniteInClosure<Ignite> { /** {@inheritDoc} */ @Override public void apply(Ignite ignite) { ((GridCacheDatabaseSharedManager)(((IgniteEx)ignite).context().cache().context().database())) .enableCheckpoints(false); long newTopVer = ignite.cluster().topologyVersion(); ignite.cluster().setBaselineTopology(newTopVer); } } /** * Create File I/O which fails after second attempt to write to File */ private static class FailingFileIOFactory implements FileIOFactory { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** Indicates that an exception should be trown when this file is going to be removed. */ private final String failOnFileRmv; /** */ private final FileIOFactory delegateFactory = new RandomAccessFileIOFactory(); /** * Creates a new instance of IO factory. */ public FailingFileIOFactory() { failOnFileRmv = null; } /** * Creates a new instance of IO factory. * * @param failOnFileRmv Indicates that an exception should be trown when the given file is removed. */ public FailingFileIOFactory(String failOnFileRmv) { this.failOnFileRmv = failOnFileRmv; } /** {@inheritDoc} */ @Override public FileIO create(File file, OpenOption... modes) throws IOException { final FileIO delegate = delegateFactory.create(file, modes); return new FileIODecorator(delegate) { @Override public void clear() throws IOException { if (failOnFileRmv != null && failOnFileRmv.equals(file.getName())) throw new IOException("Test remove fail!"); super.clear(); } }; } } }
modules/compatibility/src/test/java/org/apache/ignite/compatibility/persistence/MetaStorageCompatibilityTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ignite.compatibility.persistence; import java.io.File; import java.io.IOException; import java.nio.file.OpenOption; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgnitionEx; import org.apache.ignite.internal.processors.cache.GridCacheAbstractFullApiSelfTest; import org.apache.ignite.internal.processors.cache.persistence.CheckpointState; import org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager; import org.apache.ignite.internal.processors.cache.persistence.file.FileIO; import org.apache.ignite.internal.processors.cache.persistence.file.FileIODecorator; import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory; import org.apache.ignite.internal.processors.cache.persistence.file.RandomAccessFileIOFactory; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteInClosure; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.testframework.GridTestUtils; import org.jetbrains.annotations.Nullable; import org.junit.Test; /** * Tests migration of metastorage. */ public class MetaStorageCompatibilityTest extends IgnitePersistenceCompatibilityAbstractTest { /** Consistent id. */ private static final String CONSISTENT_ID_1 = "node1"; /** Consistent id. */ private static final String CONSISTENT_ID_2 = "node2"; /** Ignite version. */ private static final String IGNITE_VERSION = "2.4.0"; /** Filename of index. */ private static final String INDEX_BIN_FILE = "index.bin"; /** Filename of partition. */ private static final String PART_FILE = "part-0.bin"; /** * The zero partition hasn't full baseline information. The last changes are read from WAL. * * @throws Exception If failed. */ @Test public void testMigrationWithoutFullBaselineIntoPartition() throws Exception { try { U.delete(new File(U.defaultWorkDirectory())); startGrid(1, IGNITE_VERSION, new ConfigurationClosure(CONSISTENT_ID_1), new ActivateAndForceCheckpointClosure()); startGrid(2, IGNITE_VERSION, new ConfigurationClosure(CONSISTENT_ID_2), new NewBaselineTopologyClosure()); stopAllGrids(); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { // No-op. } } assertFalse(metastorageFileExists(INDEX_BIN_FILE)); assertFalse(metastorageFileExists(PART_FILE)); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { assertTrue(GridTestUtils.waitForCondition(() -> ig1.cluster().active(), 10_000)); } } } finally { stopAllGrids(); } } /** * Tests that BLT can be changed and persisted after metastorage migration. */ @Test public void testMigrationToNewBaselineSetNewBaselineAfterMigration() throws Exception { try { U.delete(new File(U.defaultWorkDirectory())); startGrid(1, IGNITE_VERSION, new ConfigurationClosure(CONSISTENT_ID_1), new ActivateAndStopClosure()); stopAllGrids(); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { ig0.cluster().setBaselineTopology(ig1.cluster().topologyVersion()); } } assertFalse(metastorageFileExists(INDEX_BIN_FILE)); assertFalse(metastorageFileExists(PART_FILE)); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { assertTrue(GridTestUtils.waitForCondition(() -> ig1.cluster().active(), 10_000)); } } } finally { stopAllGrids(); } } /** * */ @Test public void testMigrationWithExceptionDuringTheProcess() throws Exception { try { U.delete(new File(U.defaultWorkDirectory())); startGrid(1, IGNITE_VERSION, new ConfigurationClosure(CONSISTENT_ID_1), new ActivateAndStopClosure()); stopAllGrids(); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1, PART_FILE))) { ig0.getOrCreateCache("default-cache").put(1, 1); // trigger checkpoint on close() } assertTrue(metastorageFileExists(INDEX_BIN_FILE)); assertTrue(metastorageFileExists(PART_FILE)); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1, INDEX_BIN_FILE))) { ig0.getOrCreateCache("default-cache").put(1, 1); // trigger checkpoint on close() } assertTrue(metastorageFileExists(INDEX_BIN_FILE)); assertFalse(metastorageFileExists(PART_FILE)); try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { ig0.cluster().setBaselineTopology(ig1.cluster().topologyVersion()); } } try (Ignite ig0 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_1))) { try (Ignite ig1 = IgnitionEx.start(prepareConfig(getConfiguration(), CONSISTENT_ID_2))) { assertTrue(GridTestUtils.waitForCondition(() -> ig1.cluster().active(), 10_000)); } } } finally { stopAllGrids(); } } /** * Checks that file exists. * * @param fileName File name. */ private boolean metastorageFileExists(String fileName) throws IgniteCheckedException { return new File(U.defaultWorkDirectory() + "/db/" + U.maskForFileName(CONSISTENT_ID_1) + "/metastorage/" + fileName).exists(); } /** * Updates the given ignite configuration. * * @param cfg Ignite configuration to be updated. * @param consistentId Consistent id. * @return Updated configuration. */ private static IgniteConfiguration prepareConfig(IgniteConfiguration cfg, @Nullable String consistentId) { return prepareConfig(cfg, consistentId, null); } /** * Updates the given ignite configuration. * * @param cfg Ignite configuration to be updated. * @param consistentId Consistent id. * @param failOnFileRmv Indicates that an exception should be trown when partition/index file is going to be removed. * @return Updated configuration. */ private static IgniteConfiguration prepareConfig( IgniteConfiguration cfg, @Nullable String consistentId, @Nullable String failOnFileRmv ) { cfg.setLocalHost("127.0.0.1"); TcpDiscoverySpi disco = new TcpDiscoverySpi(); disco.setIpFinder(GridCacheAbstractFullApiSelfTest.LOCAL_IP_FINDER); cfg.setDiscoverySpi(disco); cfg.setPeerClassLoadingEnabled(false); DataStorageConfiguration memCfg = new DataStorageConfiguration() .setDefaultDataRegionConfiguration( new DataRegionConfiguration() .setPersistenceEnabled(true) .setInitialSize(10L * 1024 * 1024) .setMaxSize(10L * 1024 * 1024)) .setPageSize(4096); cfg.setDataStorageConfiguration(memCfg); if (consistentId != null) { cfg.setIgniteInstanceName(consistentId); cfg.setConsistentId(consistentId); } if (failOnFileRmv != null) cfg.getDataStorageConfiguration().setFileIOFactory(new FailingFileIOFactory(failOnFileRmv)); return cfg; } /** */ private static class ConfigurationClosure implements IgniteInClosure<IgniteConfiguration> { /** Consistent id. */ private final String consistentId; /** * Creates a new instance of Configuration closure. * * @param consistentId Consistent id. */ public ConfigurationClosure(String consistentId) { this.consistentId = consistentId; } /** {@inheritDoc} */ @Override public void apply(IgniteConfiguration cfg) { prepareConfig(cfg, consistentId, null); } } /** * Post-startup close that activate the grid and force checkpoint. */ private static class ActivateAndForceCheckpointClosure implements IgniteInClosure<Ignite> { /** {@inheritDoc} */ @Override public void apply(Ignite ignite) { try { ignite.active(true); ((IgniteEx)ignite).context().cache().context().database() .forceCheckpoint("force test checkpoint").futureFor(CheckpointState.FINISHED).get(); ((GridCacheDatabaseSharedManager)(((IgniteEx)ignite).context().cache().context().database())) .enableCheckpoints(false); } catch (IgniteCheckedException e) { throw new IgniteException(e); } } } /** * Activates the cluster and stops it after that. */ private static class ActivateAndStopClosure implements IgniteInClosure<Ignite> { /** {@inheritDoc} */ @Override public void apply(Ignite ignite) { ignite.active(true); ignite.close(); } } /** * Disables checkpointer and sets a new baseline topology. */ private static class NewBaselineTopologyClosure implements IgniteInClosure<Ignite> { /** {@inheritDoc} */ @Override public void apply(Ignite ignite) { ((GridCacheDatabaseSharedManager)(((IgniteEx)ignite).context().cache().context().database())) .enableCheckpoints(false); long newTopVer = ignite.cluster().topologyVersion(); ignite.cluster().setBaselineTopology(newTopVer); } } /** * Create File I/O which fails after second attempt to write to File */ private static class FailingFileIOFactory implements FileIOFactory { /** Serial version uid. */ private static final long serialVersionUID = 0L; /** Indicates that an exception should be trown when this file is going to be removed. */ private final String failOnFileRmv; /** */ private final FileIOFactory delegateFactory = new RandomAccessFileIOFactory(); /** * Creates a new instance of IO factory. */ public FailingFileIOFactory() { failOnFileRmv = null; } /** * Creates a new instance of IO factory. * * @param failOnFileRmv Indicates that an exception should be trown when the given file is removed. */ public FailingFileIOFactory(String failOnFileRmv) { this.failOnFileRmv = failOnFileRmv; } /** {@inheritDoc} */ @Override public FileIO create(File file, OpenOption... modes) throws IOException { final FileIO delegate = delegateFactory.create(file, modes); return new FileIODecorator(delegate) { @Override public void clear() throws IOException { if (failOnFileRmv != null && failOnFileRmv.equals(file.getName())) throw new IOException("Test remove fail!"); super.clear(); } }; } } }
IGNITE-12560 Fix incompatible API usage.
modules/compatibility/src/test/java/org/apache/ignite/compatibility/persistence/MetaStorageCompatibilityTest.java
IGNITE-12560 Fix incompatible API usage.
<ide><path>odules/compatibility/src/test/java/org/apache/ignite/compatibility/persistence/MetaStorageCompatibilityTest.java <ide> ignite.active(true); <ide> <ide> ((IgniteEx)ignite).context().cache().context().database() <del> .forceCheckpoint("force test checkpoint").futureFor(CheckpointState.FINISHED).get(); <add> .wakeupForCheckpoint("force test checkpoint").get(); <ide> <ide> ((GridCacheDatabaseSharedManager)(((IgniteEx)ignite).context().cache().context().database())) <ide> .enableCheckpoints(false);
Java
apache-2.0
9f7dce3eca0fb5c55814ddc1ae3fd61b04c9062d
0
mini2Dx/mini2Dx,mini2Dx/mini2Dx
/** * Copyright (c) 2017 See AUTHORS file * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.artemis.system; import com.artemis.Aspect.Builder; import com.artemis.Aspect; import com.artemis.EntitySystem; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Queue; /** * An {@link EntitySystem} that will wait for an interval then queue all * entities to be updated over the duration of the next interval. */ public abstract class DispersedIntervalEntitySystem extends EntitySystem { protected final Queue<Integer> processingQueue = new Queue<Integer>(); private float interval; private float timer; private float updateDelta; protected int entitiesPerUpdate; /** * Constructor * @param aspect The {@link Aspect} to match entities * @param interval The interval in seconds */ public DispersedIntervalEntitySystem(Builder aspect, float interval) { super(aspect); this.interval = interval; this.timer = interval; } /** * Updates an entity * * @param entityId * The entity id * @param delta * The delta since the last update */ protected abstract void update(int entityId, float delta); @Override protected void processSystem() { updateDelta += getWorld().getDelta(); for (int i = 0; i < entitiesPerUpdate && processingQueue.size > 0; i++) { int nextEntityId = processingQueue.removeFirst(); update(nextEntityId, updateDelta); } timer += getWorld().getDelta(); if (timer >= interval) { updateDelta = timer; timer = timer % interval; int totalEntities = getEntityIds().size(); entitiesPerUpdate = MathUtils.round((totalEntities + processingQueue.size) / interval); entitiesPerUpdate = Math.max(1, entitiesPerUpdate); for (int i = 0; i < totalEntities; i++) { processingQueue.addLast(getEntityIds().get(i)); } } } /** * Returns the interval of the system * @return */ public float getInterval() { return interval; } /** * Sets the interval of the system * @param interval */ public void setInterval(float interval) { this.interval = interval; } }
artemis-odb/src/main/java/com/artemis/system/DispersedIntervalEntitySystem.java
/** * Copyright (c) 2017 See AUTHORS file * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.artemis.system; import com.artemis.Aspect.Builder; import com.artemis.Aspect; import com.artemis.EntitySystem; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Queue; /** * An {@link EntitySystem} that will wait for an interval then queue all * entities to be updated over the duration of the next interval. */ public abstract class DispersedIntervalEntitySystem extends EntitySystem { private final float interval; protected final Queue<Integer> processingQueue = new Queue<Integer>(); protected int entitiesPerUpdate; private float timer; private float updateDelta; /** * Constructor * @param aspect The {@link Aspect} to match entities * @param interval The interval in seconds */ public DispersedIntervalEntitySystem(Builder aspect, float interval) { super(aspect); this.interval = interval; this.timer = interval; } /** * Updates an entity * * @param entityId * The entity id * @param delta * The delta since the last update */ protected abstract void update(int entityId, float delta); @Override protected void processSystem() { updateDelta += getWorld().getDelta(); for (int i = 0; i < entitiesPerUpdate && processingQueue.size > 0; i++) { int nextEntityId = processingQueue.removeFirst(); update(nextEntityId, updateDelta); } timer += getWorld().getDelta(); if (timer >= interval) { updateDelta = timer; timer = timer % interval; int totalEntities = getEntityIds().size(); entitiesPerUpdate = MathUtils.round((totalEntities + processingQueue.size) / interval); entitiesPerUpdate = Math.max(1, entitiesPerUpdate); for (int i = 0; i < totalEntities; i++) { processingQueue.addLast(getEntityIds().get(i)); } } } }
Added get/setInterval to DispersedIntervalEntitySystem
artemis-odb/src/main/java/com/artemis/system/DispersedIntervalEntitySystem.java
Added get/setInterval to DispersedIntervalEntitySystem
<ide><path>rtemis-odb/src/main/java/com/artemis/system/DispersedIntervalEntitySystem.java <ide> * entities to be updated over the duration of the next interval. <ide> */ <ide> public abstract class DispersedIntervalEntitySystem extends EntitySystem { <del> private final float interval; <ide> protected final Queue<Integer> processingQueue = new Queue<Integer>(); <ide> <del> protected int entitiesPerUpdate; <add> private float interval; <ide> private float timer; <ide> private float updateDelta; <add> protected int entitiesPerUpdate; <ide> <ide> /** <ide> * Constructor <ide> } <ide> } <ide> } <add> <add> /** <add> * Returns the interval of the system <add> * @return <add> */ <add> public float getInterval() { <add> return interval; <add> } <add> <add> /** <add> * Sets the interval of the system <add> * @param interval <add> */ <add> public void setInterval(float interval) { <add> this.interval = interval; <add> } <ide> }
Java
apache-2.0
3473b3ebbb3d2fca6135ae442fd1ff1a71c8428a
0
atomix/atomix,atomix/atomix,kuujo/copycat,kuujo/copycat
/* * Copyright 2014-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.atomix.serializer.kryo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Registration; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.ByteBufferInput; import com.esotericsoftware.kryo.io.ByteBufferOutput; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoCallback; import com.esotericsoftware.kryo.pool.KryoFactory; import com.esotericsoftware.kryo.pool.KryoPool; import com.esotericsoftware.kryo.serializers.CompatibleFieldSerializer; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import io.atomix.serializer.Namespace; import org.apache.commons.lang3.tuple.Pair; import org.objenesis.strategy.StdInstantiatorStrategy; import org.slf4j.Logger; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import static com.google.common.base.Preconditions.checkNotNull; import static org.slf4j.LoggerFactory.getLogger; /** * Pool of Kryo instances, with classes pre-registered. */ //@ThreadSafe public final class KryoNamespace implements Namespace, KryoFactory, KryoPool { /** * Default buffer size used for serialization. * * @see #serialize(Object) */ public static final int DEFAULT_BUFFER_SIZE = 4096; public static final int MAX_BUFFER_SIZE = 100 * 1000 * 1000; /** * ID to use if this KryoNamespace does not define registration id. */ public static final int FLOATING_ID = -1; /** * Smallest ID free to use for user defined registrations. */ public static final int INITIAL_ID = 16; private static final String NO_NAME = "(no name)"; private static final Logger log = getLogger(KryoNamespace.class); /** * Default Kryo namespace. */ public static Namespace DEFAULT = newBuilder().build(); private final KryoPool pool = new KryoPool.Builder(this) .softReferences() .build(); private final ImmutableList<RegistrationBlock> registeredBlocks; private final boolean compatible; private final boolean registrationRequired; private final String friendlyName; /** * KryoNamespace builder. */ //@NotThreadSafe public static final class Builder { private int blockHeadId = INITIAL_ID; private List<Pair<Class<?>[], Serializer<?>>> types = new ArrayList<>(); private List<RegistrationBlock> blocks = new ArrayList<>(); private boolean registrationRequired = true; private boolean compatible = false; /** * Builds a {@link KryoNamespace} instance. * * @return KryoNamespace */ public KryoNamespace build() { return build(NO_NAME); } /** * Builds a {@link KryoNamespace} instance. * * @param friendlyName friendly name for the namespace * @return KryoNamespace */ public KryoNamespace build(String friendlyName) { if (!types.isEmpty()) { blocks.add(new RegistrationBlock(this.blockHeadId, types)); } return new KryoNamespace(blocks, registrationRequired, compatible, friendlyName).populate(1); } /** * Sets the next Kryo registration Id for following register entries. * * @param id Kryo registration Id * @return this * @see Kryo#register(Class, Serializer, int) */ public Builder nextId(final int id) { if (!types.isEmpty()) { if (id != FLOATING_ID && id < blockHeadId + types.size()) { if (log.isWarnEnabled()) { log.warn("requested nextId {} could potentially overlap " + "with existing registrations {}+{} ", id, blockHeadId, types.size(), new RuntimeException()); } } blocks.add(new RegistrationBlock(this.blockHeadId, types)); types = new ArrayList<>(); } this.blockHeadId = id; return this; } /** * Registers classes to be serialized using Kryo default serializer. * * @param expectedTypes list of classes * @return this */ public Builder register(final Class<?>... expectedTypes) { for (Class<?> clazz : expectedTypes) { types.add(Pair.of(new Class<?>[]{clazz}, null)); } return this; } /** * Registers serializer for the given set of classes. * <p> * When multiple classes are registered with an explicitly provided serializer, the namespace guarantees * all instances will be serialized with the same type ID. * * @param classes list of classes to register * @param serializer serializer to use for the class * @return this */ public Builder register(Serializer<?> serializer, final Class<?>... classes) { types.add(Pair.of(classes, checkNotNull(serializer))); return this; } private Builder register(RegistrationBlock block) { if (block.begin() != FLOATING_ID) { // flush pending types nextId(block.begin()); blocks.add(block); nextId(block.begin() + block.types().size()); } else { // flush pending types final int addedBlockBegin = blockHeadId + types.size(); nextId(addedBlockBegin); blocks.add(new RegistrationBlock(addedBlockBegin, block.types())); nextId(addedBlockBegin + block.types().size()); } return this; } /** * Registers all the class registered to given KryoNamespace. * * @param ns KryoNamespace * @return this */ public Builder register(final KryoNamespace ns) { if (blocks.containsAll(ns.registeredBlocks)) { // Everything was already registered. log.debug("Ignoring {}, already registered.", ns); return this; } for (RegistrationBlock block : ns.registeredBlocks) { this.register(block); } return this; } /** * Sets whether backwards/forwards compatible versioned serialization is enabled. * <p> * When compatible serialization is enabled, the {@link CompatibleFieldSerializer} will be set as the * default serializer for types that do not otherwise explicitly specify a serializer. * * @param compatible whether versioned serialization is enabled * @return this */ public Builder setCompatible(boolean compatible) { this.compatible = compatible; return this; } /** * Sets the registrationRequired flag. * * @param registrationRequired Kryo's registrationRequired flag * @return this * @see Kryo#setRegistrationRequired(boolean) */ public Builder setRegistrationRequired(boolean registrationRequired) { this.registrationRequired = registrationRequired; return this; } } /** * Creates a new {@link KryoNamespace} builder. * * @return builder */ public static Builder newBuilder() { return new Builder(); } /** * Creates a Kryo instance pool. * * @param registeredTypes types to register * @param registrationRequired whether registration is required * @param compatible whether compatible serialization is enabled * @param friendlyName friendly name for the namespace */ private KryoNamespace(final List<RegistrationBlock> registeredTypes, boolean registrationRequired, boolean compatible, String friendlyName) { this.registeredBlocks = ImmutableList.copyOf(registeredTypes); this.registrationRequired = registrationRequired; this.compatible = compatible; this.friendlyName = checkNotNull(friendlyName); } /** * Populates the Kryo pool. * * @param instances to add to the pool * @return this */ public KryoNamespace populate(int instances) { for (int i = 0; i < instances; ++i) { release(create()); } return this; } /** * Serializes given object to byte array using Kryo instance in pool. * <p> * Note: Serialized bytes must be smaller than {@link #MAX_BUFFER_SIZE}. * * @param obj Object to serialize * @return serialized bytes */ public byte[] serialize(final Object obj) { return serialize(obj, DEFAULT_BUFFER_SIZE); } /** * Serializes given object to byte array using Kryo instance in pool. * * @param obj Object to serialize * @param bufferSize maximum size of serialized bytes * @return serialized bytes */ public byte[] serialize(final Object obj, final int bufferSize) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bufferSize); Output out = new Output(outputStream); return pool.run(kryo -> { kryo.writeClassAndObject(out, obj); out.flush(); return outputStream.toByteArray(); }); } /** * Serializes given object to byte buffer using Kryo instance in pool. * * @param obj Object to serialize * @param buffer to write to */ public void serialize(final Object obj, final ByteBuffer buffer) { ByteBufferOutput out = new ByteBufferOutput(buffer); Kryo kryo = borrow(); try { kryo.writeClassAndObject(out, obj); out.flush(); } finally { release(kryo); } } /** * Serializes given object to OutputStream using Kryo instance in pool. * * @param obj Object to serialize * @param stream to write to */ public void serialize(final Object obj, final OutputStream stream) { serialize(obj, stream, DEFAULT_BUFFER_SIZE); } /** * Serializes given object to OutputStream using Kryo instance in pool. * * @param obj Object to serialize * @param stream to write to * @param bufferSize size of the buffer in front of the stream */ public void serialize(final Object obj, final OutputStream stream, final int bufferSize) { ByteBufferOutput out = new ByteBufferOutput(stream, bufferSize); Kryo kryo = borrow(); try { kryo.writeClassAndObject(out, obj); out.flush(); } finally { release(kryo); } } /** * Deserializes given byte array to Object using Kryo instance in pool. * * @param bytes serialized bytes * @param <T> deserialized Object type * @return deserialized Object */ public <T> T deserialize(final byte[] bytes) { Input in = new Input(new ByteArrayInputStream(bytes)); Kryo kryo = borrow(); try { @SuppressWarnings("unchecked") T obj = (T) kryo.readClassAndObject(in); return obj; } finally { release(kryo); } } /** * Deserializes given byte buffer to Object using Kryo instance in pool. * * @param buffer input with serialized bytes * @param <T> deserialized Object type * @return deserialized Object */ public <T> T deserialize(final ByteBuffer buffer) { ByteBufferInput in = new ByteBufferInput(buffer); Kryo kryo = borrow(); try { @SuppressWarnings("unchecked") T obj = (T) kryo.readClassAndObject(in); return obj; } finally { release(kryo); } } /** * Deserializes given InputStream to an Object using Kryo instance in pool. * * @param stream input stream * @param <T> deserialized Object type * @return deserialized Object */ public <T> T deserialize(final InputStream stream) { return deserialize(stream, DEFAULT_BUFFER_SIZE); } /** * Deserializes given InputStream to an Object using Kryo instance in pool. * * @param stream input stream * @param <T> deserialized Object type * @param bufferSize size of the buffer in front of the stream * @return deserialized Object */ public <T> T deserialize(final InputStream stream, final int bufferSize) { ByteBufferInput in = new ByteBufferInput(stream, bufferSize); Kryo kryo = borrow(); try { @SuppressWarnings("unchecked") T obj = (T) kryo.readClassAndObject(in); return obj; } finally { release(kryo); } } private String friendlyName() { return friendlyName; } /** * Gets the number of classes registered in this Kryo namespace. * * @return size of namespace */ public int size() { return (int) registeredBlocks.stream() .flatMap(block -> block.types().stream()) .count(); } /** * Creates a Kryo instance. * * @return Kryo instance */ @Override public Kryo create() { log.trace("Creating Kryo instance for {}", this); Kryo kryo = new Kryo(); kryo.setRegistrationRequired(registrationRequired); // If compatible serialization is enabled, override the default serializer. if (compatible) { kryo.setDefaultSerializer(CompatibleFieldSerializer::new); } // TODO rethink whether we want to use StdInstantiatorStrategy kryo.setInstantiatorStrategy( new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); for (RegistrationBlock block : registeredBlocks) { int id = block.begin(); if (id == FLOATING_ID) { id = kryo.getNextRegistrationId(); } for (Pair<Class<?>[], Serializer<?>> entry : block.types()) { register(kryo, entry.getLeft(), entry.getRight(), id++); } } return kryo; } /** * Register {@code type} and {@code serializer} to {@code kryo} instance. * * @param kryo Kryo instance * @param types types to register * @param serializer Specific serializer to register or null to use default. * @param id type registration id to use */ private void register(Kryo kryo, Class<?>[] types, Serializer<?> serializer, int id) { Registration existing = kryo.getRegistration(id); if (existing != null) { boolean matches = false; for (Class<?> type : types) { if (existing.getType() == type) { matches = true; break; } } if (!matches) { log.error("{}: Failed to register {} as {}, {} was already registered.", friendlyName(), types, id, existing.getType()); throw new IllegalStateException(String.format( "Failed to register %s as %s, %s was already registered.", Arrays.toString(types), id, existing.getType())); } // falling through to register call for now. // Consider skipping, if there's reasonable // way to compare serializer equivalence. } for (Class<?> type : types) { Registration r; if (serializer == null) { r = kryo.register(type, id); } else { r = kryo.register(type, serializer, id); } if (r.getId() != id) { log.debug("{}: {} already registered as {}. Skipping {}.", friendlyName(), r.getType(), r.getId(), id); } log.trace("{} registered as {}", r.getType(), r.getId()); } } @Override public Kryo borrow() { return pool.borrow(); } @Override public void release(Kryo kryo) { pool.release(kryo); } @Override public <T> T run(KryoCallback<T> callback) { return pool.run(callback); } @Override public String toString() { if (friendlyName != NO_NAME) { return MoreObjects.toStringHelper(getClass()) .omitNullValues() .add("friendlyName", friendlyName) // omit lengthy detail, when there's a name .toString(); } return MoreObjects.toStringHelper(getClass()) .add("registeredBlocks", registeredBlocks) .toString(); } static final class RegistrationBlock { private final int begin; private final ImmutableList<Pair<Class<?>[], Serializer<?>>> types; public RegistrationBlock(int begin, List<Pair<Class<?>[], Serializer<?>>> types) { this.begin = begin; this.types = ImmutableList.copyOf(types); } public int begin() { return begin; } public ImmutableList<Pair<Class<?>[], Serializer<?>>> types() { return types; } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("begin", begin) .add("types", types) .toString(); } @Override public int hashCode() { return types.hashCode(); } // Only the registered types are used for equality. @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof RegistrationBlock) { RegistrationBlock that = (RegistrationBlock) obj; return Objects.equals(this.types, that.types); } return false; } } }
serializer/kryo/src/main/java/io/atomix/serializer/kryo/KryoNamespace.java
/* * Copyright 2014-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.atomix.serializer.kryo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Registration; import com.esotericsoftware.kryo.io.ByteBufferInput; import com.esotericsoftware.kryo.io.ByteBufferOutput; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoCallback; import com.esotericsoftware.kryo.pool.KryoFactory; import com.esotericsoftware.kryo.pool.KryoPool; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.atomix.serializer.Namespace; import org.apache.commons.lang3.tuple.Pair; import org.objenesis.strategy.StdInstantiatorStrategy; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import static com.google.common.base.Preconditions.checkNotNull; /** * Pool of Kryo instances, with classes pre-registered. */ //@ThreadSafe public final class KryoNamespace implements Namespace, KryoFactory, KryoPool { /** * ID to use if this KryoNamespace does not define registration id. */ public static final int FLOATING_ID = -1; /** * Smallest ID free to use for user defined registrations. */ public static final int INITIAL_ID = 16; private static final String NO_NAME = "(no name)"; private static final Logger log = LoggerFactory.getLogger(KryoNamespace.class); /** * Default Kryo namespace. */ public static Namespace DEFAULT = newBuilder().build(); private final KryoPool pool = new KryoPool.Builder(this) .softReferences() .build(); private final ImmutableList<RegistrationBlock> registeredBlocks; private final boolean registrationRequired; private final String friendlyName; /** * KryoNamespace builder. */ //@NotThreadSafe public static final class Builder { private int blockHeadId = INITIAL_ID; private List<Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>>> types = new ArrayList<>(); private List<RegistrationBlock> blocks = new ArrayList<>(); private boolean registrationRequired = true; /** * Builds a {@link KryoNamespace} instance. * * @return KryoNamespace */ public KryoNamespace build() { return build(NO_NAME); } /** * Builds a {@link KryoNamespace} instance. * * @param friendlyName friendly name for the namespace * @return KryoNamespace */ public KryoNamespace build(String friendlyName) { if (!types.isEmpty()) { blocks.add(new RegistrationBlock(this.blockHeadId, types)); } return new KryoNamespace(blocks, registrationRequired, friendlyName).populate(1); } /** * Sets the next Kryo registration Id for following register entries. * * @param id Kryo registration Id * @return this * @see Kryo#register(Class, com.esotericsoftware.kryo.Serializer, int) */ public Builder nextId(final int id) { if (!types.isEmpty()) { if (id != FLOATING_ID && id < blockHeadId + types.size()) { if (log.isWarnEnabled()) { log.warn("requested nextId {} could potentially overlap " + "with existing registrations {}+{} ", id, blockHeadId, types.size(), new RuntimeException()); } } blocks.add(new RegistrationBlock(this.blockHeadId, types)); types = new ArrayList<>(); } this.blockHeadId = id; return this; } /** * Registers classes to be serialized using Kryo default serializer. * * @param expectedTypes list of classes * @return this */ public Builder register(final Class<?>... expectedTypes) { for (Class<?> clazz : expectedTypes) { types.add(Pair.of(new Class<?>[]{clazz}, null)); } return this; } /** * Registers serializer for the given set of classes. * <p> * When multiple classes are registered with an explicitly provided serializer, the namespace guarantees * all instances will be serialized with the same type ID. * * @param classes list of classes to register * @param serializer serializer to use for the class * @return this */ public Builder register(com.esotericsoftware.kryo.Serializer<?> serializer, final Class<?>... classes) { types.add(Pair.of(classes, checkNotNull(serializer))); return this; } private Builder register(RegistrationBlock block) { if (block.begin() != FLOATING_ID) { // flush pending types nextId(block.begin()); blocks.add(block); nextId(block.begin() + block.types().size()); } else { // flush pending types final int addedBlockBegin = blockHeadId + types.size(); nextId(addedBlockBegin); blocks.add(new RegistrationBlock(addedBlockBegin, block.types())); nextId(addedBlockBegin + block.types().size()); } return this; } /** * Registers all the class registered to given KryoNamespace. * * @param ns KryoNamespace * @return this */ public Builder register(final KryoNamespace ns) { if (blocks.containsAll(ns.registeredBlocks)) { // Everything was already registered. log.debug("Ignoring {}, already registered.", ns); return this; } for (RegistrationBlock block : ns.registeredBlocks) { this.register(block); } return this; } /** * Sets the registrationRequired flag. * * @param registrationRequired Kryo's registrationRequired flag * @return this * @see Kryo#setRegistrationRequired(boolean) */ public Builder setRegistrationRequired(boolean registrationRequired) { this.registrationRequired = registrationRequired; return this; } } /** * Creates a new {@link KryoNamespace} builder. * * @return builder */ public static Builder newBuilder() { return new Builder(); } /** * Creates a Kryo instance pool. * * @param registeredTypes types to register * @param registrationRequired * @param friendlyName friendly name for the namespace */ private KryoNamespace(final List<RegistrationBlock> registeredTypes, boolean registrationRequired, String friendlyName) { this.registeredBlocks = ImmutableList.copyOf(registeredTypes); this.registrationRequired = registrationRequired; this.friendlyName = checkNotNull(friendlyName); } /** * Populates the Kryo pool. * * @param instances to add to the pool * @return this */ public KryoNamespace populate(int instances) { for (int i = 0; i < instances; ++i) { release(create()); } return this; } /** * Serializes given object to byte array using Kryo instance in pool. * * @param obj Object to serialize * @param bufferSize maximum size of serialized bytes * @return serialized bytes */ public byte[] serialize(final Object obj, final int bufferSize) { Output out = new Output(bufferSize, MAX_BUFFER_SIZE); return pool.run(kryo -> { kryo.writeClassAndObject(out, obj); out.flush(); return out.toBytes(); }); } /** * Serializes given object to byte buffer using Kryo instance in pool. * * @param obj Object to serialize * @param buffer to write to */ public void serialize(final Object obj, final ByteBuffer buffer) { ByteBufferOutput out = new ByteBufferOutput(buffer); Kryo kryo = borrow(); try { kryo.writeClassAndObject(out, obj); out.flush(); } finally { release(kryo); } } /** * Serializes given object to OutputStream using Kryo instance in pool. * * @param obj Object to serialize * @param stream to write to * @param bufferSize size of the buffer in front of the stream */ public void serialize(final Object obj, final OutputStream stream, final int bufferSize) { ByteBufferOutput out = new ByteBufferOutput(stream, bufferSize); Kryo kryo = borrow(); try { kryo.writeClassAndObject(out, obj); out.flush(); } finally { release(kryo); } } /** * Deserializes given byte array to Object using Kryo instance in pool. * * @param bytes serialized bytes * @param <T> deserialized Object type * @return deserialized Object */ public <T> T deserialize(final byte[] bytes) { Input in = new Input(bytes); Kryo kryo = borrow(); try { @SuppressWarnings("unchecked") T obj = (T) kryo.readClassAndObject(in); return obj; } finally { release(kryo); } } /** * Deserializes given byte buffer to Object using Kryo instance in pool. * * @param buffer input with serialized bytes * @param <T> deserialized Object type * @return deserialized Object */ public <T> T deserialize(final ByteBuffer buffer) { ByteBufferInput in = new ByteBufferInput(buffer); Kryo kryo = borrow(); try { @SuppressWarnings("unchecked") T obj = (T) kryo.readClassAndObject(in); return obj; } finally { release(kryo); } } /** * Deserializes given InputStream to an Object using Kryo instance in pool. * * @param stream input stream * @param <T> deserialized Object type * @param bufferSize size of the buffer in front of the stream * @return deserialized Object */ public <T> T deserialize(final InputStream stream, final int bufferSize) { ByteBufferInput in = new ByteBufferInput(stream, bufferSize); Kryo kryo = borrow(); try { @SuppressWarnings("unchecked") T obj = (T) kryo.readClassAndObject(in); return obj; } finally { release(kryo); } } private String friendlyName() { return friendlyName; } /** * Gets the number of classes registered in this Kryo namespace. * * @return size of namespace */ public int size() { return (int) registeredBlocks.stream() .flatMap(block -> block.types().stream()) .count(); } /** * Creates a Kryo instance. * * @return Kryo instance */ @Override public Kryo create() { log.trace("Creating Kryo instance for {}", this); Kryo kryo = new Kryo(); kryo.setRegistrationRequired(registrationRequired); // TODO rethink whether we want to use StdInstantiatorStrategy kryo.setInstantiatorStrategy( new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); for (RegistrationBlock block : registeredBlocks) { int id = block.begin(); if (id == FLOATING_ID) { id = kryo.getNextRegistrationId(); } for (Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>> entry : block.types()) { register(kryo, entry.getLeft(), entry.getRight(), id++); } } return kryo; } /** * Register {@code type} and {@code serializer} to {@code kryo} instance. * * @param kryo Kryo instance * @param types types to register * @param serializer Specific serializer to register or null to use default. * @param id type registration id to use */ private void register(Kryo kryo, Class<?>[] types, com.esotericsoftware.kryo.Serializer<?> serializer, int id) { Registration existing = kryo.getRegistration(id); if (existing != null) { boolean matches = false; for (Class<?> type : types) { if (existing.getType() == type) { matches = true; break; } } if (!matches) { log.error("{}: Failed to register {} as {}, {} was already registered.", friendlyName(), types, id, existing.getType()); throw new IllegalStateException(String.format( "Failed to register %s as %s, %s was already registered.", Arrays.toString(types), id, existing.getType())); } // falling through to register call for now. // Consider skipping, if there's reasonable // way to compare serializer equivalence. } for (Class<?> type : types) { Registration r; if (serializer == null) { r = kryo.register(type, id); } else { r = kryo.register(type, serializer, id); } if (r.getId() != id) { log.warn("{}: {} already registed as {}. Skipping {}.", friendlyName(), r.getType(), r.getId(), id); } log.trace("{} registered as {}", r.getType(), r.getId()); } } @Override public Kryo borrow() { return pool.borrow(); } @Override public void release(Kryo kryo) { pool.release(kryo); } @Override public <T> T run(KryoCallback<T> callback) { return pool.run(callback); } @Override public String toString() { if (friendlyName != NO_NAME) { return MoreObjects.toStringHelper(getClass()) .omitNullValues() .add("friendlyName", friendlyName) // omit lengthy detail, when there's a name .toString(); } return MoreObjects.toStringHelper(getClass()) .add("registeredBlocks", registeredBlocks) .toString(); } static final class RegistrationBlock { private final int begin; private final ImmutableList<Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>>> types; public RegistrationBlock(int begin, List<Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>>> types) { this.begin = begin; this.types = ImmutableList.copyOf(types); } public int begin() { return begin; } public ImmutableList<Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>>> types() { return types; } @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("begin", begin) .add("types", types) .toString(); } @Override public int hashCode() { return types.hashCode(); } // Only the registered types are used for equality. @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof RegistrationBlock) { RegistrationBlock that = (RegistrationBlock) obj; return Objects.equals(this.types, that.types); } return false; } } }
Clean up KryoNamespace.
serializer/kryo/src/main/java/io/atomix/serializer/kryo/KryoNamespace.java
Clean up KryoNamespace.
<ide><path>erializer/kryo/src/main/java/io/atomix/serializer/kryo/KryoNamespace.java <ide> <ide> import com.esotericsoftware.kryo.Kryo; <ide> import com.esotericsoftware.kryo.Registration; <add>import com.esotericsoftware.kryo.Serializer; <ide> import com.esotericsoftware.kryo.io.ByteBufferInput; <ide> import com.esotericsoftware.kryo.io.ByteBufferOutput; <ide> import com.esotericsoftware.kryo.io.Input; <ide> import com.esotericsoftware.kryo.pool.KryoCallback; <ide> import com.esotericsoftware.kryo.pool.KryoFactory; <ide> import com.esotericsoftware.kryo.pool.KryoPool; <add>import com.esotericsoftware.kryo.serializers.CompatibleFieldSerializer; <ide> import com.google.common.base.MoreObjects; <ide> import com.google.common.collect.ImmutableList; <del>import org.slf4j.Logger; <del>import org.slf4j.LoggerFactory; <ide> import io.atomix.serializer.Namespace; <ide> import org.apache.commons.lang3.tuple.Pair; <ide> import org.objenesis.strategy.StdInstantiatorStrategy; <del> <add>import org.slf4j.Logger; <add> <add>import java.io.ByteArrayInputStream; <add>import java.io.ByteArrayOutputStream; <ide> import java.io.InputStream; <ide> import java.io.OutputStream; <ide> import java.nio.ByteBuffer; <ide> import java.util.Objects; <ide> <ide> import static com.google.common.base.Preconditions.checkNotNull; <add>import static org.slf4j.LoggerFactory.getLogger; <ide> <ide> /** <ide> * Pool of Kryo instances, with classes pre-registered. <ide> public final class KryoNamespace implements Namespace, KryoFactory, KryoPool { <ide> <ide> /** <add> * Default buffer size used for serialization. <add> * <add> * @see #serialize(Object) <add> */ <add> public static final int DEFAULT_BUFFER_SIZE = 4096; <add> public static final int MAX_BUFFER_SIZE = 100 * 1000 * 1000; <add> <add> /** <ide> * ID to use if this KryoNamespace does not define registration id. <ide> */ <ide> public static final int FLOATING_ID = -1; <ide> <ide> private static final String NO_NAME = "(no name)"; <ide> <del> private static final Logger log = LoggerFactory.getLogger(KryoNamespace.class); <add> private static final Logger log = getLogger(KryoNamespace.class); <ide> <ide> /** <ide> * Default Kryo namespace. <ide> <ide> private final ImmutableList<RegistrationBlock> registeredBlocks; <ide> <add> private final boolean compatible; <ide> private final boolean registrationRequired; <ide> private final String friendlyName; <ide> <ide> */ <ide> //@NotThreadSafe <ide> public static final class Builder { <del> <ide> private int blockHeadId = INITIAL_ID; <del> private List<Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>>> types = new ArrayList<>(); <add> private List<Pair<Class<?>[], Serializer<?>>> types = new ArrayList<>(); <ide> private List<RegistrationBlock> blocks = new ArrayList<>(); <ide> private boolean registrationRequired = true; <add> private boolean compatible = false; <ide> <ide> /** <ide> * Builds a {@link KryoNamespace} instance. <ide> if (!types.isEmpty()) { <ide> blocks.add(new RegistrationBlock(this.blockHeadId, types)); <ide> } <del> return new KryoNamespace(blocks, registrationRequired, friendlyName).populate(1); <add> return new KryoNamespace(blocks, registrationRequired, compatible, friendlyName).populate(1); <ide> } <ide> <ide> /** <ide> * <ide> * @param id Kryo registration Id <ide> * @return this <del> * @see Kryo#register(Class, com.esotericsoftware.kryo.Serializer, int) <add> * @see Kryo#register(Class, Serializer, int) <ide> */ <ide> public Builder nextId(final int id) { <ide> if (!types.isEmpty()) { <ide> * @param serializer serializer to use for the class <ide> * @return this <ide> */ <del> public Builder register(com.esotericsoftware.kryo.Serializer<?> serializer, final Class<?>... classes) { <add> public Builder register(Serializer<?> serializer, final Class<?>... classes) { <ide> types.add(Pair.of(classes, checkNotNull(serializer))); <ide> return this; <ide> } <ide> * @return this <ide> */ <ide> public Builder register(final KryoNamespace ns) { <add> <ide> if (blocks.containsAll(ns.registeredBlocks)) { <ide> // Everything was already registered. <ide> log.debug("Ignoring {}, already registered.", ns); <ide> } <ide> <ide> /** <add> * Sets whether backwards/forwards compatible versioned serialization is enabled. <add> * <p> <add> * When compatible serialization is enabled, the {@link CompatibleFieldSerializer} will be set as the <add> * default serializer for types that do not otherwise explicitly specify a serializer. <add> * <add> * @param compatible whether versioned serialization is enabled <add> * @return this <add> */ <add> public Builder setCompatible(boolean compatible) { <add> this.compatible = compatible; <add> return this; <add> } <add> <add> /** <ide> * Sets the registrationRequired flag. <ide> * <ide> * @param registrationRequired Kryo's registrationRequired flag <ide> * Creates a Kryo instance pool. <ide> * <ide> * @param registeredTypes types to register <del> * @param registrationRequired <add> * @param registrationRequired whether registration is required <add> * @param compatible whether compatible serialization is enabled <ide> * @param friendlyName friendly name for the namespace <ide> */ <ide> private KryoNamespace(final List<RegistrationBlock> registeredTypes, <ide> boolean registrationRequired, <add> boolean compatible, <ide> String friendlyName) { <ide> this.registeredBlocks = ImmutableList.copyOf(registeredTypes); <ide> this.registrationRequired = registrationRequired; <add> this.compatible = compatible; <ide> this.friendlyName = checkNotNull(friendlyName); <ide> } <ide> <ide> * @return this <ide> */ <ide> public KryoNamespace populate(int instances) { <add> <ide> for (int i = 0; i < instances; ++i) { <ide> release(create()); <ide> } <ide> return this; <add> } <add> <add> /** <add> * Serializes given object to byte array using Kryo instance in pool. <add> * <p> <add> * Note: Serialized bytes must be smaller than {@link #MAX_BUFFER_SIZE}. <add> * <add> * @param obj Object to serialize <add> * @return serialized bytes <add> */ <add> public byte[] serialize(final Object obj) { <add> return serialize(obj, DEFAULT_BUFFER_SIZE); <ide> } <ide> <ide> /** <ide> * @return serialized bytes <ide> */ <ide> public byte[] serialize(final Object obj, final int bufferSize) { <del> Output out = new Output(bufferSize, MAX_BUFFER_SIZE); <add> ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bufferSize); <add> Output out = new Output(outputStream); <ide> return pool.run(kryo -> { <ide> kryo.writeClassAndObject(out, obj); <ide> out.flush(); <del> return out.toBytes(); <add> return outputStream.toByteArray(); <ide> }); <ide> } <ide> <ide> /** <ide> * Serializes given object to OutputStream using Kryo instance in pool. <ide> * <add> * @param obj Object to serialize <add> * @param stream to write to <add> */ <add> public void serialize(final Object obj, final OutputStream stream) { <add> serialize(obj, stream, DEFAULT_BUFFER_SIZE); <add> } <add> <add> /** <add> * Serializes given object to OutputStream using Kryo instance in pool. <add> * <ide> * @param obj Object to serialize <ide> * @param stream to write to <ide> * @param bufferSize size of the buffer in front of the stream <ide> * @return deserialized Object <ide> */ <ide> public <T> T deserialize(final byte[] bytes) { <del> Input in = new Input(bytes); <add> Input in = new Input(new ByteArrayInputStream(bytes)); <ide> Kryo kryo = borrow(); <ide> try { <ide> @SuppressWarnings("unchecked") <ide> /** <ide> * Deserializes given InputStream to an Object using Kryo instance in pool. <ide> * <add> * @param stream input stream <add> * @param <T> deserialized Object type <add> * @return deserialized Object <add> */ <add> public <T> T deserialize(final InputStream stream) { <add> return deserialize(stream, DEFAULT_BUFFER_SIZE); <add> } <add> <add> /** <add> * Deserializes given InputStream to an Object using Kryo instance in pool. <add> * <ide> * @param stream input stream <ide> * @param <T> deserialized Object type <ide> * @param bufferSize size of the buffer in front of the stream <ide> Kryo kryo = new Kryo(); <ide> kryo.setRegistrationRequired(registrationRequired); <ide> <add> // If compatible serialization is enabled, override the default serializer. <add> if (compatible) { <add> kryo.setDefaultSerializer(CompatibleFieldSerializer::new); <add> } <add> <ide> // TODO rethink whether we want to use StdInstantiatorStrategy <ide> kryo.setInstantiatorStrategy( <ide> new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy())); <ide> if (id == FLOATING_ID) { <ide> id = kryo.getNextRegistrationId(); <ide> } <del> for (Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>> entry : block.types()) { <add> for (Pair<Class<?>[], Serializer<?>> entry : block.types()) { <ide> register(kryo, entry.getLeft(), entry.getRight(), id++); <ide> } <ide> } <ide> * @param serializer Specific serializer to register or null to use default. <ide> * @param id type registration id to use <ide> */ <del> private void register(Kryo kryo, Class<?>[] types, com.esotericsoftware.kryo.Serializer<?> serializer, int id) { <add> private void register(Kryo kryo, Class<?>[] types, Serializer<?> serializer, int id) { <ide> Registration existing = kryo.getRegistration(id); <ide> if (existing != null) { <ide> boolean matches = false; <ide> r = kryo.register(type, serializer, id); <ide> } <ide> if (r.getId() != id) { <del> log.warn("{}: {} already registed as {}. Skipping {}.", <add> log.debug("{}: {} already registered as {}. Skipping {}.", <ide> friendlyName(), r.getType(), r.getId(), id); <ide> } <ide> log.trace("{} registered as {}", r.getType(), r.getId()); <ide> <ide> static final class RegistrationBlock { <ide> private final int begin; <del> private final ImmutableList<Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>>> types; <del> <del> public RegistrationBlock(int begin, List<Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>>> types) { <add> private final ImmutableList<Pair<Class<?>[], Serializer<?>>> types; <add> <add> public RegistrationBlock(int begin, List<Pair<Class<?>[], Serializer<?>>> types) { <ide> this.begin = begin; <ide> this.types = ImmutableList.copyOf(types); <ide> } <ide> return begin; <ide> } <ide> <del> public ImmutableList<Pair<Class<?>[], com.esotericsoftware.kryo.Serializer<?>>> types() { <add> public ImmutableList<Pair<Class<?>[], Serializer<?>>> types() { <ide> return types; <ide> } <ide>
Java
mit
6b6f6d6e0d8baf73d4c65abb19f3bc8dd6899f6f
0
Sylvain-Bugat/standalone-jetty-war-skeleton,Sylvain-Bugat/standalone-jetty-war-skeleton,Sylvain-Bugat/standalone-jetty-war-skeleton
package com.github.sbugat.samplewebapp; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Sample class of a web-app servlet * * @author Sylvain Bugat */ @WebServlet("/redirect") public class SampleWebapp extends HttpServlet { private static final long serialVersionUID = 1997452078400181160L; @Override protected void doGet(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException { System.out.println("SampleWebapp class: doGet method called on:" + httpServletRequest.getRequestURI()); String argumentValue = httpServletRequest.getParameter("argument"); if (null == argumentValue || argumentValue.isEmpty()) { argumentValue = "redirect"; } // Forward all get request to test-el.jsp page with the argument value or redirect by default httpServletRequest.setAttribute("requestedURI", httpServletRequest.getRequestURI()); httpServletRequest.getRequestDispatcher("/test-el.jsp?argument=" + argumentValue).forward(httpServletRequest, httpServletResponse); } }
src/main/java/com/github/sbugat/samplewebapp/SampleWebapp.java
package com.github.sbugat.samplewebapp; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Sample class of a web-app servlet * * @author Sylvain Bugat */ @WebServlet("/redirect") public class SampleWebapp extends HttpServlet { private static final long serialVersionUID = 1997452078400181160L; @Override protected void doGet(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException { System.out.println("SampleWebapp class: doGet method called on:" + httpServletRequest.getRequestURI()); httpServletRequest.setAttribute("requestedURI", httpServletRequest.getRequestURI()); // Redirect all get request to index.jsp page httpServletRequest.getRequestDispatcher("/index.html").forward(httpServletRequest, httpServletResponse); } }
Change sample webapp
src/main/java/com/github/sbugat/samplewebapp/SampleWebapp.java
Change sample webapp
<ide><path>rc/main/java/com/github/sbugat/samplewebapp/SampleWebapp.java <ide> protected void doGet(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException { <ide> <ide> System.out.println("SampleWebapp class: doGet method called on:" + httpServletRequest.getRequestURI()); <add> String argumentValue = httpServletRequest.getParameter("argument"); <add> if (null == argumentValue || argumentValue.isEmpty()) { <add> argumentValue = "redirect"; <add> } <add> <add> // Forward all get request to test-el.jsp page with the argument value or redirect by default <ide> httpServletRequest.setAttribute("requestedURI", httpServletRequest.getRequestURI()); <del> // Redirect all get request to index.jsp page <del> httpServletRequest.getRequestDispatcher("/index.html").forward(httpServletRequest, httpServletResponse); <add> httpServletRequest.getRequestDispatcher("/test-el.jsp?argument=" + argumentValue).forward(httpServletRequest, httpServletResponse); <ide> } <ide> }
Java
mit
888c50b7194972b489b57fb2e368d216be529ffb
0
romelo333/notenoughwands1.8.8
package romelo333.notenoughwands.blocks; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.opengl.GL11; import romelo333.notenoughwands.ModRenderers; import romelo333.notenoughwands.NotEnoughWands; @SideOnly(Side.CLIENT) public class LightRenderer extends TileEntitySpecialRenderer { ResourceLocation texture = new ResourceLocation(NotEnoughWands.MODID.toLowerCase(), "textures/blocks/light.png"); @Override public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float time, int destroyStage) { bindTexture(texture); GlStateManager.pushMatrix(); GlStateManager.enableRescaleNormal(); GlStateManager.color(1.0f, 1.0f, 1.0f); GlStateManager.enableBlend(); GlStateManager.translate((float) x + 0.5F, (float) y + 0.5F, (float) z + 0.5F); GlStateManager.blendFunc(GL11.GL_ONE, GL11.GL_ONE); long t = System.currentTimeMillis() % 6; ModRenderers.renderBillboardQuad(0.6f, t * (1.0f / 6.0f), (1.0f / 6.0f)); GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GlStateManager.popMatrix(); } }
src/main/java/romelo333/notenoughwands/blocks/LightRenderer.java
package romelo333.notenoughwands.blocks; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.opengl.GL11; import romelo333.notenoughwands.ModRenderers; import romelo333.notenoughwands.NotEnoughWands; @SideOnly(Side.CLIENT) public class LightRenderer extends TileEntitySpecialRenderer { ResourceLocation texture = new ResourceLocation(NotEnoughWands.MODID.toLowerCase(), "textures/blocks/light.png"); @Override public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float time, int destroyStage) { bindTexture(texture); GlStateManager.pushMatrix(); GlStateManager.enableRescaleNormal(); GlStateManager.color(1.0f, 1.0f, 1.0f); GlStateManager.enableBlend(); GlStateManager.translate((float) x + 0.5F, (float) y + 0.5F, (float) z + 0.5F); GlStateManager.blendFunc(GL11.GL_ONE, GL11.GL_ONE); long t = System.currentTimeMillis() % 6; ModRenderers.renderBillboardQuad(0.6f, t * (1.0f / 6.0f), (1.0f / 6.0f)); GlStateManager.popMatrix(); } }
Fixed potential GL state bleeding with the illumination orb
src/main/java/romelo333/notenoughwands/blocks/LightRenderer.java
Fixed potential GL state bleeding with the illumination orb
<ide><path>rc/main/java/romelo333/notenoughwands/blocks/LightRenderer.java <ide> long t = System.currentTimeMillis() % 6; <ide> ModRenderers.renderBillboardQuad(0.6f, t * (1.0f / 6.0f), (1.0f / 6.0f)); <ide> <add> GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); <ide> GlStateManager.popMatrix(); <ide> } <ide> }
Java
apache-2.0
663ae343869df8fb116f891818552419e12d6e32
0
suninformation/ymate-platform-v2,suninformation/ymate-platform-v2
/* * Copyright 2007-2107 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.platform.core.util; import com.esotericsoftware.reflectasm.MethodAccess; import com.thoughtworks.paranamer.AdaptiveParanamer; import net.ymate.platform.core.lang.PairObject; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.net.URL; import java.net.URLClassLoader; import java.util.*; /** * <p> * ClassUtils * </p> * <p> * 类操作相关工具; * </p> * * @author 刘镇 ([email protected]) * @version 0.0.0 * <table style="border:1px solid gray;"> * <tr> * <th width="100px">版本号</th><th width="100px">动作</th><th * width="100px">修改人</th><th width="100px">修改时间</th> * </tr> * <!-- 以 Table 方式书写修改历史 --> * <tr> * <td>0.0.0</td> * <td>创建类</td> * <td>刘镇</td> * <td>2012-12-5下午6:41:23</td> * </tr> * </table> */ public class ClassUtils { private static final Log _LOG = LogFactory.getLog(ClassUtils.class); private static InnerClassLoader _INNER_CLASS_LOADER = new InnerClassLoader(new URL[]{}, ClassUtils.class.getClassLoader()); public static class InnerClassLoader extends URLClassLoader { public InnerClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); } @Override public void addURL(URL url) { super.addURL(url); } } /** * @return 返回默认类加载器对象 */ public static ClassLoader getDefaultClassLoader() { return _INNER_CLASS_LOADER; } /** * 获得指定名称、限定接口的实现类 * * @param <T> * @param className 实现类名 * @param interfaceClass 限制接口名 * @param callingClass * @return 如果可以得到并且限定于指定实现,那么返回实例,否则为空 */ @SuppressWarnings("unchecked") public static <T> T impl(String className, Class<T> interfaceClass, Class<?> callingClass) { if (StringUtils.isNotBlank(className)) { try { Class<?> implClass = loadClass(className, callingClass); if (interfaceClass == null || interfaceClass.isAssignableFrom(implClass)) { return (T) implClass.newInstance(); } } catch (Exception e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } } return null; } @SuppressWarnings("unchecked") public static <T> T impl(Class<?> implClass, Class<T> interfaceClass) { if (implClass != null) { if (interfaceClass == null || interfaceClass.isAssignableFrom(implClass)) { try { return (T) implClass.newInstance(); } catch (Exception e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } } } return null; } /** * @param className * @param callingClass * @return * @throws ClassNotFoundException */ public static Class<?> loadClass(String className, Class<?> callingClass) throws ClassNotFoundException { Class<?> _targetClass = null; try { _targetClass = Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e) { try { _targetClass = Class.forName(className, false, ClassUtils.class.getClassLoader()); } catch (ClassNotFoundException ex) { try { _targetClass = _INNER_CLASS_LOADER.loadClass(className); } catch (ClassNotFoundException exc) { _targetClass = callingClass.getClassLoader().loadClass(className); } } } return _targetClass; } /** * 判断类clazz是否是superClass类的子类对象 * * @param clazz * @param superClass * @return */ public static boolean isSubclassOf(Class<?> clazz, Class<?> superClass) { boolean _flag = false; do { Class<?> cc = clazz.getSuperclass(); if (cc != null) { if (cc.equals(superClass)) { _flag = true; break; } else { clazz = clazz.getSuperclass(); } } else { break; } } while ((clazz != null && clazz != Object.class)); return _flag; } /** * @param clazz 目标对象 * @param interfaceClass 接口类型 * @return 判断clazz类中是否实现了interfaceClass接口 */ public static boolean isInterfaceOf(Class<?> clazz, Class<?> interfaceClass) { boolean _flag = false; do { for (Class<?> cc : clazz.getInterfaces()) { if (cc.equals(interfaceClass)) { _flag = true; } } clazz = clazz.getSuperclass(); } while (!_flag && (clazz != null && clazz != Object.class)); return _flag; } /** * @param target 目标对象,即可以是Field对象、Method对象或是Class对象 * @param annotationClass 注解类对象 * @return 判断target对象是否存在annotationClass注解 */ public static boolean isAnnotationOf(Object target, Class<? extends Annotation> annotationClass) { if (target instanceof Field) { if (((Field) target).isAnnotationPresent(annotationClass)) { return true; } } else if (target instanceof Method) { if (((Method) target).isAnnotationPresent(annotationClass)) { return true; } } else if (target instanceof Class) { if (((Class<?>) target).isAnnotationPresent(annotationClass)) { return true; } } return false; } /** * @param clazz 类型 * @return 返回类中实现的接口名称集合 */ public static String[] getInterfaceNames(Class<?> clazz) { Class<?>[] interfaces = clazz.getInterfaces(); List<String> names = new ArrayList<String>(); for (Class<?> i : interfaces) { names.add(i.getName()); } return names.toArray(new String[names.size()]); } /** * @param clazz 类对象 * @return 获取泛型的数据类型集合,注:不适用于泛型嵌套, 即泛型里若包含泛型则返回此泛型的RawType类型 */ public static List<Class<?>> getParameterizedTypes(Class<?> clazz) { List<Class<?>> _clazzs = new ArrayList<Class<?>>(); Type _types = clazz.getGenericSuperclass(); if (ParameterizedType.class.isAssignableFrom(_types.getClass())) { for (Type _type : ((ParameterizedType) _types).getActualTypeArguments()) { if (ParameterizedType.class.isAssignableFrom(_type.getClass())) { _clazzs.add((Class<?>) ((ParameterizedType) _type).getRawType()); } else { _clazzs.add((Class<?>) _type); } } } else { _clazzs.add((Class<?>) _types); } return _clazzs; } /** * 获取clazz指定的类对象所有的Field对象(若包含其父类对象,直至其父类为空) * * @param clazz 目标类 * @param parent 是否包含其父类对象 * @return Field对象集合 */ public static List<Field> getFields(Class<?> clazz, boolean parent) { List<Field> fieldList = new ArrayList<Field>(); Class<?> clazzin = clazz; do { if (clazzin == null) { break; } fieldList.addAll(Arrays.asList(clazzin.getDeclaredFields())); if (parent) { clazzin = clazzin.getSuperclass(); } else { clazzin = null; } } while (true); return fieldList; } /** * @param <A> * @param clazz * @param annotationClazz * @return 获取clazz类中成员声明的所有annotationClazz注解 */ public static <A extends Annotation> List<PairObject<Field, A>> getFieldAnnotations(Class<?> clazz, Class<A> annotationClazz) { List<PairObject<Field, A>> _annotations = new ArrayList<PairObject<Field, A>>(); for (Field _field : ClassUtils.getFields(clazz, true)) { A _annotation = _field.getAnnotation(annotationClazz); if (_annotation != null) { _annotations.add(new PairObject<Field, A>(_field, _annotation)); } } return _annotations; } /** * @param clazz * @param annotationClazz * @param <A> * @return 获取clazz类中成员声明的第一个annotationClazz注解 */ public static <A extends Annotation> PairObject<Field, A> getFieldAnnotationFirst(Class<?> clazz, Class<A> annotationClazz) { PairObject<Field, A> _returnAnno = null; for (Field _field : ClassUtils.getFields(clazz, true)) { A _annotation = _field.getAnnotation(annotationClazz); if (_annotation != null) { _returnAnno = new PairObject<Field, A>(_field, _annotation); break; } } return _returnAnno; } /** * @param method * @return 获取方法的参数名 */ public static String[] getMethodParamNames(final Method method) { return new AdaptiveParanamer().lookupParameterNames(method); } /** * @param clazz 数组类型 * @return 返回数组元素类型 */ public static Class<?> getArrayClassType(Class<?> clazz) { try { return Class.forName(StringUtils.substringBetween(clazz.getName(), "[L", ";")); } catch (ClassNotFoundException e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } return null; } /** * @param clazz 目标类型 * @return 创建一个类对象实例,包裹它并赋予其简单对象属性操作能力,可能返回空 */ public static <T> ClassBeanWrapper<T> wrapper(Class<T> clazz) { try { return wrapper(clazz.newInstance()); } catch (Exception e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } return null; } /** * @param target 目标类对象 * @return 包裹它并赋予其简单对象属性操作能力,可能返回空 */ public static <T> ClassBeanWrapper<T> wrapper(T target) { return new ClassBeanWrapper<T>(target); } /** * <p> * ClassBeanWrapper * </p> * <p> * 类对象包裹器,赋予对象简单的属性操作能力; * </p> * * @author 刘镇 ([email protected]) * @version 0.0.0 * <table style="border:1px solid gray;"> * <tr> * <th width="100px">版本号</th><th width="100px">动作</th><th * width="100px">修改人</th><th width="100px">修改时间</th> * </tr> * <!-- 以 Table 方式书写修改历史 --> * <tr> * <td>0.0.0</td> * <td>创建类</td> * <td>刘镇</td> * <td>2012-12-23上午12:46:50</td> * </tr> * </table> */ public static class ClassBeanWrapper<T> { protected static Map<Class<?>, MethodAccess> __methodCache = new WeakHashMap<Class<?>, MethodAccess>(); private T target; private Map<String, Field> _fields; private MethodAccess methodAccess; /** * 构造器 * * @param target */ protected ClassBeanWrapper(T target) { this.target = target; this._fields = new HashMap<String, Field>(); for (Field _field : getFields(target.getClass(), true)/*target.getClass().getDeclaredFields()*/) { if (Modifier.isStatic(_field.getModifiers())) { continue; } this._fields.put(_field.getName(), _field); } // this.methodAccess = __methodCache.get(target.getClass()); if (this.methodAccess == null) { this.methodAccess = MethodAccess.get(target.getClass()); __methodCache.put(target.getClass(), this.methodAccess); } } public T getTarget() { return target; } public Set<String> getFieldNames() { return _fields.keySet(); } public Annotation[] getFieldAnnotations(String fieldName) { return getField(fieldName).getAnnotations(); } public Field getField(String fieldName) { return _fields.get(StringUtils.uncapitalize(fieldName)); } public Class<?> getFieldType(String fieldName) { return getField(fieldName).getType(); } public ClassBeanWrapper<T> setValue(String fieldName, Object value) { methodAccess.invoke(this.target, "set" + StringUtils.capitalize(fieldName), value); return this; } public Object getValue(String fieldName) { return methodAccess.invoke(this.target, "get" + StringUtils.capitalize(fieldName)); } /** * 拷贝当前对象的成员属性值到dist对象 * * @param dist * @param <D> * @return */ public <D> D copy(D dist) { ClassBeanWrapper<D> _wrapDist = wrapper(dist); for (String _fieldName : getFieldNames()) { if (_wrapDist.getFieldNames().contains(_fieldName)) { try { _wrapDist.setValue(_fieldName, getValue(_fieldName)); } catch (Exception e) { } } } return _wrapDist.getTarget(); } } }
ymate-platform-core/src/main/java/net/ymate/platform/core/util/ClassUtils.java
/* * Copyright 2007-2107 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.platform.core.util; import com.esotericsoftware.reflectasm.MethodAccess; import com.thoughtworks.paranamer.AdaptiveParanamer; import net.ymate.platform.core.lang.PairObject; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.net.URL; import java.net.URLClassLoader; import java.util.*; /** * <p> * ClassUtils * </p> * <p> * 类操作相关工具; * </p> * * @author 刘镇 ([email protected]) * @version 0.0.0 * <table style="border:1px solid gray;"> * <tr> * <th width="100px">版本号</th><th width="100px">动作</th><th * width="100px">修改人</th><th width="100px">修改时间</th> * </tr> * <!-- 以 Table 方式书写修改历史 --> * <tr> * <td>0.0.0</td> * <td>创建类</td> * <td>刘镇</td> * <td>2012-12-5下午6:41:23</td> * </tr> * </table> */ public class ClassUtils { private static final Log _LOG = LogFactory.getLog(ClassUtils.class); private static InnerClassLoader _INNER_CLASS_LOADER = new InnerClassLoader(new URL[]{}, ClassUtils.class.getClassLoader()); public static class InnerClassLoader extends URLClassLoader { public InnerClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); } @Override public void addURL(URL url) { super.addURL(url); } } /** * @return 返回默认类加载器对象 */ public static ClassLoader getDefaultClassLoader() { return _INNER_CLASS_LOADER; } /** * 获得指定名称、限定接口的实现类 * * @param <T> * @param className 实现类名 * @param interfaceClass 限制接口名 * @param callingClass * @return 如果可以得到并且限定于指定实现,那么返回实例,否则为空 */ @SuppressWarnings("unchecked") public static <T> T impl(String className, Class<T> interfaceClass, Class<?> callingClass) { if (StringUtils.isNotBlank(className)) { try { Class<?> implClass = loadClass(className, callingClass); if (interfaceClass == null || interfaceClass.isAssignableFrom(implClass)) { return (T) implClass.newInstance(); } } catch (Exception e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } } return null; } @SuppressWarnings("unchecked") public static <T> T impl(Class<?> implClass, Class<T> interfaceClass) { if (implClass != null) { if (interfaceClass == null || interfaceClass.isAssignableFrom(implClass)) { try { return (T) implClass.newInstance(); } catch (Exception e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } } } return null; } /** * @param className * @param callingClass * @return * @throws ClassNotFoundException */ public static Class<?> loadClass(String className, Class<?> callingClass) throws ClassNotFoundException { Class<?> _targetClass = null; try { _targetClass = Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e) { try { _targetClass = Class.forName(className, false, ClassUtils.class.getClassLoader()); } catch (ClassNotFoundException ex) { try { _targetClass = _INNER_CLASS_LOADER.loadClass(className); } catch (ClassNotFoundException exc) { _targetClass = callingClass.getClassLoader().loadClass(className); } } } return _targetClass; } /** * 判断类clazz是否是superClass类的子类对象 * * @param clazz * @param superClass * @return */ public static boolean isSubclassOf(Class<?> clazz, Class<?> superClass) { boolean _flag = false; do { Class<?> cc = clazz.getSuperclass(); if (cc != null) { if (cc.equals(superClass)) { _flag = true; break; } else { clazz = clazz.getSuperclass(); } } else { break; } } while ((clazz != null && clazz != Object.class)); return _flag; } /** * @param clazz 目标对象 * @param interfaceClass 接口类型 * @return 判断clazz类中是否实现了interfaceClass接口 */ public static boolean isInterfaceOf(Class<?> clazz, Class<?> interfaceClass) { boolean _flag = false; do { for (Class<?> cc : clazz.getInterfaces()) { if (cc.equals(interfaceClass)) { _flag = true; } } clazz = clazz.getSuperclass(); } while (!_flag && (clazz != null && clazz != Object.class)); return _flag; } /** * @param target 目标对象,即可以是Field对象、Method对象或是Class对象 * @param annotationClass 注解类对象 * @return 判断target对象是否存在annotationClass注解 */ public static boolean isAnnotationOf(Object target, Class<? extends Annotation> annotationClass) { if (target instanceof Field) { if (((Field) target).isAnnotationPresent(annotationClass)) { return true; } } else if (target instanceof Method) { if (((Method) target).isAnnotationPresent(annotationClass)) { return true; } } else if (target instanceof Class) { if (((Class<?>) target).isAnnotationPresent(annotationClass)) { return true; } } return false; } /** * @param clazz 类型 * @return 返回类中实现的接口名称集合 */ public static String[] getInterfaceNames(Class<?> clazz) { Class<?>[] interfaces = clazz.getInterfaces(); List<String> names = new ArrayList<String>(); for (Class<?> i : interfaces) { names.add(i.getName()); } return names.toArray(new String[names.size()]); } /** * @param clazz 类对象 * @return 获取泛型的数据类型集合,注:不适用于泛型嵌套, 即泛型里若包含泛型则返回此泛型的RawType类型 */ public static List<Class<?>> getParameterizedTypes(Class<?> clazz) { List<Class<?>> _clazzs = new ArrayList<Class<?>>(); Type _types = clazz.getGenericSuperclass(); if (ParameterizedType.class.isAssignableFrom(_types.getClass())) { for (Type _type : ((ParameterizedType) _types).getActualTypeArguments()) { if (ParameterizedType.class.isAssignableFrom(_type.getClass())) { _clazzs.add((Class<?>) ((ParameterizedType) _type).getRawType()); } else { _clazzs.add((Class<?>) _type); } } } else { _clazzs.add((Class<?>) _types); } return _clazzs; } /** * 获取clazz指定的类对象所有的Field对象(若包含其父类对象,直至其父类为空) * * @param clazz 目标类 * @param parent 是否包含其父类对象 * @return Field对象集合 */ public static List<Field> getFields(Class<?> clazz, boolean parent) { List<Field> fieldList = new ArrayList<Field>(); Class<?> clazzin = clazz; do { if (clazzin == null) { break; } fieldList.addAll(Arrays.asList(clazzin.getDeclaredFields())); if (parent) { clazzin = clazzin.getSuperclass(); } else { clazzin = null; } } while (true); return fieldList; } /** * @param <A> * @param clazz * @param annotationClazz * @param onlyFirst * @return 获取clazz类中成员声明的annotationClazz注解 */ public static <A extends Annotation> List<PairObject<Field, A>> getFieldAnnotations(Class<?> clazz, Class<A> annotationClazz, boolean onlyFirst) { List<PairObject<Field, A>> _annotations = new ArrayList<PairObject<Field, A>>(); for (Field _field : ClassUtils.getFields(clazz, true)) { A _annotation = _field.getAnnotation(annotationClazz); if (_annotation != null) { _annotations.add(new PairObject<Field, A>(_field, _annotation)); if (onlyFirst) { break; } } } return _annotations; } /** * @param method * @return 获取方法的参数名 */ public static String[] getMethodParamNames(final Method method) { return new AdaptiveParanamer().lookupParameterNames(method); } /** * @param clazz 数组类型 * @return 返回数组元素类型 */ public static Class<?> getArrayClassType(Class<?> clazz) { try { return Class.forName(StringUtils.substringBetween(clazz.getName(), "[L", ";")); } catch (ClassNotFoundException e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } return null; } /** * @param clazz 目标类型 * @return 创建一个类对象实例,包裹它并赋予其简单对象属性操作能力,可能返回空 */ public static <T> ClassBeanWrapper<T> wrapper(Class<T> clazz) { try { return wrapper(clazz.newInstance()); } catch (Exception e) { _LOG.warn("", RuntimeUtils.unwrapThrow(e)); } return null; } /** * @param target 目标类对象 * @return 包裹它并赋予其简单对象属性操作能力,可能返回空 */ public static <T> ClassBeanWrapper<T> wrapper(T target) { return new ClassBeanWrapper<T>(target); } /** * <p> * ClassBeanWrapper * </p> * <p> * 类对象包裹器,赋予对象简单的属性操作能力; * </p> * * @author 刘镇 ([email protected]) * @version 0.0.0 * <table style="border:1px solid gray;"> * <tr> * <th width="100px">版本号</th><th width="100px">动作</th><th * width="100px">修改人</th><th width="100px">修改时间</th> * </tr> * <!-- 以 Table 方式书写修改历史 --> * <tr> * <td>0.0.0</td> * <td>创建类</td> * <td>刘镇</td> * <td>2012-12-23上午12:46:50</td> * </tr> * </table> */ public static class ClassBeanWrapper<T> { protected static Map<Class<?>, MethodAccess> __methodCache = new WeakHashMap<Class<?>, MethodAccess>(); private T target; private Map<String, Field> _fields; private MethodAccess methodAccess; /** * 构造器 * * @param target */ protected ClassBeanWrapper(T target) { this.target = target; this._fields = new HashMap<String, Field>(); for (Field _field : getFields(target.getClass(), true)/*target.getClass().getDeclaredFields()*/) { if (Modifier.isStatic(_field.getModifiers())) { continue; } this._fields.put(_field.getName(), _field); } // this.methodAccess = __methodCache.get(target.getClass()); if (this.methodAccess == null) { this.methodAccess = MethodAccess.get(target.getClass()); __methodCache.put(target.getClass(), this.methodAccess); } } public T getTarget() { return target; } public Set<String> getFieldNames() { return _fields.keySet(); } public Annotation[] getFieldAnnotations(String fieldName) { return getField(fieldName).getAnnotations(); } public Field getField(String fieldName) { return _fields.get(StringUtils.uncapitalize(fieldName)); } public Class<?> getFieldType(String fieldName) { return getField(fieldName).getType(); } public ClassBeanWrapper<T> setValue(String fieldName, Object value) { methodAccess.invoke(this.target, "set" + StringUtils.capitalize(fieldName), value); return this; } public Object getValue(String fieldName) { return methodAccess.invoke(this.target, "get" + StringUtils.capitalize(fieldName)); } /** * 拷贝当前对象的成员属性值到dist对象 * * @param dist * @param <D> * @return */ public <D> D copy(D dist) { ClassBeanWrapper<D> _wrapDist = wrapper(dist); for (String _fieldName : getFieldNames()) { if (_wrapDist.getFieldNames().contains(_fieldName)) { try { _wrapDist.setValue(_fieldName, getValue(_fieldName)); } catch (Exception e) { } } } return _wrapDist.getTarget(); } } }
将getFieldAnnotations方法拆分并增加getFieldAnnotationFirst方法
ymate-platform-core/src/main/java/net/ymate/platform/core/util/ClassUtils.java
将getFieldAnnotations方法拆分并增加getFieldAnnotationFirst方法
<ide><path>mate-platform-core/src/main/java/net/ymate/platform/core/util/ClassUtils.java <ide> * @param <A> <ide> * @param clazz <ide> * @param annotationClazz <del> * @param onlyFirst <del> * @return 获取clazz类中成员声明的annotationClazz注解 <del> */ <del> public static <A extends Annotation> List<PairObject<Field, A>> getFieldAnnotations(Class<?> clazz, Class<A> annotationClazz, boolean onlyFirst) { <add> * @return 获取clazz类中成员声明的所有annotationClazz注解 <add> */ <add> public static <A extends Annotation> List<PairObject<Field, A>> getFieldAnnotations(Class<?> clazz, Class<A> annotationClazz) { <ide> List<PairObject<Field, A>> _annotations = new ArrayList<PairObject<Field, A>>(); <ide> for (Field _field : ClassUtils.getFields(clazz, true)) { <ide> A _annotation = _field.getAnnotation(annotationClazz); <ide> if (_annotation != null) { <ide> _annotations.add(new PairObject<Field, A>(_field, _annotation)); <del> if (onlyFirst) { <del> break; <del> } <ide> } <ide> } <ide> return _annotations; <add> } <add> <add> /** <add> * @param clazz <add> * @param annotationClazz <add> * @param <A> <add> * @return 获取clazz类中成员声明的第一个annotationClazz注解 <add> */ <add> public static <A extends Annotation> PairObject<Field, A> getFieldAnnotationFirst(Class<?> clazz, Class<A> annotationClazz) { <add> PairObject<Field, A> _returnAnno = null; <add> for (Field _field : ClassUtils.getFields(clazz, true)) { <add> A _annotation = _field.getAnnotation(annotationClazz); <add> if (_annotation != null) { <add> _returnAnno = new PairObject<Field, A>(_field, _annotation); <add> break; <add> } <add> } <add> return _returnAnno; <ide> } <ide> <ide> /**
JavaScript
mit
fa74171fca7bd727a2089a9a018933b3a805926f
0
WebJamApps/combined-front,WebJamApps/combined-front
import React from 'react'; import ReactDOM from 'react-dom'; import TimeInput from 'material-ui-time-picker'; import { noView, customElement, bindable, inject } from 'aurelia-framework'; @noView() @inject(Element) @bindable('data') @bindable('type') @customElement('time-picker') export class TimePicker { constructor(element) { this.element = element; this.updateTime = this.updateTime.bind(this); this.el = null; this.picker = null; this.showTimer = this.showTimer.bind(this); } get component() { return ( <div> <div style={{ display: 'none' }}><TimeInput ref={(el) => { this.picker = el; }} mode="12h" onChange={this.updateTime} /></div> <section ref={(el) => { this.el = el; }} style={{ border: '1px solid #ccc', color: '#fff', padding: '1px 5px', width: '83%', margin: 0, outline: 0, textAlign: 'left', cursor: 'text' }} onClick={this.showTimer} onKeyDown={() => {}} role="presentation" >{this.type === 'start' ? '8:00 am' : '5:00 pm'} </section> </div> ); } showTimer() { const el = this.type === 'start' ? document.querySelector('#start input') : document.querySelector('#end input'); el.click(); } render() { ReactDOM.render(this.component, this.element); } updateTime(time) { const a = time.getHours(); const b = time.getMinutes(); const zone = a > 11 && a !== 0 ? 'pm' : 'am'; const offset = a > 12 && a !== 0 ? a % 12 : a === 0 ? 12 : a; this.data = `${offset}:${b < 10 ? `0${b}` : b} ${zone}`; this.el.style.color = '#000'; this.el.innerText = this.data; } bind() { this.render(); } }
src/components/time-picker.js
import React from 'react'; import ReactDOM from 'react-dom'; import TimeInput from 'material-ui-time-picker'; import { noView, customElement, bindable, inject } from 'aurelia-framework'; @noView() @inject(Element) @bindable('data') @bindable('type') @customElement('time-picker') export class TimePicker { constructor(element) { this.element = element; this.updateTime = this.updateTime.bind(this); this.el = null; this.picker = null; this.showTimer = this.showTimer.bind(this); } get component() { return ( <div> <div style={{ display: 'none' }}><TimeInput ref={(el) => { this.picker = el; }} mode="12h" onChange={this.updateTime} /></div> <section ref={(el) => { this.el = el; }} style={{ border: '1px solid #ccc', color: '#fff', padding: '1px 5px', width: '83%', margin: 0, outline: 0, textAlign: 'left', cursor: 'text' }} onClick={this.showTimer} >{this.type === 'start' ? '8:00 am' : '5:00 pm'} </section> </div> ); } showTimer() { const el = this.type === 'start' ? document.querySelector('#start input') : document.querySelector('#end input'); el.click(); } render() { ReactDOM.render(this.component, this.element); } updateTime(time) { const a = time.getHours(); const b = time.getMinutes(); const zone = a > 11 && a !== 0 ? 'pm' : 'am'; const offset = a > 12 && a !== 0 ? a % 12 : a === 0 ? 12 : a; this.data = `${offset}:${b < 10 ? `0${b}` : b} ${zone}`; this.el.style.color = '#000'; this.el.innerText = this.data; } bind() { this.render(); } }
added key event for element with click event handler and static html element has a role of presentation.
src/components/time-picker.js
added key event for element with click event handler and static html element has a role of presentation.
<ide><path>rc/components/time-picker.js <ide> border: '1px solid #ccc', color: '#fff', padding: '1px 5px', width: '83%', margin: 0, outline: 0, textAlign: 'left', cursor: 'text' <ide> }} <ide> onClick={this.showTimer} <add> onKeyDown={() => {}} <add> role="presentation" <ide> >{this.type === 'start' ? '8:00 am' : '5:00 pm'} <ide> </section> <ide> </div>
Java
apache-2.0
c2e51e8c08548d6548a101cd7ccedb14e086e88f
0
tectronics/scalaris,tectronics/scalaris,digshock/scalaris,seyyed/scalaris,tectronics/scalaris,tectronics/scalaris,tectronics/scalaris,digshock/scalaris,digshock/scalaris,tectronics/scalaris,digshock/scalaris,seyyed/scalaris,seyyed/scalaris,seyyed/scalaris,digshock/scalaris,digshock/scalaris,tectronics/scalaris,seyyed/scalaris,seyyed/scalaris,digshock/scalaris,seyyed/scalaris
/** * Copyright 2011 Zuse Institute Berlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.zib.scalaris.examples.wikipedia.data.xml; import java.io.FileNotFoundException; import java.util.Calendar; import java.util.List; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import com.almworks.sqlite4java.SQLiteConnection; import com.almworks.sqlite4java.SQLiteException; import com.almworks.sqlite4java.SQLiteStatement; import de.zib.scalaris.examples.wikipedia.SQLiteDataHandler; import de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel; import de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel.NormalisedTitle; import de.zib.scalaris.examples.wikipedia.data.Page; import de.zib.scalaris.examples.wikipedia.data.Revision; import de.zib.scalaris.examples.wikipedia.data.SiteInfo; /** * Provides abilities to read an xml wiki dump file and write its contents into * a local SQLite db. * * @author Nico Kruber, [email protected] */ public class WikiDumpXml2SQLite extends WikiDumpHandler { protected SQLiteConnection db = null; protected SQLiteStatement stWritePage = null; protected SQLiteStatement stWriteRevision = null; protected SQLiteStatement stWriteText = null; final protected String dbFileName; protected long nextPageId = 0l; protected ArrayBlockingQueue<SQLiteJob> sqliteJobs = new ArrayBlockingQueue<SQLiteJob>(10); SQLiteWorker sqliteWorker = new SQLiteWorker(); private SiteInfo siteInfo = null; /** * Sets up a SAX XmlHandler exporting all parsed pages except the ones in a * blacklist to Scalaris but with an additional pre-process phase. * * @param blacklist * a number of page titles to ignore * @param whitelist * only import these pages * @param maxRevisions * maximum number of revisions per page (starting with the most * recent) - <tt>-1/tt> imports all revisions * (useful to speed up the import / reduce the DB size) * @param minTime * minimum time a revision should have (only one revision older * than this will be imported) - <tt>null/tt> imports all * revisions * @param maxTime * maximum time a revision should have (newer revisions are * omitted) - <tt>null/tt> imports all revisions * (useful to create dumps of a wiki at a specific point in time) * @param dbFileName * the name of the database file to write to * * @throws RuntimeException * if the connection to Scalaris fails */ public WikiDumpXml2SQLite(Set<String> blacklist, Set<String> whitelist, int maxRevisions, Calendar minTime, Calendar maxTime, String dbFileName) throws RuntimeException { super(blacklist, whitelist, maxRevisions, minTime, maxTime); this.dbFileName = dbFileName; } protected void addSQLiteJob(SQLiteJob job) throws RuntimeException { try { sqliteJobs.put(job); } catch (InterruptedException e) { throw new RuntimeException(e); } } /* (non-Javadoc) * @see de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpPrepareForScalarisHandler#setUp() */ @Override public void setUp() { super.setUp(); println("Pre-processing pages from XML to SQLite DB..."); sqliteWorker.start(); // wait for worker to initialise the DB and the prepared statements while (!sqliteWorker.initialised) { try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } } /* (non-Javadoc) * @see de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler#tearDown() */ @Override public void tearDown() { super.tearDown(); sqliteWorker.stopWhenQueueEmpty = true; addSQLiteJob(new SQLiteNoOpJob()); // wait for worker to close the DB try { sqliteWorker.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } importEnd(); } /* (non-Javadoc) * @see java.lang.Object#finalize() */ @Override protected void finalize() throws Throwable { super.finalize(); db.dispose(); } @Override protected void export(XmlSiteInfo siteinfo_xml) { this.siteInfo = siteinfo_xml.getSiteInfo(); } /** * Reads the site info object from the given DB. * * @param db * the DB which was previously prepared with this class * * @return a site info object * * @throws RuntimeException */ public static SiteInfo readSiteInfo(SQLiteConnection db) throws RuntimeException { SQLiteStatement stmt = null; try { stmt = db.prepare("SELECT value FROM properties WHERE key == ?"); return WikiDumpPrepareSQLiteForScalarisHandler.readObject2(stmt, "siteinfo").jsonValue(SiteInfo.class); } catch (SQLiteException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { throw new RuntimeException(e); } finally { if (stmt != null) { stmt.dispose(); } } } @Override protected void export(XmlPage page_xml) { ++pageCount; addSQLiteJob(new SQLiteWritePageJob(page_xml.getPage(), page_xml.getRevisions())); } protected class SQLiteWorker extends Thread { boolean stopWhenQueueEmpty = false; boolean initialised = false; @Override public void run() { try { // set up DB: try { // set 1GB cache_size: db = SQLiteDataHandler.openDB(dbFileName, false, 1024l*1024l*1024l); /** * Table storing the siteinfo object. */ db.exec("CREATE TABLE properties(key STRING PRIMARY KEY ASC, value);"); /** * Core of the wiki: each page has an entry here which identifies * it by title and contains some essential metadata. */ final String createPageTable = "CREATE TABLE page (" + "page_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "page_namespace int NOT NULL," + "page_title varchar(255) NOT NULL," + "page_restrictions tinyblob NOT NULL," + "page_is_redirect tinyint unsigned NOT NULL default 0," + "page_latest int unsigned NOT NULL," + "page_len int unsigned NOT NULL" + ");"; db.exec(createPageTable); // create index here as we need it during import: db.exec("CREATE UNIQUE INDEX name_title ON page (page_namespace,page_title);"); /** * Every edit of a page creates also a revision row. * This stores metadata about the revision, and a reference * to the text storage backend. */ final String createRevTable = "CREATE TABLE revision (" + "rev_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "rev_page int unsigned NOT NULL," + "rev_text_id int unsigned NOT NULL," + "rev_comment tinyblob NOT NULL," + "rev_user_text varchar(255) NOT NULL default ''," + "rev_timestamp binary(14) NOT NULL default ''," + "rev_minor_edit tinyint unsigned NOT NULL default 0," + "rev_len int unsigned" + ");"; db.exec(createRevTable); /** * Holds text of individual page revisions. */ final String createTextTable = "CREATE TABLE text (" + "old_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "old_text mediumblob NOT NULL," + "old_flags tinyblob NOT NULL" + ");"; db.exec(createTextTable); stWritePage = db .prepare("INSERT INTO page " + "(page_id, page_namespace, page_title, page_restrictions, page_is_redirect, page_latest, page_len) " + "VALUES (?, ?, ?, ?, ?, ?, ?);"); stWriteRevision = db .prepare("INSERT INTO revision " + "(rev_id, rev_page, rev_text_id, rev_comment, rev_user_text, rev_timestamp, rev_minor_edit, rev_len) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?);"); stWriteText = db.prepare("INSERT INTO text " + "(old_text, old_flags) " + "VALUES (?, 'utf8,gzip')"); } catch (SQLiteException e) { throw new RuntimeException(e); } initialised = true; // take jobs while(!(sqliteJobs.isEmpty() && stopWhenQueueEmpty)) { SQLiteJob job; try { job = sqliteJobs.take(); } catch (InterruptedException e) { throw new RuntimeException(e); } job.run(); } // write siteinfo object last (may not have been initialised at the beginning): SQLiteStatement stmt = null; try { stmt = db.prepare("REPLACE INTO properties (key, value) VALUES (?, ?);"); WikiDumpPrepareSQLiteForScalarisHandler.writeObject(stmt, "siteinfo", siteInfo); } catch (SQLiteException e) { throw new RuntimeException(e); } finally { if (stmt != null) { stmt.dispose(); } } // create indices at last (improves performance) try { db.exec("CREATE INDEX page_len ON page (page_len);"); db.exec("CREATE UNIQUE INDEX rev_page_id ON revision (rev_page, rev_id);"); db.exec("CREATE INDEX rev_timestamp ON revision (rev_timestamp);"); db.exec("CREATE INDEX page_timestamp ON revision (rev_page,rev_timestamp);"); db.exec("CREATE INDEX usertext_timestamp ON revision (rev_user_text,rev_timestamp);"); } catch (SQLiteException e) { throw new RuntimeException(e); } } finally { if (stWritePage != null) { stWritePage.dispose(); } if (stWriteRevision != null) { stWriteRevision.dispose(); } if (stWriteText != null) { stWriteText.dispose(); } if (db != null) { db.dispose(); } initialised = false; } } } protected static interface SQLiteJob { public abstract void run(); } protected static class SQLiteNoOpJob implements SQLiteJob { @Override public void run() { } } protected class SQLiteWritePageJob implements SQLiteJob { Page page; List<Revision> revisions; public SQLiteWritePageJob(Page page, List<Revision> revisions) { this.page = page; this.revisions = revisions; } @Override public void run() { NormalisedTitle normTitle = MyWikiModel.normalisePageTitle(page.getTitle(), wikiModel.getNamespace()); // check if page exists: try { final SQLiteStatement stmt = db.prepare("SELECT page_id FROM page WHERE page_namespace == ? AND page_title = ?;"); stmt.bind(1, normTitle.namespace).bind(2, normTitle.title); if (stmt.step()) { // exists System.err.println("duplicate page in dump: " + page.getTitle() + " (=" + normTitle.toString() + ")"); return; } stmt.dispose(); } catch (SQLiteException e) { System.err.println("existance check of " + page.getTitle() + " failed (sqlite error: " + e.toString() + ")"); throw new RuntimeException(e); } String pageRestrictions = Page.restrictionsToString(page.getRestrictions()); final int pageId = page.getId(); try { try { stWritePage.bind(1, pageId).bind(2, normTitle.namespace) .bind(3, normTitle.title).bind(4, pageRestrictions) .bind(5, page.isRedirect() ? 1 : 0) .bind(6, page.getCurRev().getId()) .bind(7, page.getCurRev().unpackedText().getBytes().length); stWritePage.stepThrough(); } finally { stWritePage.reset(); } for (Revision rev : revisions) { int revTextId = -1; try { stWriteText.bind(1, rev.packedText()); stWriteText.stepThrough(); // get the text's ID: final SQLiteStatement stmt = db.prepare("SELECT last_insert_rowid();"); if (stmt.step()) { revTextId = stmt.columnInt(0); } stmt.dispose(); } catch (SQLiteException e) { System.err.println("write of text for " + page.getTitle() + ", rev " + rev.getId() + " failed (sqlite error: " + e.toString() + ")"); throw new RuntimeException(e); } finally { stWriteText.reset(); } try { stWriteRevision.bind(1, rev.getId()).bind(2, pageId) .bind(3, revTextId) .bind(4, rev.getComment()) .bind(5, rev.getContributor().toString()) .bind(6, rev.getTimestamp()) .bind(7, rev.isMinor() ? 1 : 0) .bind(8, rev.unpackedText().getBytes().length); stWriteRevision.stepThrough(); } catch (SQLiteException e) { System.err.println("write of " + page.getTitle() + ", rev " + rev.getId() + " failed (sqlite error: " + e.toString() + ")"); throw new RuntimeException(e); } finally { stWriteRevision.reset(); } } } catch (SQLiteException e) { System.err.println("write of " + page.getTitle() + " failed (sqlite error: " + e.toString() + ")"); throw new RuntimeException(e); } } } }
contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/WikiDumpXml2SQLite.java
/** * Copyright 2011 Zuse Institute Berlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.zib.scalaris.examples.wikipedia.data.xml; import java.io.FileNotFoundException; import java.util.Calendar; import java.util.List; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import com.almworks.sqlite4java.SQLiteConnection; import com.almworks.sqlite4java.SQLiteException; import com.almworks.sqlite4java.SQLiteStatement; import de.zib.scalaris.examples.wikipedia.SQLiteDataHandler; import de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel; import de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel.NormalisedTitle; import de.zib.scalaris.examples.wikipedia.data.Page; import de.zib.scalaris.examples.wikipedia.data.Revision; import de.zib.scalaris.examples.wikipedia.data.SiteInfo; /** * Provides abilities to read an xml wiki dump file and write its contents into * a local SQLite db. * * @author Nico Kruber, [email protected] */ public class WikiDumpXml2SQLite extends WikiDumpHandler { protected SQLiteConnection db = null; protected SQLiteStatement stWritePage = null; protected SQLiteStatement stWriteRevision = null; protected SQLiteStatement stWriteText = null; final protected String dbFileName; protected long nextPageId = 0l; protected ArrayBlockingQueue<SQLiteJob> sqliteJobs = new ArrayBlockingQueue<SQLiteJob>(10); SQLiteWorker sqliteWorker = new SQLiteWorker(); private SiteInfo siteInfo = null; /** * Sets up a SAX XmlHandler exporting all parsed pages except the ones in a * blacklist to Scalaris but with an additional pre-process phase. * * @param blacklist * a number of page titles to ignore * @param whitelist * only import these pages * @param maxRevisions * maximum number of revisions per page (starting with the most * recent) - <tt>-1/tt> imports all revisions * (useful to speed up the import / reduce the DB size) * @param minTime * minimum time a revision should have (only one revision older * than this will be imported) - <tt>null/tt> imports all * revisions * @param maxTime * maximum time a revision should have (newer revisions are * omitted) - <tt>null/tt> imports all revisions * (useful to create dumps of a wiki at a specific point in time) * @param dbFileName * the name of the database file to write to * * @throws RuntimeException * if the connection to Scalaris fails */ public WikiDumpXml2SQLite(Set<String> blacklist, Set<String> whitelist, int maxRevisions, Calendar minTime, Calendar maxTime, String dbFileName) throws RuntimeException { super(blacklist, whitelist, maxRevisions, minTime, maxTime); this.dbFileName = dbFileName; } protected void addSQLiteJob(SQLiteJob job) throws RuntimeException { try { sqliteJobs.put(job); } catch (InterruptedException e) { throw new RuntimeException(e); } } /* (non-Javadoc) * @see de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpPrepareForScalarisHandler#setUp() */ @Override public void setUp() { super.setUp(); println("Pre-processing pages from XML to SQLite DB..."); sqliteWorker.start(); // wait for worker to initialise the DB and the prepared statements while (!sqliteWorker.initialised) { try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } } /* (non-Javadoc) * @see de.zib.scalaris.examples.wikipedia.data.xml.WikiDumpHandler#tearDown() */ @Override public void tearDown() { super.tearDown(); sqliteWorker.stopWhenQueueEmpty = true; addSQLiteJob(new SQLiteNoOpJob()); // wait for worker to close the DB try { sqliteWorker.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } importEnd(); } /* (non-Javadoc) * @see java.lang.Object#finalize() */ @Override protected void finalize() throws Throwable { super.finalize(); db.dispose(); } @Override protected void export(XmlSiteInfo siteinfo_xml) { this.siteInfo = siteinfo_xml.getSiteInfo(); } /** * Reads the site info object from the given DB. * * @param db * the DB which was previously prepared with this class * * @return a site info object * * @throws RuntimeException */ public static SiteInfo readSiteInfo(SQLiteConnection db) throws RuntimeException { SQLiteStatement stmt = null; try { stmt = db.prepare("SELECT value FROM properties WHERE key == ?"); return WikiDumpPrepareSQLiteForScalarisHandler.readObject2(stmt, "siteinfo").jsonValue(SiteInfo.class); } catch (SQLiteException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { throw new RuntimeException(e); } finally { if (stmt != null) { stmt.dispose(); } } } @Override protected void export(XmlPage page_xml) { addSQLiteJob(new SQLiteWritePageJob(page_xml.getPage(), page_xml.getRevisions())); } protected class SQLiteWorker extends Thread { boolean stopWhenQueueEmpty = false; boolean initialised = false; @Override public void run() { try { // set up DB: try { // set 1GB cache_size: db = SQLiteDataHandler.openDB(dbFileName, false, 1024l*1024l*1024l); /** * Table storing the siteinfo object. */ db.exec("CREATE TABLE properties(key STRING PRIMARY KEY ASC, value);"); /** * Core of the wiki: each page has an entry here which identifies * it by title and contains some essential metadata. */ final String createPageTable = "CREATE TABLE page (" + "page_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "page_namespace int NOT NULL," + "page_title varchar(255) NOT NULL," + "page_restrictions tinyblob NOT NULL," + "page_is_redirect tinyint unsigned NOT NULL default 0," + "page_latest int unsigned NOT NULL," + "page_len int unsigned NOT NULL" + ");"; db.exec(createPageTable); // create index here as we need it during import: db.exec("CREATE UNIQUE INDEX name_title ON page (page_namespace,page_title);"); /** * Every edit of a page creates also a revision row. * This stores metadata about the revision, and a reference * to the text storage backend. */ final String createRevTable = "CREATE TABLE revision (" + "rev_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "rev_page int unsigned NOT NULL," + "rev_text_id int unsigned NOT NULL," + "rev_comment tinyblob NOT NULL," + "rev_user_text varchar(255) NOT NULL default ''," + "rev_timestamp binary(14) NOT NULL default ''," + "rev_minor_edit tinyint unsigned NOT NULL default 0," + "rev_len int unsigned" + ");"; db.exec(createRevTable); /** * Holds text of individual page revisions. */ final String createTextTable = "CREATE TABLE text (" + "old_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + "old_text mediumblob NOT NULL," + "old_flags tinyblob NOT NULL" + ");"; db.exec(createTextTable); stWritePage = db .prepare("INSERT INTO page " + "(page_id, page_namespace, page_title, page_restrictions, page_is_redirect, page_latest, page_len) " + "VALUES (?, ?, ?, ?, ?, ?, ?);"); stWriteRevision = db .prepare("INSERT INTO revision " + "(rev_id, rev_page, rev_text_id, rev_comment, rev_user_text, rev_timestamp, rev_minor_edit, rev_len) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?);"); stWriteText = db.prepare("INSERT INTO text " + "(old_text, old_flags) " + "VALUES (?, 'utf8,gzip')"); } catch (SQLiteException e) { throw new RuntimeException(e); } initialised = true; // take jobs while(!(sqliteJobs.isEmpty() && stopWhenQueueEmpty)) { SQLiteJob job; try { job = sqliteJobs.take(); } catch (InterruptedException e) { throw new RuntimeException(e); } job.run(); } // write siteinfo object last (may not have been initialised at the beginning): SQLiteStatement stmt = null; try { stmt = db.prepare("REPLACE INTO properties (key, value) VALUES (?, ?);"); WikiDumpPrepareSQLiteForScalarisHandler.writeObject(stmt, "siteinfo", siteInfo); } catch (SQLiteException e) { throw new RuntimeException(e); } finally { if (stmt != null) { stmt.dispose(); } } // create indices at last (improves performance) try { db.exec("CREATE INDEX page_len ON page (page_len);"); db.exec("CREATE UNIQUE INDEX rev_page_id ON revision (rev_page, rev_id);"); db.exec("CREATE INDEX rev_timestamp ON revision (rev_timestamp);"); db.exec("CREATE INDEX page_timestamp ON revision (rev_page,rev_timestamp);"); db.exec("CREATE INDEX usertext_timestamp ON revision (rev_user_text,rev_timestamp);"); } catch (SQLiteException e) { throw new RuntimeException(e); } } finally { if (stWritePage != null) { stWritePage.dispose(); } if (stWriteRevision != null) { stWriteRevision.dispose(); } if (stWriteText != null) { stWriteText.dispose(); } if (db != null) { db.dispose(); } initialised = false; } } } protected static interface SQLiteJob { public abstract void run(); } protected static class SQLiteNoOpJob implements SQLiteJob { @Override public void run() { } } protected class SQLiteWritePageJob implements SQLiteJob { Page page; List<Revision> revisions; public SQLiteWritePageJob(Page page, List<Revision> revisions) { this.page = page; this.revisions = revisions; } @Override public void run() { NormalisedTitle normTitle = MyWikiModel.normalisePageTitle(page.getTitle(), wikiModel.getNamespace()); // check if page exists: try { final SQLiteStatement stmt = db.prepare("SELECT page_id FROM page WHERE page_namespace == ? AND page_title = ?;"); stmt.bind(1, normTitle.namespace).bind(2, normTitle.title); if (stmt.step()) { // exists return; } stmt.dispose(); } catch (SQLiteException e) { System.err.println("existance check of " + page.getTitle() + " failed (sqlite error: " + e.toString() + ")"); throw new RuntimeException(e); } String pageRestrictions = Page.restrictionsToString(page.getRestrictions()); final int pageId = page.getId(); try { try { stWritePage.bind(1, pageId).bind(2, normTitle.namespace) .bind(3, normTitle.title).bind(4, pageRestrictions) .bind(5, page.isRedirect() ? 1 : 0) .bind(6, page.getCurRev().getId()) .bind(7, page.getCurRev().unpackedText().getBytes().length); stWritePage.stepThrough(); } finally { stWritePage.reset(); } for (Revision rev : revisions) { int revTextId = -1; try { stWriteText.bind(1, rev.packedText()); stWriteText.stepThrough(); // get the text's ID: final SQLiteStatement stmt = db.prepare("SELECT last_insert_rowid();"); if (stmt.step()) { revTextId = stmt.columnInt(0); } stmt.dispose(); } catch (SQLiteException e) { System.err.println("write of text for " + page.getTitle() + ", rev " + rev.getId() + " failed (sqlite error: " + e.toString() + ")"); throw new RuntimeException(e); } finally { stWriteText.reset(); } try { stWriteRevision.bind(1, rev.getId()).bind(2, pageId) .bind(3, revTextId) .bind(4, rev.getComment()) .bind(5, rev.getContributor().toString()) .bind(6, rev.getTimestamp()) .bind(7, rev.isMinor() ? 1 : 0) .bind(8, rev.unpackedText().getBytes().length); stWriteRevision.stepThrough(); } catch (SQLiteException e) { System.err.println("write of " + page.getTitle() + ", rev " + rev.getId() + " failed (sqlite error: " + e.toString() + ")"); throw new RuntimeException(e); } finally { stWriteRevision.reset(); } } } catch (SQLiteException e) { System.err.println("write of " + page.getTitle() + " failed (sqlite error: " + e.toString() + ")"); throw new RuntimeException(e); } } } }
- Wiki on Scalaris, xml2db: * warn if a duplicate was found in the XML dump * properly increase the page count
contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/WikiDumpXml2SQLite.java
- Wiki on Scalaris, xml2db: * warn if a duplicate was found in the XML dump * properly increase the page count
<ide><path>ontrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/data/xml/WikiDumpXml2SQLite.java <ide> <ide> @Override <ide> protected void export(XmlPage page_xml) { <add> ++pageCount; <ide> addSQLiteJob(new SQLiteWritePageJob(page_xml.getPage(), page_xml.getRevisions())); <ide> } <ide> <ide> stmt.bind(1, normTitle.namespace).bind(2, normTitle.title); <ide> if (stmt.step()) { <ide> // exists <add> System.err.println("duplicate page in dump: " <add> + page.getTitle() + " (=" + normTitle.toString() <add> + ")"); <ide> return; <ide> } <ide> stmt.dispose();
JavaScript
mit
98c9569d4907933d96306668534c926fc499d580
0
johhat/boids,johhat/boids
'use strict'; /* global $: true */ /* global animation: true */ /* global boidWeights: true */ //Slider for selecting initial number of boids //--------------------------------------------- $('#numBoidsSlider').slider({ min: 0, max: 400, step: 10, value: animation.numBoids }); $('#numBoidsVal').text(animation.numBoids); $('#numBoidsSlider').on('slide', function (slideEvt) { $('#numBoidsVal').text(slideEvt.value); animation.numBoids = slideEvt.value; }); //Sliders for weights //-------------------- $('#slider1').slider({ min: 0, max: 20, step: 0.1, value: boidWeights.separation }); $('#slider1val').text(boidWeights.separation); $('#slider1').on('slide', function (slideEvt) { $('#slider1val').text(slideEvt.value); boidWeights.separation = slideEvt.value; }); $('#slider2').slider({ min: 0, max: 20, step: 0.1, value: boidWeights.alginment }); $('#slider2').on('slide', function (slideEvt) { $('#slider2val').text(boidWeights.alginment); $('#slider2val').text(slideEvt.value); boidWeights.alginment = slideEvt.value; }); $('#slider3').slider({ min: 0, max: 20, step: 0.1, value: boidWeights.cohesion }); $('#slider3val').text(boidWeights.cohesion); $('#slider3').on('slide', function (slideEvt) { $('#slider3val').text(slideEvt.value); boidWeights.cohesion = slideEvt.value; }); $('#slider4').slider({ min: 0, max: 20, step: 0.1, value: boidWeights.obstacle }); $('#slider4val').text(boidWeights.obstacle); $('#slider4').on('slide', function (slideEvt) { $('#slider4val').text(slideEvt.value); boidWeights.obstacle = slideEvt.value; }); $('#slider5').slider({ min: 0, max: 20, step: 0.1, value: boidWeights.predators }); $('#slider5val').text(boidWeights.predators); $('#slider5').on('slide', function (slideEvt) { $('#slider5val').text(slideEvt.value); boidWeights.predators = slideEvt.value; });
ui-components/ui.js
'use strict'; /* global $: true */ /* global animation: true */ /* global boidWeights: true */ //Slider for selecting initial number of boids //--------------------------------------------- $('#numBoidsSlider').slider({ min: 0, max: 400, step: 10, value: animation.numBoids }); $('#numBoidsVal').text(animation.numBoids); $('#numBoidsSlider').on('slide', function (slideEvt) { $('#numBoidsVal').text(slideEvt.value); animation.numBoids = slideEvt.value; }); //Sliders for weights //-------------------- $('#slider1').slider({ min: 0, max: 20, step: 0.1, value: boidWeights.separation }); $('#slider1val').text(boidWeights.separation); $('#slider1').on('slide', function (slideEvt) { $('#slider1val').text(slideEvt.value); boidWeights.separation = slideEvt.value; }); $('#slider2').slider({ min: 0, max: 20, step: 0.1, value: boidWeights.alginment }); $('#slider2').on('slide', function (slideEvt) { $('#slider2val').text(boidWheights.alginment); $('#slider2val').text(slideEvt.value); boidWeights.alginment = slideEvt.value; }); $('#slider3').slider({ min: 0, max: 20, step: 0.1, value: boidWeights.cohesion }); $('#slider3val').text(boidWeights.cohesion); $('#slider3').on('slide', function (slideEvt) { $('#slider3val').text(slideEvt.value); boidWeights.cohesion = slideEvt.value; }); $('#slider4').slider({ min: 0, max: 20, step: 0.1, value: boidheights.obstacle }); $('#slider4val').text(boidWeights.obstacle); $('#slider4').on('slide', function (slideEvt) { $('#slider4val').text(slideEvt.value); boidWeights.obstacle = slideEvt.value; }); $('#slider5').slider({ min: 0, max: 20, step: 0.1, value: boidWeights.predators }); $('#slider5val').text(boidWeights.predators); $('#slider5').on('slide', function (slideEvt) { $('#slider5val').text(slideEvt.value); boidWeights.predators = slideEvt.value; });
Fixed typo
ui-components/ui.js
Fixed typo
<ide><path>i-components/ui.js <ide> }); <ide> $('#slider2').on('slide', function (slideEvt) { <ide> <del>$('#slider2val').text(boidWheights.alginment); <add>$('#slider2val').text(boidWeights.alginment); <ide> $('#slider2val').text(slideEvt.value); <ide> boidWeights.alginment = slideEvt.value; <ide> }); <ide> min: 0, <ide> max: 20, <ide> step: 0.1, <del> value: boidheights.obstacle <add> value: boidWeights.obstacle <ide> }); <ide> $('#slider4val').text(boidWeights.obstacle); <ide>
Java
unlicense
912cf32d81c311b992206b119a9270bfb985ab9f
0
pagarme/pagarme-java,pagarme/pagarme-java
package me.pagar.model; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.ws.rs.HttpMethod; import org.joda.time.DateTime; import org.joda.time.LocalDate; import com.google.common.base.CaseFormat; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import me.pagar.model.filter.PayableQueriableFields; import me.pagar.util.JSONUtils; public class Transaction extends PagarMeModel<Integer> { @Expose(deserialize = false) private Boolean async; @Expose(deserialize = false) private Boolean capture; /** * Caso essa transação tenha sido originada na cobrança de uma assinatura, o * <code>id</code> desta será o valor dessa propriedade */ @Expose(serialize = false) @SerializedName("subscription_id") private Integer subscriptionId; /** * Valor, em centavos, da transação */ @Expose private Integer amount; /** * Valor refund, em centavos, da transação */ @Expose @SerializedName("refunded_amount") private Integer refundedAmount; /** * Valor autorizado, em centavos, da transação */ @Expose @SerializedName("authorized_amount") private Integer authorizedAmount; /** * Valor pago, em centavos, da transação */ @Expose @SerializedName("paid_amount") private Integer paidAmount; /** * Número de parcelas/prestações a serem cobradas */ @Expose private Integer installments; @Expose(deserialize = false) @SerializedName("card_id") private String cardId; @Expose(deserialize = false) @SerializedName("card_number") private String cardNumber; @Expose(deserialize = false) @SerializedName("card_holder_name") private String cardHolderName; @Expose(deserialize = false) @SerializedName("card_expiration_date") private String cardExpirationDate; @Expose(deserialize = false) @SerializedName("card_cvv") private String cardCvv; @Expose(deserialize = false) @SerializedName("card_emv_data") private String cardEmvData; @Expose @SerializedName("card_emv_response") private String cardEmvResponse; @Expose(deserialize = false) @SerializedName("card_pin_mode") private String cardPinMode; @Expose(deserialize = false) @SerializedName("card_track_1") private String cardTrack1; @Expose(deserialize = false) @SerializedName("card_track_2") private String cardTrack2; @Expose(deserialize = false) @SerializedName("card_track_3") private String cardTrack3; @Expose(deserialize = false) @SerializedName("card_pin") private String cardPin; @Expose(deserialize = false) @SerializedName("card_pin_kek") private String cardPinKek; public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; addUnsavedProperty("cardNumber"); } public String getCardHolderName() { return cardHolderName; } public void setCardHolderName(String cardHolderName) { this.cardHolderName = cardHolderName; addUnsavedProperty("cardHolderName"); } public String getCardExpirationDate() { return cardExpirationDate; } public void setCardExpirationDate(String cardExpirationDate) { this.cardExpirationDate = cardExpirationDate; addUnsavedProperty("cardExpirationDate"); } public String getCardCvv() { return cardCvv; } public void setCardCvv(String cardCvv) { this.cardCvv = cardCvv; addUnsavedProperty("cardCvv"); } public String getCardEmvData() { return cardEmvData; } public void setCardEmvData(String cardEmvData) { this.cardEmvData = cardEmvData; addUnsavedProperty("cardEmvData"); } public String getCardEmvResponse() { return cardEmvResponse; } public void setCardEmvResponse(String cardEmvResponse) { this.cardEmvResponse = cardEmvResponse; addUnsavedProperty("cardEmvResponse"); } public String getCardTrack1() { return cardTrack2; } public void setCardTrack1(String cardTrack1) { this.cardTrack1 = cardTrack1; addUnsavedProperty("cardTrack1"); } public String getCardTrack2() { return cardTrack2; } public void setCardTrack2(String cardTrack2) { this.cardTrack2 = cardTrack2; addUnsavedProperty("cardTrack2"); } public String getCardTrack3() { return cardTrack3; } public void setCardTrack3(String cardTrack3) { this.cardTrack3 = cardTrack3; addUnsavedProperty("cardTrack3"); } public String getCardPinMode() { return cardPinMode; } public void setCardPinMode(String cardPinMode) { this.cardPinMode = cardPinMode; addUnsavedProperty("cardPinMode"); } public String getCardPin() { return cardPin; } public void setCardPin(String cardPin) { this.cardPin = cardPin; addUnsavedProperty("cardPin"); } public String getCardPinKek() { return cardPinKek; } public void setCardPinKek(String cardPinKek) { this.cardPinKek = cardPinKek; addUnsavedProperty("cardPinKek"); } /** * Custo da transação para o lojista */ @Expose(serialize = false) private Integer cost; /** * Mensagem de resposta do adquirente referente ao status da transação. */ @Expose(serialize = false) @SerializedName("acquirer_response_code") private String acquirerResponseCode; /** * Código de autorização retornado pela bandeira. */ @Expose(serialize = false) @SerializedName("authorization_code") private String authorizationCode; /** * Texto que irá aparecer na fatura do cliente depois do nome da loja. * <b>OBS:</b> Limite de 13 caracteres. */ @Expose @SerializedName("soft_descriptor") private String softDescriptor; /** * Código que identifica a transação no adquirente. */ @Expose(serialize = false) private String tid; /** * Código que identifica a transação no adquirente. */ @Expose(serialize = false) private String nsu; /** * URL (endpoint) do sistema integrado a Pagar.me que receberá as respostas * a cada atualização do processamento da transação */ @Expose @SerializedName("postback_url") private String postbackUrl; /** * URL do boleto para impressão */ @Expose(serialize = false) @SerializedName("boleto_url") private String boletoUrl; /** * Código de barras do boleto gerado na transação */ @Expose(serialize = false) @SerializedName("boleto_barcode") private String boletoBarcode; /** * Mostra se a transação foi criada utilizando a API Key ou Encryption Key. */ @Expose(serialize = false) private String referer; /** * Mostra se a transação foi criada utilizando a API Key ou Encryption Key. */ @Expose(serialize = false) private String ip; @Expose(deserialize = false) @SerializedName("card_hash") private String cardHash; /** * Adquirente responsável pelo processamento da transação. */ @Expose(serialize = false) @SerializedName("acquirer_name") private AcquirerName acquirerName; /** * Métodos de pagamento possíveis: <code>credit_card</code>, * <code>boleto</code> e <code>debit_card</code> */ @Expose @SerializedName("payment_method") private PaymentMethod paymentMethod; /** * Métodos de captura possíveis: <code>emv</code>, <code>magstripe</code> e * <code>ecommerce</code> */ @Expose @SerializedName("capture_method") private CaptureMethod captureMethod; /** * Para cada atualização no processamento da transação, esta propriedade * será alterada, e o objeto <code>transaction</code> retornado como * resposta através da sua URL de postback ou após o término do * processamento da ação atual. */ @Expose(serialize = false) private Status status; /** * Motivo/agente responsável pela validação ou anulação da transação. */ @Expose(serialize = false) @SerializedName(value = "status_reason") private StatusReason statusReason; /** * Data de expiração do boleto (em ISODate) */ @Expose(deserialize = false) @SerializedName("boleto_expiration_date") private LocalDate boletoExpirationDate; /** * Data de atualização da transação no formato ISODate */ @Expose(serialize = false) @SerializedName("date_updated") private DateTime updatedAt; /** * Objeto com dados do telefone do cliente */ @Expose(serialize = false) private Phone phone; /** * Objeto com dados do endereço do cliente */ @Expose(serialize = false) private Address address; /** * Objeto com dados do cliente */ @Expose private Customer customer; /** * Objeto com dados do cartão do cliente */ @Expose(serialize = false) private Card card; /** * Objeto com dados adicionais do cliente/produto/serviço vendido */ @Expose private Map<String, Object> metadata; @Expose @SerializedName("antifraud_metadata") private Object antifraudMetadata; @Expose(serialize = false) @SerializedName("event") private Event event; @Expose(serialize = false) @SerializedName("old_status") private Status oldStatus; @Expose(serialize = false) @SerializedName("current_status") private Status currentStatus; @Expose(serialize = false) @SerializedName("desired_status") private Status desiredStatus; @SerializedName("refuse_reason") public String getRefuseReason() { return refuseReason; } @SerializedName("refuse_reason") private String refuseReason; @Expose(serialize = true) @SerializedName("split_rules") private Collection<SplitRule> splitRules; public Transaction() { super(); } /** * <b>OBS:</b> Apenas para transações de <b>cartão de crédito</b> você deve * passar <b>ou</b> o <code>card_hash</code> <b>ou</b> o * <code>card_id</code>. * * @param amount * Valor a ser cobrado. Deve ser passado em centavos. * @param cardHash * Informações do cartão do cliente criptografadas no navegador. * @param cardId * Ao realizar uma transação, retornamos o <code>card_id</code> * do cartão para que nas próximas transações desse cartão possa * ser utilizado esse identificador ao invés do * <code>card_hash</code> * @param customer * Dados do cliente a ser cadastrado */ public Transaction(final Integer amount, final String cardHash, final String cardId, final Customer customer) { this(); this.amount = amount; this.cardHash = cardHash; this.cardId = cardId; this.customer = customer; } public Transaction find(String id) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), id)); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } public Transaction find(Integer id) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), id)); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } public Collection<Transaction> findCollection(int totalPerPage, int page) throws PagarMeException { return JSONUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken<Collection<Transaction>>() { }.getType()); } /** * @return {@link #subscriptionId} */ public Integer getSubscriptionId() { return subscriptionId; } /** * @return {@link #amount} */ public Integer getAmount() { return amount; } /** * @return {@link #refundedAmount} */ public Integer getRefundedAmount() { return refundedAmount; } /** * @return {@link #authorizedAmount} */ public Integer getAuthorizedAmount() { return authorizedAmount; } /** * @return {@link #paidAmount} */ public Integer getPaidAmount() { return paidAmount; } /** * @return {@link #installments} */ public Integer getInstallments() { return installments; } /** * @return {@link #cost} */ public Integer getCost() { return cost; } /** * @return {@link #acquirerResponseCode} */ public String getAcquirerResponseCode() { return acquirerResponseCode; } /** * @return {@link #authorizationCode} */ public String getAuthorizationCode() { return authorizationCode; } /** * @return {@link #softDescriptor} */ public String getSoftDescriptor() { return softDescriptor; } /** * @return {@link #tid} */ public String getTid() { return tid; } /** * @return {@link #nsu} */ public String getNsu() { return nsu; } /** * @return {@link Transaction#postbackUrl} */ public String getPostbackUrl() { return postbackUrl; } public String getBoletoUrl() { return boletoUrl; } /** * @return {@link #boletoBarcode} */ public String getBoletoBarcode() { return boletoBarcode; } /** * @return {@link #referer} */ public String getReferer() { return referer; } /** * @return {@link #ip} */ public String getIp() { return ip; } /** * @return {@link #acquirerName} */ public AcquirerName getAcquirerName() { return acquirerName; } /** * @return {@link #paymentMethod} */ public PaymentMethod getPaymentMethod() { return paymentMethod; } /** * @return {@link #captureMethod} */ public CaptureMethod getCaptureMethod() { return captureMethod; } /** * @return {@link #status} */ public Status getStatus() { return status; } /** * @return {@link #statusReason} */ public StatusReason getStatusReason() { return statusReason; } /** * @return {@link #updatedAt} */ public DateTime getUpdatedAt() { return updatedAt; } /** * @return {@link #metadata} */ public Map<String, Object> getMetadata() { return metadata; } /** * @return {@link #card} */ public Card getCard() { return card; } /** * @return {@link #customer} */ public Customer getCustomer() { return customer; } /** * @return {@link #event} */ public Event getEvent() { return event; } /** * @return {@link #oldStatus} */ public Status getOldStatus() { return oldStatus; } /** * @return {@link #currentStatus} */ public Status getCurrentStatus() { return currentStatus; } /** * @return {@link #desiredStatus} */ public Status getDesiredStatus() { return desiredStatus; } public Object getAntifraudMetadata() { return antifraudMetadata; } public void setAsync(final Boolean async) { this.async = async; addUnsavedProperty("async"); } public void setCapture(final Boolean capture) { this.capture = capture; addUnsavedProperty("capture"); } public void setAmount(final Integer amount) { this.amount = amount; addUnsavedProperty("amount"); } public void setInstallments(final Integer installments) { this.installments = installments; addUnsavedProperty("installments"); } public void setSoftDescriptor(final String softDescriptor) { this.softDescriptor = softDescriptor; addUnsavedProperty("softDescriptor"); } public void setPostbackUrl(final String postbackUrl) { this.postbackUrl = postbackUrl; addUnsavedProperty("postbackUrl"); } public void setCardHash(final String cardHash) { this.cardHash = cardHash; addUnsavedProperty("cardHash"); } public void setPaymentMethod(final PaymentMethod paymentMethod) { this.paymentMethod = paymentMethod; addUnsavedProperty("paymentMethod"); } public void setCaptureMethod(final CaptureMethod captureMethod) { this.captureMethod = captureMethod; addUnsavedProperty("captureMethod"); } public void setCardId(final String cardId) { this.cardId = cardId; addUnsavedProperty("cardId"); } public void setCustomer(final Customer customer) { this.customer = customer; addUnsavedProperty("customer"); } public void setBoletoExpirationDate(final LocalDate boletoExpirationDate) { this.boletoExpirationDate = boletoExpirationDate; addUnsavedProperty("boletoExpirationDate"); } public void setMetadata(final Map<String, Object> metadata) { this.metadata = metadata; addUnsavedProperty("metadata"); } public void setSplitRules(final Collection<SplitRule> splitRules) { this.splitRules = splitRules; if (this.splitRules.size() != 0) { addUnsavedProperty("splitRules"); } } public void setAntifraudMetadata(Object antifraudMetadata) { this.antifraudMetadata = antifraudMetadata; addUnsavedProperty("antifraud_metadata"); } public Collection<SplitRule> getSplitRules() { return splitRules; } public Transaction save() throws PagarMeException { final Transaction saved = super.save(getClass()); copy(saved); return saved; } /** * @see #list(int, int) */ public Collection<Transaction> list() throws PagarMeException { return list(100, 0); } /** * @param totalPerPage * Retorna <code>n</code> objetos de transação * @param page * Útil para implementação de uma paginação de resultados * @return Uma {@link Collection} contendo objetos de transações, ordenadas * a partir da transação realizada mais recentemente. * @throws PagarMeException */ public Collection<Transaction> list(int totalPerPage, int page) throws PagarMeException { return JSONUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken<Collection<Transaction>>() { }.getType()); } /** * Caso você queira/precise criar o card_hash manualmente, essa rota deverá * ser utilizada para obtenção de uma chave pública de encriptação dos dados * do cartão de seu cliente. * * @return Um {@link CardHashKey} * @throws PagarMeException */ public CardHashKey cardHashKey() throws PagarMeException { final String cardHashKeyEndpoint = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, CardHashKey.class.getSimpleName()); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), cardHashKeyEndpoint)); return JSONUtils.getAsObject((JsonObject) request.execute(), CardHashKey.class); } /** * * @param antifraudAnalysisId * @return * @throws PagarMeException */ public AntifraudAnalysis antifraudAnalysis(final Integer antifraudAnalysisId) throws PagarMeException { validateId(); final AntifraudAnalysis antifraudAnalysis = new AntifraudAnalysis(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), getId(), antifraudAnalysis.getClassName(), antifraudAnalysisId)); return JSONUtils.getAsObject((JsonObject) request.execute(), AntifraudAnalysis.class); } /** * Retorna todas as {@link AntifraudAnalysis} realizadas em uma transação. * * @return Lista de {@link AntifraudAnalysis} * @throws PagarMeException */ public Collection<AntifraudAnalysis> antifraudAnalysises() throws PagarMeException { validateId(); final AntifraudAnalysis antifraudAnalysis = new AntifraudAnalysis(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), antifraudAnalysis.getClassName())); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<AntifraudAnalysis>>() { }.getType()); } /** * Retorna um objeto {@link Payable} informando os dados de um pagamento * referente a uma determinada transação. * * @param payableId * ID do {@link Payable} * @return Um {@link Payable} * @throws PagarMeException */ public Payable payables(final Integer payableId) throws PagarMeException { validateId(); final Payable splitRule = new Payable(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), getId(), splitRule.getClassName(), payableId)); return JSONUtils.getAsObject((JsonObject) request.execute(), Payable.class); } /** * Retorna um array com objetos {@link Payable} informando os dados dos * pagamentos referentes a uma transação. * * @return Lista de {@link Payable} * @throws PagarMeException */ public Collection<Payable> payables() throws PagarMeException { validateId(); final Payable payable = new Payable(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), payable.getClassName())); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<Payable>>() { }.getType()); } /** * Retorna um {@link Postback} específico relacionado a transação. * * @param postbackId * ID do {@link Postback} * @return Um {@link Postback} * @throws PagarMeException */ public Postback postbacks(final String postbackId) throws PagarMeException { validateId(); final Postback postback = new Postback(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), getId(), postback.getClassName(), postbackId)); return JSONUtils.getAsObject((JsonObject) request.execute(), Postback.class); } /** * Com essa rota você pode reenviar qualquer {@link Postback} que já foi * enviado de uma transação. Lembrando que caso o envio de um * {@link Postback} falhe ou seu servidor não o receba, nós o retentamos * diversas vezes (com um total de 31 vezes). * * @param postbackId * ID do {@link Postback} * @return Reenviando um {@link Postback} * @throws PagarMeException */ public Postback postbackRedeliver(final String postbackId) throws PagarMeException { validateId(); final Postback postback = new Postback(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/%s/%s/redeliver", getClassName(), getId(), postback.getClassName(), postbackId)); return JSONUtils.getAsObject((JsonObject) request.execute(), Postback.class); } /** * Retorna todos os {@link Postback} enviados relacionados a transação. * * @return Todos os {@link Postback}s * @throws PagarMeException */ public Collection<Postback> postbacks() throws PagarMeException { validateId(); final Postback postback = new Postback(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), postback.getClassName())); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<Postback>>() { }.getType()); } /** * Retorna os dados das {@link SplitRule} do valor transacionado. * * @param splitRuleId * O ID da Regra de Split * @return Retornando uma {@link SplitRule} específica * @throws PagarMeException */ public SplitRule splitRules(final String splitRuleId) throws PagarMeException { validateId(); final SplitRule splitRule = new SplitRule(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), getId(), splitRule.getClassName(), splitRuleId)); return JSONUtils.getAsObject((JsonObject) request.execute(), SplitRule.class); } /** * Retorna os dados de uma {@link SplitRule} de uma determinada transação. * * @return Lista de {@link SplitRule} para a transação * @throws PagarMeException */ public Collection<SplitRule> splitRules() throws PagarMeException { validateId(); final SplitRule splitRule = new SplitRule(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), splitRule.getClassName())); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<SplitRule>>() { }.getType()); } /** * Essa rota é utilizada quando se deseja estornar uma transação, realizada * por uma cobrança via cartão de crédito ou boleto bancário. * <p> * Em caso de estorno de uma transação realizada com cartão de crédito, * apenas o <code>id</code> da transação é necessário para efetivação do * estorno. * <p> * Caso a compra tenha sido feita por boleto bancário, você precisará passar * os dados da conta bancária que irá receber o valor estornado, ou o id * desta conta, que pode ser gerada com o modelo {@link BankAccount}. * * @throws PagarMeException */ public Transaction refund(final Integer amount) throws PagarMeException { validateId(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/refund", getClassName(), getId())); request.getParameters().put("amount", amount); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } public Transaction refund(final BankAccount bankAccount) throws PagarMeException { validateId(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/refund", getClassName(), getId())); Map<String, Object> bankAccountMap = JSONUtils.objectToMap(bankAccount); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("bank_account", bankAccountMap); request.setParameters(parameters); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } /** * Você pode capturar o valor de uma transação após a autorização desta, no * prazo máximo de 5 dias após a autorização. * * @param amount * @return * @throws PagarMeException */ public Transaction capture(final Integer amount) throws PagarMeException { validateId(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/capture", getClassName(), getId())); request.getParameters().put("amount", amount); if (this.getMetadata() != null) request.getParameters().put("metadata", this.getMetadata()); if (this.getSplitRules() != null) request.getParameters().put("split_rules", this.getSplitRules()); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } public Collection<Payable> findPayableCollection(final Integer totalPerPage, Integer page) throws PagarMeException { validateId(); JsonArray responseArray = super.paginateThrough(totalPerPage, page, new PayableQueriableFields()); return JSONUtils.getAsList(responseArray, new TypeToken<Collection<Payable>>() { }.getType()); } public Payable findPayable(Integer payableId) throws PagarMeException { validateId(); Payable payable = new Payable(); payable.setId(payableId); JsonObject responseObject = super.getThrough(payable); return JSONUtils.getAsObject(responseObject, Payable.class); } /** * Atualiza a instância do objeto com os dados mais recentes do backend. * * @return Instância atualizada do Objeto. */ public Transaction refresh() throws PagarMeException { final Transaction other = JSONUtils.getAsObject(refreshModel(), Transaction.class); copy(other); flush(); return other; } private void copy(Transaction other) { super.copy(other); this.subscriptionId = other.subscriptionId; this.amount = other.amount; this.installments = other.installments; this.cost = other.cost; this.status = other.status; this.statusReason = other.statusReason; this.acquirerName = other.acquirerName; this.acquirerResponseCode = other.acquirerResponseCode; this.authorizationCode = other.authorizationCode; this.softDescriptor = other.softDescriptor; this.tid = other.tid; this.nsu = other.nsu; this.postbackUrl = other.postbackUrl; this.paymentMethod = other.paymentMethod; this.boletoUrl = other.boletoUrl; this.boletoBarcode = other.boletoBarcode; this.referer = other.referer; this.ip = other.ip; this.cardId = other.cardId; this.metadata = other.metadata; this.card = other.card; this.paidAmount = other.paidAmount; this.refundedAmount = other.refundedAmount; this.authorizedAmount = other.authorizedAmount; this.refuseReason = other.refuseReason; this.antifraudMetadata = other.antifraudMetadata; this.splitRules = other.splitRules; this.cardEmvResponse = other.cardEmvResponse; this.updatedAt = other.updatedAt; } /** * Adquirente responsável pelo processamento da transação. */ public enum AcquirerName { /** * em ambiente de testes */ @SerializedName("development") DEVELOPMENT, /** * adquirente Pagar.me */ @SerializedName("pagarme") PAGARME, @SerializedName("stone") STONE, @SerializedName("cielo") CIELO, @SerializedName("rede") REDE, @SerializedName("mundipagg") MUNDIPAGG } public enum Event { @SerializedName("transaction_status_changed") TRANSACTION_STATUS_CHANGED } /** * Método de pagamento */ public enum PaymentMethod { @SerializedName("credit_card") CREDIT_CARD, @SerializedName("boleto") BOLETO, @SerializedName("debit_card") DEBIT_CARD } public enum CaptureMethod { @SerializedName("emv") EMV, @SerializedName("magstripe") MAGSTRIPE, @SerializedName("ecommerce") ECOMMERCE } /** * Quando uma transação é criada, ela inicialmente é retornada com o status * {@link #PROCESSING}. */ public enum Status { /** * Transação sendo processada. */ @SerializedName("processing") PROCESSING, /** * Transação autorizada. Cliente possui saldo na conta e este valor foi * reservado para futura captura, que deve acontecer em no máximo 5 * dias. Caso a transação <b>não seja capturada</b>, a autorização é * cancelada automaticamente. */ @SerializedName("authorized") AUTHORIZED, /** * Transação paga (autorizada e capturada). */ @SerializedName("paid") PAID, /** * Transação estornada. */ @SerializedName("refunded") REFUNDED, /** * Transação aguardando pagamento (status para transações criadas com * boleto bancário). */ @SerializedName("waiting_payment") WAITING_PAYMENT, /** * Transação paga com boleto aguardando para ser estornada. */ @SerializedName("pending_refund") PENDING_REFUND, /** * Transação não autorizada. */ @SerializedName("refused") REFUSED, /** * Transação sofreu chargeback. */ @SerializedName("chargedback") CHARGEDBACK } /** * Motivo/agente responsável pela validação ou anulação da transação. */ public enum StatusReason { @SerializedName("acquirer") ACQUIRER, @SerializedName("antifraud") ANTIFRAUD, @SerializedName("internal_error") INTERNAL_ERROR, @SerializedName("no_acquirer") NO_ACQUIRER, @SerializedName("acquirer_timeout") ACQUIRER_TIMEOUT } }
src/main/java/me/pagar/model/Transaction.java
package me.pagar.model; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.ws.rs.HttpMethod; import org.joda.time.DateTime; import org.joda.time.LocalDate; import com.google.common.base.CaseFormat; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import me.pagar.model.filter.PayableQueriableFields; import me.pagar.util.JSONUtils; public class Transaction extends PagarMeModel<Integer> { @Expose(deserialize = false) private Boolean async; @Expose(deserialize = false) private Boolean capture; /** * Caso essa transação tenha sido originada na cobrança de uma assinatura, o * <code>id</code> desta será o valor dessa propriedade */ @Expose(serialize = false) @SerializedName("subscription_id") private Integer subscriptionId; /** * Valor, em centavos, da transação */ @Expose private Integer amount; /** * Valor refund, em centavos, da transação */ @Expose @SerializedName("refunded_amount") private Integer refundedAmount; /** * Valor autorizado, em centavos, da transação */ @Expose @SerializedName("authorized_amount") private Integer authorizedAmount; /** * Valor pago, em centavos, da transação */ @Expose @SerializedName("paid_amount") private Integer paidAmount; /** * Número de parcelas/prestações a serem cobradas */ @Expose private Integer installments; @Expose(deserialize = false) @SerializedName("card_id") private String cardId; @Expose(deserialize = false) @SerializedName("card_number") private String cardNumber; @Expose(deserialize = false) @SerializedName("card_holder_name") private String cardHolderName; @Expose(deserialize = false) @SerializedName("card_expiration_date") private String cardExpirationDate; @Expose(deserialize = false) @SerializedName("card_cvv") private String cardCvv; @Expose(deserialize = false) @SerializedName("card_emv_data") private String cardEmvData; @Expose @SerializedName("card_emv_response") private String cardEmvResponse; @Expose(deserialize = false) @SerializedName("card_pin_mode") private String cardPinMode; @Expose(deserialize = false) @SerializedName("card_track_1") private String cardTrack1; @Expose(deserialize = false) @SerializedName("card_track_2") private String cardTrack2; @Expose(deserialize = false) @SerializedName("card_track_3") private String cardTrack3; @Expose(deserialize = false) @SerializedName("card_pin") private String cardPin; @Expose(deserialize = false) @SerializedName("card_pin_kek") private String cardPinKek; public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; addUnsavedProperty("cardNumber"); } public String getCardHolderName() { return cardHolderName; } public void setCardHolderName(String cardHolderName) { this.cardHolderName = cardHolderName; addUnsavedProperty("cardHolderName"); } public String getCardExpirationDate() { return cardExpirationDate; } public void setCardExpirationDate(String cardExpirationDate) { this.cardExpirationDate = cardExpirationDate; addUnsavedProperty("cardExpirationDate"); } public String getCardCvv() { return cardCvv; } public void setCardCvv(String cardCvv) { this.cardCvv = cardCvv; addUnsavedProperty("cardCvv"); } public String getCardEmvData() { return cardEmvData; } public void setCardEmvData(String cardEmvData) { this.cardEmvData = cardEmvData; addUnsavedProperty("cardEmvData"); } public String getCardEmvResponse() { return cardEmvResponse; } public void setCardEmvResponse(String cardEmvResponse) { this.cardEmvResponse = cardEmvResponse; addUnsavedProperty("cardEmvResponse"); } public String getCardTrack1() { return cardTrack2; } public void setCardTrack1(String cardTrack1) { this.cardTrack1 = cardTrack1; addUnsavedProperty("cardTrack1"); } public String getCardTrack2() { return cardTrack2; } public void setCardTrack2(String cardTrack2) { this.cardTrack2 = cardTrack2; addUnsavedProperty("cardTrack2"); } public String getCardTrack3() { return cardTrack3; } public void setCardTrack3(String cardTrack3) { this.cardTrack3 = cardTrack3; addUnsavedProperty("cardTrack3"); } public String getCardPinMode() { return cardPinMode; } public void setCardPinMode(String cardPinMode) { this.cardPinMode = cardPinMode; addUnsavedProperty("cardPinMode"); } public String getCardPin() { return cardPin; } public void setCardPin(String cardPin) { this.cardPin = cardPin; addUnsavedProperty("cardPin"); } public String getCardPinKek() { return cardPinKek; } public void setCardPinKek(String cardPinKek) { this.cardPinKek = cardPinKek; addUnsavedProperty("cardPinKek"); } /** * Custo da transação para o lojista */ @Expose(serialize = false) private Integer cost; /** * Mensagem de resposta do adquirente referente ao status da transação. */ @Expose(serialize = false) @SerializedName("acquirer_response_code") private String acquirerResponseCode; /** * Código de autorização retornado pela bandeira. */ @Expose(serialize = false) @SerializedName("authorization_code") private String authorizationCode; /** * Texto que irá aparecer na fatura do cliente depois do nome da loja. * <b>OBS:</b> Limite de 13 caracteres. */ @Expose @SerializedName("soft_descriptor") private String softDescriptor; /** * Código que identifica a transação no adquirente. */ @Expose(serialize = false) private String tid; /** * Código que identifica a transação no adquirente. */ @Expose(serialize = false) private String nsu; /** * URL (endpoint) do sistema integrado a Pagar.me que receberá as respostas * a cada atualização do processamento da transação */ @Expose @SerializedName("postback_url") private String postbackUrl; /** * URL do boleto para impressão */ @Expose(serialize = false) @SerializedName("boleto_url") private String boletoUrl; /** * Código de barras do boleto gerado na transação */ @Expose(serialize = false) @SerializedName("boleto_barcode") private String boletoBarcode; /** * Mostra se a transação foi criada utilizando a API Key ou Encryption Key. */ @Expose(serialize = false) private String referer; /** * Mostra se a transação foi criada utilizando a API Key ou Encryption Key. */ @Expose(serialize = false) private String ip; @Expose(deserialize = false) @SerializedName("card_hash") private String cardHash; /** * Adquirente responsável pelo processamento da transação. */ @Expose(serialize = false) @SerializedName("acquirer_name") private AcquirerName acquirerName; /** * Métodos de pagamento possíveis: <code>credit_card</code>, * <code>boleto</code> e <code>debit_card</code> */ @Expose @SerializedName("payment_method") private PaymentMethod paymentMethod; /** * Métodos de captura possíveis: <code>emv</code>, <code>magstripe</code> e * <code>ecommerce</code> */ @Expose @SerializedName("capture_method") private CaptureMethod captureMethod; /** * Para cada atualização no processamento da transação, esta propriedade * será alterada, e o objeto <code>transaction</code> retornado como * resposta através da sua URL de postback ou após o término do * processamento da ação atual. */ @Expose(serialize = false) private Status status; /** * Motivo/agente responsável pela validação ou anulação da transação. */ @Expose(serialize = false) @SerializedName(value = "status_reason") private StatusReason statusReason; /** * Data de expiração do boleto (em ISODate) */ @Expose(deserialize = false) @SerializedName("boleto_expiration_date") private LocalDate boletoExpirationDate; /** * Data de atualização da transação no formato ISODate */ @Expose(serialize = false) @SerializedName("date_updated") private DateTime updatedAt; /** * Objeto com dados do telefone do cliente */ @Expose(serialize = false) private Phone phone; /** * Objeto com dados do endereço do cliente */ @Expose(serialize = false) private Address address; /** * Objeto com dados do cliente */ @Expose private Customer customer; /** * Objeto com dados do cartão do cliente */ @Expose(serialize = false) private Card card; /** * Objeto com dados adicionais do cliente/produto/serviço vendido */ @Expose private Map<String, Object> metadata; @Expose @SerializedName("antifraud_metadata") private Object antifraudMetadata; @Expose(serialize = false) @SerializedName("event") private Event event; @Expose(serialize = false) @SerializedName("old_status") private Status oldStatus; @Expose(serialize = false) @SerializedName("current_status") private Status currentStatus; @Expose(serialize = false) @SerializedName("desired_status") private Status desiredStatus; @SerializedName("refuse_reason") public String getRefuseReason() { return refuseReason; } @SerializedName("refuse_reason") private String refuseReason; @Expose(serialize = true) @SerializedName("split_rules") private Collection<SplitRule> splitRules; public Transaction() { super(); } /** * <b>OBS:</b> Apenas para transações de <b>cartão de crédito</b> você deve * passar <b>ou</b> o <code>card_hash</code> <b>ou</b> o * <code>card_id</code>. * * @param amount * Valor a ser cobrado. Deve ser passado em centavos. * @param cardHash * Informações do cartão do cliente criptografadas no navegador. * @param cardId * Ao realizar uma transação, retornamos o <code>card_id</code> * do cartão para que nas próximas transações desse cartão possa * ser utilizado esse identificador ao invés do * <code>card_hash</code> * @param customer * Dados do cliente a ser cadastrado */ public Transaction(final Integer amount, final String cardHash, final String cardId, final Customer customer) { this(); this.amount = amount; this.cardHash = cardHash; this.cardId = cardId; this.customer = customer; } public Transaction find(String id) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), id)); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } public Transaction find(Integer id) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), id)); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } public Collection<Transaction> findCollection(int totalPerPage, int page) throws PagarMeException { return JSONUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken<Collection<Transaction>>() { }.getType()); } /** * @return {@link #subscriptionId} */ public Integer getSubscriptionId() { return subscriptionId; } /** * @return {@link #amount} */ public Integer getAmount() { return amount; } /** * @return {@link #refundedAmount} */ public Integer getRefundedAmount() { return refundedAmount; } /** * @return {@link #authorizedAmount} */ public Integer getAuthorizedAmount() { return authorizedAmount; } /** * @return {@link #paidAmount} */ public Integer getPaidAmount() { return paidAmount; } /** * @return {@link #installments} */ public Integer getInstallments() { return installments; } /** * @return {@link #cost} */ public Integer getCost() { return cost; } /** * @return {@link #acquirerResponseCode} */ public String getAcquirerResponseCode() { return acquirerResponseCode; } /** * @return {@link #authorizationCode} */ public String getAuthorizationCode() { return authorizationCode; } /** * @return {@link #softDescriptor} */ public String getSoftDescriptor() { return softDescriptor; } /** * @return {@link #tid} */ public String getTid() { return tid; } /** * @return {@link #nsu} */ public String getNsu() { return nsu; } /** * @return {@link Transaction#postbackUrl} */ public String getPostbackUrl() { return postbackUrl; } public String getBoletoUrl() { return boletoUrl; } /** * @return {@link #boletoBarcode} */ public String getBoletoBarcode() { return boletoBarcode; } /** * @return {@link #referer} */ public String getReferer() { return referer; } /** * @return {@link #ip} */ public String getIp() { return ip; } /** * @return {@link #acquirerName} */ public AcquirerName getAcquirerName() { return acquirerName; } /** * @return {@link #paymentMethod} */ public PaymentMethod getPaymentMethod() { return paymentMethod; } /** * @return {@link #captureMethod} */ public CaptureMethod getCaptureMethod() { return captureMethod; } /** * @return {@link #status} */ public Status getStatus() { return status; } /** * @return {@link #statusReason} */ public StatusReason getStatusReason() { return statusReason; } /** * @return {@link #updatedAt} */ public DateTime getUpdatedAt() { return updatedAt; } /** * @return {@link #metadata} */ public Map<String, Object> getMetadata() { return metadata; } /** * @return {@link #card} */ public Card getCard() { return card; } /** * @return {@link #customer} */ public Customer getCustomer() { return customer; } /** * @return {@link #event} */ public Event getEvent() { return event; } /** * @return {@link #oldStatus} */ public Status getOldStatus() { return oldStatus; } /** * @return {@link #currentStatus} */ public Status getCurrentStatus() { return currentStatus; } /** * @return {@link #desiredStatus} */ public Status getDesiredStatus() { return desiredStatus; } public Object getAntifraudMetadata() { return antifraudMetadata; } public void setAsync(final Boolean async) { this.async = async; addUnsavedProperty("async"); } public void setCapture(final Boolean capture) { this.capture = capture; addUnsavedProperty("capture"); } public void setAmount(final Integer amount) { this.amount = amount; addUnsavedProperty("amount"); } public void setInstallments(final Integer installments) { this.installments = installments; addUnsavedProperty("installments"); } public void setSoftDescriptor(final String softDescriptor) { this.softDescriptor = softDescriptor; addUnsavedProperty("softDescriptor"); } public void setPostbackUrl(final String postbackUrl) { this.postbackUrl = postbackUrl; addUnsavedProperty("postbackUrl"); } public void setCardHash(final String cardHash) { this.cardHash = cardHash; addUnsavedProperty("cardHash"); } public void setPaymentMethod(final PaymentMethod paymentMethod) { this.paymentMethod = paymentMethod; addUnsavedProperty("paymentMethod"); } public void setCaptureMethod(final CaptureMethod captureMethod) { this.captureMethod = captureMethod; addUnsavedProperty("captureMethod"); } public void setCardId(final String cardId) { this.cardId = cardId; addUnsavedProperty("cardId"); } public void setCustomer(final Customer customer) { this.customer = customer; addUnsavedProperty("customer"); } public void setBoletoExpirationDate(final LocalDate boletoExpirationDate) { this.boletoExpirationDate = boletoExpirationDate; addUnsavedProperty("boletoExpirationDate"); } public void setMetadata(final Map<String, Object> metadata) { this.metadata = metadata; addUnsavedProperty("metadata"); } public void setSplitRules(final Collection<SplitRule> splitRules) { this.splitRules = splitRules; if (this.splitRules.size() != 0) { addUnsavedProperty("splitRules"); } } public void setAntifraudMetadata(Object antifraudMetadata) { this.antifraudMetadata = antifraudMetadata; addUnsavedProperty("antifraud_metadata"); } public Collection<SplitRule> getSplitRules() { return splitRules; } public Transaction save() throws PagarMeException { final Transaction saved = super.save(getClass()); copy(saved); return saved; } /** * @see #list(int, int) */ public Collection<Transaction> list() throws PagarMeException { return list(100, 0); } /** * @param totalPerPage * Retorna <code>n</code> objetos de transação * @param page * Útil para implementação de uma paginação de resultados * @return Uma {@link Collection} contendo objetos de transações, ordenadas * a partir da transação realizada mais recentemente. * @throws PagarMeException */ public Collection<Transaction> list(int totalPerPage, int page) throws PagarMeException { return JSONUtils.getAsList(super.paginate(totalPerPage, page), new TypeToken<Collection<Transaction>>() { }.getType()); } /** * Caso você queira/precise criar o card_hash manualmente, essa rota deverá * ser utilizada para obtenção de uma chave pública de encriptação dos dados * do cartão de seu cliente. * * @return Um {@link CardHashKey} * @throws PagarMeException */ public CardHashKey cardHashKey() throws PagarMeException { final String cardHashKeyEndpoint = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, CardHashKey.class.getSimpleName()); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s", getClassName(), cardHashKeyEndpoint)); return JSONUtils.getAsObject((JsonObject) request.execute(), CardHashKey.class); } /** * * @param antifraudAnalysisId * @return * @throws PagarMeException */ public AntifraudAnalysis antifraudAnalysis(final Integer antifraudAnalysisId) throws PagarMeException { validateId(); final AntifraudAnalysis antifraudAnalysis = new AntifraudAnalysis(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), getId(), antifraudAnalysis.getClassName(), antifraudAnalysisId)); return JSONUtils.getAsObject((JsonObject) request.execute(), AntifraudAnalysis.class); } /** * Retorna todas as {@link AntifraudAnalysis} realizadas em uma transação. * * @return Lista de {@link AntifraudAnalysis} * @throws PagarMeException */ public Collection<AntifraudAnalysis> antifraudAnalysises() throws PagarMeException { validateId(); final AntifraudAnalysis antifraudAnalysis = new AntifraudAnalysis(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), antifraudAnalysis.getClassName())); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<AntifraudAnalysis>>() { }.getType()); } /** * Retorna um objeto {@link Payable} informando os dados de um pagamento * referente a uma determinada transação. * * @param payableId * ID do {@link Payable} * @return Um {@link Payable} * @throws PagarMeException */ public Payable payables(final Integer payableId) throws PagarMeException { validateId(); final Payable splitRule = new Payable(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), getId(), splitRule.getClassName(), payableId)); return JSONUtils.getAsObject((JsonObject) request.execute(), Payable.class); } /** * Retorna um array com objetos {@link Payable} informando os dados dos * pagamentos referentes a uma transação. * * @return Lista de {@link Payable} * @throws PagarMeException */ public Collection<Payable> payables() throws PagarMeException { validateId(); final Payable payable = new Payable(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), payable.getClassName())); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<Payable>>() { }.getType()); } /** * Retorna um {@link Postback} específico relacionado a transação. * * @param postbackId * ID do {@link Postback} * @return Um {@link Postback} * @throws PagarMeException */ public Postback postbacks(final String postbackId) throws PagarMeException { validateId(); final Postback postback = new Postback(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), getId(), postback.getClassName(), postbackId)); return JSONUtils.getAsObject((JsonObject) request.execute(), Postback.class); } /** * Com essa rota você pode reenviar qualquer {@link Postback} que já foi * enviado de uma transação. Lembrando que caso o envio de um * {@link Postback} falhe ou seu servidor não o receba, nós o retentamos * diversas vezes (com um total de 31 vezes). * * @param postbackId * ID do {@link Postback} * @return Reenviando um {@link Postback} * @throws PagarMeException */ public Postback postbackRedeliver(final String postbackId) throws PagarMeException { validateId(); final Postback postback = new Postback(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/%s/%s/redeliver", getClassName(), getId(), postback.getClassName(), postbackId)); return JSONUtils.getAsObject((JsonObject) request.execute(), Postback.class); } /** * Retorna todos os {@link Postback} enviados relacionados a transação. * * @return Todos os {@link Postback}s * @throws PagarMeException */ public Collection<Postback> postbacks() throws PagarMeException { validateId(); final Postback postback = new Postback(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), postback.getClassName())); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<Postback>>() { }.getType()); } /** * Retorna os dados das {@link SplitRule} do valor transacionado. * * @param splitRuleId * O ID da Regra de Split * @return Retornando uma {@link SplitRule} específica * @throws PagarMeException */ public SplitRule splitRules(final String splitRuleId) throws PagarMeException { validateId(); final SplitRule splitRule = new SplitRule(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s/%s", getClassName(), getId(), splitRule.getClassName(), splitRuleId)); return JSONUtils.getAsObject((JsonObject) request.execute(), SplitRule.class); } /** * Retorna os dados de uma {@link SplitRule} de uma determinada transação. * * @return Lista de {@link SplitRule} para a transação * @throws PagarMeException */ public Collection<SplitRule> splitRules() throws PagarMeException { validateId(); final SplitRule splitRule = new SplitRule(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, String.format("/%s/%s/%s", getClassName(), getId(), splitRule.getClassName())); return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<SplitRule>>() { }.getType()); } /** * Essa rota é utilizada quando se deseja estornar uma transação, realizada * por uma cobrança via cartão de crédito ou boleto bancário. * <p> * Em caso de estorno de uma transação realizada com cartão de crédito, * apenas o <code>id</code> da transação é necessário para efetivação do * estorno. * <p> * Caso a compra tenha sido feita por boleto bancário, você precisará passar * os dados da conta bancária que irá receber o valor estornado, ou o id * desta conta, que pode ser gerada com o modelo {@link BankAccount}. * * @throws PagarMeException */ public Transaction refund(final Integer amount) throws PagarMeException { validateId(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/refund", getClassName(), getId())); request.getParameters().put("amount", amount); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } public Transaction refund(final BankAccount bankAccount) throws PagarMeException { validateId(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/refund", getClassName(), getId())); Map<String, Object> bankAccountMap = JSONUtils.objectToMap(bankAccount); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("bank_account", bankAccountMap); request.setParameters(parameters); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } /** * Você pode capturar o valor de uma transação após a autorização desta, no * prazo máximo de 5 dias após a autorização. * * @param amount * @return * @throws PagarMeException */ public Transaction capture(final Integer amount) throws PagarMeException { validateId(); final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, String.format("/%s/%s/capture", getClassName(), getId())); request.getParameters().put("amount", amount); if (this.getMetadata() != null) request.getParameters().put("metadata", this.getMetadata()); if (this.getSplitRules() != null) request.getParameters().put("split_rules", this.getSplitRules()); final Transaction other = JSONUtils.getAsObject((JsonObject) request.execute(), Transaction.class); copy(other); flush(); return other; } public Collection<Payable> findPayableCollection(final Integer totalPerPage, Integer page) throws PagarMeException { validateId(); JsonArray responseArray = super.paginateThrough(totalPerPage, page, new PayableQueriableFields()); return JSONUtils.getAsList(responseArray, new TypeToken<Collection<Payable>>() { }.getType()); } public Payable findPayable(Integer payableId) throws PagarMeException { validateId(); Payable payable = new Payable(); payable.setId(payableId); JsonObject responseObject = super.getThrough(payable); return JSONUtils.getAsObject(responseObject, Payable.class); } /** * Atualiza a instância do objeto com os dados mais recentes do backend. * * @return Instância atualizada do Objeto. */ public Transaction refresh() throws PagarMeException { final Transaction other = JSONUtils.getAsObject(refreshModel(), Transaction.class); copy(other); flush(); return other; } private void copy(Transaction other) { super.copy(other); this.subscriptionId = other.subscriptionId; this.amount = other.amount; this.installments = other.installments; this.cost = other.cost; this.status = other.status; this.statusReason = other.statusReason; this.acquirerName = other.acquirerName; this.acquirerResponseCode = other.acquirerResponseCode; this.authorizationCode = other.authorizationCode; this.softDescriptor = other.softDescriptor; this.tid = other.tid; this.nsu = other.nsu; this.postbackUrl = other.postbackUrl; this.paymentMethod = other.paymentMethod; this.boletoUrl = other.boletoUrl; this.boletoBarcode = other.boletoBarcode; this.referer = other.referer; this.ip = other.ip; this.cardId = other.cardId; this.metadata = other.metadata; this.card = other.card; this.paidAmount = other.paidAmount; this.refundedAmount = other.refundedAmount; this.authorizedAmount = other.authorizedAmount; this.refuseReason = other.refuseReason; this.antifraudMetadata = other.antifraudMetadata; this.splitRules = other.splitRules; this.cardEmvResponse = other.cardEmvResponse; this.updatedAt = other.updatedAt; } /** * Adquirente responsável pelo processamento da transação. */ public enum AcquirerName { /** * em ambiente de testes */ @SerializedName("development") DEVELOPMENT, /** * adquirente Pagar.me */ @SerializedName("pagarme") PAGARME, @SerializedName("stone") STONE, @SerializedName("cielo") CIELO, @SerializedName("rede") REDE, @SerializedName("mundipagg") MUNDIPAGG } public enum Event { @SerializedName("transaction_status_changed") TRANSACTION_STATUS_CHANGED } /** * Método de pagamento */ public enum PaymentMethod { @SerializedName("credit_card") CREDIT_CARD, @SerializedName("boleto") BOLETO, @SerializedName("debit_card") DEBIT_CARD } public enum CaptureMethod { @SerializedName("emv") EMV, @SerializedName("magstripe") MAGSTRIPE, @SerializedName("ecommerce") ECOMMERCE } /** * Quando uma transação é criada, ela inicialmente é retornada com o status * {@link #PROCESSING}. */ public enum Status { /** * Transação sendo processada. */ @SerializedName("processing") PROCESSING, /** * Transação autorizada. Cliente possui saldo na conta e este valor foi * reservado para futura captura, que deve acontecer em no máximo 5 * dias. Caso a transação <b>não seja capturada</b>, a autorização é * cancelada automaticamente. */ @SerializedName("authorized") AUTHORIZED, /** * Transação paga (autorizada e capturada). */ @SerializedName("paid") PAID, /** * Transação estornada. */ @SerializedName("refunded") REFUNDED, /** * Transação aguardando pagamento (status para transações criadas com * boleto bancário). */ @SerializedName("waiting_payment") WAITING_PAYMENT, /** * Transação paga com boleto aguardando para ser estornada. */ @SerializedName("pending_refund") PENDING_REFUND, /** * Transação não autorizada. */ @SerializedName("refused") REFUSED, /** * Transação sofreu chargeback. */ @SerializedName("chargedback") CHARGEDBACK } /** * Motivo/agente responsável pela validação ou anulação da transação. */ public enum StatusReason { @SerializedName("acquirer") ACQUIRER, @SerializedName("antifraud") ANTIFRAUD, @SerializedName("internal_error") INTERNAL_ERROR, @SerializedName("no_acquirer") NO_ACQUIRER, @SerializedName("acquirer_timeout") ACQUIRER_TIMEOUT } }
remove extra tab
src/main/java/me/pagar/model/Transaction.java
remove extra tab
<ide><path>rc/main/java/me/pagar/model/Transaction.java <ide> <ide> final PagarMeRequest request = new PagarMeRequest(HttpMethod.POST, <ide> String.format("/%s/%s/capture", getClassName(), getId())); <del> <add> <ide> request.getParameters().put("amount", amount); <del> <add> <ide> if (this.getMetadata() != null) <ide> request.getParameters().put("metadata", this.getMetadata()); <del> <add> <ide> if (this.getSplitRules() != null) <ide> request.getParameters().put("split_rules", this.getSplitRules()); <ide>
JavaScript
mit
ae8184e20cec426f4b50a51102e011fc8c9cc917
0
melvincarvalho/inartes.com,melvincarvalho/inartes.com,melvincarvalho/inartes.com,melvincarvalho/inartes.com
/* * Set up globals */ var f,g; var template; var BIBO = $rdf.Namespace("http://purl.org/ontology/bibo/"); var CHAT = $rdf.Namespace("https://ns.rww.io/chat#"); var COMM = $rdf.Namespace("https://w3id.org/commerce/"); var CURR = $rdf.Namespace("https://w3id.org/cc#"); var DCT = $rdf.Namespace("http://purl.org/dc/terms/"); var FACE = $rdf.Namespace("https://graph.facebook.com/schema/~/"); var FOAF = $rdf.Namespace("http://xmlns.com/foaf/0.1/"); var LIKE = $rdf.Namespace("http://ontologi.es/like#"); var LINK = $rdf.Namespace("http://www.w3.org/2007/ont/link#"); var LDP = $rdf.Namespace("http://www.w3.org/ns/ldp#"); var MBLOG = $rdf.Namespace("http://www.w3.org/ns/mblog#"); var OWL = $rdf.Namespace("http://www.w3.org/2002/07/owl#"); var PIM = $rdf.Namespace("http://www.w3.org/ns/pim/space#"); var RDF = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); var RDFS = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"); var SIOC = $rdf.Namespace("http://rdfs.org/sioc/ns#"); var SOLID = $rdf.Namespace("http://www.w3.org/ns/solid/app#"); var URN = $rdf.Namespace("urn:"); var XHV = $rdf.Namespace("http://www.w3.org/1999/xhtml/vocab#"); var AUTHENDPOINT = "https://klaranet.com/"; //var PROXY = "https://rww.io/proxy.php?uri={uri}"; var TIMEOUT = 2000; var DEBUG = true; var defaultContentURI = 'https://inartes.databox.me/Public/dante/inferno-01#001'; //$rdf.Fetcher.crossSiteProxyTemplate=PROXY; /** * The app an angular module */ var App = angular.module('myApp', [ 'lumx', 'ngAudio' ]); /** * The app config */ App.config(function($locationProvider) { $locationProvider .html5Mode({ enabled: true, requireBase: false }); }); /** * The App controller */ App.controller('Main', function($scope, $http, $location, $timeout, $sce, LxNotificationService, LxProgressService, LxDialogService, ngAudio) { /* * INIT functions */ /** * Initializes the app */ $scope.initApp = function() { $scope.init(); }; /** * Initialize the app */ $scope.init = function() { template = $scope; $scope.verse = 0; $scope.artes = 'loading...'; $scope.chapter = 1; $scope.line = 1; $scope.likeIcon = 'favorite_border'; $scope.balance = 0; $scope.defaultAPI = 'http://gitpay.org/wallet/github.com/melvincarvalho/inartes.com/api/v1/'; if ( $location.search().api ) { $scope.api = $location.search().api; } else { $scope.api = $scope.defaultAPI; } $scope.shortcuts(); $scope.amount = 25; // default cost $scope.defaultSound = 'audio/button-3.mp3'; $scope.audio = ngAudio.load($scope.defaultSound); // start in memory DB g = $rdf.graph(); f = $rdf.fetcher(g); // add CORS proxy var PROXY = "https://klaranet.com/proxy?uri={uri}"; //var AUTH_PROXY = "https://rww.io/auth-proxy?uri="; $rdf.Fetcher.crossSiteProxyTemplate=PROXY; var kb = $rdf.graph(); var fetcher = $rdf.fetcher(kb); $scope.initialized = true; $scope.loggedIn = false; $scope.loginTLSButtonText = "Login"; // display elements object $scope.contentURI = $scope.getContentURI(); $location.search('contentURI', $scope.contentURI); f.nowOrWhenFetched($scope.contentURI.split('#')[0], undefined, function(ok, body) { $scope.render(); }); }; /* * AUTH functions */ /** * TLS login */ $scope.TLSlogin = function() { $scope.loginTLSButtonText = 'Logging in...'; console.log('logging in'); $http({ method: 'HEAD', url: AUTHENDPOINT, withCredentials: true }).success(function(data, status, headers) { // add dir to local list var user = headers('User'); if (user && user.length > 0 && user.slice(0,4) == 'http') { //LxNotificationService.success('Login Successful!'); $scope.loggedIn = true; $scope.me = user; console.log('success logged in a ' + user); $scope.afterLogin(); } else { //LxNotificationService.error('WebID-TLS authentication failed.'); console.log('WebID-TLS authentication failed.'); } $scope.loginTLSButtonText = 'Login'; }).error(function(data, status, headers) { LxNotificationService.error('Could not connect to auth server: HTTP '+status); console.log('Could not connect to auth server: HTTP '+status); $scope.loginTLSButtonText = 'Login'; }); }; /** * Logout */ $scope.logout = function() { $scope.init(); LxNotificationService.success('Logout Successful!'); }; /** * After Login Hook */ $scope.afterLogin = function() { $scope.fetchBalance(); LxDialogService.close('login'); }; /* * WEB functions */ /** * fetch balance */ $scope.fetchBalance = function() { if (!$scope.me) return; if (!$scope.api) return; var balanceURI = $scope.api + 'balance?uri=' + encodeURIComponent($scope.me); $http.get(balanceURI). success(function(data, status, headers, config) { $scope.balance = data.amount; }). error(function(data, status, headers, config) { // log error }); }; /** * Toggle */ $scope.toggle = function() { if ($scope.likeIcon === 'favorite') { $scope.unlike(); } else { $scope.like(); } }; /** * Like */ $scope.like = function() { if (!$scope.me) return; if (!$scope.contentURI) return; $http({ method: 'PATCH', url: $scope.contentURI.split('#')[0], withCredentials: true, headers: { 'Content-Type': 'application/sparql-update' }, data: "INSERT DATA { <"+ $scope.me +"> <http://ontologi.es/like#likes> <"+ $scope.contentURI +"> . } " }).success(function(data, status, headers) { // add dir to local list console.log('success liked ' + $scope.me); $scope.likeIcon = 'favorite'; g.add($rdf.sym($scope.me), LIKE('likes'), $rdf.sym($scope.contentURI), $rdf.sym($scope.contentURI.split('#')[0])); }).error(function(data, status, headers) { console.log('Could not like post: HTTP '+status); }); }; /** * Unlike */ $scope.unlike = function() { if (!$scope.me) return; if (!$scope.contentURI) return; $http({ method: 'PATCH', url: $scope.contentURI.split('#')[0], withCredentials: true, headers: { 'Content-Type': 'application/sparql-update' }, data: "DELETE DATA { <"+ $scope.me +"> <http://ontologi.es/like#likes> <"+ $scope.contentURI +"> . } " }).success(function(data, status, headers) { // add dir to local list $scope.likeIcon = 'favorite_border'; g.remove($rdf.st($rdf.sym($scope.me), LIKE('likes'), $rdf.sym($scope.contentURI), $rdf.sym($scope.contentURI.split('#')[0]))); console.log('success unliked ' + $scope.me); }).error(function(data, status, headers) { console.log('Could not like post: HTTP '+status); }); }; /* * HELPER functions */ /** * Gets number of lines from a string * @param {String} the content * @return {Number} number of lines */ $scope.getNumLines = function(artes) { ret = 0; if (!artes) artes = $scope.artes; var count = artes.split("\n").length; ret += count; return ret; }; /** * Gets the next chapter from a document using rel=next * @return {String} The next chapter */ $scope.getNextChapter = function() { var n = g.statementsMatching($rdf.sym($scope.contentURI.split('#')[0]), XHV('next')); if (n.length > 0) { return n[0].object.value; } var chapter = parseInt($scope.contentURI.substr(-2)); chapter += 1; var stem = $scope.contentURI.substr(0, $scope.contentURI.length - 2); if ($scope.chapter < 10) { stem += '0'; } return stem + chapter; }; /** * Gets all fragments from a URI * @param {String} uri * @return {Array} fragments All known fragments from that uri */ $scope.getFragments = function(uri) { if (!uri) { console.error('uri is required'); } var res = g.statementsMatching( null, null, null, $rdf.sym(uri.split('#')[0]) ); if (!res || !res.length) return null; var ret = []; for (var i=0; i<res.length; i++) { if (res[i].subject && res[i].subject.value && res[i].subject.value.split('#').length > 1 ) { var subject = res[i].subject.value; var fragment = subject.substring(subject.indexOf('#') + 1); if (ret.indexOf(fragment) === -1 && subject.indexOf(uri.split('#')[0]) === 0) { ret.push(fragment); } } } // sort numerically or alphabetically ret = ret.sort(function(a,b){ if ( !isNaN(a) && !isNaN(b) ) { return a - b; } else { return a < b; } }); return ret; }; /** * Gets the fragment * @param {String} the uri to get a fragment from * @return {String} the fragment */ $scope.getFragment = function(uri) { if (!uri) { console.error('uri is required'); return; } if (uri.split('#').length === 1) return; var fragment = uri.substring(uri.indexOf('#') + 1); return fragment; }; /** * Gets the next line number * @param {String} uri * @return {Number} The verse number */ $scope.getVerseNumber = function(uri) { if (!uri) { console.error('uri is required'); return; } var fragments = $scope.getFragments(uri); if (!fragments || !fragments.length) return 1; var fragment = $scope.getFragment(uri); var index = fragments.indexOf(fragment); if ( index !== -1 ) { return index + 1; } }; /** * Gets the next line number * @param {String} uri * @return {Number} The verse number */ $scope.getLineNumber = function(uri) { if (!uri) { console.error('uri is required'); return; } var fragment = $scope.getFragment(uri); if (!isNaN(parseInt(fragment))) { return parseInt(fragment); } }; /** * Gets artes * @param {String} uri * @return {String} The content */ $scope.getArtes = function(uri) { if (!uri) { console.error('uri is required'); return; } var artes = g.any($rdf.sym(uri), BIBO('#content')) || g.any($rdf.sym(uri), BIBO('content')); if (artes && artes.value) { if (artes.value.indexOf('http') === 0) { if (artes.value.indexOf('.mp3') !== -1) { $timeout(function () { $("audio source").attr("src", artes.value); $("audio").attr("src", artes.value); }, 500); } if (artes.value.indexOf('youtube') !== -1) { $timeout(function () { $("#iframe").attr("src", artes.value); }, 500); } } return artes.value; } }; /** * Gets chapter * @param {String} uri * @return {String} The chapter */ $scope.getChapter = function(uri) { if (!uri) { console.error('uri is required'); return; } var chapter = g.any($rdf.sym(uri), BIBO('chapter')); if (chapter && chapter.value) { return chapter.value; } var url = $scope.contentURI.split('#')[0]; var ch = url.substr(-2); if (!isNaN(parseInt(ch))) { return parseInt(ch); } }; /** * Gets title * @param {String} uri * @return {String} The title */ $scope.getTitle = function(uri) { if (!uri) { console.error('uri is required'); return; } var title = g.any($rdf.sym(uri.split('#')[0]), DCT('title'), null, $rdf.sym(uri.split('#')[0])); if (title && title.value) { return title.value; } var url = $scope.contentURI.split('#')[0]; var slashes = url.split('/'); var last = slashes[slashes.length-1]; if (last) { if (last.indexOf('inferno') === 0) return "Dante's Inferno"; return last; } }; /** * Gets like * @param {String} uri * @return {String} The like icon */ $scope.getLike = function(uri) { if (!uri) { console.error('uri is required'); return; } var like = g.statementsMatching($rdf.sym($scope.me), LIKE('likes'), $rdf.sym(uri), $rdf.sym(uri.split('#')[0])); if (like && like.length) { return 'favorite'; } else { return 'favorite_outline'; } }; /** * Gets the next line in a page or flip to next page */ $scope.next = function() { var fragments = $scope.getFragments($scope.contentURI); if ($scope.verse < fragments.length) { $scope.verse++; $scope.line += $scope.getNumLines($scope.artes); $scope.contentURI = $scope.contentURI.split('#')[0] + '#' + fragments[$scope.verse-1]; $location.search('contentURI', $scope.contentURI); $scope.render(); } else { console.log('load next chapter'); $scope.nextURI = $scope.getNextChapter(); f.requestURI($scope.nextURI, undefined, true, function(ok, body) { var error = g.statementsMatching($rdf.sym($scope.nextURI), LINK('error')); if (error.length>0) { // TODO this should come from header var paymentDomain = window.location.toString().split('?')[0]; $scope.paymentURI = paymentDomain + '.well-known/payment?uri=' + encodeURIComponent($scope.nextURI); var m = g.any( $rdf.sym($scope.contentURI.split('#')[0]), FOAF('maker') ); if (m) $scope.paymentURI += '&maker=' + encodeURIComponent(m.value); f.nowOrWhenFetched($scope.paymentURI, undefined, function(ok, body) { // process 402 or 403 if (!$scope.me) { $scope.openDialog('login'); return; } $scope.openDialog('pay'); return; }); } else { $scope.verse = 1; $scope.line = 1; $scope.chapter++; var fragments = $scope.getFragments($scope.nextURI); $scope.contentURI = $scope.nextURI + '#' + fragments[0]; $location.search('contentURI', $scope.contentURI); $scope.render(); } }); } }; /** * Gets the previous line in a page or flip to previous page */ $scope.prev = function() { var fragments = $scope.getFragments($scope.contentURI); if ($scope.verse > 1) { $scope.verse--; $scope.line -= $scope.getNumLines($scope.artes); $scope.contentURI = $scope.contentURI.split('#')[0] + '#' + fragments[$scope.verse-1]; $location.search('contentURI', $scope.contentURI); $scope.render(); } }; /** * Gets content URI or default * @return {String} The content URI or default */ $scope.getContentURI = function() { var contentURI; if ($location.search().contentURI) { contentURI = $location.search().contentURI; } else { contentURI = defaultContentURI; } return contentURI; }; /* * PAYMENT functions */ /** * Pay when required */ function pay() { if (!$scope.me) alert('Please log in first. (use up arrow)'); // TODO Follow your nose to get params var source = $scope.me; var hash = CryptoJS.SHA256($scope.me).toString(); //var destination = 'https://inartes.databox.me/profile/card#me'; //var amount = 1; //var inbox = 'https://gitpay.databox.me/Public/.wallet/github.com/melvincarvalho/inartes.com/inbox/' + hash + '/'; var resource = $scope.nextURI; var amount = g.any($rdf.sym($scope.nextURI.split('#')[0]), COMM('rate')); if (amount) amount = amount.value; $scope.amount = amount; var destination = g.any($rdf.sym($scope.nextURI.split('#')[0]), FOAF('maker')); if (destination) destination = destination.value; var wallet = g.any($rdf.sym(destination), CURR('wallet')); if (wallet) wallet = wallet.value; var inbox = g.any($rdf.sym(wallet), CURR('inbox')); if (inbox) inbox = inbox.value + hash + '/'; console.log('paying ' + amount + ' bits to ' + destination + ' \ninbox : ' + inbox); $scope.balance -= amount; var wc = '<#this> a <https://w3id.org/cc#Credit> ;\n'; wc += ' <https://w3id.org/cc#source> \n <' + source + '> ;\n'; wc += ' <https://w3id.org/cc#destination> \n <' + destination + '> ;\n'; wc += ' <https://w3id.org/cc#amount> "' + amount + '" ;\n'; wc += ' <https://w3id.org/cc#variable> "' + resource + '" ;\n'; wc += ' <https://w3id.org/cc#currency> \n <https://w3id.org/cc#bit> .\n'; function postFile(file, data) { xhr = new XMLHttpRequest(); xhr.open('POST', file, false); xhr.setRequestHeader('Content-Type', 'text/turtle; charset=UTF-8'); xhr.send(data); } postFile(inbox, wc); console.log(wc); var error = g.statementsMatching($rdf.sym($scope.nextURI), LINK('error')); for (var i=0; i<error.length; i++) { g.remove(error[i]); } var DELAY = 2000; setTimeout($scope.next, DELAY); } /* * RENDER functions */ /** * Renders the screen */ $scope.render = function() { // get content URI $scope.contentURI = $scope.getContentURI(); // get and render verse number $scope.verse = $scope.getVerseNumber($scope.contentURI); // get and render line number $scope.line = $scope.getLineNumber($scope.contentURI); // get and render content $scope.artes = $scope.getArtes($scope.contentURI); // get and render chapter $scope.chapter = $scope.getChapter($scope.contentURI); // get and render title $scope.title = $scope.getTitle($scope.contentURI); // get and render like $scope.likeIcon = $scope.getLike($scope.contentURI); // render if necessary $scope.$apply(); }; /** * Opens a dialog */ $scope.openDialog = function(elem, reset) { LxDialogService.open(elem); }; /** * Agrees to a payment */ $scope.agree = function(elem) { LxDialogService.close('pay'); pay(); }; /** * Adds shortcuts */ $scope.shortcuts = function(elem) { $('#pay').keyup(function(e) { if (e.keyCode===27) { LxDialogService.close('pay'); } }); }; /** * Checks for keypresses of arrow keys */ $scope.keydown = function(event) { if (event.which === 27) { if ($('#login').is(":visible")) { LxDialogService.close('login'); } if ($('#pay').is(":visible")) { LxDialogService.close('pay'); } } if (event.which === 13) { if ($('#pay').is(":visible")) { LxDialogService.close('pay'); $scope.agree(); } } if (event.which === 37) { $scope.prev(); } if (event.which === 38) { if (!$scope.me) { $scope.TLSlogin(); } else { event.preventDefault(); $scope.like(); } } if (event.which === 39) { $scope.next(); } if (event.which === 40) { if (!$scope.me) { $scope.TLSlogin(); } else { event.preventDefault(); $scope.unlike(); } } }; /* * MAIN */ $scope.initApp(); });
app/app.js
/* * Set up globals */ var f,g; var template; var BIBO = $rdf.Namespace("http://purl.org/ontology/bibo/"); var CHAT = $rdf.Namespace("https://ns.rww.io/chat#"); var COMM = $rdf.Namespace("https://w3id.org/commerce/"); var CURR = $rdf.Namespace("https://w3id.org/cc#"); var DCT = $rdf.Namespace("http://purl.org/dc/terms/"); var FACE = $rdf.Namespace("https://graph.facebook.com/schema/~/"); var FOAF = $rdf.Namespace("http://xmlns.com/foaf/0.1/"); var LIKE = $rdf.Namespace("http://ontologi.es/like#"); var LINK = $rdf.Namespace("http://www.w3.org/2007/ont/link#"); var LDP = $rdf.Namespace("http://www.w3.org/ns/ldp#"); var MBLOG = $rdf.Namespace("http://www.w3.org/ns/mblog#"); var OWL = $rdf.Namespace("http://www.w3.org/2002/07/owl#"); var PIM = $rdf.Namespace("http://www.w3.org/ns/pim/space#"); var RDF = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); var RDFS = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"); var SIOC = $rdf.Namespace("http://rdfs.org/sioc/ns#"); var SOLID = $rdf.Namespace("http://www.w3.org/ns/solid/app#"); var URN = $rdf.Namespace("urn:"); var XHV = $rdf.Namespace("http://www.w3.org/1999/xhtml/vocab#"); var AUTHENDPOINT = "https://klaranet.com/"; //var PROXY = "https://rww.io/proxy.php?uri={uri}"; var TIMEOUT = 2000; var DEBUG = true; var defaultContentURI = 'https://inartes.databox.me/Public/dante/inferno-01#001'; //$rdf.Fetcher.crossSiteProxyTemplate=PROXY; /** * The app an angular module */ var App = angular.module('myApp', [ 'lumx', 'ngAudio' ]); /** * The app config */ App.config(function($locationProvider) { $locationProvider .html5Mode({ enabled: true, requireBase: false }); }); /** * The App controller */ App.controller('Main', function($scope, $http, $location, $timeout, $sce, LxNotificationService, LxProgressService, LxDialogService, ngAudio) { /* * INIT functions */ /** * Initializes the app */ $scope.initApp = function() { $scope.init(); }; /** * Initialize the app */ $scope.init = function() { template = $scope; $scope.verse = 0; $scope.artes = 'loading...'; $scope.chapter = 1; $scope.line = 1; $scope.likeIcon = 'favorite_border'; $scope.balance = 0; $scope.defaultAPI = 'http://gitpay.org/wallet/github.com/melvincarvalho/inartes.com/api/v1/'; if ( $location.search().api ) { $scope.api = $location.search().api; } else { $scope.api = $scope.defaultAPI; } $scope.shortcuts(); $scope.amount = 25; // default cost $scope.defaultSound = 'audio/button-3.mp3'; $scope.audio = ngAudio.load($scope.defaultSound); // start in memory DB g = $rdf.graph(); f = $rdf.fetcher(g); // add CORS proxy var PROXY = "https://klaranet.com/proxy?uri={uri}"; //var AUTH_PROXY = "https://rww.io/auth-proxy?uri="; $rdf.Fetcher.crossSiteProxyTemplate=PROXY; var kb = $rdf.graph(); var fetcher = $rdf.fetcher(kb); $scope.initialized = true; $scope.loggedIn = false; $scope.loginTLSButtonText = "Login"; // display elements object $scope.contentURI = $scope.getContentURI(); $location.search('contentURI', $scope.contentURI); f.nowOrWhenFetched($scope.contentURI.split('#')[0], undefined, function(ok, body) { $scope.render(); }); }; /* * AUTH functions */ /** * TLS login */ $scope.TLSlogin = function() { $scope.loginTLSButtonText = 'Logging in...'; console.log('logging in'); $http({ method: 'HEAD', url: AUTHENDPOINT, withCredentials: true }).success(function(data, status, headers) { // add dir to local list var user = headers('User'); if (user && user.length > 0 && user.slice(0,4) == 'http') { //LxNotificationService.success('Login Successful!'); $scope.loggedIn = true; $scope.me = user; console.log('success logged in a ' + user); $scope.afterLogin(); } else { //LxNotificationService.error('WebID-TLS authentication failed.'); console.log('WebID-TLS authentication failed.'); } $scope.loginTLSButtonText = 'Login'; }).error(function(data, status, headers) { LxNotificationService.error('Could not connect to auth server: HTTP '+status); console.log('Could not connect to auth server: HTTP '+status); $scope.loginTLSButtonText = 'Login'; }); }; /** * Logout */ $scope.logout = function() { $scope.init(); LxNotificationService.success('Logout Successful!'); }; /** * After Login Hook */ $scope.afterLogin = function() { $scope.fetchBalance(); LxDialogService.close('login'); }; /* * WEB functions */ /** * fetch balance */ $scope.fetchBalance = function() { if (!$scope.me) return; if (!$scope.api) return; var balanceURI = $scope.api + 'balance?uri=' + encodeURIComponent($scope.me); $http.get(balanceURI). success(function(data, status, headers, config) { $scope.balance = data.amount; }). error(function(data, status, headers, config) { // log error }); }; /** * Toggle */ $scope.toggle = function() { if ($scope.likeIcon === 'favorite') { $scope.unlike(); } else { $scope.like(); } }; /** * Like */ $scope.like = function() { if (!$scope.me) return; if (!$scope.contentURI) return; $http({ method: 'PATCH', url: $scope.contentURI.split('#')[0], withCredentials: true, headers: { 'Content-Type': 'application/sparql-update' }, data: "INSERT DATA { <"+ $scope.me +"> <http://ontologi.es/like#likes> <"+ $scope.contentURI +"> . } " }).success(function(data, status, headers) { // add dir to local list console.log('success liked ' + $scope.me); $scope.likeIcon = 'favorite'; g.add($rdf.sym($scope.me), LIKE('likes'), $rdf.sym($scope.contentURI), $rdf.sym($scope.contentURI.split('#')[0])); }).error(function(data, status, headers) { console.log('Could not like post: HTTP '+status); }); }; /** * Unlike */ $scope.unlike = function() { if (!$scope.me) return; if (!$scope.contentURI) return; $http({ method: 'PATCH', url: $scope.contentURI.split('#')[0], withCredentials: true, headers: { 'Content-Type': 'application/sparql-update' }, data: "DELETE DATA { <"+ $scope.me +"> <http://ontologi.es/like#likes> <"+ $scope.contentURI +"> . } " }).success(function(data, status, headers) { // add dir to local list $scope.likeIcon = 'favorite_border'; g.remove($rdf.st($rdf.sym($scope.me), LIKE('likes'), $rdf.sym($scope.contentURI), $rdf.sym($scope.contentURI.split('#')[0]))); console.log('success unliked ' + $scope.me); }).error(function(data, status, headers) { console.log('Could not like post: HTTP '+status); }); }; /* * HELPER functions */ /** * Gets number of lines from a string * @param {String} the content * @return {Number} number of lines */ $scope.getNumLines = function(artes) { ret = 0; if (!artes) artes = $scope.artes; var count = artes.split("\n").length; ret += count; return ret; }; /** * Gets the next chapter from a document using rel=next * @return {String} The next chapter */ $scope.getNextChapter = function() { var n = g.statementsMatching($rdf.sym($scope.contentURI.split('#')[0]), XHV('next')); if (n.length > 0) { return n[0].object.value; } var chapter = parseInt($scope.contentURI.substr(-2)); chapter += 1; var stem = $scope.contentURI.substr(0, $scope.contentURI.length - 2); if ($scope.chapter < 10) { stem += '0'; } return stem + chapter; }; /** * Gets all fragments from a URI * @param {String} uri * @return {Array} fragments All known fragments from that uri */ $scope.getFragments = function(uri) { if (!uri) { console.error('uri is required'); } var res = g.statementsMatching( null, null, null, $rdf.sym(uri.split('#')[0]) ); if (!res || !res.length) return null; var ret = []; for (var i=0; i<res.length; i++) { if (res[i].subject && res[i].subject.value && res[i].subject.value.split('#').length > 1 ) { var subject = res[i].subject.value; var fragment = subject.substring(subject.indexOf('#') + 1); if (ret.indexOf(fragment) === -1 && subject.indexOf(uri.split('#')[0]) === 0) { ret.push(fragment); } } } // sort numerically or alphabetically ret = ret.sort(function(a,b){ if ( !isNaN(a) && !isNaN(b) ) { return a - b; } else { return a < b; } }); return ret; }; /** * Gets the fragment * @param {String} the uri to get a fragment from * @return {String} the fragment */ $scope.getFragment = function(uri) { if (!uri) { console.error('uri is required'); return; } if (uri.split('#').length === 1) return; var fragment = uri.substring(uri.indexOf('#') + 1); return fragment; }; /** * Gets the next line number * @param {String} uri * @return {Number} The verse number */ $scope.getVerseNumber = function(uri) { if (!uri) { console.error('uri is required'); return; } var fragments = $scope.getFragments(uri); if (!fragments || !fragments.length) return 1; var fragment = $scope.getFragment(uri); var index = fragments.indexOf(fragment); if ( index !== -1 ) { return index + 1; } }; /** * Gets the next line number * @param {String} uri * @return {Number} The verse number */ $scope.getLineNumber = function(uri) { if (!uri) { console.error('uri is required'); return; } var fragment = $scope.getFragment(uri); if (!isNaN(parseInt(fragment))) { return parseInt(fragment); } }; /** * Gets artes * @param {String} uri * @return {String} The content */ $scope.getArtes = function(uri) { if (!uri) { console.error('uri is required'); return; } var artes = g.any($rdf.sym(uri), BIBO('#content')) || g.any($rdf.sym(uri), BIBO('content')); if (artes && artes.value) { if (artes.value.indexOf('http') === 0) { if (artes.value.indexOf('.mp3') !== -1) { $timeout(function () { $("audio source").attr("src", artes.value); $("audio").attr("src", artes.value); }, 500); } if (artes.value.indexOf('youtube') !== -1) { $timeout(function () { $("#iframe").attr("src", artes.value); }, 500); } } return artes.value; } }; /** * Gets chapter * @param {String} uri * @return {String} The chapter */ $scope.getChapter = function(uri) { if (!uri) { console.error('uri is required'); return; } var chapter = g.any($rdf.sym(uri), BIBO('chapter')); if (chapter && chapter.value) { return chapter.value; } var url = $scope.contentURI.split('#')[0]; var ch = url.substr(-2); if (!isNaN(parseInt(ch))) { return parseInt(ch); } }; /** * Gets title * @param {String} uri * @return {String} The title */ $scope.getTitle = function(uri) { if (!uri) { console.error('uri is required'); return; } var title = g.any($rdf.sym(uri.split('#')[0]), DCT('title'), null, $rdf.sym(uri.split('#')[0])); if (title && title.value) { return title.value; } var url = $scope.contentURI.split('#')[0]; var slashes = url.split('/'); var last = slashes[slashes.length-1]; if (last) { if (last.indexOf('inferno') === 0) return "Dante's Inferno"; return last; } }; /** * Gets like * @param {String} uri * @return {String} The like icon */ $scope.getLike = function(uri) { if (!uri) { console.error('uri is required'); return; } var like = g.statementsMatching($rdf.sym($scope.me), LIKE('likes'), $rdf.sym(uri), $rdf.sym(uri.split('#')[0])); if (like && like.length) { return 'favorite'; } else { return 'favorite_outline'; } }; /** * Gets the next line in a page or flip to next page */ $scope.next = function() { var fragments = $scope.getFragments($scope.contentURI); if ($scope.verse < fragments.length) { $scope.verse++; $scope.line += $scope.getNumLines($scope.artes); $scope.contentURI = $scope.contentURI.split('#')[0] + '#' + fragments[$scope.verse-1]; $location.search('contentURI', $scope.contentURI); $scope.render(); } else { console.log('load next chapter'); $scope.nextURI = $scope.getNextChapter(); f.requestURI($scope.nextURI, undefined, true, function(ok, body) { var error = g.statementsMatching($rdf.sym($scope.nextURI), LINK('error')); if (error.length>0) { // TODO this should come from header var paymentDomain = window.location.toString().split('?')[0]; $scope.paymentURI = paymentDomain + '.well-known/payment?uri=' + encodeURIComponent($scope.nextURI); f.nowOrWhenFetched($scope.paymentURI, undefined, function(ok, body) { // process 402 or 403 if (!$scope.me) { $scope.openDialog('login'); return; } $scope.openDialog('pay'); return; }); } else { $scope.verse = 1; $scope.line = 1; $scope.chapter++; var fragments = $scope.getFragments($scope.nextURI); $scope.contentURI = $scope.nextURI + '#' + fragments[0]; $location.search('contentURI', $scope.contentURI); $scope.render(); } }); } }; /** * Gets the previous line in a page or flip to previous page */ $scope.prev = function() { var fragments = $scope.getFragments($scope.contentURI); if ($scope.verse > 1) { $scope.verse--; $scope.line -= $scope.getNumLines($scope.artes); $scope.contentURI = $scope.contentURI.split('#')[0] + '#' + fragments[$scope.verse-1]; $location.search('contentURI', $scope.contentURI); $scope.render(); } }; /** * Gets content URI or default * @return {String} The content URI or default */ $scope.getContentURI = function() { var contentURI; if ($location.search().contentURI) { contentURI = $location.search().contentURI; } else { contentURI = defaultContentURI; } return contentURI; }; /* * PAYMENT functions */ /** * Pay when required */ function pay() { if (!$scope.me) alert('Please log in first. (use up arrow)'); // TODO Follow your nose to get params var source = $scope.me; var hash = CryptoJS.SHA256($scope.me).toString(); //var destination = 'https://inartes.databox.me/profile/card#me'; //var amount = 1; //var inbox = 'https://gitpay.databox.me/Public/.wallet/github.com/melvincarvalho/inartes.com/inbox/' + hash + '/'; var resource = $scope.nextURI; var amount = g.any($rdf.sym($scope.nextURI.split('#')[0]), COMM('rate')); if (amount) amount = amount.value; $scope.amount = amount; var destination = g.any($rdf.sym($scope.nextURI.split('#')[0]), FOAF('maker')); if (destination) destination = destination.value; var wallet = g.any($rdf.sym(destination), CURR('wallet')); if (wallet) wallet = wallet.value; var inbox = g.any($rdf.sym(wallet), CURR('inbox')); if (inbox) inbox = inbox.value + hash + '/'; console.log('paying ' + amount + ' bits to ' + destination + ' \ninbox : ' + inbox); $scope.balance -= amount; var wc = '<#this> a <https://w3id.org/cc#Credit> ;\n'; wc += ' <https://w3id.org/cc#source> \n <' + source + '> ;\n'; wc += ' <https://w3id.org/cc#destination> \n <' + destination + '> ;\n'; wc += ' <https://w3id.org/cc#amount> "' + amount + '" ;\n'; wc += ' <https://w3id.org/cc#variable> "' + resource + '" ;\n'; wc += ' <https://w3id.org/cc#currency> \n <https://w3id.org/cc#bit> .\n'; function postFile(file, data) { xhr = new XMLHttpRequest(); xhr.open('POST', file, false); xhr.setRequestHeader('Content-Type', 'text/turtle; charset=UTF-8'); xhr.send(data); } postFile(inbox, wc); console.log(wc); var error = g.statementsMatching($rdf.sym($scope.nextURI), LINK('error')); for (var i=0; i<error.length; i++) { g.remove(error[i]); } var DELAY = 2000; setTimeout($scope.next, DELAY); } /* * RENDER functions */ /** * Renders the screen */ $scope.render = function() { // get content URI $scope.contentURI = $scope.getContentURI(); // get and render verse number $scope.verse = $scope.getVerseNumber($scope.contentURI); // get and render line number $scope.line = $scope.getLineNumber($scope.contentURI); // get and render content $scope.artes = $scope.getArtes($scope.contentURI); // get and render chapter $scope.chapter = $scope.getChapter($scope.contentURI); // get and render title $scope.title = $scope.getTitle($scope.contentURI); // get and render like $scope.likeIcon = $scope.getLike($scope.contentURI); // render if necessary $scope.$apply(); }; /** * Opens a dialog */ $scope.openDialog = function(elem, reset) { LxDialogService.open(elem); }; /** * Agrees to a payment */ $scope.agree = function(elem) { LxDialogService.close('pay'); pay(); }; /** * Adds shortcuts */ $scope.shortcuts = function(elem) { $('#pay').keyup(function(e) { if (e.keyCode===27) { LxDialogService.close('pay'); } }); }; /** * Checks for keypresses of arrow keys */ $scope.keydown = function(event) { if (event.which === 27) { if ($('#login').is(":visible")) { LxDialogService.close('login'); } if ($('#pay').is(":visible")) { LxDialogService.close('pay'); } } if (event.which === 13) { if ($('#pay').is(":visible")) { LxDialogService.close('pay'); $scope.agree(); } } if (event.which === 37) { $scope.prev(); } if (event.which === 38) { if (!$scope.me) { $scope.TLSlogin(); } else { event.preventDefault(); $scope.like(); } } if (event.which === 39) { $scope.next(); } if (event.which === 40) { if (!$scope.me) { $scope.TLSlogin(); } else { event.preventDefault(); $scope.unlike(); } } }; /* * MAIN */ $scope.initApp(); });
maker
app/app.js
maker
<ide><path>pp/app.js <ide> // TODO this should come from header <ide> var paymentDomain = window.location.toString().split('?')[0]; <ide> $scope.paymentURI = paymentDomain + '.well-known/payment?uri=' + encodeURIComponent($scope.nextURI); <add> var m = g.any( $rdf.sym($scope.contentURI.split('#')[0]), FOAF('maker') ); <add> if (m) $scope.paymentURI += '&maker=' + encodeURIComponent(m.value); <ide> f.nowOrWhenFetched($scope.paymentURI, undefined, function(ok, body) { <ide> // process 402 or 403 <ide> if (!$scope.me) {
Java
apache-2.0
c7eebddb17820398ac5e8ee740c6944d893ec95a
0
niketanpansare/incubator-systemml,gweidner/incubator-systemml,gweidner/systemml,iyounus/incubator-systemml,akchinSTC/systemml,dusenberrymw/systemml,deroneriksson/systemml,deroneriksson/systemml,niketanpansare/incubator-systemml,asurve/systemml,gweidner/incubator-systemml,asurve/systemml,deroneriksson/systemml,niketanpansare/systemml,deroneriksson/systemml,asurve/arvind-sysml2,akchinSTC/systemml,niketanpansare/systemml,dusenberrymw/incubator-systemml,dusenberrymw/incubator-systemml,apache/incubator-systemml,nakul02/incubator-systemml,apache/incubator-systemml,deroneriksson/incubator-systemml,dusenberrymw/incubator-systemml,dhutchis/systemml,dhutchis/systemml,asurve/incubator-systemml,deroneriksson/systemml,asurve/incubator-systemml,akchinSTC/systemml,gweidner/systemml,asurve/arvind-sysml2,niketanpansare/systemml,deroneriksson/incubator-systemml,deroneriksson/incubator-systemml,nakul02/incubator-systemml,dusenberrymw/systemml,asurve/incubator-systemml,asurve/arvind-sysml2,sandeep-n/incubator-systemml,gweidner/incubator-systemml,dhutchis/systemml,asurve/systemml,dhutchis/systemml,akchinSTC/systemml,gweidner/systemml,apache/incubator-systemml,gweidner/incubator-systemml,gweidner/systemml,iyounus/incubator-systemml,sandeep-n/incubator-systemml,gweidner/systemml,asurve/systemml,nakul02/systemml,deroneriksson/incubator-systemml,dusenberrymw/systemml,deroneriksson/systemml,dhutchis/systemml,nakul02/incubator-systemml,dusenberrymw/incubator-systemml,iyounus/incubator-systemml,iyounus/incubator-systemml,nakul02/systemml,asurve/incubator-systemml,gweidner/incubator-systemml,nakul02/incubator-systemml,nakul02/systemml,nakul02/systemml,nakul02/incubator-systemml,asurve/incubator-systemml,apache/incubator-systemml,iyounus/incubator-systemml,apache/incubator-systemml,gweidner/systemml,niketanpansare/incubator-systemml,dusenberrymw/systemml,nakul02/systemml,nakul02/systemml,asurve/incubator-systemml,akchinSTC/systemml,asurve/arvind-sysml2,niketanpansare/systemml,nakul02/incubator-systemml,dusenberrymw/systemml,gweidner/incubator-systemml,asurve/systemml,sandeep-n/incubator-systemml,asurve/arvind-sysml2,apache/incubator-systemml,asurve/arvind-sysml2,asurve/systemml,niketanpansare/systemml,niketanpansare/incubator-systemml,deroneriksson/incubator-systemml,dusenberrymw/incubator-systemml,deroneriksson/incubator-systemml,sandeep-n/incubator-systemml,niketanpansare/systemml,dhutchis/systemml,akchinSTC/systemml,dusenberrymw/incubator-systemml,dusenberrymw/systemml,iyounus/incubator-systemml
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sysml.runtime.util; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.sysml.parser.Expression.ValueType; import org.apache.sysml.runtime.DMLRuntimeException; import org.apache.sysml.runtime.controlprogram.caching.MatrixObject; import org.apache.sysml.runtime.io.MatrixReader; import org.apache.sysml.runtime.io.MatrixReaderFactory; import org.apache.sysml.runtime.io.MatrixWriter; import org.apache.sysml.runtime.io.MatrixWriterFactory; import org.apache.sysml.runtime.io.ReadProperties; import org.apache.sysml.runtime.matrix.MatrixCharacteristics; import org.apache.sysml.runtime.matrix.data.CTableMap; import org.apache.sysml.runtime.matrix.data.FileFormatProperties; import org.apache.sysml.runtime.matrix.data.FrameBlock; import org.apache.sysml.runtime.matrix.data.IJV; import org.apache.sysml.runtime.matrix.data.InputInfo; import org.apache.sysml.runtime.matrix.data.MatrixBlock; import org.apache.sysml.runtime.matrix.data.MatrixIndexes; import org.apache.sysml.runtime.matrix.data.OutputInfo; import org.apache.sysml.runtime.matrix.data.SparseBlock; /** * This class provides methods to read and write matrix blocks from to HDFS using different data formats. * Those functionalities are used especially for CP read/write and exporting in-memory matrices to HDFS * (before executing MR jobs). * */ public class DataConverter { ////////////// // READING and WRITING of matrix blocks to/from HDFS // (textcell, binarycell, binaryblock) /////// public static void writeMatrixToHDFS(MatrixBlock mat, String dir, OutputInfo outputinfo, MatrixCharacteristics mc ) throws IOException { writeMatrixToHDFS(mat, dir, outputinfo, mc, -1, null); } public static void writeMatrixToHDFS(MatrixBlock mat, String dir, OutputInfo outputinfo, MatrixCharacteristics mc, int replication, FileFormatProperties formatProperties) throws IOException { try { MatrixWriter writer = MatrixWriterFactory.createMatrixWriter( outputinfo, replication, formatProperties ); writer.writeMatrixToHDFS(mat, dir, mc.getRows(), mc.getCols(), mc.getRowsPerBlock(), mc.getColsPerBlock(), mc.getNonZeros()); } catch(Exception e) { throw new IOException(e); } } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen, boolean localFS) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; prop.localFS = localFS; //expected matrix is sparse (default SystemML usecase) return readMatrixFromHDFS(prop); } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; //expected matrix is sparse (default SystemML usecase) return readMatrixFromHDFS(prop); } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen, double expectedSparsity) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; prop.expectedSparsity = expectedSparsity; return readMatrixFromHDFS(prop); } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen, double expectedSparsity, boolean localFS) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; prop.expectedSparsity = expectedSparsity; prop.localFS = localFS; return readMatrixFromHDFS(prop); } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen, double expectedSparsity, FileFormatProperties formatProperties) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; prop.expectedSparsity = expectedSparsity; prop.formatProperties = formatProperties; //prop.printMe(); return readMatrixFromHDFS(prop); } /** * Core method for reading matrices in format textcell, matrixmarket, binarycell, or binaryblock * from HDFS into main memory. For expected dense matrices we directly copy value- or block-at-a-time * into the target matrix. In contrast, for sparse matrices, we append (column-value)-pairs and do a * final sort if required in order to prevent large reorg overheads and increased memory consumption * in case of unordered inputs. * * DENSE MxN input: * * best/average/worst: O(M*N) * SPARSE MxN input * * best (ordered, or binary block w/ clen&lt;=bclen): O(M*N) * * average (unordered): O(M*N*log(N)) * * worst (descending order per row): O(M * N^2) * * NOTE: providing an exact estimate of 'expected sparsity' can prevent a full copy of the result * matrix block (required for changing sparse-&gt;dense, or vice versa) * * @param prop read properties * @return matrix block * @throws IOException if IOException occurs */ public static MatrixBlock readMatrixFromHDFS(ReadProperties prop) throws IOException { //Timing time = new Timing(true); long estnnz = (long)(prop.expectedSparsity*prop.rlen*prop.clen); //core matrix reading MatrixBlock ret = null; try { MatrixReader reader = MatrixReaderFactory.createMatrixReader(prop); ret = reader.readMatrixFromHDFS(prop.path, prop.rlen, prop.clen, prop.brlen, prop.bclen, estnnz); } catch(DMLRuntimeException rex) { throw new IOException(rex); } //System.out.println("read matrix ("+prop.rlen+","+prop.clen+","+ret.getNonZeros()+") in "+time.stop()); return ret; } ////////////// // Utils for CREATING and COPYING matrix blocks /////// /** * Creates a two-dimensional double matrix of the input matrix block. * * @param mb matrix block * @return 2d double array */ public static double[][] convertToDoubleMatrix( MatrixBlock mb ) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); double[][] ret = new double[rows][cols]; //0-initialized if( mb.getNonZeros() > 0 ) { if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getI()][cell.getJ()] = cell.getV(); } } else { for( int i=0; i<rows; i++ ) for( int j=0; j<cols; j++ ) ret[i][j] = mb.getValueDenseUnsafe(i, j); } } return ret; } public static boolean [] convertToBooleanVector(MatrixBlock mb) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); boolean[] ret = new boolean[rows*cols]; //false-initialized if( mb.getNonZeros() > 0 ) { if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getI()*cols+cell.getJ()] = (cell.getV() != 0.0); } } else { for( int i=0, cix=0; i<rows; i++ ) for( int j=0; j<cols; j++, cix++) ret[cix] = (mb.getValueDenseUnsafe(i, j) != 0.0); } } return ret; } public static int[] convertToIntVector( MatrixBlock mb) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); int[] ret = new int[rows*cols]; //0-initialized if( mb.getNonZeros() > 0 ) { if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getI()*cols+cell.getJ()] = (int)cell.getV(); } } else { //memcopy row major representation if at least 1 non-zero for( int i=0, cix=0; i<rows; i++ ) for( int j=0; j<cols; j++, cix++ ) ret[cix] = (int)(mb.getValueDenseUnsafe(i, j)); } } return ret; } public static double[] convertToDoubleVector( MatrixBlock mb ) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); double[] ret = new double[rows*cols]; //0-initialized if( mb.getNonZeros() > 0 ) { if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getI()*cols+cell.getJ()] = cell.getV(); } } else { //memcopy row major representation if at least 1 non-zero System.arraycopy(mb.getDenseBlock(), 0, ret, 0, rows*cols); } } return ret; } public static List<Double> convertToDoubleList( MatrixBlock mb ) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); long nnz = mb.getNonZeros(); ArrayList<Double> ret = new ArrayList<Double>(); if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret.add( cell.getV() ); } for( long i=nnz; i<(long)rows*cols; i++ ) ret.add( 0d ); //add remaining values } else { for( int i=0; i<rows; i++ ) for( int j=0; j<cols; j++ ) ret.add( mb.getValueDenseUnsafe(i, j) ); } return ret; } /** * Creates a dense Matrix Block and copies the given double matrix into it. * * @param data 2d double array * @return matrix block * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static MatrixBlock convertToMatrixBlock( double[][] data ) throws DMLRuntimeException { int rows = data.length; int cols = (rows > 0)? data[0].length : 0; MatrixBlock mb = new MatrixBlock(rows, cols, false); try { //copy data to mb (can be used because we create a dense matrix) mb.init( data, rows, cols ); } catch (Exception e){} //can never happen //check and convert internal representation mb.examSparsity(); return mb; } /** * Creates a dense Matrix Block and copies the given double vector into it. * * @param data double array * @param columnVector if true, create matrix with single column. if false, create matrix with single row * @return matrix block * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static MatrixBlock convertToMatrixBlock( double[] data, boolean columnVector ) throws DMLRuntimeException { int rows = columnVector ? data.length : 1; int cols = columnVector ? 1 : data.length; MatrixBlock mb = new MatrixBlock(rows, cols, false); try { //copy data to mb (can be used because we create a dense matrix) mb.init( data, rows, cols ); } catch (Exception e){} //can never happen //check and convert internal representation mb.examSparsity(); return mb; } public static MatrixBlock convertToMatrixBlock( HashMap<MatrixIndexes,Double> map ) { // compute dimensions from the map long nrows=0, ncols=0; for (MatrixIndexes index : map.keySet()) { nrows = Math.max( nrows, index.getRowIndex() ); ncols = Math.max( ncols, index.getColumnIndex() ); } // convert to matrix block return convertToMatrixBlock(map, (int)nrows, (int)ncols); } /** * NOTE: this method also ensures the specified matrix dimensions * * @param map map of matrix index keys and double values * @param rlen number of rows * @param clen number of columns * @return matrix block */ public static MatrixBlock convertToMatrixBlock( HashMap<MatrixIndexes,Double> map, int rlen, int clen ) { int nnz = map.size(); boolean sparse = MatrixBlock.evalSparseFormatInMemory(rlen, clen, nnz); MatrixBlock mb = new MatrixBlock(rlen, clen, sparse, nnz); // copy map values into new block if( sparse ) //SPARSE <- cells { //append cells to sparse target (prevent shifting) for( Entry<MatrixIndexes,Double> e : map.entrySet() ) { MatrixIndexes index = e.getKey(); double value = e.getValue(); int rix = (int)index.getRowIndex(); int cix = (int)index.getColumnIndex(); if( value != 0 && rix<=rlen && cix<=clen ) mb.appendValue( rix-1, cix-1, value ); } //sort sparse target representation mb.sortSparseRows(); } else //DENSE <- cells { //directly insert cells into dense target for( Entry<MatrixIndexes,Double> e : map.entrySet() ) { MatrixIndexes index = e.getKey(); double value = e.getValue(); int rix = (int)index.getRowIndex(); int cix = (int)index.getColumnIndex(); if( value != 0 && rix<=rlen && cix<=clen ) mb.quickSetValue( rix-1, cix-1, value ); } } return mb; } public static MatrixBlock convertToMatrixBlock( CTableMap map ) { // compute dimensions from the map int nrows = (int)map.getMaxRow(); int ncols = (int)map.getMaxColumn(); // convert to matrix block return convertToMatrixBlock(map, nrows, ncols); } /** * NOTE: this method also ensures the specified matrix dimensions * * @param map ? * @param rlen number of rows * @param clen number of columns * @return matrix block */ public static MatrixBlock convertToMatrixBlock( CTableMap map, int rlen, int clen ) { return map.toMatrixBlock(rlen, clen); } /** * Converts a frame block with arbitrary schema into a matrix block. * Since matrix block only supports value type double, we do a best * effort conversion of non-double types which might result in errors * for non-numerical data. * * @param frame frame block * @return matrix block * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static MatrixBlock convertToMatrixBlock(FrameBlock frame) throws DMLRuntimeException { int m = frame.getNumRows(); int n = frame.getNumColumns(); MatrixBlock mb = new MatrixBlock(m, n, false); mb.allocateDenseBlock(); ValueType[] schema = frame.getSchema(); int dFreq = UtilFunctions.frequency(schema, ValueType.DOUBLE); if( dFreq == schema.length ) { // special case double schema (without cell-object creation, // cache-friendly row-column copy) double[][] a = new double[n][]; double[] c = mb.getDenseBlock(); for( int j=0; j<n; j++ ) a[j] = (double[])frame.getColumn(j); int blocksizeIJ = 16; //blocks of a+overhead/c in L1 cache for( int bi=0; bi<m; bi+=blocksizeIJ ) for( int bj=0; bj<n; bj+=blocksizeIJ ) { int bimin = Math.min(bi+blocksizeIJ, m); int bjmin = Math.min(bj+blocksizeIJ, n); for( int i=bi, aix=bi*n; i<bimin; i++, aix+=n ) for( int j=bj; j<bjmin; j++ ) c[aix+j] = a[j][i]; } } else { //general case for( int i=0; i<frame.getNumRows(); i++ ) for( int j=0; j<frame.getNumColumns(); j++ ) { mb.appendValue(i, j, UtilFunctions.objectToDouble( schema[j], frame.get(i, j))); } } //post-processing mb.examSparsity(); return mb; } /** * Converts a frame block with arbitrary schema into a two dimensional * string array. * * @param frame frame block * @return 2d string array * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static String[][] convertToStringFrame(FrameBlock frame) throws DMLRuntimeException { String[][] ret = new String[frame.getNumRows()][]; Iterator<String[]> iter = frame.getStringRowIterator(); for( int i=0; iter.hasNext(); i++ ) { //deep copy output rows due to internal reuse ret[i] = iter.next().clone(); } return ret; } /** * Converts a two dimensions string array into a frame block of * value type string. If the given array is null or of length 0, * we return an empty frame block. * * @param data 2d string array * @return frame block */ public static FrameBlock convertToFrameBlock(String[][] data) { //check for empty frame block if( data == null || data.length==0 ) return new FrameBlock(); //create schema and frame block ValueType[] schema = UtilFunctions.nCopies(data[0].length, ValueType.STRING); return convertToFrameBlock(data, schema); } public static FrameBlock convertToFrameBlock(String[][] data, ValueType[] schema) { //check for empty frame block if( data == null || data.length==0 ) return new FrameBlock(); //create frame block return new FrameBlock(schema, data); } public static FrameBlock convertToFrameBlock(String[][] data, ValueType[] schema, String[] colnames) { //check for empty frame block if( data == null || data.length==0 ) return new FrameBlock(); //create frame block return new FrameBlock(schema, colnames, data); } /** * Converts a matrix block into a frame block of value type double. * * @param mb matrix block * @return frame block of type double */ public static FrameBlock convertToFrameBlock(MatrixBlock mb) { return convertToFrameBlock(mb, ValueType.DOUBLE); } /** * Converts a matrix block into a frame block of a given value type. * * @param mb matrix block * @param vt value type * @return frame block */ public static FrameBlock convertToFrameBlock(MatrixBlock mb, ValueType vt) { //create schema and frame block ValueType[] schema = UtilFunctions.nCopies(mb.getNumColumns(), vt); return convertToFrameBlock(mb, schema); } public static FrameBlock convertToFrameBlock(MatrixBlock mb, ValueType[] schema) { FrameBlock frame = new FrameBlock(schema); Object[] row = new Object[mb.getNumColumns()]; if( mb.isInSparseFormat() ) //SPARSE { SparseBlock sblock = mb.getSparseBlock(); for( int i=0; i<mb.getNumRows(); i++ ) { Arrays.fill(row, null); //reset if( sblock != null && !sblock.isEmpty(i) ) { int apos = sblock.pos(i); int alen = sblock.size(i); int[] aix = sblock.indexes(i); double[] aval = sblock.values(i); for( int j=apos; j<apos+alen; j++ ) { row[aix[j]] = UtilFunctions.doubleToObject( schema[aix[j]], aval[j]); } } frame.appendRow(row); } } else //DENSE { int dFreq = UtilFunctions.frequency(schema, ValueType.DOUBLE); if( dFreq == schema.length ) { // special case double schema (without cell-object creation, // col pre-allocation, and cache-friendly row-column copy) int m = mb.getNumRows(); int n = mb.getNumColumns(); double[] a = mb.getDenseBlock(); double[][] c = new double[n][m]; int blocksizeIJ = 16; //blocks of a/c+overhead in L1 cache if( !mb.isEmptyBlock(false) ) for( int bi=0; bi<m; bi+=blocksizeIJ ) for( int bj=0; bj<n; bj+=blocksizeIJ ) { int bimin = Math.min(bi+blocksizeIJ, m); int bjmin = Math.min(bj+blocksizeIJ, n); for( int i=bi, aix=bi*n; i<bimin; i++, aix+=n ) for( int j=bj; j<bjmin; j++ ) c[j][i] = a[aix+j]; } frame.reset(); frame.appendColumns(c); } else { // general case for( int i=0; i<mb.getNumRows(); i++ ) { for( int j=0; j<mb.getNumColumns(); j++ ) { row[j] = UtilFunctions.doubleToObject( schema[j], mb.quickGetValue(i, j)); } frame.appendRow(row); } } } return frame; } public static MatrixBlock[] convertToMatrixBlockPartitions( MatrixBlock mb, boolean colwise ) throws DMLRuntimeException { MatrixBlock[] ret = null; int rows = mb.getNumRows(); int cols = mb.getNumColumns(); long nnz = mb.getNonZeros(); boolean sparse = mb.isInSparseFormat(); double sparsity = ((double)nnz)/(rows*cols); if( colwise ) //COL PARTITIONS { //allocate output partitions ret = new MatrixBlock[ cols ]; for( int j=0; j<cols; j++ ) ret[j] = new MatrixBlock(rows, 1, false); //cache-friendly sequential read/append if( !mb.isEmptyBlock(false) ) { if( sparse ){ //SPARSE Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getJ()].appendValue(cell.getI(), 0, cell.getV()); } } else { //DENSE for( int i=0; i<rows; i++ ) for( int j=0; j<cols; j++ ) ret[j].appendValue(i, 0, mb.getValueDenseUnsafe(i, j)); } } } else //ROW PARTITIONS { //allocate output partitions ret = new MatrixBlock[ rows ]; for( int i=0; i<rows; i++ ) ret[i] = new MatrixBlock(1, cols, sparse, (long)(cols*sparsity)); //cache-friendly sparse/dense row slicing if( !mb.isEmptyBlock(false) ) { for( int i=0; i<rows; i++ ) mb.sliceOperations(i, i, 0, cols-1, ret[i]); } } return ret; } /** * Helper method that converts SystemML matrix variable (<code>varname</code>) into a Array2DRowRealMatrix format, * which is useful in invoking Apache CommonsMath. * * @param mo matrix object * @return matrix as a commons-math3 Array2DRowRealMatrix * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static Array2DRowRealMatrix convertToArray2DRowRealMatrix(MatrixObject mo) throws DMLRuntimeException { MatrixBlock mb = mo.acquireRead(); double[][] data = DataConverter.convertToDoubleMatrix(mb); mo.release(); return new Array2DRowRealMatrix(data, false); } public static void copyToDoubleVector( MatrixBlock mb, double[] dest, int destPos ) { if( mb.isEmptyBlock(false) ) return; //quick path int rows = mb.getNumRows(); int cols = mb.getNumColumns(); if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); dest[destPos+cell.getI()*cols+cell.getJ()] = cell.getV(); } } else { //memcopy row major representation if at least 1 non-zero System.arraycopy(mb.getDenseBlock(), 0, dest, destPos, rows*cols); } } /** * Convenience method to print NaN & Infinity compliant with how as.scalar prints them. * {@link DecimalFormat} prints NaN as \uFFFD and Infinity as \u221E * http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html * @param df The {@link DecimalFormat} instance, constructed with the appropriate options * @param value The double value to print * @return a string formatted with the {@link DecimalFormat} instance or "NaN" or "Infinity" or "-Infinity" */ private static String dfFormat(DecimalFormat df, double value) { if (Double.isNaN(value) || Double.isInfinite(value)){ return Double.toString(value); } else { return df.format(value); } } public static String toString(MatrixBlock mb) { return toString(mb, false, " ", "\n", mb.getNumRows(), mb.getNumColumns(), 3); } /** * Returns a string representation of a matrix * @param mb matrix block * @param sparse if true, string will contain a table with row index, col index, value (where value != 0.0) * otherwise it will be a rectangular string with all values of the matrix block * @param separator Separator string between each element in a row, or between the columns in sparse format * @param lineseparator Separator string between each row * @param rowsToPrint maximum number of rows to print, -1 for all * @param colsToPrint maximum number of columns to print, -1 for all * @param decimal number of decimal places to print, -1 for default * @return matrix as a string */ public static String toString(MatrixBlock mb, boolean sparse, String separator, String lineseparator, int rowsToPrint, int colsToPrint, int decimal){ StringBuffer sb = new StringBuffer(); // Setup number of rows and columns to print int rlen = mb.getNumRows(); int clen = mb.getNumColumns(); int rowLength = rlen; int colLength = clen; if (rowsToPrint >= 0) rowLength = rowsToPrint < rlen ? rowsToPrint : rlen; if (colsToPrint >= 0) colLength = colsToPrint < clen ? colsToPrint : clen; DecimalFormat df = new DecimalFormat(); df.setGroupingUsed(false); if (decimal >= 0){ df.setMinimumFractionDigits(decimal); } if (sparse){ // Sparse Print Format if (mb.isInSparseFormat()){ // Block is in sparse format Iterator<IJV> sbi = mb.getSparseBlockIterator(); while (sbi.hasNext()){ IJV ijv = sbi.next(); int row = ijv.getI(); int col = ijv.getJ(); double value = ijv.getV(); if (row < rowLength && col < colLength) { // Print (row+1) and (col+1) since for a DML user, everything is 1-indexed sb.append(row+1).append(separator).append(col+1).append(separator); sb.append(dfFormat(df, value)).append(lineseparator); } } } else { // Block is in dense format for (int i=0; i<rowLength; i++){ for (int j=0; j<colLength; j++){ double value = mb.getValue(i, j); if (value != 0.0){ sb.append(i+1).append(separator).append(j+1).append(separator); sb.append(dfFormat(df, value)).append(lineseparator); } } } } } else { // Dense Print Format for (int i=0; i<rowLength; i++){ for (int j=0; j<colLength-1; j++){ double value = mb.quickGetValue(i, j); sb.append(dfFormat(df, value)); sb.append(separator); } double value = mb.quickGetValue(i, colLength-1); sb.append(dfFormat(df, value)); // Do not put separator after last element sb.append(lineseparator); } } return sb.toString(); } public static String toString(FrameBlock fb) { return toString(fb, false, " ", "\n", fb.getNumRows(), fb.getNumColumns(), 3); } public static String toString(FrameBlock fb, boolean sparse, String separator, String lineseparator, int rowsToPrint, int colsToPrint, int decimal) { StringBuffer sb = new StringBuffer(); // Setup number of rows and columns to print int rlen = fb.getNumRows(); int clen = fb.getNumColumns(); int rowLength = rlen; int colLength = clen; if (rowsToPrint >= 0) rowLength = rowsToPrint < rlen ? rowsToPrint : rlen; if (colsToPrint >= 0) colLength = colsToPrint < clen ? colsToPrint : clen; //print frame header sb.append("# FRAME: "); sb.append("nrow = " + fb.getNumRows() + ", "); sb.append("ncol = " + fb.getNumColumns() + lineseparator); //print column names sb.append("#"); sb.append(separator); for( int j=0; j<colLength; j++ ) { sb.append(fb.getColumnNames()[j]); if( j != colLength-1 ) sb.append(separator); } sb.append(lineseparator); //print schema sb.append("#"); sb.append(separator); for( int j=0; j<colLength; j++ ) { sb.append(fb.getSchema()[j]); if( j != colLength-1 ) sb.append(separator); } sb.append(lineseparator); //print data DecimalFormat df = new DecimalFormat(); df.setGroupingUsed(false); if (decimal >= 0) df.setMinimumFractionDigits(decimal); Iterator<Object[]> iter = fb.getObjectRowIterator(0, rowLength); while( iter.hasNext() ) { Object[] row = iter.next(); for( int j=0; j<colLength; j++ ) { if( row[j]!=null ) { if( fb.getSchema()[j] == ValueType.DOUBLE ) sb.append(dfFormat(df, (Double)row[j])); else sb.append(row[j]); if( j != colLength-1 ) sb.append(separator); } } sb.append(lineseparator); } return sb.toString(); } }
src/main/java/org/apache/sysml/runtime/util/DataConverter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sysml.runtime.util; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.sysml.parser.Expression.ValueType; import org.apache.sysml.runtime.DMLRuntimeException; import org.apache.sysml.runtime.controlprogram.caching.MatrixObject; import org.apache.sysml.runtime.io.MatrixReader; import org.apache.sysml.runtime.io.MatrixReaderFactory; import org.apache.sysml.runtime.io.MatrixWriter; import org.apache.sysml.runtime.io.MatrixWriterFactory; import org.apache.sysml.runtime.io.ReadProperties; import org.apache.sysml.runtime.matrix.MatrixCharacteristics; import org.apache.sysml.runtime.matrix.data.CTableMap; import org.apache.sysml.runtime.matrix.data.FileFormatProperties; import org.apache.sysml.runtime.matrix.data.FrameBlock; import org.apache.sysml.runtime.matrix.data.IJV; import org.apache.sysml.runtime.matrix.data.InputInfo; import org.apache.sysml.runtime.matrix.data.MatrixBlock; import org.apache.sysml.runtime.matrix.data.MatrixIndexes; import org.apache.sysml.runtime.matrix.data.OutputInfo; import org.apache.sysml.runtime.matrix.data.SparseBlock; /** * This class provides methods to read and write matrix blocks from to HDFS using different data formats. * Those functionalities are used especially for CP read/write and exporting in-memory matrices to HDFS * (before executing MR jobs). * */ public class DataConverter { ////////////// // READING and WRITING of matrix blocks to/from HDFS // (textcell, binarycell, binaryblock) /////// public static void writeMatrixToHDFS(MatrixBlock mat, String dir, OutputInfo outputinfo, MatrixCharacteristics mc ) throws IOException { writeMatrixToHDFS(mat, dir, outputinfo, mc, -1, null); } public static void writeMatrixToHDFS(MatrixBlock mat, String dir, OutputInfo outputinfo, MatrixCharacteristics mc, int replication, FileFormatProperties formatProperties) throws IOException { try { MatrixWriter writer = MatrixWriterFactory.createMatrixWriter( outputinfo, replication, formatProperties ); writer.writeMatrixToHDFS(mat, dir, mc.getRows(), mc.getCols(), mc.getRowsPerBlock(), mc.getColsPerBlock(), mc.getNonZeros()); } catch(Exception e) { throw new IOException(e); } } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen, boolean localFS) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; prop.localFS = localFS; //expected matrix is sparse (default SystemML usecase) return readMatrixFromHDFS(prop); } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; //expected matrix is sparse (default SystemML usecase) return readMatrixFromHDFS(prop); } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen, double expectedSparsity) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; prop.expectedSparsity = expectedSparsity; return readMatrixFromHDFS(prop); } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen, double expectedSparsity, boolean localFS) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; prop.expectedSparsity = expectedSparsity; prop.localFS = localFS; return readMatrixFromHDFS(prop); } public static MatrixBlock readMatrixFromHDFS(String dir, InputInfo inputinfo, long rlen, long clen, int brlen, int bclen, double expectedSparsity, FileFormatProperties formatProperties) throws IOException { ReadProperties prop = new ReadProperties(); prop.path = dir; prop.inputInfo = inputinfo; prop.rlen = rlen; prop.clen = clen; prop.brlen = brlen; prop.bclen = bclen; prop.expectedSparsity = expectedSparsity; prop.formatProperties = formatProperties; //prop.printMe(); return readMatrixFromHDFS(prop); } /** * Core method for reading matrices in format textcell, matrixmarket, binarycell, or binaryblock * from HDFS into main memory. For expected dense matrices we directly copy value- or block-at-a-time * into the target matrix. In contrast, for sparse matrices, we append (column-value)-pairs and do a * final sort if required in order to prevent large reorg overheads and increased memory consumption * in case of unordered inputs. * * DENSE MxN input: * * best/average/worst: O(M*N) * SPARSE MxN input * * best (ordered, or binary block w/ clen&lt;=bclen): O(M*N) * * average (unordered): O(M*N*log(N)) * * worst (descending order per row): O(M * N^2) * * NOTE: providing an exact estimate of 'expected sparsity' can prevent a full copy of the result * matrix block (required for changing sparse-&gt;dense, or vice versa) * * @param prop read properties * @return matrix block * @throws IOException if IOException occurs */ public static MatrixBlock readMatrixFromHDFS(ReadProperties prop) throws IOException { //Timing time = new Timing(true); long estnnz = (long)(prop.expectedSparsity*prop.rlen*prop.clen); //core matrix reading MatrixBlock ret = null; try { MatrixReader reader = MatrixReaderFactory.createMatrixReader(prop); ret = reader.readMatrixFromHDFS(prop.path, prop.rlen, prop.clen, prop.brlen, prop.bclen, estnnz); } catch(DMLRuntimeException rex) { throw new IOException(rex); } //System.out.println("read matrix ("+prop.rlen+","+prop.clen+","+ret.getNonZeros()+") in "+time.stop()); return ret; } ////////////// // Utils for CREATING and COPYING matrix blocks /////// /** * Creates a two-dimensional double matrix of the input matrix block. * * @param mb matrix block * @return 2d double array */ public static double[][] convertToDoubleMatrix( MatrixBlock mb ) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); double[][] ret = new double[rows][cols]; //0-initialized if( mb.getNonZeros() > 0 ) { if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getI()][cell.getJ()] = cell.getV(); } } else { for( int i=0; i<rows; i++ ) for( int j=0; j<cols; j++ ) ret[i][j] = mb.getValueDenseUnsafe(i, j); } } return ret; } public static boolean [] convertToBooleanVector(MatrixBlock mb) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); boolean[] ret = new boolean[rows*cols]; //false-initialized if( mb.getNonZeros() > 0 ) { if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getI()*cols+cell.getJ()] = (cell.getV() != 0.0); } } else { for( int i=0, cix=0; i<rows; i++ ) for( int j=0; j<cols; j++, cix++) ret[cix] = (mb.getValueDenseUnsafe(i, j) != 0.0); } } return ret; } public static int[] convertToIntVector( MatrixBlock mb) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); int[] ret = new int[rows*cols]; //0-initialized if( mb.getNonZeros() > 0 ) { if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getI()*cols+cell.getJ()] = (int)cell.getV(); } } else { //memcopy row major representation if at least 1 non-zero for( int i=0, cix=0; i<rows; i++ ) for( int j=0; j<cols; j++, cix++ ) ret[cix] = (int)(mb.getValueDenseUnsafe(i, j)); } } return ret; } public static double[] convertToDoubleVector( MatrixBlock mb ) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); double[] ret = new double[rows*cols]; //0-initialized if( mb.getNonZeros() > 0 ) { if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getI()*cols+cell.getJ()] = cell.getV(); } } else { //memcopy row major representation if at least 1 non-zero System.arraycopy(mb.getDenseBlock(), 0, ret, 0, rows*cols); } } return ret; } public static List<Double> convertToDoubleList( MatrixBlock mb ) { int rows = mb.getNumRows(); int cols = mb.getNumColumns(); long nnz = mb.getNonZeros(); ArrayList<Double> ret = new ArrayList<Double>(); if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret.add( cell.getV() ); } for( long i=nnz; i<(long)rows*cols; i++ ) ret.add( 0d ); //add remaining values } else { for( int i=0; i<rows; i++ ) for( int j=0; j<cols; j++ ) ret.add( mb.getValueDenseUnsafe(i, j) ); } return ret; } /** * Creates a dense Matrix Block and copies the given double matrix into it. * * @param data 2d double array * @return matrix block * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static MatrixBlock convertToMatrixBlock( double[][] data ) throws DMLRuntimeException { int rows = data.length; int cols = (rows > 0)? data[0].length : 0; MatrixBlock mb = new MatrixBlock(rows, cols, false); try { //copy data to mb (can be used because we create a dense matrix) mb.init( data, rows, cols ); } catch (Exception e){} //can never happen //check and convert internal representation mb.examSparsity(); return mb; } /** * Creates a dense Matrix Block and copies the given double vector into it. * * @param data double array * @param columnVector if true, create matrix with single column. if false, create matrix with single row * @return matrix block * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static MatrixBlock convertToMatrixBlock( double[] data, boolean columnVector ) throws DMLRuntimeException { int rows = columnVector ? data.length : 1; int cols = columnVector ? 1 : data.length; MatrixBlock mb = new MatrixBlock(rows, cols, false); try { //copy data to mb (can be used because we create a dense matrix) mb.init( data, rows, cols ); } catch (Exception e){} //can never happen //check and convert internal representation mb.examSparsity(); return mb; } public static MatrixBlock convertToMatrixBlock( HashMap<MatrixIndexes,Double> map ) { // compute dimensions from the map long nrows=0, ncols=0; for (MatrixIndexes index : map.keySet()) { nrows = Math.max( nrows, index.getRowIndex() ); ncols = Math.max( ncols, index.getColumnIndex() ); } // convert to matrix block return convertToMatrixBlock(map, (int)nrows, (int)ncols); } /** * NOTE: this method also ensures the specified matrix dimensions * * @param map map of matrix index keys and double values * @param rlen number of rows * @param clen number of columns * @return matrix block */ public static MatrixBlock convertToMatrixBlock( HashMap<MatrixIndexes,Double> map, int rlen, int clen ) { int nnz = map.size(); boolean sparse = MatrixBlock.evalSparseFormatInMemory(rlen, clen, nnz); MatrixBlock mb = new MatrixBlock(rlen, clen, sparse, nnz); // copy map values into new block if( sparse ) //SPARSE <- cells { //append cells to sparse target (prevent shifting) for( Entry<MatrixIndexes,Double> e : map.entrySet() ) { MatrixIndexes index = e.getKey(); double value = e.getValue(); int rix = (int)index.getRowIndex(); int cix = (int)index.getColumnIndex(); if( value != 0 && rix<=rlen && cix<=clen ) mb.appendValue( rix-1, cix-1, value ); } //sort sparse target representation mb.sortSparseRows(); } else //DENSE <- cells { //directly insert cells into dense target for( Entry<MatrixIndexes,Double> e : map.entrySet() ) { MatrixIndexes index = e.getKey(); double value = e.getValue(); int rix = (int)index.getRowIndex(); int cix = (int)index.getColumnIndex(); if( value != 0 && rix<=rlen && cix<=clen ) mb.quickSetValue( rix-1, cix-1, value ); } } return mb; } public static MatrixBlock convertToMatrixBlock( CTableMap map ) { // compute dimensions from the map int nrows = (int)map.getMaxRow(); int ncols = (int)map.getMaxColumn(); // convert to matrix block return convertToMatrixBlock(map, nrows, ncols); } /** * NOTE: this method also ensures the specified matrix dimensions * * @param map ? * @param rlen number of rows * @param clen number of columns * @return matrix block */ public static MatrixBlock convertToMatrixBlock( CTableMap map, int rlen, int clen ) { return map.toMatrixBlock(rlen, clen); } /** * Converts a frame block with arbitrary schema into a matrix block. * Since matrix block only supports value type double, we do a best * effort conversion of non-double types which might result in errors * for non-numerical data. * * @param frame frame block * @return matrix block * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static MatrixBlock convertToMatrixBlock(FrameBlock frame) throws DMLRuntimeException { int m = frame.getNumRows(); int n = frame.getNumColumns(); MatrixBlock mb = new MatrixBlock(m, n, false); mb.allocateDenseBlock(); ValueType[] schema = frame.getSchema(); int dFreq = UtilFunctions.frequency(schema, ValueType.DOUBLE); if( dFreq == schema.length ) { // special case double schema (without cell-object creation, // cache-friendly row-column copy) double[][] a = new double[n][]; double[] c = mb.getDenseBlock(); for( int j=0; j<n; j++ ) a[j] = (double[])frame.getColumn(j); int blocksizeIJ = 16; //blocks of a+overhead/c in L1 cache for( int bi=0; bi<m; bi+=blocksizeIJ ) for( int bj=0; bj<n; bj+=blocksizeIJ ) { int bimin = Math.min(bi+blocksizeIJ, m); int bjmin = Math.min(bj+blocksizeIJ, n); for( int i=bi, aix=bi*n; i<bimin; i++, aix+=n ) for( int j=bj; j<bjmin; j++ ) c[aix+j] = a[j][i]; } } else { //general case for( int i=0; i<frame.getNumRows(); i++ ) for( int j=0; j<frame.getNumColumns(); j++ ) { mb.appendValue(i, j, UtilFunctions.objectToDouble( schema[j], frame.get(i, j))); } } //post-processing mb.examSparsity(); return mb; } /** * Converts a frame block with arbitrary schema into a two dimensional * string array. * * @param frame frame block * @return 2d string array * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static String[][] convertToStringFrame(FrameBlock frame) throws DMLRuntimeException { String[][] ret = new String[frame.getNumRows()][]; Iterator<String[]> iter = frame.getStringRowIterator(); for( int i=0; iter.hasNext(); i++ ) { //deep copy output rows due to internal reuse ret[i] = iter.next().clone(); } return ret; } /** * Converts a two dimensions string array into a frame block of * value type string. If the given array is null or of length 0, * we return an empty frame block. * * @param data 2d string array * @return frame block */ public static FrameBlock convertToFrameBlock(String[][] data) { //check for empty frame block if( data == null || data.length==0 ) return new FrameBlock(); //create schema and frame block ValueType[] schema = UtilFunctions.nCopies(data[0].length, ValueType.STRING); return convertToFrameBlock(data, schema); } public static FrameBlock convertToFrameBlock(String[][] data, ValueType[] schema) { //check for empty frame block if( data == null || data.length==0 ) return new FrameBlock(); //create frame block return new FrameBlock(schema, data); } public static FrameBlock convertToFrameBlock(String[][] data, ValueType[] schema, String[] colnames) { //check for empty frame block if( data == null || data.length==0 ) return new FrameBlock(); //create frame block return new FrameBlock(schema, colnames, data); } /** * Converts a matrix block into a frame block of value type double. * * @param mb matrix block * @return frame block of type double */ public static FrameBlock convertToFrameBlock(MatrixBlock mb) { return convertToFrameBlock(mb, ValueType.DOUBLE); } /** * Converts a matrix block into a frame block of a given value type. * * @param mb matrix block * @param vt value type * @return frame block */ public static FrameBlock convertToFrameBlock(MatrixBlock mb, ValueType vt) { //create schema and frame block ValueType[] schema = UtilFunctions.nCopies(mb.getNumColumns(), vt); return convertToFrameBlock(mb, schema); } public static FrameBlock convertToFrameBlock(MatrixBlock mb, ValueType[] schema) { FrameBlock frame = new FrameBlock(schema); Object[] row = new Object[mb.getNumColumns()]; if( mb.isInSparseFormat() ) //SPARSE { SparseBlock sblock = mb.getSparseBlock(); for( int i=0; i<mb.getNumRows(); i++ ) { Arrays.fill(row, null); //reset if( sblock != null && !sblock.isEmpty(i) ) { int apos = sblock.pos(i); int alen = sblock.size(i); int[] aix = sblock.indexes(i); double[] aval = sblock.values(i); for( int j=apos; j<apos+alen; j++ ) { row[aix[j]] = UtilFunctions.doubleToObject( schema[aix[j]], aval[j]); } } frame.appendRow(row); } } else //DENSE { int dFreq = UtilFunctions.frequency(schema, ValueType.DOUBLE); if( dFreq == schema.length ) { // special case double schema (without cell-object creation, // col pre-allocation, and cache-friendly row-column copy) int m = mb.getNumRows(); int n = mb.getNumColumns(); double[] a = mb.getDenseBlock(); double[][] c = new double[n][m]; int blocksizeIJ = 16; //blocks of a/c+overhead in L1 cache if( !mb.isEmptyBlock(false) ) for( int bi=0; bi<m; bi+=blocksizeIJ ) for( int bj=0; bj<n; bj+=blocksizeIJ ) { int bimin = Math.min(bi+blocksizeIJ, m); int bjmin = Math.min(bj+blocksizeIJ, n); for( int i=bi, aix=bi*n; i<bimin; i++, aix+=n ) for( int j=bj; j<bjmin; j++ ) c[j][i] = a[aix+j]; } frame.reset(); frame.appendColumns(c); } else { // general case for( int i=0; i<mb.getNumRows(); i++ ) { for( int j=0; j<mb.getNumColumns(); j++ ) { row[j] = UtilFunctions.doubleToObject( schema[j], mb.quickGetValue(i, j)); } frame.appendRow(row); } } } return frame; } public static MatrixBlock[] convertToMatrixBlockPartitions( MatrixBlock mb, boolean colwise ) throws DMLRuntimeException { MatrixBlock[] ret = null; int rows = mb.getNumRows(); int cols = mb.getNumColumns(); long nnz = mb.getNonZeros(); boolean sparse = mb.isInSparseFormat(); double sparsity = ((double)nnz)/(rows*cols); if( colwise ) //COL PARTITIONS { //allocate output partitions ret = new MatrixBlock[ cols ]; for( int j=0; j<cols; j++ ) ret[j] = new MatrixBlock(rows, 1, false); //cache-friendly sequential read/append if( !mb.isEmptyBlock(false) ) { if( sparse ){ //SPARSE Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); ret[cell.getJ()].appendValue(cell.getI(), 0, cell.getV()); } } else { //DENSE for( int i=0; i<rows; i++ ) for( int j=0; j<cols; j++ ) ret[j].appendValue(i, 0, mb.getValueDenseUnsafe(i, j)); } } } else //ROW PARTITIONS { //allocate output partitions ret = new MatrixBlock[ rows ]; for( int i=0; i<rows; i++ ) ret[i] = new MatrixBlock(1, cols, sparse, (long)(cols*sparsity)); //cache-friendly sparse/dense row slicing if( !mb.isEmptyBlock(false) ) { for( int i=0; i<rows; i++ ) mb.sliceOperations(i, i, 0, cols-1, ret[i]); } } return ret; } /** * Helper method that converts SystemML matrix variable (<code>varname</code>) into a Array2DRowRealMatrix format, * which is useful in invoking Apache CommonsMath. * * @param mo matrix object * @return matrix as a commons-math3 Array2DRowRealMatrix * @throws DMLRuntimeException if DMLRuntimeException occurs */ public static Array2DRowRealMatrix convertToArray2DRowRealMatrix(MatrixObject mo) throws DMLRuntimeException { MatrixBlock mb = mo.acquireRead(); double[][] data = DataConverter.convertToDoubleMatrix(mb); mo.release(); return new Array2DRowRealMatrix(data, false); } public static void copyToDoubleVector( MatrixBlock mb, double[] dest, int destPos ) { if( mb.isEmptyBlock(false) ) return; //quick path int rows = mb.getNumRows(); int cols = mb.getNumColumns(); if( mb.isInSparseFormat() ) { Iterator<IJV> iter = mb.getSparseBlockIterator(); while( iter.hasNext() ) { IJV cell = iter.next(); dest[destPos+cell.getI()*cols+cell.getJ()] = cell.getV(); } } else { //memcopy row major representation if at least 1 non-zero System.arraycopy(mb.getDenseBlock(), 0, dest, destPos, rows*cols); } } public static String toString(MatrixBlock mb) { return toString(mb, false, " ", "\n", mb.getNumRows(), mb.getNumColumns(), 3); } /** * Returns a string representation of a matrix * @param mb matrix block * @param sparse if true, string will contain a table with row index, col index, value (where value != 0.0) * otherwise it will be a rectangular string with all values of the matrix block * @param separator Separator string between each element in a row, or between the columns in sparse format * @param lineseparator Separator string between each row * @param rowsToPrint maximum number of rows to print, -1 for all * @param colsToPrint maximum number of columns to print, -1 for all * @param decimal number of decimal places to print, -1 for default * @return matrix as a string */ public static String toString(MatrixBlock mb, boolean sparse, String separator, String lineseparator, int rowsToPrint, int colsToPrint, int decimal){ StringBuffer sb = new StringBuffer(); // Setup number of rows and columns to print int rlen = mb.getNumRows(); int clen = mb.getNumColumns(); int rowLength = rlen; int colLength = clen; if (rowsToPrint >= 0) rowLength = rowsToPrint < rlen ? rowsToPrint : rlen; if (colsToPrint >= 0) colLength = colsToPrint < clen ? colsToPrint : clen; DecimalFormat df = new DecimalFormat(); df.setGroupingUsed(false); if (decimal >= 0){ df.setMinimumFractionDigits(decimal); } if (sparse){ // Sparse Print Format if (mb.isInSparseFormat()){ // Block is in sparse format Iterator<IJV> sbi = mb.getSparseBlockIterator(); while (sbi.hasNext()){ IJV ijv = sbi.next(); int row = ijv.getI(); int col = ijv.getJ(); double value = ijv.getV(); if (row < rowLength && col < colLength) { // Print (row+1) and (col+1) since for a DML user, everything is 1-indexed sb.append(row+1).append(separator).append(col+1).append(separator); sb.append(df.format(value)).append(lineseparator); } } } else { // Block is in dense format for (int i=0; i<rowLength; i++){ for (int j=0; j<colLength; j++){ double value = mb.getValue(i, j); if (value != 0.0){ sb.append(i+1).append(separator).append(j+1).append(separator); sb.append(df.format(value)).append(lineseparator); } } } } } else { // Dense Print Format for (int i=0; i<rowLength; i++){ for (int j=0; j<colLength-1; j++){ double value = mb.quickGetValue(i, j); sb.append(df.format(value)); sb.append(separator); } double value = mb.quickGetValue(i, colLength-1); sb.append(df.format(value)); // Do not put separator after last element sb.append(lineseparator); } } return sb.toString(); } public static String toString(FrameBlock fb) { return toString(fb, false, " ", "\n", fb.getNumRows(), fb.getNumColumns(), 3); } public static String toString(FrameBlock fb, boolean sparse, String separator, String lineseparator, int rowsToPrint, int colsToPrint, int decimal) { StringBuffer sb = new StringBuffer(); // Setup number of rows and columns to print int rlen = fb.getNumRows(); int clen = fb.getNumColumns(); int rowLength = rlen; int colLength = clen; if (rowsToPrint >= 0) rowLength = rowsToPrint < rlen ? rowsToPrint : rlen; if (colsToPrint >= 0) colLength = colsToPrint < clen ? colsToPrint : clen; //print frame header sb.append("# FRAME: "); sb.append("nrow = " + fb.getNumRows() + ", "); sb.append("ncol = " + fb.getNumColumns() + lineseparator); //print column names sb.append("#"); sb.append(separator); for( int j=0; j<colLength; j++ ) { sb.append(fb.getColumnNames()[j]); if( j != colLength-1 ) sb.append(separator); } sb.append(lineseparator); //print schema sb.append("#"); sb.append(separator); for( int j=0; j<colLength; j++ ) { sb.append(fb.getSchema()[j]); if( j != colLength-1 ) sb.append(separator); } sb.append(lineseparator); //print data DecimalFormat df = new DecimalFormat(); df.setGroupingUsed(false); if (decimal >= 0) df.setMinimumFractionDigits(decimal); Iterator<Object[]> iter = fb.getObjectRowIterator(0, rowLength); while( iter.hasNext() ) { Object[] row = iter.next(); for( int j=0; j<colLength; j++ ) { if( row[j]!=null ) { if( fb.getSchema()[j] == ValueType.DOUBLE ) sb.append(df.format(row[j])); else sb.append(row[j]); if( j != colLength-1 ) sb.append(separator); } } sb.append(lineseparator); } return sb.toString(); } }
toString now prints NaN & Infinity like how as.scalar prints them Closes #415
src/main/java/org/apache/sysml/runtime/util/DataConverter.java
toString now prints NaN & Infinity like how as.scalar prints them
<ide><path>rc/main/java/org/apache/sysml/runtime/util/DataConverter.java <ide> System.arraycopy(mb.getDenseBlock(), 0, dest, destPos, rows*cols); <ide> } <ide> } <add> <add> /** <add> * Convenience method to print NaN & Infinity compliant with how as.scalar prints them. <add> * {@link DecimalFormat} prints NaN as \uFFFD and Infinity as \u221E <add> * http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html <add> * @param df The {@link DecimalFormat} instance, constructed with the appropriate options <add> * @param value The double value to print <add> * @return a string formatted with the {@link DecimalFormat} instance or "NaN" or "Infinity" or "-Infinity" <add> */ <add> private static String dfFormat(DecimalFormat df, double value) { <add> if (Double.isNaN(value) || Double.isInfinite(value)){ <add> return Double.toString(value); <add> } else { <add> return df.format(value); <add> } <add> } <ide> <ide> public static String toString(MatrixBlock mb) { <ide> return toString(mb, false, " ", "\n", mb.getNumRows(), mb.getNumColumns(), 3); <ide> if (row < rowLength && col < colLength) { <ide> // Print (row+1) and (col+1) since for a DML user, everything is 1-indexed <ide> sb.append(row+1).append(separator).append(col+1).append(separator); <del> sb.append(df.format(value)).append(lineseparator); <add> sb.append(dfFormat(df, value)).append(lineseparator); <ide> } <ide> } <ide> } else { // Block is in dense format <ide> double value = mb.getValue(i, j); <ide> if (value != 0.0){ <ide> sb.append(i+1).append(separator).append(j+1).append(separator); <del> sb.append(df.format(value)).append(lineseparator); <add> sb.append(dfFormat(df, value)).append(lineseparator); <ide> } <ide> } <ide> } <ide> for (int i=0; i<rowLength; i++){ <ide> for (int j=0; j<colLength-1; j++){ <ide> double value = mb.quickGetValue(i, j); <del> sb.append(df.format(value)); <add> sb.append(dfFormat(df, value)); <ide> sb.append(separator); <ide> } <ide> double value = mb.quickGetValue(i, colLength-1); <del> sb.append(df.format(value)); // Do not put separator after last element <add> sb.append(dfFormat(df, value)); // Do not put separator after last element <ide> sb.append(lineseparator); <ide> } <ide> } <ide> for( int j=0; j<colLength; j++ ) { <ide> if( row[j]!=null ) { <ide> if( fb.getSchema()[j] == ValueType.DOUBLE ) <del> sb.append(df.format(row[j])); <add> sb.append(dfFormat(df, (Double)row[j])); <ide> else <ide> sb.append(row[j]); <ide> if( j != colLength-1 )
Java
apache-2.0
160c209fb72e7b347e81cd081930999f3c520f5f
0
tsygipova/java_first
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactsData; /** * Created by Дарья on 03-Sep-16. */ public class ContactsDeletionTests extends TestBase { @Test public void testContactsDeletion() { if (! app.getContactsHelper().isThereAContact()) { app.getContactsHelper().createContact(new ContactsData("test1", null, null, null, null, null, null, null, null)); } app.getContactsHelper().selectContact(); app.getContactsHelper().initContactDeletion(); app.getContactsHelper().submitContactDeletion(); app.getContactsHelper().returnToContactsPage(); } }
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactsDeletionTests.java
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactsData; /** * Created by Дарья on 03-Sep-16. */ public class ContactsDeletionTests extends TestBase { @Test public void testContactsDeletion() { if (! app.getContactsHelper().isThereAContact()) { app.getContactsHelper().createContact(new ContactsData("test1", null, null, null, null, null, null, null, null)); } app.getContactsHelper().selectContact(); app.getContactsHelper().initContactDeletion(); app.getContactsHelper().submitContactDeletion(); } }
Добавлен недостающий метод
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactsDeletionTests.java
Добавлен недостающий метод
<ide><path>ddressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactsDeletionTests.java <ide> app.getContactsHelper().selectContact(); <ide> app.getContactsHelper().initContactDeletion(); <ide> app.getContactsHelper().submitContactDeletion(); <add> app.getContactsHelper().returnToContactsPage(); <ide> } <ide> }
JavaScript
mit
5461d73cbd6b86a44ce0a3f9ee09735ddbbd2392
0
Vitre/grunt-symfony
/** * grunt-symfony * @author vitre * @licence MIT * @version 1.1.21 * @url https://www.npmjs.org/package/grunt-symfony */ "use strict" var fs = require('fs'), path = require('path'), extend = require('node.extend'); //--- var defaults = { web: 'web', src: 'src', gruntFile: 'Gruntfile.js', resources: 'Resources' }; var options; var bundles; var grunt; /** * getBundles * @param root * @param r */ var getBundles = function (root, r) { if (typeof root === 'undefined') { root = defaults.src; } if (typeof r === 'undefined') { r = []; } var files = fs.readdirSync(root); for (var i in files) { var path = root + '/' + files[i]; if (fs.statSync(path).isDirectory()) { if (path.match(/Bundle$/)) { var name = path.substr(defaults.src.length + 1, path.length); var bundle = { name: name, name_camelcase: name.replace(/\//g, ''), path: path, resources: path + '/' + defaults.resources }; //console.log(bundle); r.push(bundle); } getBundles(path, r); } } return r; }; /** * importBundle * @param bundle * @param config */ var importBundle = function (bundle, config) { var gruntFile = bundle.path + '/' + defaults.gruntFile; if (fs.existsSync(gruntFile)) { var filePath = path.resolve(gruntFile); console.log('Importing bundle: ' + bundle.name + ' [' + gruntFile + ']'); require(filePath)(grunt, config, bundle, options); } }; /** * importBundles * @param config */ var importBundles = function (config) { bundles = getBundles(); for (var i = 0; i < bundles.length; i++) { importBundle(bundles[i], config); } }; /** * Export importBundles * @param _grunt * @param config * @param _options */ exports.importBundles = function (_grunt, config, _options) { grunt = _grunt; if (typeof _options === 'undefined') { options = defaults; } else { options = extend(true, {}, defaults, _options); } importBundles(config); }
grunt-symfony.js
"use strict" var fs = require('fs'), path = require('path'), extend = require('node.extend'); //--- var defaults = { web: 'web', src: 'src', gruntFile: 'Gruntfile.js', resources: 'Resources' }; var options; var bundles; var grunt; /** * getBundles * @param root * @param r * @returns {*} */ var getBundles = function (root, r) { if (typeof root === 'undefined') { root = defaults.src; } if (typeof r === 'undefined') { r = []; } var files = fs.readdirSync(root); for (var i in files) { var path = root + '/' + files[i]; if (fs.statSync(path).isDirectory()) { if (path.match(/Bundle$/)) { var name = path.substr(defaults.src.length + 1, path.length); var bundle = { name: name, name_camelcase: name.replace(/\//g, ''), path: path, resources: path + '/' + defaults.resources }; //console.log(bundle); r.push(bundle); } getBundles(path, r); } } return r; }; /** * importBundle * @param bundle * @param config */ var importBundle = function (bundle, config) { var gruntFile = bundle.path + '/' + defaults.gruntFile; if (fs.existsSync(gruntFile)) { var filePath = path.resolve(gruntFile); console.log('Importing bundle: ' + bundle.name + ' [' + gruntFile + ']'); require(filePath)(grunt, config, bundle, options); } }; /** * importBundles * @param config */ var importBundles = function (config) { bundles = getBundles(); for (var i = 0; i < bundles.length; i++) { importBundle(bundles[i], config); } }; /** * Export importBundles * @param _grunt * @param config * @param _options */ exports.importBundles = function (_grunt, config, _options) { grunt = _grunt; if (typeof _options === 'undefined') { options = defaults; } else { options = extend(true, {}, defaults, _options); } importBundles(config); }
1.1.21
grunt-symfony.js
1.1.21
<ide><path>runt-symfony.js <add>/** <add> * grunt-symfony <add> * @author vitre <add> * @licence MIT <add> * @version 1.1.21 <add> * @url https://www.npmjs.org/package/grunt-symfony <add> */ <add> <ide> "use strict" <ide> <ide> var fs = require('fs'), <ide> * getBundles <ide> * @param root <ide> * @param r <del> * @returns {*} <ide> */ <ide> var getBundles = function (root, r) { <ide> if (typeof root === 'undefined') {
Java
agpl-3.0
d5fc590b8c4753b360b2c9259d966b200a1ef052
0
wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,shunwang/sql-layer-1,relateiq/sql-layer,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,relateiq/sql-layer,relateiq/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,jaytaylor/sql-layer,relateiq/sql-layer,jaytaylor/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,jaytaylor/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer
/** * Copyright (C) 2011 Akiban Technologies Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses. */ package com.akiban.server.test.it.bugs.bug696156; import com.akiban.ais.model.AISBuilder; import com.akiban.server.api.dml.scan.ScanAllRequest; import com.akiban.server.error.DuplicateKeyException; import com.akiban.server.error.InvalidOperationException; import com.akiban.server.test.it.ITBase; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MultipleNullUniqueIndexIT extends ITBase { @Test public void reportTestCase() throws InvalidOperationException { String SCHEMA = "test"; String TABLE = "t1"; String COLUMN = "c1"; AISBuilder builder = new AISBuilder(); builder.userTable(SCHEMA, TABLE); builder.column(SCHEMA, TABLE, COLUMN, 0, "TINYINT", null, null, true, true, null, null); builder.index(SCHEMA, TABLE, "c1", true, "UNIQUE"); builder.indexColumn(SCHEMA, TABLE, COLUMN, COLUMN, 0, true, null); ddl().createTable(session(), builder.akibanInformationSchema().getUserTable(SCHEMA, TABLE)); updateAISGeneration(); final int tid = tableId(SCHEMA, TABLE); writeRows(createNewRow(tid, null, -1L)); writeRows(createNewRow(tid, null, -1L)); expectFullRows(tid, createNewRow(tid, (Object)null), createNewRow(tid, (Object)null)); } @Test public void singleColumnUniqueWithNulls() throws InvalidOperationException { final int tid = createTable("test", "t1", "id int not null primary key, name varchar(32), unique(name)"); writeRows(createNewRow(tid, 1, "abc"), createNewRow(tid, 2, "def"), createNewRow(tid, 3, null), createNewRow(tid, 4, "ghi"), createNewRow(tid, 5, null)); assertEquals(5, scanAll(new ScanAllRequest(tid, null)).size()); try { writeRows(createNewRow(tid, 6, "abc")); Assert.fail("DuplicateKeyException expected"); } catch(DuplicateKeyException e) { } } @Test public void multiColumnUniqueWithNulls() throws InvalidOperationException { final int tid = createTable("test", "t1", "id int not null primary key, seg1 int, seg2 int, seg3 int, unique(seg1,seg2,seg3)"); writeRows(createNewRow(tid, 1, 1, 1, 1), createNewRow(tid, 2, 1, 1, null), createNewRow(tid, 3, 1, null, 1), createNewRow(tid, 4, 1, null, null), createNewRow(tid, 5, null, 1, 1), createNewRow(tid, 6, null, 1, null), createNewRow(tid, 7, null, null, null), createNewRow(tid, 8, null, null, null)); assertEquals(8, scanAll(new ScanAllRequest(tid, null)).size()); try { writeRows(createNewRow(tid, 9, 1, 1, 1)); Assert.fail("DuplicateKeyException expected"); } catch(DuplicateKeyException e) { } } @Test public void singleColumnIndexWithNulls() throws InvalidOperationException { final int tid = createTable("test", "t1", "id int not null primary key, name varchar(32)"); createIndex("test", "t1", "name", "name"); writeRows(createNewRow(tid, 1, "abc"), createNewRow(tid, 2, "def"), createNewRow(tid, 3, "abc"), createNewRow(tid, 4, null), createNewRow(tid, 5, null)); assertEquals(5, scanAll(new ScanAllRequest(tid, null)).size()); } @Test public void multiColumnIndexWithNulls() throws InvalidOperationException { final int tid = createTable("test", "t1", "id int not null primary key, seg1 int, seg2 int"); createIndex("test", "t1", "seg1", "seg1", "seg2"); writeRows(createNewRow(tid, 1, 1, 1), createNewRow(tid, 2, 2, 2), createNewRow(tid, 3, 1, 1), createNewRow(tid, 4, 1, null), createNewRow(tid, 5, null, 1), createNewRow(tid, 6, 1, null), createNewRow(tid, 7, null, 1), createNewRow(tid, 8, null, null), createNewRow(tid, 9, null, null)); assertEquals(9, scanAll(new ScanAllRequest(tid, null)).size()); } }
src/test/java/com/akiban/server/test/it/bugs/bug696156/MultipleNullUniqueIndexIT.java
/** * Copyright (C) 2011 Akiban Technologies Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses. */ package com.akiban.server.test.it.bugs.bug696156; import com.akiban.server.api.dml.scan.ScanAllRequest; import com.akiban.server.error.DuplicateKeyException; import com.akiban.server.error.InvalidOperationException; import com.akiban.server.test.it.ITBase; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MultipleNullUniqueIndexIT extends ITBase { @Test public void reportTestCase() throws InvalidOperationException { final int tid = createTable("test", "t1", "c1 TINYINT AUTO_INCREMENT NULL UNIQUE KEY"); writeRows(createNewRow(tid, null, -1L)); writeRows(createNewRow(tid, null, -1L)); expectFullRows(tid, createNewRow(tid, (Object)null), createNewRow(tid, (Object)null)); } @Test public void singleColumnUniqueWithNulls() throws InvalidOperationException { final int tid = createTable("test", "t1", "id int key, name varchar(32), unique(name)"); writeRows(createNewRow(tid, 1, "abc"), createNewRow(tid, 2, "def"), createNewRow(tid, 3, null), createNewRow(tid, 4, "ghi"), createNewRow(tid, 5, null)); assertEquals(5, scanAll(new ScanAllRequest(tid, null)).size()); try { writeRows(createNewRow(tid, 6, "abc")); Assert.fail("DuplicateKeyException expected"); } catch(DuplicateKeyException e) { } } @Test public void multiColumnUniqueWithNulls() throws InvalidOperationException { final int tid = createTable("test", "t1", "id int key, seg1 int, seg2 int, seg3 int, unique(seg1,seg2,seg3)"); writeRows(createNewRow(tid, 1, 1, 1, 1), createNewRow(tid, 2, 1, 1, null), createNewRow(tid, 3, 1, null, 1), createNewRow(tid, 4, 1, null, null), createNewRow(tid, 5, null, 1, 1), createNewRow(tid, 6, null, 1, null), createNewRow(tid, 7, null, null, null), createNewRow(tid, 8, null, null, null)); assertEquals(8, scanAll(new ScanAllRequest(tid, null)).size()); try { writeRows(createNewRow(tid, 9, 1, 1, 1)); Assert.fail("DuplicateKeyException expected"); } catch(DuplicateKeyException e) { } } @Test public void singleColumnIndexWithNulls() throws InvalidOperationException { final int tid = createTable("test", "t1", "id int key, name varchar(32), index(name)"); writeRows(createNewRow(tid, 1, "abc"), createNewRow(tid, 2, "def"), createNewRow(tid, 3, "abc"), createNewRow(tid, 4, null), createNewRow(tid, 5, null)); assertEquals(5, scanAll(new ScanAllRequest(tid, null)).size()); } @Test public void multiColumnIndexWithNulls() throws InvalidOperationException { final int tid = createTable("test", "t1", "id int key, seg1 int, seg2 int, index(seg1,seg2)"); writeRows(createNewRow(tid, 1, 1, 1), createNewRow(tid, 2, 2, 2), createNewRow(tid, 3, 1, 1), createNewRow(tid, 4, 1, null), createNewRow(tid, 5, null, 1), createNewRow(tid, 6, 1, null), createNewRow(tid, 7, null, 1), createNewRow(tid, 8, null, null), createNewRow(tid, 9, null, null)); assertEquals(9, scanAll(new ScanAllRequest(tid, null)).size()); } }
Fix MultipleNullUniqueIndexIT schemas
src/test/java/com/akiban/server/test/it/bugs/bug696156/MultipleNullUniqueIndexIT.java
Fix MultipleNullUniqueIndexIT schemas
<ide><path>rc/test/java/com/akiban/server/test/it/bugs/bug696156/MultipleNullUniqueIndexIT.java <ide> <ide> package com.akiban.server.test.it.bugs.bug696156; <ide> <add>import com.akiban.ais.model.AISBuilder; <ide> import com.akiban.server.api.dml.scan.ScanAllRequest; <ide> import com.akiban.server.error.DuplicateKeyException; <ide> import com.akiban.server.error.InvalidOperationException; <ide> <ide> @Test <ide> public void reportTestCase() throws InvalidOperationException { <del> final int tid = createTable("test", "t1", "c1 TINYINT AUTO_INCREMENT NULL UNIQUE KEY"); <add> String SCHEMA = "test"; <add> String TABLE = "t1"; <add> String COLUMN = "c1"; <add> AISBuilder builder = new AISBuilder(); <add> builder.userTable(SCHEMA, TABLE); <add> builder.column(SCHEMA, TABLE, COLUMN, 0, "TINYINT", null, null, true, true, null, null); <add> builder.index(SCHEMA, TABLE, "c1", true, "UNIQUE"); <add> builder.indexColumn(SCHEMA, TABLE, COLUMN, COLUMN, 0, true, null); <add> ddl().createTable(session(), builder.akibanInformationSchema().getUserTable(SCHEMA, TABLE)); <add> updateAISGeneration(); <add> final int tid = tableId(SCHEMA, TABLE); <add> <ide> writeRows(createNewRow(tid, null, -1L)); <ide> writeRows(createNewRow(tid, null, -1L)); <ide> expectFullRows(tid, <ide> <ide> @Test <ide> public void singleColumnUniqueWithNulls() throws InvalidOperationException { <del> final int tid = createTable("test", "t1", "id int key, name varchar(32), unique(name)"); <add> final int tid = createTable("test", "t1", "id int not null primary key, name varchar(32), unique(name)"); <ide> writeRows(createNewRow(tid, 1, "abc"), <ide> createNewRow(tid, 2, "def"), <ide> createNewRow(tid, 3, null), <ide> <ide> @Test <ide> public void multiColumnUniqueWithNulls() throws InvalidOperationException { <del> final int tid = createTable("test", "t1", "id int key, seg1 int, seg2 int, seg3 int, unique(seg1,seg2,seg3)"); <add> final int tid = createTable("test", "t1", "id int not null primary key, seg1 int, seg2 int, seg3 int, unique(seg1,seg2,seg3)"); <ide> writeRows(createNewRow(tid, 1, 1, 1, 1), <ide> createNewRow(tid, 2, 1, 1, null), <ide> createNewRow(tid, 3, 1, null, 1), <ide> <ide> @Test <ide> public void singleColumnIndexWithNulls() throws InvalidOperationException { <del> final int tid = createTable("test", "t1", "id int key, name varchar(32), index(name)"); <add> final int tid = createTable("test", "t1", "id int not null primary key, name varchar(32)"); <add> createIndex("test", "t1", "name", "name"); <ide> writeRows(createNewRow(tid, 1, "abc"), <ide> createNewRow(tid, 2, "def"), <ide> createNewRow(tid, 3, "abc"), <ide> <ide> @Test <ide> public void multiColumnIndexWithNulls() throws InvalidOperationException { <del> final int tid = createTable("test", "t1", "id int key, seg1 int, seg2 int, index(seg1,seg2)"); <add> final int tid = createTable("test", "t1", "id int not null primary key, seg1 int, seg2 int"); <add> createIndex("test", "t1", "seg1", "seg1", "seg2"); <ide> writeRows(createNewRow(tid, 1, 1, 1), <ide> createNewRow(tid, 2, 2, 2), <ide> createNewRow(tid, 3, 1, 1),
Java
mit
359d3748c6d52d5f16a679c98aaca011430a2f9e
0
lukehutch/fast-classpath-scanner,lukehutch/fast-classpath-scanner,classgraph/classgraph,RaimondKempees/fast-classpath-scanner
package io.github.lukehutch.fastclasspathscanner.utils; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Queue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; public abstract class LoggedThread<T> implements Callable<T> { protected ThreadLog log = new ThreadLog(); @Override public T call() throws Exception { try { return doWork(); } finally { log.flush(); } } public abstract T doWork() throws Exception; private static class ThreadLogEntry { private final int indentLevel; private final Date time; private final String msg; private final long elapsedTimeNanos; private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmX"); private final DecimalFormat nanoFormatter = new DecimalFormat("0.000000"); public ThreadLogEntry(final int indentLevel, final String msg, final long elapsedTimeNanos) { this.indentLevel = indentLevel; this.msg = msg; this.time = Calendar.getInstance().getTime(); this.elapsedTimeNanos = elapsedTimeNanos; } public ThreadLogEntry(final int indentLevel, final String msg) { this(indentLevel, msg, -1L); } @Override public String toString() { final StringBuilder buf = new StringBuilder(); synchronized (dateTimeFormatter) { buf.append(dateTimeFormatter.format(time)); } buf.append('\t'); buf.append(FastClasspathScanner.class.getSimpleName()); buf.append('\t'); final int numIndentChars = 2 * indentLevel; for (int i = 0; i < numIndentChars - 1; i++) { buf.append('-'); } if (numIndentChars > 0) { buf.append(" "); } buf.append(msg); if (elapsedTimeNanos >= 0L) { buf.append(" in "); buf.append(nanoFormatter.format(elapsedTimeNanos * 1e-9)); buf.append(" sec"); } return buf.toString(); } } /** * Class for accumulating ordered log entries from threads, for later writing to the log without interleaving. */ public static class ThreadLog { private static AtomicBoolean versionLogged = new AtomicBoolean(false); private final Queue<ThreadLogEntry> logEntries = new ConcurrentLinkedQueue<>(); public void log(final int indentLevel, final String msg) { logEntries.add(new ThreadLogEntry(indentLevel, msg)); } public void log(final String msg) { logEntries.add(new ThreadLogEntry(0, msg)); } public void log(final int indentLevel, final String msg, final long elapsedTimeNanos) { logEntries.add(new ThreadLogEntry(indentLevel, msg, elapsedTimeNanos)); } public void log(final String msg, final long elapsedTimeNanos) { logEntries.add(new ThreadLogEntry(0, msg, elapsedTimeNanos)); } public synchronized void flush() { if (!logEntries.isEmpty()) { final StringBuilder buf = new StringBuilder(); if (versionLogged.compareAndSet(false, true)) { if (FastClasspathScanner.verbose) { // Log the version before the first log entry buf.append(new ThreadLogEntry(0, "FastClasspathScanner version " + FastClasspathScanner.getVersion()).toString()); buf.append('\n'); } } for (ThreadLogEntry logEntry; (logEntry = logEntries.poll()) != null;) { buf.append(logEntry.toString()); buf.append('\n'); } System.err.print(buf.toString()); System.err.flush(); } } } }
src/main/java/io/github/lukehutch/fastclasspathscanner/utils/LoggedThread.java
package io.github.lukehutch.fastclasspathscanner.utils; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Queue; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner; public abstract class LoggedThread<T> implements Callable<T> { protected ThreadLog log = new ThreadLog(); @Override public T call() throws Exception { try { return doWork(); } finally { log.flush(); } } public abstract T doWork() throws Exception; private static class ThreadLogEntry { private final int indentLevel; private final Date time; private final String msg; private final long elapsedTimeNanos; private final SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmX"); private final DecimalFormat nanoFormatter = new DecimalFormat("0.000000"); public ThreadLogEntry(final int indentLevel, final String msg, final long elapsedTimeNanos) { this.indentLevel = indentLevel; this.msg = msg; this.time = Calendar.getInstance().getTime(); this.elapsedTimeNanos = elapsedTimeNanos; } public ThreadLogEntry(final int indentLevel, final String msg) { this(indentLevel, msg, -1L); } @Override public String toString() { final StringBuilder buf = new StringBuilder(); synchronized (dateTimeFormatter) { buf.append(dateTimeFormatter.format(time)); } buf.append('\t'); buf.append(FastClasspathScanner.class.getSimpleName()); buf.append('\t'); final int numIndentChars = 2 * indentLevel; for (int i = 0; i < numIndentChars - 1; i++) { buf.append('-'); } if (numIndentChars > 0) { buf.append(" "); } buf.append(msg); if (elapsedTimeNanos >= 0L) { buf.append(" in "); buf.append(nanoFormatter.format(elapsedTimeNanos * 1e-9)); buf.append(" sec"); } return buf.toString(); } } /** * Class for accumulating ordered log entries from threads, for later writing to the log without interleaving. */ public static class ThreadLog { private static AtomicBoolean versionLogged = new AtomicBoolean(false); private final Queue<ThreadLogEntry> logEntries = new ConcurrentLinkedQueue<>(); public void log(final int indentLevel, final String msg) { logEntries.add(new ThreadLogEntry(indentLevel, msg)); } public void log(final String msg) { logEntries.add(new ThreadLogEntry(0, msg)); } public void log(final int indentLevel, final String msg, final long elapsedTimeNanos) { logEntries.add(new ThreadLogEntry(indentLevel, msg, elapsedTimeNanos)); } public void log(final String msg, final long elapsedTimeNanos) { logEntries.add(new ThreadLogEntry(0, msg, elapsedTimeNanos)); } public synchronized void flush() { if (!logEntries.isEmpty()) { final StringBuilder buf = new StringBuilder(); if (versionLogged.compareAndSet(false, true)) { if (FastClasspathScanner.verbose) { // Log the version before the first log entry buf.append(new ThreadLogEntry(0, "FastClasspathScanner version " + FastClasspathScanner.getVersion()).toString()); buf.append('\n'); } } for (ThreadLogEntry logEntry; (logEntry = logEntries.poll()) != null;) { buf.append(logEntry.toString()); buf.append('\n'); } System.err.print(buf.toString()); System.err.flush(); logEntries.clear(); } } } }
Remove unnecessary Queue#clear()
src/main/java/io/github/lukehutch/fastclasspathscanner/utils/LoggedThread.java
Remove unnecessary Queue#clear()
<ide><path>rc/main/java/io/github/lukehutch/fastclasspathscanner/utils/LoggedThread.java <ide> } <ide> System.err.print(buf.toString()); <ide> System.err.flush(); <del> logEntries.clear(); <ide> } <ide> } <ide> }
Java
mit
error: pathspec 'src/main/euler/solved/Task_122_2.java' did not match any file(s) known to git
630d20cc3360de33901e7afacbea30a82ebd7aeb
1
Fantast/project-euler,Fantast/project-euler,Fantast/project-euler,Fantast/project-euler,Fantast/project-euler,Fantast/project-euler
package solved; import tasks.AbstractTask; import tasks.Tester; import utils.MyMath; import utils.log.Logger; import java.util.HashSet; import java.util.Set; //Answer : 1582 public class Task_122_2 extends AbstractTask { public static void main(String[] args) { Logger.init("default.log"); Tester.test(new Task_122_2()); Logger.close(); } int MAX = 15; public void solving() { System.out.println(minMults(15)); System.out.println(minMults(127)); // long res = 0; // for (int k = 1; k <= MAX; ++k) { // res += minMults(k); // } // // System.out.println( res ); } private int minMults(int k) { need = k; best = MyMath.bitCount(k) + MyMath.mostSignificantBit(k) - 1; Set<Integer> has = new HashSet<>(); has.add(1); find(has, 0); return best; } int best; int need; void find(Set<Integer> has, int current) { if (current >= best) { return; } Set<Integer> has2 = new HashSet<>(has); for (int e1 : has) { for (int e2 : has) { int e = e1 + e2; if (e == need) { best = current + 1; return; } if (!has.contains(e)) { has2.add(e); find(has2, current + 1); has2.remove(e); } } } } }
src/main/euler/solved/Task_122_2.java
122.new
src/main/euler/solved/Task_122_2.java
122.new
<ide><path>rc/main/euler/solved/Task_122_2.java <add>package solved; <add> <add>import tasks.AbstractTask; <add>import tasks.Tester; <add>import utils.MyMath; <add>import utils.log.Logger; <add> <add>import java.util.HashSet; <add>import java.util.Set; <add> <add>//Answer : 1582 <add>public class Task_122_2 extends AbstractTask { <add> public static void main(String[] args) { <add> Logger.init("default.log"); <add> Tester.test(new Task_122_2()); <add> Logger.close(); <add> } <add> <add> int MAX = 15; <add> <add> public void solving() { <add> System.out.println(minMults(15)); <add> System.out.println(minMults(127)); <add>// long res = 0; <add>// for (int k = 1; k <= MAX; ++k) { <add>// res += minMults(k); <add>// } <add>// <add>// System.out.println( res ); <add> } <add> <add> private int minMults(int k) { <add> need = k; <add> best = MyMath.bitCount(k) + MyMath.mostSignificantBit(k) - 1; <add> <add> Set<Integer> has = new HashSet<>(); <add> has.add(1); <add> <add> find(has, 0); <add> <add> return best; <add> } <add> <add> int best; <add> int need; <add> void find(Set<Integer> has, int current) { <add> if (current >= best) { <add> return; <add> } <add> <add> Set<Integer> has2 = new HashSet<>(has); <add> for (int e1 : has) { <add> for (int e2 : has) { <add> int e = e1 + e2; <add> if (e == need) { <add> best = current + 1; <add> return; <add> } <add> if (!has.contains(e)) { <add> has2.add(e); <add> find(has2, current + 1); <add> has2.remove(e); <add> } <add> } <add> } <add> } <add>}
Java
mit
368550a4a6ada3c4d41a933edbe15928bead697e
0
frchiron/GildedRose-Refactoring-Kata
package com.gildedrose; import java.util.Arrays; class GildedRose { private static final int QUALITY_MIN = 0; private static final int QUALITY_MAX = 50; private static final String SULFURAS = "Sulfuras, Hand of Ragnaros"; private static final String BACKSTAGE_PASSES = "Backstage passes to a TAFKAL80ETC concert"; private static final String AGED_BRIE = "Aged Brie"; Item[] items; public GildedRose(Item[] items) { this.items = items; } public void updateQuality() { for (int i = 0; i < items.length; i++) { Item item = items[i]; decrementSellIn(item); updateQuality(item); if (item.sellIn < 0) { updateQualityWhenNegativeSellIn(item); } } } public void updateQuality(Item item) { if (!Arrays.asList(AGED_BRIE, BACKSTAGE_PASSES, SULFURAS).contains(item.name)) { if (item.quality > QUALITY_MIN) { decrementQualityByOne(item); } return; } if (item.quality < QUALITY_MAX) { incrementQualityByOne(item); } if (!item.name.equals(BACKSTAGE_PASSES)) { return; } if (item.sellIn < 10) { if (item.quality < QUALITY_MAX) { incrementQualityByOne(item); } } if (item.sellIn < 5) { if (item.quality < QUALITY_MAX) { incrementQualityByOne(item); } } } public void updateQualityWhenNegativeSellIn(Item item) { if (item.name.equals(AGED_BRIE)) { if (item.quality < QUALITY_MAX) { incrementQualityByOne(item); } return; } if (item.name.equals(BACKSTAGE_PASSES)) { item.quality = QUALITY_MIN; return; } if (!item.name.equals(SULFURAS)) { if (item.quality > QUALITY_MIN) { decrementQualityByOne(item); } return; } } public int decrementQualityByOne(Item item) { return item.quality = item.quality - 1; } public int incrementQualityByOne(Item item) { return item.quality = item.quality + 1; } public void decrementSellIn(Item item) { if (!item.name.equals(SULFURAS)) { item.sellIn = item.sellIn - 1; } } }
Java/src/main/java/com/gildedrose/GildedRose.java
package com.gildedrose; class GildedRose { private static final int QUALITY_MIN = 0; private static final int QUALITY_MAX = 50; private static final String SULFURAS = "Sulfuras, Hand of Ragnaros"; private static final String BACKSTAGE_PASSES = "Backstage passes to a TAFKAL80ETC concert"; private static final String AGED_BRIE = "Aged Brie"; Item[] items; public GildedRose(Item[] items) { this.items = items; } public void updateQuality() { for (int i = 0; i < items.length; i++) { Item item = items[i]; decrementSellIn(item); updateQuality(item); if (item.sellIn < 0) { updateQualityWhenNegativeSellIn(item); } } } public void updateQuality(Item item) { if (!item.name.equals(AGED_BRIE) && !item.name.equals(BACKSTAGE_PASSES) && !item.name.equals(SULFURAS)) { if (item.quality > QUALITY_MIN) { decrementQualityByOne(item); } return; } if (item.quality < QUALITY_MAX) { incrementQualityByOne(item); } if (item.name.equals(BACKSTAGE_PASSES)) { if (item.sellIn < 10) { if (item.quality < QUALITY_MAX) { incrementQualityByOne(item); } } if (item.sellIn < 5) { if (item.quality < QUALITY_MAX) { incrementQualityByOne(item); } } } } public void updateQualityWhenNegativeSellIn(Item item) { if (item.name.equals(AGED_BRIE)) { if (item.quality < QUALITY_MAX) { incrementQualityByOne(item); } return; } if (item.name.equals(BACKSTAGE_PASSES)) { item.quality = QUALITY_MIN; return; } if (!item.name.equals(SULFURAS)) { if (item.quality > QUALITY_MIN) { decrementQualityByOne(item); } return; } } public int decrementQualityByOne(Item item) { return item.quality = item.quality - 1; } public int incrementQualityByOne(Item item) { return item.quality = item.quality + 1; } public void decrementSellIn(Item item) { if (!item.name.equals(SULFURAS)) { item.sellIn = item.sellIn - 1; } } }
additional refactor part 2
Java/src/main/java/com/gildedrose/GildedRose.java
additional refactor part 2
<ide><path>ava/src/main/java/com/gildedrose/GildedRose.java <ide> package com.gildedrose; <add> <add>import java.util.Arrays; <ide> <ide> class GildedRose { <ide> private static final int QUALITY_MIN = 0; <ide> } <ide> <ide> public void updateQuality(Item item) { <del> if (!item.name.equals(AGED_BRIE) && !item.name.equals(BACKSTAGE_PASSES) && !item.name.equals(SULFURAS)) { <add> if (!Arrays.asList(AGED_BRIE, BACKSTAGE_PASSES, SULFURAS).contains(item.name)) { <ide> if (item.quality > QUALITY_MIN) { <ide> decrementQualityByOne(item); <ide> } <ide> <ide> } <ide> <del> if (item.name.equals(BACKSTAGE_PASSES)) { <del> if (item.sellIn < 10) { <del> if (item.quality < QUALITY_MAX) { <del> incrementQualityByOne(item); <del> } <add> if (!item.name.equals(BACKSTAGE_PASSES)) { <add> return; <add> } <add> <add> if (item.sellIn < 10) { <add> if (item.quality < QUALITY_MAX) { <add> incrementQualityByOne(item); <ide> } <add> } <ide> <del> if (item.sellIn < 5) { <del> if (item.quality < QUALITY_MAX) { <del> incrementQualityByOne(item); <del> } <add> if (item.sellIn < 5) { <add> if (item.quality < QUALITY_MAX) { <add> incrementQualityByOne(item); <ide> } <ide> } <ide>
Java
apache-2.0
bfdfce18fa5d75fc75d3e1263c5a3912717bddaf
0
bonigarcia/webdrivermanager,bonigarcia/webdrivermanager,bonigarcia/webdrivermanager
package io.github.bonigarcia.wdm.test.other; import io.github.bonigarcia.wdm.WebDriverManager; import io.github.bonigarcia.wdm.config.DriverManagerType; import io.github.bonigarcia.wdm.online.HttpClient; import io.github.bonigarcia.wdm.online.S3BucketListNamespaceContext; import org.junit.Test; import javax.xml.namespace.NamespaceContext; import java.io.IOException; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Optional; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.fail; public class NamespaceContextTest { public static final S3BucketListNamespaceContext S_3_BUCKET_LIST_NAMESPACE_CONTEXT = new S3BucketListNamespaceContext(); public static final String S3_URI = "http://doc.s3.amazonaws.com/2006-03-01"; @Test public void testS3BucketListNamespaceContextUrls() throws IOException { TestWebDriverManager testManager = new TestWebDriverManager(); List<URL> urls = testManager.getDriverUrls(); assertThat(urls, is(not(empty()))); } @Test public void testS3BucketListNamespaceContextPrefixes(){ assertThat(S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getNamespaceURI("s3"), equalTo(S3_URI)); assertThat(S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefix(S3_URI), equalTo("s3")); Iterator<String> prefixes = S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefixes(S3_URI); assertThat(prefixes.next(), equalTo("s3")); assertThat(prefixes.hasNext(), equalTo(false)); } @Test public void testS3BucketListNamespaceContextInvalidPrefixes(){ try { S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getNamespaceURI("xmlns"); fail("IllegalArgumentException should be thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), equalTo("Unsupported prefix")); } try { S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefix("http://www.w3.org/2000/xmlns/"); fail("IllegalArgumentException should be thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), equalTo("Unsupported namespace URI")); } assertThat( S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefixes("http://www.w3.org/2000/xmlns/").hasNext(), is(false) ); } private static final class TestWebDriverManager extends WebDriverManager { @Override protected NamespaceContext getNamespaceContext() { return S_3_BUCKET_LIST_NAMESPACE_CONTEXT; } @Override protected List<URL> getDriverUrls() throws IOException { httpClient = new HttpClient(config()); return getDriversFromXml(getDriverUrl(), "//s3:Contents/s3:Key"); } @Override protected Optional<String> getBrowserVersionFromTheShell() { return Optional.empty(); } @Override protected String getDriverName() { return null; } @Override protected String getDriverVersion() { return null; } @Override protected void setDriverVersion(String driverVersion) { } @Override protected String getBrowserVersion() { return null; } @Override protected void setBrowserVersion(String browserVersion) { } @Override protected void setDriverUrl(URL url) { } @Override protected URL getDriverUrl() { return getDriverUrlCkeckingMirror(config().getChromeDriverUrl()); } @Override protected Optional<URL> getMirrorUrl() { return Optional.empty(); } @Override protected Optional<String> getExportParameter() { return Optional.empty(); } @Override public DriverManagerType getDriverManagerType() { return null; } } }
src/test/java/io/github/bonigarcia/wdm/test/other/NamespaceContextTest.java
package io.github.bonigarcia.wdm.test.other; import io.github.bonigarcia.wdm.WebDriverManager; import io.github.bonigarcia.wdm.config.DriverManagerType; import io.github.bonigarcia.wdm.online.HttpClient; import io.github.bonigarcia.wdm.online.S3BucketListNamespaceContext; import org.junit.Test; import javax.xml.namespace.NamespaceContext; import java.io.IOException; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Optional; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNot.not; public class NamespaceContextTest { public static final S3BucketListNamespaceContext S_3_BUCKET_LIST_NAMESPACE_CONTEXT = new S3BucketListNamespaceContext(); public static final String S3_URI = "http://doc.s3.amazonaws.com/2006-03-01"; @Test public void testS3BucketListNamespaceContext() throws IOException { assertThat(S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getNamespaceURI("s3"), equalTo(S3_URI)); assertThat(S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefix(S3_URI), equalTo("s3")); Iterator<String> prefixes = S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefixes(S3_URI); assertThat(prefixes.next(), equalTo("s3")); assertThat(prefixes.hasNext(), equalTo(false)); TestWebDriverManager testManager = new TestWebDriverManager(); List<URL> urls = testManager.getDriverUrls(); assertThat(urls, is(not(empty()))); } private static final class TestWebDriverManager extends WebDriverManager { @Override protected NamespaceContext getNamespaceContext() { return S_3_BUCKET_LIST_NAMESPACE_CONTEXT; } @Override protected List<URL> getDriverUrls() throws IOException { httpClient = new HttpClient(config()); return getDriversFromXml(getDriverUrl(), "//s3:Contents/s3:Key"); } @Override protected Optional<String> getBrowserVersionFromTheShell() { return Optional.empty(); } @Override protected String getDriverName() { return null; } @Override protected String getDriverVersion() { return null; } @Override protected void setDriverVersion(String driverVersion) { } @Override protected String getBrowserVersion() { return null; } @Override protected void setBrowserVersion(String browserVersion) { } @Override protected void setDriverUrl(URL url) { } @Override protected URL getDriverUrl() { return getDriverUrlCkeckingMirror(config().getChromeDriverUrl()); } @Override protected Optional<URL> getMirrorUrl() { return Optional.empty(); } @Override protected Optional<String> getExportParameter() { return Optional.empty(); } @Override public DriverManagerType getDriverManagerType() { return null; } } }
Another attempt to increase coverage
src/test/java/io/github/bonigarcia/wdm/test/other/NamespaceContextTest.java
Another attempt to increase coverage
<ide><path>rc/test/java/io/github/bonigarcia/wdm/test/other/NamespaceContextTest.java <ide> import static org.hamcrest.Matchers.equalTo; <ide> import static org.hamcrest.core.Is.is; <ide> import static org.hamcrest.core.IsNot.not; <add>import static org.junit.Assert.fail; <ide> <ide> public class NamespaceContextTest { <ide> <ide> public static final String S3_URI = "http://doc.s3.amazonaws.com/2006-03-01"; <ide> <ide> @Test <del> public void testS3BucketListNamespaceContext() throws IOException { <add> public void testS3BucketListNamespaceContextUrls() throws IOException { <add> TestWebDriverManager testManager = new TestWebDriverManager(); <add> List<URL> urls = testManager.getDriverUrls(); <add> assertThat(urls, is(not(empty()))); <add> } <add> <add> @Test <add> public void testS3BucketListNamespaceContextPrefixes(){ <ide> assertThat(S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getNamespaceURI("s3"), equalTo(S3_URI)); <ide> assertThat(S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefix(S3_URI), equalTo("s3")); <ide> Iterator<String> prefixes = S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefixes(S3_URI); <ide> assertThat(prefixes.next(), equalTo("s3")); <ide> assertThat(prefixes.hasNext(), equalTo(false)); <add> } <ide> <del> TestWebDriverManager testManager = new TestWebDriverManager(); <del> List<URL> urls = testManager.getDriverUrls(); <del> assertThat(urls, is(not(empty()))); <add> <add> @Test <add> public void testS3BucketListNamespaceContextInvalidPrefixes(){ <add> try { <add> S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getNamespaceURI("xmlns"); <add> fail("IllegalArgumentException should be thrown"); <add> } catch (IllegalArgumentException e) { <add> assertThat(e.getMessage(), equalTo("Unsupported prefix")); <add> } <add> try { <add> S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefix("http://www.w3.org/2000/xmlns/"); <add> fail("IllegalArgumentException should be thrown"); <add> } catch (IllegalArgumentException e) { <add> assertThat(e.getMessage(), equalTo("Unsupported namespace URI")); <add> } <add> assertThat( <add> S_3_BUCKET_LIST_NAMESPACE_CONTEXT.getPrefixes("http://www.w3.org/2000/xmlns/").hasNext(), <add> is(false) <add> ); <ide> } <ide> <ide> private static final class TestWebDriverManager extends WebDriverManager {
JavaScript
mit
1c289790ccb9bdabf19acc8d53209bfcbed3572f
0
CanalTP/navitia-playground,CanalTP/navitia-playground
// Copyright (c) 2016 CanalTP // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. 'use strict'; // fake includes var response; var storage; var summary; var utils; var d3; var map = {}; var jawg = '9bHKgmlnYBVN0RILGGVn9t5mV1htebujO8fvecasKWZPb1apHmEFD9nOpWLjrYM7'; map.DrawSectionOption = { DRAWSTART: 2, // 10 DRAWEND: 1, // 01 DRAWBOTH: 3, // 11 DRAWNEITHER: 0 // 00 }; map._should_draw_section_start = function(option) { return option & 2;// jshint ignore:line }; map._should_draw_section_end = function(option) { return option & 1;// jshint ignore:line }; map.STARTTEXT = 'Start'; map.ENDTEXT = 'End'; map.makeFeatures = { region: function(context, json) { if (json.shape) { var geoJsonShape = wkt2geojson(json.shape); return map._makePolygon(context, 'region', geoJsonShape, json, '#008ACA'); } return []; }, section: function(context, json, draw_section_option) { var style = {}; if (json.display_informations && json.display_informations.color) { style.color = '#' + json.display_informations.color; } switch (json.type) { case 'street_network': switch (json.mode) { case 'bike': style = map.bikeStyle; break; case 'taxi': style = map.taxiStyle; break; case 'car': style = map.carStyle; break; case 'carnopark': style = map.carStyle; break; case 'walking': style = map.walkingStyle; break; case 'ridesharing': style = map.ridesharingStyle; break; } break; case 'transfer': switch (json.transfer_type) { case 'guaranteed': style = map.carStyle; break; case 'extension': style = map.bikeStyle; break; case 'walking': style = map.walkingStyle; break; } break; case 'ridesharing': style = map.ridesharingStyle; break; case 'crow_fly': style = map.crowFlyStyle; break; } if (draw_section_option === undefined) { draw_section_option = map.DrawSectionOption.DRAWBOTH; } return map._makeString(context, 'section', json, style) .concat(map.makeFeatures.vias(context, json.vias || [])) .concat(map._makeStringViaToPt(context,'section', json, map.crowFlyStyle, draw_section_option)) .concat(map._makeStopTimesMarker(context, json, style, draw_section_option)); }, line: function(context, json) { return map._makeString(context, 'line', json, json); }, journey: function(context, json) { if (! ('sections' in json)) { return []; } var bind = function(s, i, array) { var draw_section_option = map.DrawSectionOption.DRAWNEITHER; if ( i === 0) { draw_section_option |= map.DrawSectionOption.DRAWSTART;// jshint ignore:line } if ( i === (array.length -1) ) { draw_section_option |= map.DrawSectionOption.DRAWEND;// jshint ignore:line } return map.makeFeatures.section(context, s, draw_section_option); }; return utils.flatMap(json.sections, bind); }, isochrone: function(context, json) { if (! ('geojson' in json)) { return []; } var color = context.getColorFromMinDuration(json.min_duration); return map._makePolygon(context, 'isochrone', json.geojson, json, color) .concat(map._makeStopTimesMarker(context, json, {}, map.DrawSectionOption.DRAWBOTH)); }, heat_map: function(context, json) { if (! ('heat_matrix' in json)) { return []; } var scale = 0; json.heat_matrix.lines.forEach(function(lines) { lines.duration.forEach(function(duration) { if (duration !== null) { scale = Math.max(duration, scale); } }); }); var local_map = []; json.heat_matrix.lines.forEach(function(lines/*, i*/) { lines.duration.forEach(function(duration, j) { var color; if (duration !== null) { var ratio = duration / scale; color = utils.getColorFromRatio(ratio); } else { color = '#000000'; // for the moment, we don't want to print the null duration squares because // it impacts the performances of the navigator. return; } var rectangle = [ [json.heat_matrix.line_headers[j].cell_lat.max_lat, lines.cell_lon.max_lon], [json.heat_matrix.line_headers[j].cell_lat.min_lat, lines.cell_lon.min_lon] ]; local_map.push(map._makePixel(context, 'heat_map', rectangle, json, color, duration)); }); }); var draw_section_option = map.DrawSectionOption.DRAWBOTH; return local_map.concat(map._makeStopTimesMarker(context, json, {}, draw_section_option)); }, address: function(context, json) { return map._makeMarker(context, 'address', json); }, administrative_region: function(context, json) { return map._makeMarker(context, 'administrative_region', json); }, stop_area: function(context, json) { return map._makeMarker(context, 'stop_area', json); }, stop_point: function(context, json) { return map._makeMarker(context, 'stop_point', json).concat(map._makeMarkerForAccessPoint(context, json)); }, place: function(context, json) { return map._makeMarker(context, 'place', json); }, pt_object: function(context, json) { return map.getFeatures(context, json.embedded_type, json[json.embedded_type]); }, poi: function(context, json) { return map._makeMarker(context, 'poi', json); }, free_floating: function(context, json) { return map._makeMarker(context, 'free_floating', json); }, access_point: function(context, json) { var icon = map._makeAccessPointIcon(); return map._makeMarker(context, 'access_point', json, null, null, icon); }, connection: function(context, json) { return utils.flatMap([json.origin, json.destination], function(json) { return map._makeMarker(context, 'stop_point', json); }); }, vias: function(context, json) { var bind = function(ap) { return map.makeFeatures.pt_object(context, ap); }; return utils.flatMap(json, bind); }, response: function(context, json) { var key = response.responseCollectionName(json); if (key === null) { return []; } var type = utils.getType(key); if (!(type in map.makeFeatures)) { return []; } var bind = function(s) { return map.makeFeatures[type](context, s); }; return utils.flatMap(json[key].slice().reverse(), bind); }, // TODO: implement when geojson_index is available elevations: function() { return []; } }; map.hasMap = function(context, type, json) { return map.getFeatures(context, type, json).length !== 0 || map.makeElevationGraph[type] instanceof Function; }; map.getFeatures = function(context, type, json) { if (! (map.makeFeatures[type] instanceof Function)) { return []; } if (! (json instanceof Object)) { return []; } try { return map.makeFeatures[type](context, json); } catch (e) { console.log(sprintf('map.makeFeatures[%s] thows an exception:', type));// jshint ignore:line console.log(e);// jshint ignore:line return []; } }; map._makeTileLayers = function() { var copyOSM = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'; var courtesy = function(name) { return sprintf('%s & %s', copyOSM, name); }; var makeStamenTileLayer = function(name) { return L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/' + name + '/{z}/{x}/{y}.png', { subdomains: 'abcd', attribution: courtesy('<a href="http://maps.stamen.com">Stamen Design</a>'), detectRetina: true }); }; return { 'Bright': L.tileLayer('https://tile.jawg.io/8030075a-bdf3-4b3a-814e-e28ab5880b40/{z}/{x}/{y}.png?access-token=' + jawg, { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'Dark': L.tileLayer('https://tile.jawg.io/d3fdb780-a086-4c52-ba10-40106332bd0c/{z}/{x}/{y}.png?access-token=' + jawg, { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'HOT': L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', { maxZoom: 19, attribution: courtesy('<a href="http://hot.openstreetmap.org/">Humanitarian OpenStreetMap Team</a>'), detectRetina: true }), 'Hydda': L.tileLayer('https://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png', { attribution: courtesy('<a href="http://openstreetmap.se/">OpenStreetMap Sweden</a>'), detectRetina: true }), 'Mapnik': L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: copyOSM, detectRetina: true }), 'Terrain': L.tileLayer('https://tile.jawg.io/d3fdb780-a086-4c52-ba10-40106332bd0c/{z}/{x}/{y}.png?access-token=' + jawg , { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'Toner': makeStamenTileLayer('toner-lite'), 'Watercolor': makeStamenTileLayer('watercolor'), }; }; map._getDefaultLayerName = function() { var saved = storage.getLayer(); if (saved) { return saved; } return 'Bright'; }; map.createMap = function(handle) { var div = $('<div/>'); // setting for default path of images used by leaflet L.Icon.Default.imagePath = 'lib/img/leaflet/dist/images/'; div.addClass('leaflet'); var m = L.map(div.get(0), {renderer: L.canvas()}); var tileLayers = map._makeTileLayers(); tileLayers[map._getDefaultLayerName()].addTo(m); L.control.layers(tileLayers).addTo(m); m.on('baselayerchange', storage.saveLayer); L.control.scale().addTo(m); var bounds = handle(m); // Cleanly destroying the map div.on('npg:remove', function() { m.remove(); }); // GPS location var circle = L.circle([0,0], { radius: 100, }); m.on('locationfound', function(e) { circle.setRadius(e.accuracy / 2) .setStyle({color: '#3388ff'}) .setLatLng(e.latlng) .bindPopup(sprintf('%.5f;%.5f ±%dm', e.latlng.lng, e.latlng.lat, e.accuracy)); }); m.on('locationerror', function(e) { circle.setStyle({color: 'red'}).bindPopup(e.message); }); m.on('unload', function() { m.stopLocate(); }); m.locate({enableHighAccuracy: true, watch: true}); m.on('moveend', function() { storage.saveBounds(m.getBounds()); }); setTimeout(function() { if (bounds) { m.fitBounds(bounds); } else { m.fitWorld(); } circle.addTo(m); // workaround for https://github.com/Leaflet/Leaflet/issues/4978 }, 100); return div; }; map.makeElevationGraph = {}; map.makeElevationGraph.elevations = function(context, json) { var data = json; if (!data) { return; } var div_elevation = $('<div/>'); div_elevation.addClass('elevation'); var height = 100; var margin = 10; var svg = d3.select(div_elevation.get(0)).append('svg') .attr('class', 'elevation-svg') .append('g') .attr('transform', 'translate(20, 20)'); svg.append('text') .attr('class', 'elevation-title') .style('font-weight', 'bold') .style('text-anchor', 'center') .attr('x', '50%') .attr('y', 0) .text('Elevation Graph'); svg.append('text') .attr('class', 'elevation-label') .attr('x', 10) .attr('y', 140) .text('Distance from start (m)'); svg.append('text') .attr('class', 'elevation-label') .attr('x', 10) .attr('y', 0) .text('Height (m)'); // define the line // set the ranges var xScale = d3.scaleLinear().range([0, 1000]); var yScale = d3.scaleLinear().range([height, 0]); // Scale the range of the data xScale.domain(d3.extent(data, function(d) { return d.distance_from_start;})); yScale.domain([d3.min(data, function(d) { return d.elevation; }) / 1.2, d3.max(data, function(d) { return d.elevation; }) * 1.2]); var xAxis = d3.axisBottom(xScale); var yAxis = d3.axisLeft(yScale); var xGrid = xAxis.ticks(5).tickFormat(''); var yGrid = yAxis.ticks(5).tickFormat(''); // add the X gridlines svg.append('g') .attr('class', 'grid x') .attr('transform', sprintf('translate(%s, %s)', margin, height)); // add the Y gridlines svg.append('g') .attr('class', 'grid y') .attr('transform', sprintf('translate(%s, 0)', margin)); // add the valueline path. svg.append('path') .data([data]) .attr('class', 'elevation-line') .attr('transform', sprintf('translate(%s, 0)', margin)); // add the X Axis svg.append('g') .attr('class', 'axis x'); // add the Y Axis svg.append('g') .attr('class', 'axis y'); // to make it responsive var draw_elevation = function (){ // It's impossible(?) to get the div's width, since it's not yet added to DOM... // the default width is set to 1600 as a good guess... var width = div_elevation.width() || 1600; // Scale the range of the data xScale.domain(d3.extent(data, function(d) { return d.distance_from_start;})); xScale.range([0, width - 50]); xGrid.tickSize(-height); svg.select('.grid.x') .call(xGrid); yGrid.tickSize(-(width - 50)); svg.select('.grid.y') .call(yGrid); svg.select('.axis.x') .attr('transform', sprintf('translate(%s, %s)', margin, height)) .call(d3.axisBottom(xScale)); svg.select('.axis.y') .attr('transform', sprintf('translate(%s, 0)', margin)) .call(d3.axisLeft(yScale)); var valueline = d3.line() .x(function(d) { return xScale(d.distance_from_start); }) .y(function(d) { return yScale(d.elevation); }); svg.selectAll('.elevation-line').attr('d', valueline); }; d3.select(window).on('resize', draw_elevation); draw_elevation(); return div_elevation; }; map.getElevationGraph = function(context, type, json) { if (! (map.makeElevationGraph[type] instanceof Function)) { return; } if (! (json instanceof Object)) { return; } try { return map.makeElevationGraph[type](context, json); } catch (e) { console.log(sprintf('map.makeFeatures[%s] thows an exception:', type));// jshint ignore:line console.log(e);// jshint ignore:line } }; map.run = function(context, type, json) { var features = []; var div_elevation; var div = $('<div/>'); // Draw elevations if ((div_elevation = map.getElevationGraph(context, type, json))) { div.append(div_elevation); // TODO: remove return once geojson_index is available return div; } if ((features = map.getFeatures(context, type, json)).length) { var div_map = map.createMap(function(m) { return L.featureGroup(features).addTo(m).getBounds(); }); div.append(div_map); return div; } else { var div_nomap = $('<div/>'); div_nomap.addClass('noMap'); div_nomap.append('No map'); return div_nomap; } }; map._makeMarkerForAccessPoint = function(context, sp) { var ap_markers = []; if (! sp.access_points){ return ap_markers; } sp.access_points.forEach(function(ap) { var obj = ap; var type = 'access_point'; var sum = summary.run(context, type, ap); var marker; marker = L.marker([ap.coord.lat, ap.coord.lon]); var style1 = {}; style1.color = 'gray'; style1.weight = 3; style1.opacity = 1; var connection = [{ 'type': 'LineString', 'coordinates': [[sp.coord.lon, sp.coord.lat], [ap.coord.lon, ap.coord.lat]] }]; ap_markers.push(L.geoJson(connection, { style: style1 })); ap_markers.push(marker.bindPopup(map._makeLink(context, type, obj, sum)[0])); }); return ap_markers; }; map._makeAccessPointIcon = function() { return L.icon({ iconUrl: '../img/pictos/metro-marker.png', iconSize: [30, 38], // size of the icon iconAnchor: [10, 40], // point of the icon which will correspond to marker's location }); }; map._makeMarker = function(context, type, json, style, label, icon) { var lat, lon; var obj = json; switch (type){ case 'stop_date_time': obj = json.stop_point; lat = obj.coord.lat; lon = obj.coord.lon; break; case 'place': lat = json[json.embedded_type].coord.lat; lon = json[json.embedded_type].coord.lon; break; default: lat = json.coord.lat; lon = json.coord.lon; } var sum = summary.run(context, type, json); var t = type === 'place' ? json.embedded_type : type; var marker; if (! style) { if (icon) { marker = L.marker([lat, lon], {icon: icon}); } else { marker = L.marker([lat, lon]); } } else { style = utils.deepClone(style || {}); delete style.dashArray; if (! style.color) { style.color = '#000000'; } style.opacity = 1; style.fillColor = 'white'; style.fillOpacity = 1; marker = L.circleMarker([lat, lon], style); marker.setRadius(5); } if (label) { marker.bindTooltip(label, {permanent: true, opacity: 1}); } return [marker.bindPopup(map._makeLink(context, t, obj, sum)[0])]; }; map.bikeStyle = { color: '#a3ab3a', dashArray: '0, 8' }; map.carStyle = { color: '#c9731d', dashArray: '0, 8' }; map.taxiStyle = { color: '#297e52', dashArray: '0, 8' }; map.walkingStyle = { color: '#298bbc', dashArray: '0, 8' }; map.ridesharingStyle = { color: '#6e3ea8', dashArray: '0, 8' }; map.crowFlyStyle = { color: '#6e3ea8', dashArray: '0, 8' }; map._getCoordFromPlace = function(place) { if (place && place[place.embedded_type] && place[place.embedded_type].coord) { return place[place.embedded_type].coord; } return null; }; map._makeStringViaToPt = function(context, type, json, style, draw_section_option) { if (! json.vias || json.vias.length === 0) { return []; } var from; var to; // At the moment, we have only one via in PathItem if (draw_section_option === map.DrawSectionOption.DRAWSTART){ from = json.vias[0].access_point.coord; to = json.to.stop_point.coord; }else { from = json.from.stop_point.coord; to = json.vias[0].access_point.coord; } var style1 = utils.deepClone(style); style1.color = 'grey'; style1.weight = 7; style1.opacity = 1; var style2 = utils.deepClone(style); style2.weight = 5; style2.opacity = 1; var sum = summary.run(context, type, json); return [ L.polyline([from, to], style1), L.polyline([from, to], style2).bindPopup(sum) ]; }; map._makeString = function(context, type, json, style) { style = utils.deepClone(style || {}); if (! style.color) { style.color = '#000000'; } if (style.color.match(/^[0-9A-Fa-f]{6}$/)) { style.color = '#' + style.color; } var sum = summary.run(context, type, json); var from = map._getCoordFromPlace(json.from); var to = map._getCoordFromPlace(json.to); var style1 = utils.deepClone(style); style1.color = 'white'; style1.weight = 7; style1.opacity = 1; var style2 = utils.deepClone(style); style2.weight = 5; style2.opacity = 1; if (json.geojson && json.geojson.coordinates.length) { return [ L.geoJson(json.geojson, { style: style1 }), L.geoJson(json.geojson, { style: style2 }).bindPopup(sum) ]; } else if (from && to) { return [ L.polyline([from, to], style1), L.polyline([from, to], style2).bindPopup(sum) ]; } else { return []; } }; map._makeStopTimesMarker = function(context, json, style, draw_section_option) { var stopTimes = json.stop_date_times; var markers = []; if (stopTimes) { // when section is PT stopTimes.forEach(function(st, i) { var label = null; if (i === 0 && map._should_draw_section_start(draw_section_option)) { label = map.STARTTEXT; }else if (i === (stopTimes.length -1 ) && map._should_draw_section_end(draw_section_option)) { label = map.ENDTEXT; } markers = markers.concat(map._makeMarker(context, 'stop_date_time', st, style, label)); }); } else { // when section is Walking var from = json.from; var to = json.to; var label_from = null; var label_to = null; if (from && map._should_draw_section_start(draw_section_option)) { label_from = map.STARTTEXT; markers.push(map._makeMarker(context, 'place', from, style, label_from)[0]); } if (to && map._should_draw_section_end(draw_section_option)) { label_to = map.ENDTEXT; markers.push(map._makeMarker(context, 'place', to, style, label_to)[0]); } } return markers; }; map._makePolygon = function(context, type, geoJsonCoords, json, color) { var sum = summary.run(context, type, json); // TODO use link when navitia has debugged the ticket NAVITIAII-2133 var link = map._makeLink(context, type, json, sum)[0]; return [ L.geoJson(geoJsonCoords, { color: '#555555', opacity: 1, weight: 0.5, fillColor: color, fillOpacity: 0.25 }).bindPopup(link) ]; }; map._makeLink = function(context, type, obj, name) { return context.makeLink(type, obj, name); }; map._makePixel = function(context, type, PolygonCoords, json, color, duration) { var sum = 'not accessible'; if (duration !== null) { sum = sprintf('duration: %s', utils.durationToString(duration)); } return L.rectangle(PolygonCoords, { smoothFactor: 0, color: '#555555', opacity: 0, weight: 0, fillColor: color, fillOpacity: 0.25 }).bindPopup(sum); };
js/map.js
// Copyright (c) 2016 CanalTP // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. 'use strict'; // fake includes var response; var storage; var summary; var utils; var d3; var map = {}; var jawg = '9bHKgmlnYBVN0RILGGVn9t5mV1htebujO8fvecasKWZPb1apHmEFD9nOpWLjrYM7'; map.DrawSectionOption = { DRAWSTART: 2, // 10 DRAWEND: 1, // 01 DRAWBOTH: 3, // 11 DRAWNEITHER: 0 // 00 }; map._should_draw_section_start = function(option) { return option & 2;// jshint ignore:line }; map._should_draw_section_end = function(option) { return option & 1;// jshint ignore:line }; map.STARTTEXT = 'Start'; map.ENDTEXT = 'End'; map.makeFeatures = { region: function(context, json) { if (json.shape) { var geoJsonShape = wkt2geojson(json.shape); return map._makePolygon(context, 'region', geoJsonShape, json, '#008ACA'); } return []; }, section: function(context, json, draw_section_option) { var style = {}; if (json.display_informations && json.display_informations.color) { style.color = '#' + json.display_informations.color; } switch (json.type) { case 'street_network': switch (json.mode) { case 'bike': style = map.bikeStyle; break; case 'taxi': style = map.taxiStyle; break; case 'car': style = map.carStyle; break; case 'carnopark': style = map.carStyle; break; case 'walking': style = map.walkingStyle; break; case 'ridesharing': style = map.ridesharingStyle; break; } break; case 'transfer': switch (json.transfer_type) { case 'guaranteed': style = map.carStyle; break; case 'extension': style = map.bikeStyle; break; case 'walking': style = map.walkingStyle; break; } break; case 'ridesharing': style = map.ridesharingStyle; break; case 'crow_fly': style = map.crowFlyStyle; break; } if (draw_section_option === undefined) { draw_section_option = map.DrawSectionOption.DRAWBOTH; } return map._makeString(context, 'section', json, style).concat(map.makeFeatures.vias(context, json.vias || [])) .concat(map._makeStopTimesMarker(context, json, style, draw_section_option)); }, line: function(context, json) { return map._makeString(context, 'line', json, json); }, journey: function(context, json) { if (! ('sections' in json)) { return []; } var bind = function(s, i, array) { var draw_section_option = map.DrawSectionOption.DRAWNEITHER; if ( i === 0) { draw_section_option |= map.DrawSectionOption.DRAWSTART;// jshint ignore:line } if ( i === (array.length -1) ) { draw_section_option |= map.DrawSectionOption.DRAWEND;// jshint ignore:line } return map.makeFeatures.section(context, s, draw_section_option); }; return utils.flatMap(json.sections, bind); }, isochrone: function(context, json) { if (! ('geojson' in json)) { return []; } var color = context.getColorFromMinDuration(json.min_duration); return map._makePolygon(context, 'isochrone', json.geojson, json, color) .concat(map._makeStopTimesMarker(context, json, {}, map.DrawSectionOption.DRAWBOTH)); }, heat_map: function(context, json) { if (! ('heat_matrix' in json)) { return []; } var scale = 0; json.heat_matrix.lines.forEach(function(lines) { lines.duration.forEach(function(duration) { if (duration !== null) { scale = Math.max(duration, scale); } }); }); var local_map = []; json.heat_matrix.lines.forEach(function(lines/*, i*/) { lines.duration.forEach(function(duration, j) { var color; if (duration !== null) { var ratio = duration / scale; color = utils.getColorFromRatio(ratio); } else { color = '#000000'; // for the moment, we don't want to print the null duration squares because // it impacts the performances of the navigator. return; } var rectangle = [ [json.heat_matrix.line_headers[j].cell_lat.max_lat, lines.cell_lon.max_lon], [json.heat_matrix.line_headers[j].cell_lat.min_lat, lines.cell_lon.min_lon] ]; local_map.push(map._makePixel(context, 'heat_map', rectangle, json, color, duration)); }); }); var draw_section_option = map.DrawSectionOption.DRAWBOTH; return local_map.concat(map._makeStopTimesMarker(context, json, {}, draw_section_option)); }, address: function(context, json) { return map._makeMarker(context, 'address', json); }, administrative_region: function(context, json) { return map._makeMarker(context, 'administrative_region', json); }, stop_area: function(context, json) { return map._makeMarker(context, 'stop_area', json); }, stop_point: function(context, json) { return map._makeMarker(context, 'stop_point', json).concat(map._makeMarkerForAccessPoint(context, json)); }, place: function(context, json) { return map._makeMarker(context, 'place', json); }, pt_object: function(context, json) { return map.getFeatures(context, json.embedded_type, json[json.embedded_type]); }, poi: function(context, json) { return map._makeMarker(context, 'poi', json); }, free_floating: function(context, json) { return map._makeMarker(context, 'free_floating', json); }, access_point: function(context, json) { var icon = map._makeAccessPointIcon(); return map._makeMarker(context, 'access_point', json, null, null, icon); }, connection: function(context, json) { return utils.flatMap([json.origin, json.destination], function(json) { return map._makeMarker(context, 'stop_point', json); }); }, vias: function(context, json) { var bind = function(ap) { return map.makeFeatures.pt_object(context, ap); }; return utils.flatMap(json, bind); }, response: function(context, json) { var key = response.responseCollectionName(json); if (key === null) { return []; } var type = utils.getType(key); if (!(type in map.makeFeatures)) { return []; } var bind = function(s) { return map.makeFeatures[type](context, s); }; return utils.flatMap(json[key].slice().reverse(), bind); }, // TODO: implement when geojson_index is available elevations: function() { return []; } }; map.hasMap = function(context, type, json) { return map.getFeatures(context, type, json).length !== 0 || map.makeElevationGraph[type] instanceof Function; }; map.getFeatures = function(context, type, json) { if (! (map.makeFeatures[type] instanceof Function)) { return []; } if (! (json instanceof Object)) { return []; } try { return map.makeFeatures[type](context, json); } catch (e) { console.log(sprintf('map.makeFeatures[%s] thows an exception:', type));// jshint ignore:line console.log(e);// jshint ignore:line return []; } }; map._makeTileLayers = function() { var copyOSM = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'; var courtesy = function(name) { return sprintf('%s & %s', copyOSM, name); }; var makeStamenTileLayer = function(name) { return L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/' + name + '/{z}/{x}/{y}.png', { subdomains: 'abcd', attribution: courtesy('<a href="http://maps.stamen.com">Stamen Design</a>'), detectRetina: true }); }; return { 'Bright': L.tileLayer('https://tile.jawg.io/8030075a-bdf3-4b3a-814e-e28ab5880b40/{z}/{x}/{y}.png?access-token=' + jawg, { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'Dark': L.tileLayer('https://tile.jawg.io/d3fdb780-a086-4c52-ba10-40106332bd0c/{z}/{x}/{y}.png?access-token=' + jawg, { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'HOT': L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', { maxZoom: 19, attribution: courtesy('<a href="http://hot.openstreetmap.org/">Humanitarian OpenStreetMap Team</a>'), detectRetina: true }), 'Hydda': L.tileLayer('https://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png', { attribution: courtesy('<a href="http://openstreetmap.se/">OpenStreetMap Sweden</a>'), detectRetina: true }), 'Mapnik': L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: copyOSM, detectRetina: true }), 'Terrain': L.tileLayer('https://tile.jawg.io/d3fdb780-a086-4c52-ba10-40106332bd0c/{z}/{x}/{y}.png?access-token=' + jawg , { attribution: courtesy('<a href="https://www.jawg.io" target="_blank">&copy; Jawg</a> - ' + '<a href="https://www.openstreetmap.org" target="_blank">&copy; OpenStreetMap</a>&nbsp;contributors'), detectRetina: true }), 'Toner': makeStamenTileLayer('toner-lite'), 'Watercolor': makeStamenTileLayer('watercolor'), }; }; map._getDefaultLayerName = function() { var saved = storage.getLayer(); if (saved) { return saved; } return 'Bright'; }; map.createMap = function(handle) { var div = $('<div/>'); // setting for default path of images used by leaflet L.Icon.Default.imagePath = 'lib/img/leaflet/dist/images/'; div.addClass('leaflet'); var m = L.map(div.get(0), {renderer: L.canvas()}); var tileLayers = map._makeTileLayers(); tileLayers[map._getDefaultLayerName()].addTo(m); L.control.layers(tileLayers).addTo(m); m.on('baselayerchange', storage.saveLayer); L.control.scale().addTo(m); var bounds = handle(m); // Cleanly destroying the map div.on('npg:remove', function() { m.remove(); }); // GPS location var circle = L.circle([0,0], { radius: 100, }); m.on('locationfound', function(e) { circle.setRadius(e.accuracy / 2) .setStyle({color: '#3388ff'}) .setLatLng(e.latlng) .bindPopup(sprintf('%.5f;%.5f ±%dm', e.latlng.lng, e.latlng.lat, e.accuracy)); }); m.on('locationerror', function(e) { circle.setStyle({color: 'red'}).bindPopup(e.message); }); m.on('unload', function() { m.stopLocate(); }); m.locate({enableHighAccuracy: true, watch: true}); m.on('moveend', function() { storage.saveBounds(m.getBounds()); }); setTimeout(function() { if (bounds) { m.fitBounds(bounds); } else { m.fitWorld(); } circle.addTo(m); // workaround for https://github.com/Leaflet/Leaflet/issues/4978 }, 100); return div; }; map.makeElevationGraph = {}; map.makeElevationGraph.elevations = function(context, json) { var data = json; if (!data) { return; } var div_elevation = $('<div/>'); div_elevation.addClass('elevation'); var height = 100; var margin = 10; var svg = d3.select(div_elevation.get(0)).append('svg') .attr('class', 'elevation-svg') .append('g') .attr('transform', 'translate(20, 20)'); svg.append('text') .attr('class', 'elevation-title') .style('font-weight', 'bold') .style('text-anchor', 'center') .attr('x', '50%') .attr('y', 0) .text('Elevation Graph'); svg.append('text') .attr('class', 'elevation-label') .attr('x', 10) .attr('y', 140) .text('Distance from start (m)'); svg.append('text') .attr('class', 'elevation-label') .attr('x', 10) .attr('y', 0) .text('Height (m)'); // define the line // set the ranges var xScale = d3.scaleLinear().range([0, 1000]); var yScale = d3.scaleLinear().range([height, 0]); // Scale the range of the data xScale.domain(d3.extent(data, function(d) { return d.distance_from_start;})); yScale.domain([d3.min(data, function(d) { return d.elevation; }) / 1.2, d3.max(data, function(d) { return d.elevation; }) * 1.2]); var xAxis = d3.axisBottom(xScale); var yAxis = d3.axisLeft(yScale); var xGrid = xAxis.ticks(5).tickFormat(''); var yGrid = yAxis.ticks(5).tickFormat(''); // add the X gridlines svg.append('g') .attr('class', 'grid x') .attr('transform', sprintf('translate(%s, %s)', margin, height)); // add the Y gridlines svg.append('g') .attr('class', 'grid y') .attr('transform', sprintf('translate(%s, 0)', margin)); // add the valueline path. svg.append('path') .data([data]) .attr('class', 'elevation-line') .attr('transform', sprintf('translate(%s, 0)', margin)); // add the X Axis svg.append('g') .attr('class', 'axis x'); // add the Y Axis svg.append('g') .attr('class', 'axis y'); // to make it responsive var draw_elevation = function (){ // It's impossible(?) to get the div's width, since it's not yet added to DOM... // the default width is set to 1600 as a good guess... var width = div_elevation.width() || 1600; // Scale the range of the data xScale.domain(d3.extent(data, function(d) { return d.distance_from_start;})); xScale.range([0, width - 50]); xGrid.tickSize(-height); svg.select('.grid.x') .call(xGrid); yGrid.tickSize(-(width - 50)); svg.select('.grid.y') .call(yGrid); svg.select('.axis.x') .attr('transform', sprintf('translate(%s, %s)', margin, height)) .call(d3.axisBottom(xScale)); svg.select('.axis.y') .attr('transform', sprintf('translate(%s, 0)', margin)) .call(d3.axisLeft(yScale)); var valueline = d3.line() .x(function(d) { return xScale(d.distance_from_start); }) .y(function(d) { return yScale(d.elevation); }); svg.selectAll('.elevation-line').attr('d', valueline); }; d3.select(window).on('resize', draw_elevation); draw_elevation(); return div_elevation; }; map.getElevationGraph = function(context, type, json) { if (! (map.makeElevationGraph[type] instanceof Function)) { return; } if (! (json instanceof Object)) { return; } try { return map.makeElevationGraph[type](context, json); } catch (e) { console.log(sprintf('map.makeFeatures[%s] thows an exception:', type));// jshint ignore:line console.log(e);// jshint ignore:line } }; map.run = function(context, type, json) { var features = []; var div_elevation; var div = $('<div/>'); // Draw elevations if ((div_elevation = map.getElevationGraph(context, type, json))) { div.append(div_elevation); // TODO: remove return once geojson_index is available return div; } if ((features = map.getFeatures(context, type, json)).length) { var div_map = map.createMap(function(m) { return L.featureGroup(features).addTo(m).getBounds(); }); div.append(div_map); return div; } else { var div_nomap = $('<div/>'); div_nomap.addClass('noMap'); div_nomap.append('No map'); return div_nomap; } }; map._makeMarkerForAccessPoint = function(context, sp) { var ap_markers = []; if (! sp.access_points){ return ap_markers; } sp.access_points.forEach(function(ap) { var obj = ap; var type = 'access_point'; var sum = summary.run(context, type, ap); var marker; marker = L.marker([ap.coord.lat, ap.coord.lon]); var style1 = {}; style1.color = 'gray'; style1.weight = 3; style1.opacity = 1; var connection = [{ 'type': 'LineString', 'coordinates': [[sp.coord.lon, sp.coord.lat], [ap.coord.lon, ap.coord.lat]] }]; ap_markers.push(L.geoJson(connection, { style: style1 })); ap_markers.push(marker.bindPopup(map._makeLink(context, type, obj, sum)[0])); }); return ap_markers; }; map._makeAccessPointIcon = function() { var greenIcon = L.icon({ iconUrl: '../img/pictos/metro-marker.png', iconSize: [30, 38], // size of the icon iconAnchor: [10, 40], // point of the icon which will correspond to marker's location }); return greenIcon; }; map._makeMarker = function(context, type, json, style, label, icon) { var lat, lon; var obj = json; switch (type){ case 'stop_date_time': obj = json.stop_point; lat = obj.coord.lat; lon = obj.coord.lon; break; case 'place': lat = json[json.embedded_type].coord.lat; lon = json[json.embedded_type].coord.lon; break; default: lat = json.coord.lat; lon = json.coord.lon; } var sum = summary.run(context, type, json); var t = type === 'place' ? json.embedded_type : type; var marker; if (! style) { if (icon) { marker = L.marker([lat, lon], {icon: icon}); } else { marker = L.marker([lat, lon]); } } else { style = utils.deepClone(style || {}); delete style.dashArray; if (! style.color) { style.color = '#000000'; } style.opacity = 1; style.fillColor = 'white'; style.fillOpacity = 1; marker = L.circleMarker([lat, lon], style); marker.setRadius(5); } if (label) { marker.bindTooltip(label, {permanent: true, opacity: 1}); } return [marker.bindPopup(map._makeLink(context, t, obj, sum)[0])]; }; map.bikeStyle = { color: '#a3ab3a', dashArray: '0, 8' }; map.carStyle = { color: '#c9731d', dashArray: '0, 8' }; map.taxiStyle = { color: '#297e52', dashArray: '0, 8' }; map.walkingStyle = { color: '#298bbc', dashArray: '0, 8' }; map.ridesharingStyle = { color: '#6e3ea8', dashArray: '0, 8' }; map.crowFlyStyle = { color: '#6e3ea8', dashArray: '0, 8' }; map._getCoordFromPlace = function(place) { if (place && place[place.embedded_type] && place[place.embedded_type].coord) { return place[place.embedded_type].coord; } return null; }; map._makeString = function(context, type, json, style) { style = utils.deepClone(style || {}); if (! style.color) { style.color = '#000000'; } if (style.color.match(/^[0-9A-Fa-f]{6}$/)) { style.color = '#' + style.color; } var sum = summary.run(context, type, json); var from = map._getCoordFromPlace(json.from); var to = map._getCoordFromPlace(json.to); var style1 = utils.deepClone(style); style1.color = 'white'; style1.weight = 7; style1.opacity = 1; var style2 = utils.deepClone(style); style2.weight = 5; style2.opacity = 1; if (json.geojson && json.geojson.coordinates.length) { return [ L.geoJson(json.geojson, { style: style1 }), L.geoJson(json.geojson, { style: style2 }).bindPopup(sum) ]; } else if (from && to) { return [ L.polyline([from, to], style1), L.polyline([from, to], style2).bindPopup(sum) ]; } else { return []; } }; map._makeStopTimesMarker = function(context, json, style, draw_section_option) { var stopTimes = json.stop_date_times; var markers = []; if (stopTimes) { // when section is PT stopTimes.forEach(function(st, i) { var label = null; if (i === 0 && map._should_draw_section_start(draw_section_option)) { label = map.STARTTEXT; }else if (i === (stopTimes.length -1 ) && map._should_draw_section_end(draw_section_option)) { label = map.ENDTEXT; } markers = markers.concat(map._makeMarker(context, 'stop_date_time', st, style, label)); }); } else { // when section is Walking var from = json.from; var to = json.to; var label_from = null; var label_to = null; if (from && map._should_draw_section_start(draw_section_option)) { label_from = map.STARTTEXT; markers.push(map._makeMarker(context, 'place', from, style, label_from)[0]); } if (to && map._should_draw_section_end(draw_section_option)) { label_to = map.ENDTEXT; markers.push(map._makeMarker(context, 'place', to, style, label_to)[0]); } } return markers; }; map._makePolygon = function(context, type, geoJsonCoords, json, color) { var sum = summary.run(context, type, json); // TODO use link when navitia has debugged the ticket NAVITIAII-2133 var link = map._makeLink(context, type, json, sum)[0]; return [ L.geoJson(geoJsonCoords, { color: '#555555', opacity: 1, weight: 0.5, fillColor: color, fillOpacity: 0.25 }).bindPopup(link) ]; }; map._makeLink = function(context, type, obj, name) { return context.makeLink(type, obj, name); }; map._makePixel = function(context, type, PolygonCoords, json, color, duration) { var sum = 'not accessible'; if (duration !== null) { sum = sprintf('duration: %s', utils.durationToString(duration)); } return L.rectangle(PolygonCoords, { smoothFactor: 0, color: '#555555', opacity: 0, weight: 0, fillColor: color, fillOpacity: 0.25 }).bindPopup(sum); };
add string between pt and via
js/map.js
add string between pt and via
<ide><path>s/map.js <ide> if (draw_section_option === undefined) { <ide> draw_section_option = map.DrawSectionOption.DRAWBOTH; <ide> } <del> return map._makeString(context, 'section', json, style).concat(map.makeFeatures.vias(context, json.vias || [])) <add> return map._makeString(context, 'section', json, style) <add> .concat(map.makeFeatures.vias(context, json.vias || [])) <add> .concat(map._makeStringViaToPt(context,'section', json, map.crowFlyStyle, draw_section_option)) <ide> .concat(map._makeStopTimesMarker(context, json, style, draw_section_option)); <ide> }, <ide> line: function(context, json) { <ide> return map.makeFeatures.pt_object(context, ap); <ide> }; <ide> return utils.flatMap(json, bind); <del> }, <add> }, <ide> response: function(context, json) { <ide> var key = response.responseCollectionName(json); <ide> if (key === null) { <ide> }; <ide> <ide> map._makeAccessPointIcon = function() { <del> var greenIcon = L.icon({ <add> return L.icon({ <ide> iconUrl: '../img/pictos/metro-marker.png', <ide> iconSize: [30, 38], // size of the icon <ide> iconAnchor: [10, 40], // point of the icon which will correspond to marker's location <ide> }); <del> return greenIcon; <ide> }; <ide> <ide> map._makeMarker = function(context, type, json, style, label, icon) { <ide> return place[place.embedded_type].coord; <ide> } <ide> return null; <add>}; <add> <add>map._makeStringViaToPt = function(context, type, json, style, draw_section_option) { <add> if (! json.vias || json.vias.length === 0) { <add> return []; <add> } <add> var from; <add> var to; <add> // At the moment, we have only one via in PathItem <add> if (draw_section_option === map.DrawSectionOption.DRAWSTART){ <add> from = json.vias[0].access_point.coord; <add> to = json.to.stop_point.coord; <add> }else { <add> from = json.from.stop_point.coord; <add> to = json.vias[0].access_point.coord; <add> } <add> <add> var style1 = utils.deepClone(style); <add> style1.color = 'grey'; <add> style1.weight = 7; <add> style1.opacity = 1; <add> var style2 = utils.deepClone(style); <add> style2.weight = 5; <add> style2.opacity = 1; <add> <add> var sum = summary.run(context, type, json); <add> <add> return [ <add> L.polyline([from, to], style1), <add> L.polyline([from, to], style2).bindPopup(sum) <add> ]; <ide> }; <ide> <ide> map._makeString = function(context, type, json, style) {
Java
apache-2.0
e69ed95a0371c9be991bddada4b066e8b3bf4d8e
0
liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model.sql; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.Platform; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCLogicalOperator; import org.jkiss.dbeaver.model.exec.DBCSession; import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor; import org.jkiss.dbeaver.model.sql.format.SQLFormatter; import org.jkiss.dbeaver.model.sql.format.SQLFormatterConfiguration; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.struct.rdb.DBSTableForeignKey; import org.jkiss.dbeaver.model.struct.rdb.DBSTableForeignKeyColumn; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.Pair; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * SQL Utils */ public final class SQLUtils { private static final Log log = Log.getLog(SQLUtils.class); public static final Pattern PATTERN_OUT_PARAM = Pattern.compile("((\\?)|(:[a-z0-9]+))\\s*:="); public static final Pattern PATTERN_SIMPLE_NAME = Pattern.compile("[a-z][a-z0-9_]*", Pattern.CASE_INSENSITIVE); private static final Pattern CREATE_PREFIX_PATTERN = Pattern.compile("(CREATE (:OR REPLACE)?).+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); private static final int MIN_SQL_DESCRIPTION_LENGTH = 512; private static final int MAX_SQL_DESCRIPTION_LENGTH = 500; private static final String DBEAVER_DDL_COMMENT = "-- DDL generated by "; private static final String DBEAVER_DDL_WARNING = "-- WARNING: It may differ from actual native database DDL"; private static final String DBEAVER_SCRIPT_DELIMITER = "$$"; public static String stripTransformations(String query) { return query; // if (!query.contains(TOKEN_TRANSFORM_START)) { // return query; // } else { // return PATTERN_XFORM.matcher(query).replaceAll(""); // } } public static String stripComments(@NotNull SQLDialect dialect, @NotNull String query) { Pair<String, String> multiLineComments = dialect.getMultiLineComments(); return stripComments( query, multiLineComments == null ? null : multiLineComments.getFirst(), multiLineComments == null ? null : multiLineComments.getSecond(), dialect.getSingleLineComments()); } public static boolean isCommentLine(SQLDialect dialect, String line) { for (String slc : dialect.getSingleLineComments()) { if (line.startsWith(slc)) { return true; } } return false; } public static String stripComments(@NotNull String query, @Nullable String mlCommentStart, @Nullable String mlCommentEnd, String[] slComments) { String leading = "", trailing = ""; { int startPos, endPos; for (startPos = 0; startPos < query.length(); startPos++) { if (!Character.isWhitespace(query.charAt(startPos))) { break; } } for (endPos = query.length() - 1; endPos > startPos; endPos--) { if (!Character.isWhitespace(query.charAt(endPos))) { break; } } if (startPos > 0) { leading = query.substring(0, startPos); } if (endPos < query.length() - 1) { trailing = query.substring(endPos + 1); } } query = query.trim(); if (mlCommentStart != null && mlCommentEnd != null && query.startsWith(mlCommentStart)) { int endPos = query.indexOf(mlCommentEnd); if (endPos != -1) { query = query.substring(endPos + mlCommentEnd.length()); } } for (int i = 0; i < slComments.length; i++) { while (query.startsWith(slComments[i])) { int crPos = query.indexOf('\n'); if (crPos == -1) { // Query is comment line - return empty query = ""; break; } else { query = query.substring(crPos).trim(); } } } return leading + query + trailing; } public static List<String> splitFilter(String filter) { if (CommonUtils.isEmpty(filter)) { return Collections.emptyList(); } return CommonUtils.splitString(filter, ','); } public static boolean matchesAnyLike(String string, Collection<String> likes) { for (String like : likes) { if (matchesLike(string, like)) { return true; } } return false; } public static boolean isLikePattern(String like) { return like.indexOf('%') != -1 || like.indexOf('*') != -1 || like.indexOf('?') != -1;// || like.indexOf('_') != -1; } public static String makeLikePattern(String like) { StringBuilder result = new StringBuilder(); for (int i = 0; i < like.length(); i++) { char c = like.charAt(i); if (c == '*') result.append(".*"); else if (c == '?') result.append("."); else if (c == '%') result.append(".*"); else if (Character.isLetterOrDigit(c)) result.append(c); else result.append("\\").append(c); } return result.toString(); } public static String makeSQLLike(String like) { return like.replace("*", "%"); } public static boolean matchesLike(String string, String like) { Pattern pattern = Pattern.compile(makeLikePattern(like), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); return pattern.matcher(string).matches(); } public static void appendValue(StringBuilder buffer, DBSTypedObject type, Object value) { if (type.getDataKind() == DBPDataKind.NUMERIC || type.getDataKind() == DBPDataKind.BOOLEAN) { buffer.append(value); } else { buffer.append('\'').append(value).append('\''); } } public static boolean isStringQuoted(String string) { return string.length() > 1 && string.startsWith("'") && string.endsWith("'"); } public static String quoteString(DBSObject object, String string) { return quoteString(object.getDataSource(), string); } public static String quoteString(DBPDataSource dataSource, String string) { return "'" + escapeString(dataSource, string) + "'"; } public static String escapeString(DBPDataSource dataSource, String string) { @NotNull SQLDialect dialect = dataSource instanceof SQLDataSource ? ((SQLDataSource) dataSource).getSQLDialect() : BasicSQLDialect.INSTANCE; return dialect.escapeString(string); } public static String unQuoteString(DBPDataSource dataSource, String string) { if (string.length() > 1 && string.charAt(0) == '\'' && string.charAt(string.length() - 1) == '\'') { @NotNull SQLDialect dialect = dataSource instanceof SQLDataSource ? ((SQLDataSource) dataSource).getSQLDialect() : BasicSQLDialect.INSTANCE; return dialect.unEscapeString(string.substring(1, string.length() - 1)); } return string; } public static String getFirstKeyword(SQLDialect dialect, String query) { query = stripComments(dialect, query); int startPos = 0, endPos = -1; for (int i = 0; i < query.length(); i++) { if (Character.isLetterOrDigit(query.charAt(i))) { startPos = i; break; } } for (int i = startPos; i < query.length(); i++) { if (Character.isWhitespace(query.charAt(i))) { endPos = i; break; } } if (endPos == -1) { return query; } return query.substring(startPos, endPos); } @Nullable public static String getQueryOutputParameter(DBCSession session, String query) { final Matcher matcher = PATTERN_OUT_PARAM.matcher(query); if (matcher.find()) { return matcher.group(1); } return null; } /** * Removes \\r characters from query. * Actually this is done specially for Oracle due to some bug in it's driver * * * @param dataSource * @param query query * @return normalized query */ public static String makeUnifiedLineFeeds(DBPDataSource dataSource, String query) { SQLDialect dialect = SQLUtils.getDialectFromDataSource(dataSource); if (!dialect.isCRLFBroken()) { return query; } if (query.indexOf('\r') == -1) { return query; } StringBuilder result = new StringBuilder(query.length()); for (int i = 0; i < query.length(); i++) { char c = query.charAt(i); if (c == '\r') { continue; } result.append(c); } return result.toString(); } public static String formatSQL(SQLDataSource dataSource, String query) { SQLSyntaxManager syntaxManager = new SQLSyntaxManager(); syntaxManager.init(dataSource.getSQLDialect(), dataSource.getContainer().getPreferenceStore()); SQLFormatterConfiguration configuration = new SQLFormatterConfiguration(dataSource, syntaxManager); SQLFormatter formatter = dataSource.getDataSource().getContainer().getPlatform().getSQLFormatterRegistry().createFormatter(configuration); if (formatter == null) { return query; } return formatter.format(query, configuration); } public static void appendLikeCondition(StringBuilder sql, String value, boolean not) { value = makeSQLLike(value); if (value.contains("%") || value.contains("_")) { if (not) sql.append(" NOT"); sql.append(" LIKE ?"); } else { sql.append(not ? "<>?": "=?"); } } public static boolean appendFirstClause(StringBuilder sql, boolean firstClause) { if (firstClause) { sql.append(" WHERE "); } else { sql.append(" AND "); } return false; } public static String trimQueryStatement(SQLSyntaxManager syntaxManager, String sql, boolean trimDelimiter) { // This is called only when use selects query (i.e. no automatic query detection) if (sql.isEmpty() || !trimDelimiter) { // Do not trim delimiter return sql; } // Here we cur trailing query delimiter. most of DBs don't expect it in the end of query // However Oracle REQUIRES that block queries (e.g. DDL like CREATE PROCEDURE) must have trailing delimiter // So we check whether this query is a block query (by checking for all SQL dialect block delimiters) String trailingSpaces = ""; { int trailingSpacesCount = 0; for (int i = sql.length() - 1; i >= 0; i--) { if (!Character.isWhitespace(sql.charAt(i))) { break; } trailingSpacesCount++; } if (trailingSpacesCount > 0) { trailingSpaces = sql.substring(sql.length() - trailingSpacesCount); sql = sql.substring(0, sql.length() - trailingSpacesCount); } } for (String statementDelimiter : syntaxManager.getStatementDelimiters()) { if (!sql.endsWith(statementDelimiter) && sql.length() > statementDelimiter.length()) { continue; } if (Character.isAlphabetic(statementDelimiter.charAt(0))) { // Delimiter is alphabetic (e.g. "GO") so it must be prefixed with whitespace char lastChar = sql.charAt(sql.length() - statementDelimiter.length() - 1); if (Character.isUnicodeIdentifierPart(lastChar)) { break; } } // Remove trailing delimiter only if it is not block end boolean isBlockQuery = false; String trimmed = sql.substring(0, sql.length() - statementDelimiter.length()); { String test = trimmed.toUpperCase().trim(); String[][] blockBoundStrings = syntaxManager.getDialect().getBlockBoundStrings(); if (blockBoundStrings != null) { for (String[] blocks : blockBoundStrings) { int endIndex = test.indexOf(blocks[1]); if (endIndex > 0) { // This is a block query if it ends with 'END' or with 'END id' if (test.endsWith(blocks[1])) { isBlockQuery = true; break; } else { String afterEnd = test.substring(endIndex + blocks[1].length()).trim(); if (CommonUtils.isJavaIdentifier(afterEnd)) { isBlockQuery = true; break; } } } } } } if (!isBlockQuery) { sql = trimmed; } break; } return sql + trailingSpaces; } @NotNull public static SQLDialect getDialectFromObject(DBPObject object) { if (object instanceof DBSObject) { DBPDataSource dataSource = ((DBSObject)object).getDataSource(); return getDialectFromDataSource(dataSource); } return BasicSQLDialect.INSTANCE; } @NotNull public static SQLDialect getDialectFromDataSource(DBPDataSource dataSource) { if (dataSource instanceof SQLDataSource) { return ((SQLDataSource) dataSource).getSQLDialect(); } return BasicSQLDialect.INSTANCE; } public static void appendConditionString( @NotNull DBDDataFilter filter, @NotNull DBPDataSource dataSource, @Nullable String conditionTable, @NotNull StringBuilder query, boolean inlineCriteria) { String operator = filter.isAnyConstraint() ? " OR " : " AND "; //$NON-NLS-1$ $NON-NLS-2$ boolean hasWhere = false; for (DBDAttributeConstraint constraint : filter.getConstraints()) { String condition = getConstraintCondition(dataSource, constraint, inlineCriteria); if (condition == null) { continue; } if (hasWhere) query.append(operator); hasWhere = true; if (constraint.getEntityAlias() != null) { query.append(constraint.getEntityAlias()).append('.'); } else if (conditionTable != null) { query.append(conditionTable).append('.'); } // Attribute name could be an expression. So check if this is a real attribute // and generate full/quoted name for it. String attrName; DBSAttributeBase cAttr = constraint.getAttribute(); if (cAttr instanceof DBDAttributeBinding) { DBDAttributeBinding binding = (DBDAttributeBinding) cAttr; if (binding.getEntityAttribute() != null && binding.getEntityAttribute().getName().equals(binding.getMetaAttribute().getName()) || binding instanceof DBDAttributeBindingType) { attrName = DBUtils.getObjectFullName(dataSource, binding, DBPEvaluationContext.DML); } else { // Most likely it is an expression so we don't want to quote it attrName = binding.getMetaAttribute().getName(); } } else { attrName = DBUtils.getObjectFullName(dataSource, cAttr, DBPEvaluationContext.DML); } query.append(attrName).append(' ').append(condition); } if (!CommonUtils.isEmpty(filter.getWhere())) { if (hasWhere) query.append(operator); query.append(filter.getWhere()); } } public static void appendOrderString(@NotNull DBDDataFilter filter, @NotNull DBPDataSource dataSource, @Nullable String conditionTable, @NotNull StringBuilder query) { // Construct ORDER BY boolean hasOrder = false; for (DBDAttributeConstraint co : filter.getOrderConstraints()) { if (hasOrder) query.append(','); String orderString = null; if (co.getAttribute() instanceof DBDAttributeBindingMeta) { String orderColumn = co.getAttribute().getName(); if (PATTERN_SIMPLE_NAME.matcher(orderColumn).matches()) { // It is a simple column. orderString = DBUtils.getObjectFullName(co.getAttribute(), DBPEvaluationContext.DML); if (conditionTable != null) { orderString = conditionTable + '.' + orderString; } } } if (orderString == null) { // Use position number int orderIndex = filter.getConstraints().indexOf(co); if (orderIndex != -1) { orderString = String.valueOf(orderIndex + 1); } else { log.debug("Can't generate column order: no name and no position found"); continue; } } query.append(orderString); if (co.isOrderDescending()) { query.append(" DESC"); //$NON-NLS-1$ } hasOrder = true; } if (!CommonUtils.isEmpty(filter.getOrder())) { if (hasOrder) query.append(','); query.append(filter.getOrder()); } } @Nullable public static String getConstraintCondition(@NotNull DBPDataSource dataSource, @NotNull DBDAttributeConstraint constraint, boolean inlineCriteria) { String criteria = constraint.getCriteria(); if (!CommonUtils.isEmpty(criteria)) { final char firstChar = criteria.trim().charAt(0); if (!Character.isLetter(firstChar) && firstChar != '=' && firstChar != '>' && firstChar != '<' && firstChar != '!') { return '=' + criteria; } else { return criteria; } } else if (constraint.getOperator() != null) { DBCLogicalOperator operator = constraint.getOperator(); StringBuilder conString = new StringBuilder(); Object value = constraint.getValue(); if (DBUtils.isNullValue(value)) { if (operator.getArgumentCount() == 0) { return operator.getStringValue(); } conString.append("IS "); if (constraint.isReverseOperator()) { conString.append("NOT "); } conString.append("NULL"); return conString.toString(); } if (constraint.isReverseOperator()) { conString.append("NOT "); } if (operator.getArgumentCount() > 0) { conString.append(operator.getStringValue()); for (int i = 0; i < operator.getArgumentCount(); i++) { if (i > 0) { conString.append(" AND"); } if (inlineCriteria) { conString.append(' ').append(convertValueToSQL(dataSource, constraint.getAttribute(), value)); } else { conString.append(" ?"); } } } else if (operator.getArgumentCount() < 0) { // Multiple arguments int valueCount = Array.getLength(value); boolean hasNull = false, hasNotNull = false; for (int i = 0; i < valueCount; i++) { final boolean isNull = DBUtils.isNullValue(Array.get(value, i)); if (isNull && !hasNull) { hasNull = true; } if (!isNull && !hasNotNull) { hasNotNull = true; } } if (!hasNotNull) { return "IS NULL"; } if (hasNull) { conString.append("IS NULL OR ").append(DBUtils.getObjectFullName(dataSource, constraint.getAttribute(), DBPEvaluationContext.DML)).append(" "); } conString.append(operator.getStringValue()); conString.append(" ("); if (!value.getClass().isArray()) { value = new Object[] {value}; } boolean hasValue = false; for (int i = 0; i < valueCount; i++) { Object itemValue = Array.get(value, i); if (DBUtils.isNullValue(itemValue)) { continue; } if (hasValue) { conString.append(","); } hasValue = true; if (inlineCriteria) { conString.append(convertValueToSQL(dataSource, constraint.getAttribute(), itemValue)); } else { conString.append("?"); } } conString.append(")"); } return conString.toString(); } else { return null; } } public static String convertValueToSQL(@NotNull DBPDataSource dataSource, @NotNull DBSAttributeBase attribute, @Nullable Object value) { DBDValueHandler valueHandler = DBUtils.findValueHandler(dataSource, attribute); return convertValueToSQL(dataSource, attribute, valueHandler, value); } public static String convertValueToSQL(@NotNull DBPDataSource dataSource, @NotNull DBSAttributeBase attribute, @NotNull DBDValueHandler valueHandler, @Nullable Object value) { if (DBUtils.isNullValue(value)) { return SQLConstants.NULL_VALUE; } String strValue; if (value instanceof DBDContent && dataSource instanceof SQLDataSource) { strValue = convertStreamToSQL(attribute, (DBDContent) value, valueHandler, (SQLDataSource) dataSource); } else { strValue = valueHandler.getValueDisplayString(attribute, value, DBDDisplayFormat.NATIVE); } if (value instanceof Number) { return strValue; } SQLDialect sqlDialect = null; if (dataSource instanceof SQLDataSource) { sqlDialect = ((SQLDataSource) dataSource).getSQLDialect(); } switch (attribute.getDataKind()) { case BOOLEAN: case NUMERIC: return strValue; case CONTENT: return strValue; case STRING: case ROWID: if (sqlDialect != null) { strValue = sqlDialect.escapeString(strValue); } return '\'' + strValue + '\''; default: if (sqlDialect != null) { return sqlDialect.escapeScriptValue(attribute, value, strValue); } return strValue; } } public static String convertStreamToSQL(DBSAttributeBase attribute, DBDContent content, DBDValueHandler valueHandler, SQLDataSource dataSource) { try { DBRProgressMonitor monitor = new VoidProgressMonitor(); if (ContentUtils.isTextContent(content)) { String strValue = ContentUtils.getContentStringValue(monitor, content); strValue = dataSource.getSQLDialect().escapeString(strValue); return "'" + strValue + "'"; } else { byte[] binValue = ContentUtils.getContentBinaryValue(monitor, content); return dataSource.getSQLDialect().getNativeBinaryFormatter().toString(binValue, 0, binValue.length); } } catch (Throwable e) { log.warn(e); return SQLConstants.NULL_VALUE; } } public static String getColumnTypeModifiers(@Nullable DBPDataSource dataSource, DBSTypedObject column, @NotNull String typeName, @NotNull DBPDataKind dataKind) { if (column == null) { return null; } if (!(dataSource instanceof SQLDataSource)) { return null; } SQLDialect dialect = ((SQLDataSource) dataSource).getSQLDialect(); return dialect.getColumnTypeModifiers(column, typeName, dataKind); } public static boolean isExecQuery(@NotNull SQLDialect dialect, String query) { // Check for EXEC query final String[] executeKeywords = dialect.getExecuteKeywords(); if (executeKeywords.length > 0) { final String queryStart = getFirstKeyword(dialect, query); for (String keyword : executeKeywords) { if (keyword.equalsIgnoreCase(queryStart)) { return true; } } } return false; } public static String getScriptDescripion(@NotNull String sql) { sql = stripComments(BasicSQLDialect.INSTANCE, sql); Matcher matcher = CREATE_PREFIX_PATTERN.matcher(sql); if (matcher.find() && matcher.start(0) == 0) { sql = sql.substring(matcher.end(1)); } sql = sql.replaceAll(" +", " "); if (sql.length() > MAX_SQL_DESCRIPTION_LENGTH) { sql = sql.substring(0, MAX_SQL_DESCRIPTION_LENGTH) + " ..."; } return sql; } @Nullable public static String getScriptDescription(@NotNull IFile sqlScript) { try { //log.debug("Read script '" + sqlScript.getName() + "' description"); StringBuilder sql = new StringBuilder(); try (BufferedReader is = new BufferedReader(new InputStreamReader(sqlScript.getContents()))) { for (;;) { String line = is.readLine(); if (line == null) { break; } line = line.trim(); if (line.startsWith(SQLConstants.SL_COMMENT) || line.startsWith("Rem") || line.startsWith("rem") || line.startsWith("REM") ) { continue; } sql.append(line).append('\n'); if (sql.length() > MIN_SQL_DESCRIPTION_LENGTH) { break; } } } return SQLUtils.getScriptDescripion(sql.toString()); } catch (Exception e) { log.warn("", e); } return null; } @NotNull public static String generateCommentLine(DBPDataSource dataSource, String comment) { String slComment = SQLConstants.ML_COMMENT_END; if (dataSource instanceof SQLDataSource) { String[] slComments = ((SQLDataSource) dataSource).getSQLDialect().getSingleLineComments(); if (!ArrayUtils.isEmpty(slComments)) { slComment = slComments[0]; } } return slComment + " " + comment + GeneralUtils.getDefaultLineSeparator(); } public static String generateParamList(int paramCount) { if (paramCount == 0) { return ""; } else if (paramCount == 1) { return "?"; } StringBuilder sql = new StringBuilder("?"); for (int i = 0; i < paramCount - 1; i++) { sql.append(",?"); } return sql.toString(); } /** * Replaces single \r linefeeds with space (some databases don't like them) */ public static String fixLineFeeds(String sql) { if (sql.indexOf('\r') == -1) { return sql; } boolean hasFixes = false; char[] fixed = sql.toCharArray(); for (int i = 0; i < fixed.length; i++) { if (fixed[i] == '\r') { if (i > 0 && fixed[i - 1] == '\n') { // \n\r continue; } if (i == fixed.length - 1 || fixed[i + 1] == '\n') { // \r\n continue; } // Single \r - replace it with space fixed[i] = ' '; hasFixes = true; } } return hasFixes ? String.valueOf(fixed) : sql; } /** * Compares two string ignoring extra whitespaces. * We can remove double whitespaces and any whitespaces between special chars (*-+,: etc). */ public static boolean compareAliases(String str1, String str2) { return removeExtraSpaces(str1).equals(removeExtraSpaces(str2)); } public static String removeExtraSpaces(String str) { if (str.indexOf(' ') == -1) { return str; } StringBuilder result = new StringBuilder(str.length()); int length = str.length(); for (int i = 0; i < length; i++) { char c = str.charAt(i); if (Character.isWhitespace(c)) { boolean needsSpace = i > 0 && Character.isLetterOrDigit(str.charAt(i - 1)); for (i = i + 1; i < length; i++) { c = str.charAt(i); if (Character.isWhitespace(c)) { continue; } if (needsSpace && Character.isLetterOrDigit(c)) { // We need exactly one space before letter/digit result.append(' '); } else { // We don't need spaces before control symbols } result.append(c); break; } } else { result.append(c); } } return result.toString(); } @NotNull public static String generateScript(DBPDataSource dataSource, DBEPersistAction[] persistActions, boolean addComments) { final SQLDialect sqlDialect = SQLUtils.getDialectFromDataSource(dataSource); final String lineSeparator = GeneralUtils.getDefaultLineSeparator(); StringBuilder script = new StringBuilder(64); if (addComments) { script.append(DBEAVER_DDL_COMMENT).append(Platform.getProduct().getName()).append(lineSeparator) .append(DBEAVER_DDL_WARNING).append(lineSeparator); } if (persistActions != null) { String redefiner = sqlDialect.getScriptDelimiterRedefiner(); for (DBEPersistAction action : persistActions) { String scriptLine = action.getScript(); if (CommonUtils.isEmpty(scriptLine)) { continue; } String delimiter = sqlDialect.getScriptDelimiter(); if (!delimiter.isEmpty() && Character.isLetterOrDigit(delimiter.charAt(0))) { delimiter = ' ' + delimiter; } if (action.isComplex() && redefiner != null) { script.append(lineSeparator).append(redefiner).append(" ").append(DBEAVER_SCRIPT_DELIMITER).append(lineSeparator); delimiter = DBEAVER_SCRIPT_DELIMITER; script.append(delimiter).append(lineSeparator); } else if (action.getType() == DBEPersistAction.ActionType.COMMENT) { if (script.length() > 2) { int lfCount = 0; for (int i = script.length() - 1; i >= 0; i--) { if (!Character.isWhitespace(script.charAt(i))) { break; } if (script.charAt(i) == '\n') lfCount++; } if (lfCount < 2) { // Add line feed if we do not have empty line before script.append(lineSeparator); } } } script.append(scriptLine); if (action.getType() != DBEPersistAction.ActionType.COMMENT) { script.append(delimiter); } else { script.append(lineSeparator); } script.append(lineSeparator); if (action.isComplex() && redefiner != null) { script.append(redefiner).append(" ").append(sqlDialect.getScriptDelimiter()).append(lineSeparator); } } } return script.toString(); } public static String[] splitFullIdentifier(final String fullName, char nameSeparator, String[][] quoteStrings) { return splitFullIdentifier(fullName, String.valueOf(nameSeparator), quoteStrings, false); } public static String[] splitFullIdentifier(final String fullName, String nameSeparator, String[][] quoteStrings, boolean keepQuotes) { String name = fullName.trim(); if (ArrayUtils.isEmpty(quoteStrings)) { return name.split(Pattern.quote(nameSeparator)); } if (!name.contains(nameSeparator)) { return new String[] { name }; } List<String> nameList = new ArrayList<>(); while (!name.isEmpty()) { boolean hadQuotedPart = false; for (String[] quotePair : quoteStrings) { String startQuote = quotePair[0]; String endQuote = quotePair[1]; if (!CommonUtils.isEmpty(startQuote) && !CommonUtils.isEmpty(endQuote) && name.startsWith(startQuote)) { int endPos = name.indexOf(endQuote, startQuote.length()); if (endPos != -1) { // Quoted part String partName = keepQuotes ? name.substring(0, endPos + endQuote.length()) : name.substring(startQuote.length(), endPos); nameList.add(partName); name = name.substring(endPos + endQuote.length()).trim(); hadQuotedPart = true; break; } } } if (!hadQuotedPart) { int endPos = name.indexOf(nameSeparator); if (endPos != -1) { nameList.add(name.substring(0, endPos)); name = name.substring(endPos); } else { nameList.add(name); break; } } if (!name.isEmpty() && name.startsWith(nameSeparator)) { name = name.substring(nameSeparator.length()).trim(); } } return nameList.toArray(new String[nameList.size()]); } public static String generateTableJoin(DBRProgressMonitor monitor, DBSEntity leftTable, String leftAlias, DBSEntity rightTable, String rightAlias) throws DBException { // Try to find FK in left table referencing to right table String sql = generateTableJoinByAssociation(monitor, leftTable, leftAlias, rightTable, rightAlias); if (sql != null) return sql; // Now try right to left sql = generateTableJoinByAssociation(monitor, rightTable, rightAlias, leftTable, leftAlias); if (sql != null) return sql; // Try to find columns in left table which match unique key in right table sql = generateTableJoinByColumns(monitor, leftTable, leftAlias, rightTable, rightAlias); if (sql != null) return sql; // In reverse order sql = generateTableJoinByColumns(monitor, rightTable, rightAlias, leftTable, leftAlias); if (sql != null) return sql; return null; } private static String generateTableJoinByColumns(DBRProgressMonitor monitor, DBSEntity leftTable, String leftAlias, DBSEntity rightTable, String rightAlias) throws DBException { List<DBSEntityAttribute> leftIdentifier = new ArrayList<>(DBUtils.getBestTableIdentifier(monitor, leftTable)); if (!leftIdentifier.isEmpty()) { List<DBSEntityAttribute> rightAttributes = new ArrayList<>(); for (DBSEntityAttribute attr : leftIdentifier) { DBSEntityAttribute rightAttr = rightTable.getAttribute(monitor, attr.getName()); if (rightAttr == null) { break; } rightAttributes.add(rightAttr); } if (leftIdentifier.size() != rightAttributes.size()) { return null; } StringBuilder joinSQL = new StringBuilder(); for (int i = 0; i < leftIdentifier.size(); i++) { joinSQL .append(leftAlias).append(".").append(DBUtils.getQuotedIdentifier(leftIdentifier.get(i))).append(" = ") .append(rightAlias).append(".").append(DBUtils.getQuotedIdentifier(rightAttributes.get(i))); } return joinSQL.toString(); } return null; } private static String generateTableJoinByAssociation(DBRProgressMonitor monitor, DBSEntity leftTable, String leftAlias, DBSEntity rightTable, String rightAlias) throws DBException { Collection<? extends DBSEntityAssociation> associations = leftTable.getAssociations(monitor); if (!CommonUtils.isEmpty(associations)) { for (DBSEntityAssociation fk : associations) { if (fk instanceof DBSTableForeignKey && fk.getAssociatedEntity() == rightTable) { return generateTablesJoin(monitor, (DBSTableForeignKey)fk, leftAlias, rightAlias); } } } return null; } private static String generateTablesJoin(DBRProgressMonitor monitor, DBSTableForeignKey fk, String leftAlias, String rightAlias) throws DBException { boolean hasCriteria = false; StringBuilder joinSQL = new StringBuilder(); for (DBSEntityAttributeRef ar : fk.getAttributeReferences(monitor)) { if (ar instanceof DBSTableForeignKeyColumn) { if (hasCriteria) { joinSQL.append(" AND "); } DBSTableForeignKeyColumn fkc = (DBSTableForeignKeyColumn)ar; joinSQL .append(leftAlias).append(".").append(DBUtils.getQuotedIdentifier(fkc)).append(" = ") .append(rightAlias).append(".").append(DBUtils.getQuotedIdentifier(fkc.getReferencedColumn())); hasCriteria = true; } } return joinSQL.toString(); } public static String getTableAlias(DBSEntity table) { return CommonUtils.escapeIdentifier(table.getName()); } public static void appendQueryConditions(DBPDataSource dataSource, @NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter) { if (dataFilter != null && dataFilter.hasConditions()) { query.append("\nWHERE "); //$NON-NLS-1$ appendConditionString(dataFilter, dataSource, tableAlias, query, true); } } public static void appendQueryOrder(DBPDataSource dataSource, @NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter) { if (dataFilter != null) { // Construct ORDER BY if (dataFilter.hasOrdering()) { query.append("\nORDER BY "); //$NON-NLS-1$ appendOrderString(dataFilter, dataSource, tableAlias, query); } } } }
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLUtils.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model.sql; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.Platform; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.data.*; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCLogicalOperator; import org.jkiss.dbeaver.model.exec.DBCSession; import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor; import org.jkiss.dbeaver.model.sql.format.SQLFormatter; import org.jkiss.dbeaver.model.sql.format.SQLFormatterConfiguration; import org.jkiss.dbeaver.model.struct.*; import org.jkiss.dbeaver.model.struct.rdb.DBSTableForeignKey; import org.jkiss.dbeaver.model.struct.rdb.DBSTableForeignKeyColumn; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.dbeaver.utils.GeneralUtils; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.Pair; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * SQL Utils */ public final class SQLUtils { private static final Log log = Log.getLog(SQLUtils.class); public static final Pattern PATTERN_OUT_PARAM = Pattern.compile("((\\?)|(:[a-z0-9]+))\\s*:="); public static final Pattern PATTERN_SIMPLE_NAME = Pattern.compile("[a-z][a-z0-9]*", Pattern.CASE_INSENSITIVE); private static final Pattern CREATE_PREFIX_PATTERN = Pattern.compile("(CREATE (:OR REPLACE)?).+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); private static final int MIN_SQL_DESCRIPTION_LENGTH = 512; private static final int MAX_SQL_DESCRIPTION_LENGTH = 500; private static final String DBEAVER_DDL_COMMENT = "-- DDL generated by "; private static final String DBEAVER_DDL_WARNING = "-- WARNING: It may differ from actual native database DDL"; private static final String DBEAVER_SCRIPT_DELIMITER = "$$"; public static String stripTransformations(String query) { return query; // if (!query.contains(TOKEN_TRANSFORM_START)) { // return query; // } else { // return PATTERN_XFORM.matcher(query).replaceAll(""); // } } public static String stripComments(@NotNull SQLDialect dialect, @NotNull String query) { Pair<String, String> multiLineComments = dialect.getMultiLineComments(); return stripComments( query, multiLineComments == null ? null : multiLineComments.getFirst(), multiLineComments == null ? null : multiLineComments.getSecond(), dialect.getSingleLineComments()); } public static boolean isCommentLine(SQLDialect dialect, String line) { for (String slc : dialect.getSingleLineComments()) { if (line.startsWith(slc)) { return true; } } return false; } public static String stripComments(@NotNull String query, @Nullable String mlCommentStart, @Nullable String mlCommentEnd, String[] slComments) { String leading = "", trailing = ""; { int startPos, endPos; for (startPos = 0; startPos < query.length(); startPos++) { if (!Character.isWhitespace(query.charAt(startPos))) { break; } } for (endPos = query.length() - 1; endPos > startPos; endPos--) { if (!Character.isWhitespace(query.charAt(endPos))) { break; } } if (startPos > 0) { leading = query.substring(0, startPos); } if (endPos < query.length() - 1) { trailing = query.substring(endPos + 1); } } query = query.trim(); if (mlCommentStart != null && mlCommentEnd != null && query.startsWith(mlCommentStart)) { int endPos = query.indexOf(mlCommentEnd); if (endPos != -1) { query = query.substring(endPos + mlCommentEnd.length()); } } for (int i = 0; i < slComments.length; i++) { while (query.startsWith(slComments[i])) { int crPos = query.indexOf('\n'); if (crPos == -1) { // Query is comment line - return empty query = ""; break; } else { query = query.substring(crPos).trim(); } } } return leading + query + trailing; } public static List<String> splitFilter(String filter) { if (CommonUtils.isEmpty(filter)) { return Collections.emptyList(); } return CommonUtils.splitString(filter, ','); } public static boolean matchesAnyLike(String string, Collection<String> likes) { for (String like : likes) { if (matchesLike(string, like)) { return true; } } return false; } public static boolean isLikePattern(String like) { return like.indexOf('%') != -1 || like.indexOf('*') != -1 || like.indexOf('?') != -1;// || like.indexOf('_') != -1; } public static String makeLikePattern(String like) { StringBuilder result = new StringBuilder(); for (int i = 0; i < like.length(); i++) { char c = like.charAt(i); if (c == '*') result.append(".*"); else if (c == '?') result.append("."); else if (c == '%') result.append(".*"); else if (Character.isLetterOrDigit(c)) result.append(c); else result.append("\\").append(c); } return result.toString(); } public static String makeSQLLike(String like) { return like.replace("*", "%"); } public static boolean matchesLike(String string, String like) { Pattern pattern = Pattern.compile(makeLikePattern(like), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); return pattern.matcher(string).matches(); } public static void appendValue(StringBuilder buffer, DBSTypedObject type, Object value) { if (type.getDataKind() == DBPDataKind.NUMERIC || type.getDataKind() == DBPDataKind.BOOLEAN) { buffer.append(value); } else { buffer.append('\'').append(value).append('\''); } } public static boolean isStringQuoted(String string) { return string.length() > 1 && string.startsWith("'") && string.endsWith("'"); } public static String quoteString(DBSObject object, String string) { return quoteString(object.getDataSource(), string); } public static String quoteString(DBPDataSource dataSource, String string) { return "'" + escapeString(dataSource, string) + "'"; } public static String escapeString(DBPDataSource dataSource, String string) { @NotNull SQLDialect dialect = dataSource instanceof SQLDataSource ? ((SQLDataSource) dataSource).getSQLDialect() : BasicSQLDialect.INSTANCE; return dialect.escapeString(string); } public static String unQuoteString(DBPDataSource dataSource, String string) { if (string.length() > 1 && string.charAt(0) == '\'' && string.charAt(string.length() - 1) == '\'') { @NotNull SQLDialect dialect = dataSource instanceof SQLDataSource ? ((SQLDataSource) dataSource).getSQLDialect() : BasicSQLDialect.INSTANCE; return dialect.unEscapeString(string.substring(1, string.length() - 1)); } return string; } public static String getFirstKeyword(SQLDialect dialect, String query) { query = stripComments(dialect, query); int startPos = 0, endPos = -1; for (int i = 0; i < query.length(); i++) { if (Character.isLetterOrDigit(query.charAt(i))) { startPos = i; break; } } for (int i = startPos; i < query.length(); i++) { if (Character.isWhitespace(query.charAt(i))) { endPos = i; break; } } if (endPos == -1) { return query; } return query.substring(startPos, endPos); } @Nullable public static String getQueryOutputParameter(DBCSession session, String query) { final Matcher matcher = PATTERN_OUT_PARAM.matcher(query); if (matcher.find()) { return matcher.group(1); } return null; } /** * Removes \\r characters from query. * Actually this is done specially for Oracle due to some bug in it's driver * * * @param dataSource * @param query query * @return normalized query */ public static String makeUnifiedLineFeeds(DBPDataSource dataSource, String query) { SQLDialect dialect = SQLUtils.getDialectFromDataSource(dataSource); if (!dialect.isCRLFBroken()) { return query; } if (query.indexOf('\r') == -1) { return query; } StringBuilder result = new StringBuilder(query.length()); for (int i = 0; i < query.length(); i++) { char c = query.charAt(i); if (c == '\r') { continue; } result.append(c); } return result.toString(); } public static String formatSQL(SQLDataSource dataSource, String query) { SQLSyntaxManager syntaxManager = new SQLSyntaxManager(); syntaxManager.init(dataSource.getSQLDialect(), dataSource.getContainer().getPreferenceStore()); SQLFormatterConfiguration configuration = new SQLFormatterConfiguration(dataSource, syntaxManager); SQLFormatter formatter = dataSource.getDataSource().getContainer().getPlatform().getSQLFormatterRegistry().createFormatter(configuration); if (formatter == null) { return query; } return formatter.format(query, configuration); } public static void appendLikeCondition(StringBuilder sql, String value, boolean not) { value = makeSQLLike(value); if (value.contains("%") || value.contains("_")) { if (not) sql.append(" NOT"); sql.append(" LIKE ?"); } else { sql.append(not ? "<>?": "=?"); } } public static boolean appendFirstClause(StringBuilder sql, boolean firstClause) { if (firstClause) { sql.append(" WHERE "); } else { sql.append(" AND "); } return false; } public static String trimQueryStatement(SQLSyntaxManager syntaxManager, String sql, boolean trimDelimiter) { // This is called only when use selects query (i.e. no automatic query detection) if (sql.isEmpty() || !trimDelimiter) { // Do not trim delimiter return sql; } // Here we cur trailing query delimiter. most of DBs don't expect it in the end of query // However Oracle REQUIRES that block queries (e.g. DDL like CREATE PROCEDURE) must have trailing delimiter // So we check whether this query is a block query (by checking for all SQL dialect block delimiters) String trailingSpaces = ""; { int trailingSpacesCount = 0; for (int i = sql.length() - 1; i >= 0; i--) { if (!Character.isWhitespace(sql.charAt(i))) { break; } trailingSpacesCount++; } if (trailingSpacesCount > 0) { trailingSpaces = sql.substring(sql.length() - trailingSpacesCount); sql = sql.substring(0, sql.length() - trailingSpacesCount); } } for (String statementDelimiter : syntaxManager.getStatementDelimiters()) { if (!sql.endsWith(statementDelimiter) && sql.length() > statementDelimiter.length()) { continue; } if (Character.isAlphabetic(statementDelimiter.charAt(0))) { // Delimiter is alphabetic (e.g. "GO") so it must be prefixed with whitespace char lastChar = sql.charAt(sql.length() - statementDelimiter.length() - 1); if (Character.isUnicodeIdentifierPart(lastChar)) { break; } } // Remove trailing delimiter only if it is not block end boolean isBlockQuery = false; String trimmed = sql.substring(0, sql.length() - statementDelimiter.length()); { String test = trimmed.toUpperCase().trim(); String[][] blockBoundStrings = syntaxManager.getDialect().getBlockBoundStrings(); if (blockBoundStrings != null) { for (String[] blocks : blockBoundStrings) { int endIndex = test.indexOf(blocks[1]); if (endIndex > 0) { // This is a block query if it ends with 'END' or with 'END id' if (test.endsWith(blocks[1])) { isBlockQuery = true; break; } else { String afterEnd = test.substring(endIndex + blocks[1].length()).trim(); if (CommonUtils.isJavaIdentifier(afterEnd)) { isBlockQuery = true; break; } } } } } } if (!isBlockQuery) { sql = trimmed; } break; } return sql + trailingSpaces; } @NotNull public static SQLDialect getDialectFromObject(DBPObject object) { if (object instanceof DBSObject) { DBPDataSource dataSource = ((DBSObject)object).getDataSource(); return getDialectFromDataSource(dataSource); } return BasicSQLDialect.INSTANCE; } @NotNull public static SQLDialect getDialectFromDataSource(DBPDataSource dataSource) { if (dataSource instanceof SQLDataSource) { return ((SQLDataSource) dataSource).getSQLDialect(); } return BasicSQLDialect.INSTANCE; } public static void appendConditionString( @NotNull DBDDataFilter filter, @NotNull DBPDataSource dataSource, @Nullable String conditionTable, @NotNull StringBuilder query, boolean inlineCriteria) { String operator = filter.isAnyConstraint() ? " OR " : " AND "; //$NON-NLS-1$ $NON-NLS-2$ boolean hasWhere = false; for (DBDAttributeConstraint constraint : filter.getConstraints()) { String condition = getConstraintCondition(dataSource, constraint, inlineCriteria); if (condition == null) { continue; } if (hasWhere) query.append(operator); hasWhere = true; if (constraint.getEntityAlias() != null) { query.append(constraint.getEntityAlias()).append('.'); } else if (conditionTable != null) { query.append(conditionTable).append('.'); } // Attribute name could be an expression. So check if this is a real attribute // and generate full/quoted name for it. String attrName; DBSAttributeBase cAttr = constraint.getAttribute(); if (cAttr instanceof DBDAttributeBinding) { DBDAttributeBinding binding = (DBDAttributeBinding) cAttr; if (binding.getEntityAttribute() != null && binding.getEntityAttribute().getName().equals(binding.getMetaAttribute().getName()) || binding instanceof DBDAttributeBindingType) { attrName = DBUtils.getObjectFullName(dataSource, binding, DBPEvaluationContext.DML); } else { // Most likely it is an expression so we don't want to quote it attrName = binding.getMetaAttribute().getName(); } } else { attrName = DBUtils.getObjectFullName(dataSource, cAttr, DBPEvaluationContext.DML); } query.append(attrName).append(' ').append(condition); } if (!CommonUtils.isEmpty(filter.getWhere())) { if (hasWhere) query.append(operator); query.append(filter.getWhere()); } } public static void appendOrderString(@NotNull DBDDataFilter filter, @NotNull DBPDataSource dataSource, @Nullable String conditionTable, @NotNull StringBuilder query) { // Construct ORDER BY boolean hasOrder = false; for (DBDAttributeConstraint co : filter.getOrderConstraints()) { if (hasOrder) query.append(','); if (conditionTable != null) { query.append(conditionTable).append('.'); } String orderString = null; if (co.getAttribute() instanceof DBDAttributeBindingMeta) { String orderColumn = co.getAttribute().getName(); if (PATTERN_SIMPLE_NAME.matcher(orderColumn).matches()) { // It is a simple column. orderString = DBUtils.getObjectFullName(co.getAttribute(), DBPEvaluationContext.DML); } } if (orderString == null) { // Use position number int orderIndex = filter.getConstraints().indexOf(co); if (orderIndex != -1) { orderString = String.valueOf(orderIndex + 1); } else { log.debug("Can't generate column order: no name and no position found"); continue; } } query.append(orderString); if (co.isOrderDescending()) { query.append(" DESC"); //$NON-NLS-1$ } hasOrder = true; } if (!CommonUtils.isEmpty(filter.getOrder())) { if (hasOrder) query.append(','); query.append(filter.getOrder()); } } @Nullable public static String getConstraintCondition(@NotNull DBPDataSource dataSource, @NotNull DBDAttributeConstraint constraint, boolean inlineCriteria) { String criteria = constraint.getCriteria(); if (!CommonUtils.isEmpty(criteria)) { final char firstChar = criteria.trim().charAt(0); if (!Character.isLetter(firstChar) && firstChar != '=' && firstChar != '>' && firstChar != '<' && firstChar != '!') { return '=' + criteria; } else { return criteria; } } else if (constraint.getOperator() != null) { DBCLogicalOperator operator = constraint.getOperator(); StringBuilder conString = new StringBuilder(); Object value = constraint.getValue(); if (DBUtils.isNullValue(value)) { if (operator.getArgumentCount() == 0) { return operator.getStringValue(); } conString.append("IS "); if (constraint.isReverseOperator()) { conString.append("NOT "); } conString.append("NULL"); return conString.toString(); } if (constraint.isReverseOperator()) { conString.append("NOT "); } if (operator.getArgumentCount() > 0) { conString.append(operator.getStringValue()); for (int i = 0; i < operator.getArgumentCount(); i++) { if (i > 0) { conString.append(" AND"); } if (inlineCriteria) { conString.append(' ').append(convertValueToSQL(dataSource, constraint.getAttribute(), value)); } else { conString.append(" ?"); } } } else if (operator.getArgumentCount() < 0) { // Multiple arguments int valueCount = Array.getLength(value); boolean hasNull = false, hasNotNull = false; for (int i = 0; i < valueCount; i++) { final boolean isNull = DBUtils.isNullValue(Array.get(value, i)); if (isNull && !hasNull) { hasNull = true; } if (!isNull && !hasNotNull) { hasNotNull = true; } } if (!hasNotNull) { return "IS NULL"; } if (hasNull) { conString.append("IS NULL OR ").append(DBUtils.getObjectFullName(dataSource, constraint.getAttribute(), DBPEvaluationContext.DML)).append(" "); } conString.append(operator.getStringValue()); conString.append(" ("); if (!value.getClass().isArray()) { value = new Object[] {value}; } boolean hasValue = false; for (int i = 0; i < valueCount; i++) { Object itemValue = Array.get(value, i); if (DBUtils.isNullValue(itemValue)) { continue; } if (hasValue) { conString.append(","); } hasValue = true; if (inlineCriteria) { conString.append(convertValueToSQL(dataSource, constraint.getAttribute(), itemValue)); } else { conString.append("?"); } } conString.append(")"); } return conString.toString(); } else { return null; } } public static String convertValueToSQL(@NotNull DBPDataSource dataSource, @NotNull DBSAttributeBase attribute, @Nullable Object value) { DBDValueHandler valueHandler = DBUtils.findValueHandler(dataSource, attribute); return convertValueToSQL(dataSource, attribute, valueHandler, value); } public static String convertValueToSQL(@NotNull DBPDataSource dataSource, @NotNull DBSAttributeBase attribute, @NotNull DBDValueHandler valueHandler, @Nullable Object value) { if (DBUtils.isNullValue(value)) { return SQLConstants.NULL_VALUE; } String strValue; if (value instanceof DBDContent && dataSource instanceof SQLDataSource) { strValue = convertStreamToSQL(attribute, (DBDContent) value, valueHandler, (SQLDataSource) dataSource); } else { strValue = valueHandler.getValueDisplayString(attribute, value, DBDDisplayFormat.NATIVE); } if (value instanceof Number) { return strValue; } SQLDialect sqlDialect = null; if (dataSource instanceof SQLDataSource) { sqlDialect = ((SQLDataSource) dataSource).getSQLDialect(); } switch (attribute.getDataKind()) { case BOOLEAN: case NUMERIC: return strValue; case CONTENT: return strValue; case STRING: case ROWID: if (sqlDialect != null) { strValue = sqlDialect.escapeString(strValue); } return '\'' + strValue + '\''; default: if (sqlDialect != null) { return sqlDialect.escapeScriptValue(attribute, value, strValue); } return strValue; } } public static String convertStreamToSQL(DBSAttributeBase attribute, DBDContent content, DBDValueHandler valueHandler, SQLDataSource dataSource) { try { DBRProgressMonitor monitor = new VoidProgressMonitor(); if (ContentUtils.isTextContent(content)) { String strValue = ContentUtils.getContentStringValue(monitor, content); strValue = dataSource.getSQLDialect().escapeString(strValue); return "'" + strValue + "'"; } else { byte[] binValue = ContentUtils.getContentBinaryValue(monitor, content); return dataSource.getSQLDialect().getNativeBinaryFormatter().toString(binValue, 0, binValue.length); } } catch (Throwable e) { log.warn(e); return SQLConstants.NULL_VALUE; } } public static String getColumnTypeModifiers(@Nullable DBPDataSource dataSource, DBSTypedObject column, @NotNull String typeName, @NotNull DBPDataKind dataKind) { if (column == null) { return null; } if (!(dataSource instanceof SQLDataSource)) { return null; } SQLDialect dialect = ((SQLDataSource) dataSource).getSQLDialect(); return dialect.getColumnTypeModifiers(column, typeName, dataKind); } public static boolean isExecQuery(@NotNull SQLDialect dialect, String query) { // Check for EXEC query final String[] executeKeywords = dialect.getExecuteKeywords(); if (executeKeywords.length > 0) { final String queryStart = getFirstKeyword(dialect, query); for (String keyword : executeKeywords) { if (keyword.equalsIgnoreCase(queryStart)) { return true; } } } return false; } public static String getScriptDescripion(@NotNull String sql) { sql = stripComments(BasicSQLDialect.INSTANCE, sql); Matcher matcher = CREATE_PREFIX_PATTERN.matcher(sql); if (matcher.find() && matcher.start(0) == 0) { sql = sql.substring(matcher.end(1)); } sql = sql.replaceAll(" +", " "); if (sql.length() > MAX_SQL_DESCRIPTION_LENGTH) { sql = sql.substring(0, MAX_SQL_DESCRIPTION_LENGTH) + " ..."; } return sql; } @Nullable public static String getScriptDescription(@NotNull IFile sqlScript) { try { //log.debug("Read script '" + sqlScript.getName() + "' description"); StringBuilder sql = new StringBuilder(); try (BufferedReader is = new BufferedReader(new InputStreamReader(sqlScript.getContents()))) { for (;;) { String line = is.readLine(); if (line == null) { break; } line = line.trim(); if (line.startsWith(SQLConstants.SL_COMMENT) || line.startsWith("Rem") || line.startsWith("rem") || line.startsWith("REM") ) { continue; } sql.append(line).append('\n'); if (sql.length() > MIN_SQL_DESCRIPTION_LENGTH) { break; } } } return SQLUtils.getScriptDescripion(sql.toString()); } catch (Exception e) { log.warn("", e); } return null; } @NotNull public static String generateCommentLine(DBPDataSource dataSource, String comment) { String slComment = SQLConstants.ML_COMMENT_END; if (dataSource instanceof SQLDataSource) { String[] slComments = ((SQLDataSource) dataSource).getSQLDialect().getSingleLineComments(); if (!ArrayUtils.isEmpty(slComments)) { slComment = slComments[0]; } } return slComment + " " + comment + GeneralUtils.getDefaultLineSeparator(); } public static String generateParamList(int paramCount) { if (paramCount == 0) { return ""; } else if (paramCount == 1) { return "?"; } StringBuilder sql = new StringBuilder("?"); for (int i = 0; i < paramCount - 1; i++) { sql.append(",?"); } return sql.toString(); } /** * Replaces single \r linefeeds with space (some databases don't like them) */ public static String fixLineFeeds(String sql) { if (sql.indexOf('\r') == -1) { return sql; } boolean hasFixes = false; char[] fixed = sql.toCharArray(); for (int i = 0; i < fixed.length; i++) { if (fixed[i] == '\r') { if (i > 0 && fixed[i - 1] == '\n') { // \n\r continue; } if (i == fixed.length - 1 || fixed[i + 1] == '\n') { // \r\n continue; } // Single \r - replace it with space fixed[i] = ' '; hasFixes = true; } } return hasFixes ? String.valueOf(fixed) : sql; } /** * Compares two string ignoring extra whitespaces. * We can remove double whitespaces and any whitespaces between special chars (*-+,: etc). */ public static boolean compareAliases(String str1, String str2) { return removeExtraSpaces(str1).equals(removeExtraSpaces(str2)); } public static String removeExtraSpaces(String str) { if (str.indexOf(' ') == -1) { return str; } StringBuilder result = new StringBuilder(str.length()); int length = str.length(); for (int i = 0; i < length; i++) { char c = str.charAt(i); if (Character.isWhitespace(c)) { boolean needsSpace = i > 0 && Character.isLetterOrDigit(str.charAt(i - 1)); for (i = i + 1; i < length; i++) { c = str.charAt(i); if (Character.isWhitespace(c)) { continue; } if (needsSpace && Character.isLetterOrDigit(c)) { // We need exactly one space before letter/digit result.append(' '); } else { // We don't need spaces before control symbols } result.append(c); break; } } else { result.append(c); } } return result.toString(); } @NotNull public static String generateScript(DBPDataSource dataSource, DBEPersistAction[] persistActions, boolean addComments) { final SQLDialect sqlDialect = SQLUtils.getDialectFromDataSource(dataSource); final String lineSeparator = GeneralUtils.getDefaultLineSeparator(); StringBuilder script = new StringBuilder(64); if (addComments) { script.append(DBEAVER_DDL_COMMENT).append(Platform.getProduct().getName()).append(lineSeparator) .append(DBEAVER_DDL_WARNING).append(lineSeparator); } if (persistActions != null) { String redefiner = sqlDialect.getScriptDelimiterRedefiner(); for (DBEPersistAction action : persistActions) { String scriptLine = action.getScript(); if (CommonUtils.isEmpty(scriptLine)) { continue; } String delimiter = sqlDialect.getScriptDelimiter(); if (!delimiter.isEmpty() && Character.isLetterOrDigit(delimiter.charAt(0))) { delimiter = ' ' + delimiter; } if (action.isComplex() && redefiner != null) { script.append(lineSeparator).append(redefiner).append(" ").append(DBEAVER_SCRIPT_DELIMITER).append(lineSeparator); delimiter = DBEAVER_SCRIPT_DELIMITER; script.append(delimiter).append(lineSeparator); } else if (action.getType() == DBEPersistAction.ActionType.COMMENT) { if (script.length() > 2) { int lfCount = 0; for (int i = script.length() - 1; i >= 0; i--) { if (!Character.isWhitespace(script.charAt(i))) { break; } if (script.charAt(i) == '\n') lfCount++; } if (lfCount < 2) { // Add line feed if we do not have empty line before script.append(lineSeparator); } } } script.append(scriptLine); if (action.getType() != DBEPersistAction.ActionType.COMMENT) { script.append(delimiter); } else { script.append(lineSeparator); } script.append(lineSeparator); if (action.isComplex() && redefiner != null) { script.append(redefiner).append(" ").append(sqlDialect.getScriptDelimiter()).append(lineSeparator); } } } return script.toString(); } public static String[] splitFullIdentifier(final String fullName, char nameSeparator, String[][] quoteStrings) { return splitFullIdentifier(fullName, String.valueOf(nameSeparator), quoteStrings, false); } public static String[] splitFullIdentifier(final String fullName, String nameSeparator, String[][] quoteStrings, boolean keepQuotes) { String name = fullName.trim(); if (ArrayUtils.isEmpty(quoteStrings)) { return name.split(Pattern.quote(nameSeparator)); } if (!name.contains(nameSeparator)) { return new String[] { name }; } List<String> nameList = new ArrayList<>(); while (!name.isEmpty()) { boolean hadQuotedPart = false; for (String[] quotePair : quoteStrings) { String startQuote = quotePair[0]; String endQuote = quotePair[1]; if (!CommonUtils.isEmpty(startQuote) && !CommonUtils.isEmpty(endQuote) && name.startsWith(startQuote)) { int endPos = name.indexOf(endQuote, startQuote.length()); if (endPos != -1) { // Quoted part String partName = keepQuotes ? name.substring(0, endPos + endQuote.length()) : name.substring(startQuote.length(), endPos); nameList.add(partName); name = name.substring(endPos + endQuote.length()).trim(); hadQuotedPart = true; break; } } } if (!hadQuotedPart) { int endPos = name.indexOf(nameSeparator); if (endPos != -1) { nameList.add(name.substring(0, endPos)); name = name.substring(endPos); } else { nameList.add(name); break; } } if (!name.isEmpty() && name.startsWith(nameSeparator)) { name = name.substring(nameSeparator.length()).trim(); } } return nameList.toArray(new String[nameList.size()]); } public static String generateTableJoin(DBRProgressMonitor monitor, DBSEntity leftTable, String leftAlias, DBSEntity rightTable, String rightAlias) throws DBException { // Try to find FK in left table referencing to right table String sql = generateTableJoinByAssociation(monitor, leftTable, leftAlias, rightTable, rightAlias); if (sql != null) return sql; // Now try right to left sql = generateTableJoinByAssociation(monitor, rightTable, rightAlias, leftTable, leftAlias); if (sql != null) return sql; // Try to find columns in left table which match unique key in right table sql = generateTableJoinByColumns(monitor, leftTable, leftAlias, rightTable, rightAlias); if (sql != null) return sql; // In reverse order sql = generateTableJoinByColumns(monitor, rightTable, rightAlias, leftTable, leftAlias); if (sql != null) return sql; return null; } private static String generateTableJoinByColumns(DBRProgressMonitor monitor, DBSEntity leftTable, String leftAlias, DBSEntity rightTable, String rightAlias) throws DBException { List<DBSEntityAttribute> leftIdentifier = new ArrayList<>(DBUtils.getBestTableIdentifier(monitor, leftTable)); if (!leftIdentifier.isEmpty()) { List<DBSEntityAttribute> rightAttributes = new ArrayList<>(); for (DBSEntityAttribute attr : leftIdentifier) { DBSEntityAttribute rightAttr = rightTable.getAttribute(monitor, attr.getName()); if (rightAttr == null) { break; } rightAttributes.add(rightAttr); } if (leftIdentifier.size() != rightAttributes.size()) { return null; } StringBuilder joinSQL = new StringBuilder(); for (int i = 0; i < leftIdentifier.size(); i++) { joinSQL .append(leftAlias).append(".").append(DBUtils.getQuotedIdentifier(leftIdentifier.get(i))).append(" = ") .append(rightAlias).append(".").append(DBUtils.getQuotedIdentifier(rightAttributes.get(i))); } return joinSQL.toString(); } return null; } private static String generateTableJoinByAssociation(DBRProgressMonitor monitor, DBSEntity leftTable, String leftAlias, DBSEntity rightTable, String rightAlias) throws DBException { Collection<? extends DBSEntityAssociation> associations = leftTable.getAssociations(monitor); if (!CommonUtils.isEmpty(associations)) { for (DBSEntityAssociation fk : associations) { if (fk instanceof DBSTableForeignKey && fk.getAssociatedEntity() == rightTable) { return generateTablesJoin(monitor, (DBSTableForeignKey)fk, leftAlias, rightAlias); } } } return null; } private static String generateTablesJoin(DBRProgressMonitor monitor, DBSTableForeignKey fk, String leftAlias, String rightAlias) throws DBException { boolean hasCriteria = false; StringBuilder joinSQL = new StringBuilder(); for (DBSEntityAttributeRef ar : fk.getAttributeReferences(monitor)) { if (ar instanceof DBSTableForeignKeyColumn) { if (hasCriteria) { joinSQL.append(" AND "); } DBSTableForeignKeyColumn fkc = (DBSTableForeignKeyColumn)ar; joinSQL .append(leftAlias).append(".").append(DBUtils.getQuotedIdentifier(fkc)).append(" = ") .append(rightAlias).append(".").append(DBUtils.getQuotedIdentifier(fkc.getReferencedColumn())); hasCriteria = true; } } return joinSQL.toString(); } public static String getTableAlias(DBSEntity table) { return CommonUtils.escapeIdentifier(table.getName()); } public static void appendQueryConditions(DBPDataSource dataSource, @NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter) { if (dataFilter != null && dataFilter.hasConditions()) { query.append("\nWHERE "); //$NON-NLS-1$ appendConditionString(dataFilter, dataSource, tableAlias, query, true); } } public static void appendQueryOrder(DBPDataSource dataSource, @NotNull StringBuilder query, @Nullable String tableAlias, @Nullable DBDDataFilter dataFilter) { if (dataFilter != null) { // Construct ORDER BY if (dataFilter.hasOrdering()) { query.append("\nORDER BY "); //$NON-NLS-1$ appendOrderString(dataFilter, dataSource, tableAlias, query); } } } }
#4284 Results ordering fix: do not use numeric column identifiers is table alias is used
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLUtils.java
#4284 Results ordering fix: do not use numeric column identifiers is table alias is used
<ide><path>lugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLUtils.java <ide> private static final Log log = Log.getLog(SQLUtils.class); <ide> <ide> public static final Pattern PATTERN_OUT_PARAM = Pattern.compile("((\\?)|(:[a-z0-9]+))\\s*:="); <del> public static final Pattern PATTERN_SIMPLE_NAME = Pattern.compile("[a-z][a-z0-9]*", Pattern.CASE_INSENSITIVE); <add> public static final Pattern PATTERN_SIMPLE_NAME = Pattern.compile("[a-z][a-z0-9_]*", Pattern.CASE_INSENSITIVE); <ide> <ide> private static final Pattern CREATE_PREFIX_PATTERN = Pattern.compile("(CREATE (:OR REPLACE)?).+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); <ide> <ide> boolean hasOrder = false; <ide> for (DBDAttributeConstraint co : filter.getOrderConstraints()) { <ide> if (hasOrder) query.append(','); <del> if (conditionTable != null) { <del> query.append(conditionTable).append('.'); <del> } <ide> String orderString = null; <ide> if (co.getAttribute() instanceof DBDAttributeBindingMeta) { <ide> String orderColumn = co.getAttribute().getName(); <ide> if (PATTERN_SIMPLE_NAME.matcher(orderColumn).matches()) { <ide> // It is a simple column. <ide> orderString = DBUtils.getObjectFullName(co.getAttribute(), DBPEvaluationContext.DML); <add> if (conditionTable != null) { <add> orderString = conditionTable + '.' + orderString; <add> } <ide> } <ide> } <ide> if (orderString == null) {
Java
mit
bd39306664cf66416360033ec3a950bfe8c1a6da
0
Sylvain-Bugat/java-classic-algorithms
package com.github.sbugat.problems.sudoku; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; public class SudokuRecursiveSolver { private final int[][] grid; private final boolean[][] lines; private final boolean[][] columns; private final boolean[][] blocks; private int solutionCount; private final int dimension; private final int sudokuSize; public SudokuRecursiveSolver(final int dimensionArg) throws IOException { dimension = dimensionArg; sudokuSize = dimensionArg * 3; final int arraySize = dimensionArg * dimensionArg + 1; grid = new int[arraySize][arraySize]; lines = new boolean[arraySize][arraySize]; columns = new boolean[arraySize][arraySize]; blocks = new boolean[arraySize][arraySize]; for (int i = 0; i < arraySize; i++) { Arrays.fill(lines[i], true); Arrays.fill(columns[i], true); Arrays.fill(blocks[i], true); } read(); solve(0, 0); } /** * Solve Sudoku with depth-first/back-tracking algorithm * * @param x * @param y */ public void solve(int x, int y) { // If a symbol is already in the grid at this position if (grid[y][x] > 0) { x++; if (x >= sudokuSize) { x = 0; y++; if (y >= sudokuSize) { solutionCount++; System.out.println("solution number " + solutionCount + ":"); print(); return; } } solve(x, y); return; } for (int nb = 1; nb <= sudokuSize; nb++) { if (columns[x][nb] && lines[y][nb]) { final int blocId = x / dimension + dimension * (y / dimension); if (blocks[blocId][nb]) { columns[x][nb] = false; lines[y][nb] = false; blocks[blocId][nb] = false; grid[y][x] = nb; int newX = x + 1; int newY = y; if (newX >= sudokuSize) { newX = 0; newY++; if (newY >= sudokuSize) { solutionCount++; System.out.println("solution number " + solutionCount + ":"); print(); } else { solve(newX, newY); } } else { solve(newX, newY); } columns[x][nb] = true; lines[y][nb] = true; blocks[blocId][nb] = true; grid[y][x] = 0; } } } } public void read() throws IOException { try (BufferedReader br = new BufferedReader(new FileReader("grid.txt"))) { for (int y = 0; y < 9; y++) { char[] ligne = br.readLine().toCharArray(); for (int x = 0; x < 9; x++) { grid[y][x] = ligne[x] - '0'; if (grid[y][x] > 0) { columns[x][grid[y][x]] = false; lines[y][grid[y][x]] = false; blocks[x / 3 + 3 * (y / 3)][grid[y][x]] = false; } } } } } public void print() { for (int y = 0; y < sudokuSize; y++) { if (y % dimension == 0) { System.out.println(); } for (int x = 0; x < sudokuSize; x++) { if (x % dimension == 0) { System.out.print(" "); } System.out.print(grid[y][x]); } System.out.println(); } } public static void main(String args[]) throws IOException { SudokuRecursiveSolver solver = new SudokuRecursiveSolver(3); if (0 == solver.solutionCount) { System.out.println("No solution found"); System.exit(1); } else if ( solver.solutionCount > 1 ) { System.out.println("Multiple solutions found, this is not a true Soduku grid!"); System.exit(1); } } }
src/main/java/com/github/sbugat/problems/sudoku/SudokuRecursiveSolver.java
package com.github.sbugat.problems.sudoku; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; public class SudokuRecursiveSolver { private final int[][] grid; private final boolean[][] lines; private final boolean[][] columns; private final boolean[][] blocks; private int solutionCount; private final int dimension; private final int sudokuSize; public SudokuRecursiveSolver(final int dimensionArg) throws IOException { dimension = dimensionArg; sudokuSize = dimensionArg * 3; final int arraySize = dimensionArg * dimensionArg + 1; grid = new int[arraySize][arraySize]; lines = new boolean[arraySize][arraySize]; columns = new boolean[arraySize][arraySize]; blocks = new boolean[arraySize][arraySize]; for (int i = 0; i < arraySize; i++) { Arrays.fill(lines[i], true); Arrays.fill(columns[i], true); Arrays.fill(blocks[i], true); } read(); solve(0, 0); } /** * Solve Sudoku with depth-first/back-tracking algorithm * * @param x * @param y */ public void solve(int x, int y) { // If a symbol is already in the grid at this position if (grid[y][x] > 0) { x++; if (x >= sudokuSize) { x = 0; y++; if (y >= sudokuSize) { solutionCount++; System.out.println("solution number " + solutionCount + ":"); print(); return; } } solve(x, y); return; } for (int nb = 1; nb <= sudokuSize; nb++) { if (columns[x][nb] && lines[y][nb]) { final int blocId = x / dimension + dimension * (y / dimension); if (blocks[blocId][nb]) { columns[x][nb] = false; lines[y][nb] = false; blocks[blocId][nb] = false; grid[y][x] = nb; int newX = x + 1; int newY = y; if (newX >= sudokuSize) { newX = 0; newY++; if (newY >= sudokuSize) { solutionCount++; System.out.println("solution number " + solutionCount + ":"); print(); } else { solve(newX, newY); } } else { solve(newX, newY); } columns[x][nb] = true; lines[y][nb] = true; blocks[blocId][nb] = true; grid[y][x] = 0; } } } } public void read() throws IOException { try (BufferedReader br = new BufferedReader(new FileReader("grid.txt"))) { for (int y = 0; y < 9; y++) { char[] ligne = br.readLine().toCharArray(); for (int x = 0; x < 9; x++) { grid[y][x] = ligne[x] - '0'; if (grid[y][x] > 0) { columns[x][grid[y][x]] = false; lines[y][grid[y][x]] = false; blocks[x / 3 + 3 * (y / 3)][grid[y][x]] = false; } } } } } public void print() { for (int y = 0; y < sudokuSize; y++) { if (y % dimension == 0) { System.out.println(); } for (int x = 0; x < sudokuSize; x++) { if (x % dimension == 0) { System.out.print(" "); } System.out.print(grid[y][x]); } System.out.println(); } } public static void main(String args[]) throws IOException { SudokuRecursiveSolver solver = new SudokuRecursiveSolver(3); if (0 == solver.solutionCount) { System.out.println("No solution found"); System.exit(1); } } }
Display false soduku grid
src/main/java/com/github/sbugat/problems/sudoku/SudokuRecursiveSolver.java
Display false soduku grid
<ide><path>rc/main/java/com/github/sbugat/problems/sudoku/SudokuRecursiveSolver.java <ide> System.out.println("No solution found"); <ide> System.exit(1); <ide> } <add> else if ( solver.solutionCount > 1 ) { <add> <add> System.out.println("Multiple solutions found, this is not a true Soduku grid!"); <add> System.exit(1); <add> } <ide> } <ide> }
Java
bsd-3-clause
84f4e0fa18e24fbc0ce4eef46835e9bae5236fda
0
NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate,NCIP/cadsr-cdecurate
/** * */ package gov.nih.nci.cadsr.persist.evs; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.Logger; import gov.nih.nci.cadsr.cdecurate.database.SQLHelper; import gov.nih.nci.cadsr.cdecurate.tool.ConBean; import gov.nih.nci.cadsr.persist.common.BaseVO; import gov.nih.nci.cadsr.persist.common.DBConstants; import gov.nih.nci.cadsr.persist.exception.DBException; import gov.nih.nci.cadsr.persist.common.DBManager; import gov.nih.nci.cadsr.persist.concept.Component_Concepts_Ext_Mgr; import gov.nih.nci.cadsr.persist.concept.ConVO; import gov.nih.nci.cadsr.persist.concept.Concepts_Ext_Mgr; import gov.nih.nci.cadsr.persist.de.DeErrorCodes; /** * @author hveerla * */ public abstract class Evs_Mgr extends DBManager { private Logger logger = Logger.getLogger(this.getClass()); /** * Inserts a single row of Evs Object(Object Class, Property, Representation) and returns primary key IDSEQ * * @param sql * @param EVSBean * @param conn * @return * @throws DBException */ public String insert(String sql, BaseVO vO, Connection conn) throws DBException { EvsVO evsVO = (EvsVO) vO; PreparedStatement statement = null; String primaryKey = null; this.initialize(evsVO, conn); // generate IDSEQ(primary key) evsVO.setIDSEQ(this.generatePrimaryKey(conn)); evsVO.setDeleted_ind(DBConstants.RECORD_DELETED_NO); evsVO.setBegin_date(new java.sql.Timestamp(new java.util.Date().getTime())); try { int column = 0; statement = conn.prepareStatement(sql); statement.setString(++column, evsVO.getIDSEQ()); statement.setString(++column, evsVO.getPrefferred_name()); statement.setString(++column, evsVO.getLong_name()); statement.setString(++column, evsVO.getPrefferred_def()); statement.setString(++column, evsVO.getConte_IDSEQ()); statement.setDouble(++column, evsVO.getVersion()); statement.setString(++column, evsVO.getAsl_name()); statement.setString(++column, evsVO.getLastest_version_ind()); statement.setTimestamp(++column, evsVO.getBegin_date()); statement.setString(++column, evsVO.getDefinition_source()); statement.setString(++column, evsVO.getOrigin()); statement.setString(++column, evsVO.getCreated_by()); statement.setString(++column, evsVO.getDeleted_ind()); statement.setString(++column, evsVO.getCondr_IDSEQ()); int count = statement.executeUpdate(); if (count == 0) { throw new Exception("Unable to insert the record"); } else { primaryKey = evsVO.getIDSEQ(); if (logger.isDebugEnabled()) { logger.debug("Inserted EVS Object"); logger.debug("IDSEQ(primary key )-----> " + primaryKey); } } } catch (Exception e) { logger.error("Error inserting EVS object " + e); errorList.add("Error inserting EVS object "); throw new DBException(errorList); } finally { statement = SQLHelper.closePreparedStatement(statement); } return primaryKey; } /* * */ public ArrayList<ResultVO> isCondrExists(ArrayList<ConBean> list, String sql, Connection conn) throws DBException{ Statement statement = null; ResultSet rs = null; ArrayList resultList = new ArrayList(); try { StringBuffer sqlBuff = new StringBuffer(); sqlBuff.append("WITH conlist AS ( "); if (list != null){ for(int i=0; i<list.size(); i++){ ConBean con = (ConBean)list.get(i); sqlBuff.append("select '" + con.getCon_IDSEQ() + "' as con_idseq, '"); sqlBuff.append(con.getConcept_value() + "' as concept_value, "); sqlBuff.append(con.getDisplay_order() + " as display_order from dual "); if ((i+1) != list.size()){ sqlBuff.append("union "); } } } sqlBuff.append(") "); sqlBuff.append(sql); statement = conn.createStatement(); rs = statement.executeQuery(sqlBuff.toString()); while (rs.next()) { ResultVO vo = new ResultVO(); vo.setCondr_IDSEQ(rs.getString("CONDR_IDSEQ")); vo.setIDSEQ(rs.getString("IDSEQ")); vo.setLong_name(rs.getString("LONG_NAME")); vo.setPublicId(rs.getString("PUBLIC_ID")); vo.setVersion(rs.getString("VERSION")); vo.setAsl_name(rs.getString("ASL_NAME")); vo.setContext(rs.getString("CONTEXT")); resultList.add(vo); } } catch (Exception e) { logger.error("Error in isCondrExists method in EVS_Mgr " + e); //errorList.add(); throw new DBException(errorList); } finally { statement = SQLHelper.closeStatement(statement); } return resultList; } public void initialize(EvsVO vo, Connection conn) throws DBException{ Component_Concepts_Ext_Mgr ccmgr = new Component_Concepts_Ext_Mgr(); Concepts_Ext_Mgr conMgr = new Concepts_Ext_Mgr(); vo.setVersion(1); vo.setAsl_name(DBConstants.ASL_NAME_RELEASED); vo.setLastest_version_ind(DBConstants.LATEST_VERSION_IND_YES); Vector<ConVO> conceptsList = ccmgr.getConceptsByCondrIdseq(vo.getCondr_IDSEQ(), conn); String longName = ""; String preferredName = ""; String prefferredDef =""; String defSource =""; String origin = ""; for(int i=0; i<conceptsList.size(); i++){ ConVO conVO = conceptsList.get(i); EvsVO conceptVO = conMgr.getConceptByIdseq(conVO.getConIDSEQ(), conn); String lName = ""; String pName = ""; String pDef = ""; if (conVO.getConcept_value() != null && !conVO.getConcept_value().equals("")) { lName = conceptVO.getLong_name() + "::" + conVO.getConcept_value(); pName = conceptVO.getPrefferred_name() + "::" + conVO.getConcept_value(); pDef = conceptVO.getPrefferred_def() + "::" + conVO.getConcept_value(); } else { lName = conceptVO.getLong_name(); pName = conceptVO.getPrefferred_name(); pDef = conceptVO.getPrefferred_def(); } if (lName != null && !lName.equals("")) { if (longName.equals("")) { longName = lName; } else { longName = longName + " " + lName; } } if (pName != null && !pName.equals("")) { if (preferredName.equals("")) { preferredName = pName; } else { preferredName = preferredName + ":" + pName; } } if (pDef != null & !pDef.equals("")) { if (prefferredDef.equals("")) { prefferredDef = pDef; } else { prefferredDef = prefferredDef + ":" + pDef; } } if (conceptVO.getDefinition_source() != null && !conceptVO.getDefinition_source().equals("")) { if (defSource.equals("")) { defSource = conceptVO.getDefinition_source(); } else { defSource = defSource + ":" + conceptVO.getDefinition_source(); } } if (conceptVO.getOrigin() != null && !conceptVO.getOrigin().equals("")) { if (origin.equals("")) { origin = conceptVO.getOrigin(); } else { origin = origin + ":" + conceptVO.getOrigin(); } } } if (preferredName != null && preferredName.length()>30){ preferredName = null; } if (longName != null && longName.length()>255){ longName = longName.substring(0, 255); } if (prefferredDef != null && prefferredDef.length()>2000){ prefferredDef =prefferredDef.substring(0,2000); } if (defSource != null && defSource.length()>2000){ defSource = defSource.substring(0,2000); } if (origin != null && origin.length()>240){ origin = origin.substring(0,240); } vo.setLong_name(longName); vo.setPrefferred_name(preferredName); vo.setPrefferred_def(prefferredDef); vo.setDefinition_source(defSource); vo.setOrigin(origin); } public abstract ArrayList<ResultVO> isCondrExists(ArrayList<ConBean> list, Connection conn) throws DBException; public abstract String insert(BaseVO vO, Connection conn) throws DBException; }
src/gov/nih/nci/cadsr/persist/evs/Evs_Mgr.java
/** * */ package gov.nih.nci.cadsr.persist.evs; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Vector; import org.apache.log4j.Logger; import gov.nih.nci.cadsr.cdecurate.database.SQLHelper; import gov.nih.nci.cadsr.cdecurate.tool.ConBean; import gov.nih.nci.cadsr.persist.common.BaseVO; import gov.nih.nci.cadsr.persist.common.DBConstants; import gov.nih.nci.cadsr.persist.exception.DBException; import gov.nih.nci.cadsr.persist.common.DBManager; import gov.nih.nci.cadsr.persist.concept.Component_Concepts_Ext_Mgr; import gov.nih.nci.cadsr.persist.concept.ConVO; import gov.nih.nci.cadsr.persist.concept.Concepts_Ext_Mgr; import gov.nih.nci.cadsr.persist.de.DeErrorCodes; /** * @author hveerla * */ public abstract class Evs_Mgr extends DBManager { private Logger logger = Logger.getLogger(this.getClass()); /** * Inserts a single row of Evs Object(Object Class, Property, Representation) and returns primary key IDSEQ * * @param sql * @param EVSBean * @param conn * @return * @throws DBException */ public String insert(String sql, BaseVO vO, Connection conn) throws DBException { EvsVO evsVO = (EvsVO) vO; PreparedStatement statement = null; String primaryKey = null; this.initialize(evsVO, conn); // generate IDSEQ(primary key) evsVO.setIDSEQ(this.generatePrimaryKey(conn)); evsVO.setDeleted_ind(DBConstants.RECORD_DELETED_NO); evsVO.setDate_created(new java.sql.Timestamp(new java.util.Date().getTime())); try { int column = 0; statement = conn.prepareStatement(sql); statement.setString(++column, evsVO.getIDSEQ()); statement.setString(++column, evsVO.getPrefferred_name()); statement.setString(++column, evsVO.getLong_name()); statement.setString(++column, evsVO.getPrefferred_def()); statement.setString(++column, evsVO.getConte_IDSEQ()); statement.setDouble(++column, evsVO.getVersion()); statement.setString(++column, evsVO.getAsl_name()); statement.setString(++column, evsVO.getLastest_version_ind()); statement.setTimestamp(++column, evsVO.getBegin_date()); statement.setString(++column, evsVO.getDefinition_source()); statement.setString(++column, evsVO.getOrigin()); statement.setString(++column, evsVO.getCreated_by()); statement.setString(++column, evsVO.getDeleted_ind()); statement.setString(++column, evsVO.getCondr_IDSEQ()); int count = statement.executeUpdate(); if (count == 0) { throw new Exception("Unable to insert the record"); } else { primaryKey = evsVO.getIDSEQ(); if (logger.isDebugEnabled()) { logger.debug("Inserted EVS Object"); logger.debug("IDSEQ(primary key )-----> " + primaryKey); } } } catch (Exception e) { logger.error("Error inserting EVS object " + e); errorList.add("Error inserting EVS object "); throw new DBException(errorList); } finally { statement = SQLHelper.closePreparedStatement(statement); } return primaryKey; } /* * */ public ArrayList<ResultVO> isCondrExists(ArrayList<ConBean> list, String sql, Connection conn) throws DBException{ Statement statement = null; ResultSet rs = null; ArrayList resultList = new ArrayList(); try { StringBuffer sqlBuff = new StringBuffer(); sqlBuff.append("WITH conlist AS ( "); if (list != null){ for(int i=0; i<list.size(); i++){ ConBean con = (ConBean)list.get(i); sqlBuff.append("select '" + con.getCon_IDSEQ() + "' as con_idseq, '"); sqlBuff.append(con.getConcept_value() + "' as concept_value, "); sqlBuff.append(con.getDisplay_order() + " as display_order from dual "); if ((i+1) != list.size()){ sqlBuff.append("union "); } } } sqlBuff.append(") "); sqlBuff.append(sql); statement = conn.createStatement(); rs = statement.executeQuery(sqlBuff.toString()); while (rs.next()) { ResultVO vo = new ResultVO(); vo.setCondr_IDSEQ(rs.getString("CONDR_IDSEQ")); vo.setIDSEQ(rs.getString("IDSEQ")); vo.setLong_name(rs.getString("LONG_NAME")); vo.setPublicId(rs.getString("PUBLIC_ID")); vo.setVersion(rs.getString("VERSION")); vo.setAsl_name(rs.getString("ASL_NAME")); vo.setContext(rs.getString("CONTEXT")); resultList.add(vo); } } catch (Exception e) { logger.error("Error in isCondrExists method in EVS_Mgr " + e); //errorList.add(); throw new DBException(errorList); } finally { statement = SQLHelper.closeStatement(statement); } return resultList; } public void initialize(EvsVO vo, Connection conn) throws DBException{ Component_Concepts_Ext_Mgr ccmgr = new Component_Concepts_Ext_Mgr(); Concepts_Ext_Mgr conMgr = new Concepts_Ext_Mgr(); vo.setVersion(1); vo.setAsl_name(DBConstants.ASL_NAME_RELEASED); vo.setLastest_version_ind(DBConstants.LATEST_VERSION_IND_YES); Vector<ConVO> conceptsList = ccmgr.getConceptsByCondrIdseq(vo.getCondr_IDSEQ(), conn); String longName = ""; String preferredName = ""; String prefferredDef =""; String defSource =""; String origin = ""; for(int i=0; i<conceptsList.size(); i++){ ConVO conVO = conceptsList.get(i); EvsVO conceptVO = conMgr.getConceptByIdseq(conVO.getConIDSEQ(), conn); String lName = ""; String pName = ""; String pDef = ""; if (conVO.getConcept_value() != null && !conVO.getConcept_value().equals("")) { lName = conceptVO.getLong_name() + "::" + conVO.getConcept_value(); pName = conceptVO.getPrefferred_name() + "::" + conVO.getConcept_value(); pDef = conceptVO.getPrefferred_def() + "::" + conVO.getConcept_value(); } else { lName = conceptVO.getLong_name(); pName = conceptVO.getPrefferred_name(); pDef = conceptVO.getPrefferred_def(); } if (lName != null && !lName.equals("")) { if (longName.equals("")) { longName = lName; } else { longName = longName + " " + lName; } } if (pName != null && !pName.equals("")) { if (preferredName.equals("")) { preferredName = pName; } else { preferredName = preferredName + ":" + pName; } } if (pDef != null & !pDef.equals("")) { if (prefferredDef.equals("")) { prefferredDef = pDef; } else { prefferredDef = prefferredDef + ":" + pDef; } } if (conceptVO.getDefinition_source() != null && !conceptVO.getDefinition_source().equals("")) { if (defSource.equals("")) { defSource = conceptVO.getDefinition_source(); } else { defSource = defSource + ":" + conceptVO.getDefinition_source(); } } if (conceptVO.getOrigin() != null && !conceptVO.getOrigin().equals("")) { if (origin.equals("")) { origin = conceptVO.getOrigin(); } else { origin = origin + ":" + conceptVO.getOrigin(); } } } if (preferredName != null && preferredName.length()>30){ preferredName = null; } if (longName != null && longName.length()>255){ longName = longName.substring(0, 255); } if (prefferredDef != null && prefferredDef.length()>2000){ prefferredDef =prefferredDef.substring(0,2000); } if (defSource != null && defSource.length()>2000){ defSource = defSource.substring(0,2000); } if (origin != null && origin.length()>240){ origin = origin.substring(0,240); } vo.setLong_name(longName); vo.setPrefferred_name(preferredName); vo.setPrefferred_def(prefferredDef); vo.setDefinition_source(defSource); vo.setOrigin(origin); } public abstract ArrayList<ResultVO> isCondrExists(ArrayList<ConBean> list, Connection conn) throws DBException; public abstract String insert(BaseVO vO, Connection conn) throws DBException; }
set Begin date SVN-Revision: 1263
src/gov/nih/nci/cadsr/persist/evs/Evs_Mgr.java
set Begin date
<ide><path>rc/gov/nih/nci/cadsr/persist/evs/Evs_Mgr.java <ide> // generate IDSEQ(primary key) <ide> evsVO.setIDSEQ(this.generatePrimaryKey(conn)); <ide> evsVO.setDeleted_ind(DBConstants.RECORD_DELETED_NO); <del> evsVO.setDate_created(new java.sql.Timestamp(new java.util.Date().getTime())); <add> evsVO.setBegin_date(new java.sql.Timestamp(new java.util.Date().getTime())); <ide> <ide> try { <ide> int column = 0;
Java
apache-2.0
4b56770118091efa3f0d328f4ff8399d6ccc4026
0
lizhanhui/Alibaba_RocketMQ,lizhanhui/Alibaba_RocketMQ,lizhanhui/Alibaba_RocketMQ
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.rocketmq.store; import com.alibaba.rocketmq.common.UtilAll; import com.alibaba.rocketmq.common.constant.LoggerName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 存储队列,数据定时删除,无限增长<br> * 队列是由多个文件组成 * * @author shijia.wxr<[email protected]> * @since 2013-7-21 */ public class MappedFileQueue { private static final Logger log = LoggerFactory.getLogger(LoggerName.StoreLoggerName); private static final Logger logError = LoggerFactory.getLogger(LoggerName.StoreErrorLoggerName); // 每次触发删除文件,最多删除多少个文件 private static final int DeleteFilesBatchMax = 10; // 文件存储位置 private String storePath; // 每个文件的大小 private final int mappedFileSize; // 各个文件 private final List<MappedFile> mappedFiles = new ArrayList<MappedFile>(); // 读写锁(针对mappedFiles) private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); // 预分配MappedFile对象服务 private final AllocateMappedFileService allocateMappedFileService; // 刷盘刷到哪里 private long committedWhere = 0; // 最后一条消息存储时间 private volatile long storeTimestamp = 0; private static final String MAPPED_FILE_NAME_PATTERN_STRING = "\\d+"; private static final Pattern MAPPED_FILE_NAME_PATTERN = Pattern.compile(MAPPED_FILE_NAME_PATTERN_STRING); public MappedFileQueue(final String storePath, int mappedFileSize, AllocateMappedFileService allocateMappedFileService) { this.storePath = storePath; this.mappedFileSize = mappedFileSize; this.allocateMappedFileService = allocateMappedFileService; } public MappedFile getMappedFileByTime(final long timestamp) { Object[] mfs = this.copyMappedFiles(0); if (null == mfs) return null; for (Object mf : mfs) { MappedFile mappedFile = (MappedFile) mf; if (mappedFile.getLastModifiedTimestamp() >= timestamp) { return mappedFile; } } return (MappedFile) mfs[mfs.length - 1]; } private Object[] copyMappedFiles(final int reservedMappedFiles) { Object[] mfs = null; try { this.readWriteLock.readLock().lock(); if (this.mappedFiles.size() <= reservedMappedFiles) { return null; } mfs = this.mappedFiles.toArray(); } catch (Exception e) { e.printStackTrace(); } finally { this.readWriteLock.readLock().unlock(); } return mfs; } /** * recover时调用,不需要加锁 */ public void truncateDirtyFiles(long offset) { List<MappedFile> willRemoveFiles = new ArrayList<MappedFile>(); for (MappedFile file : this.mappedFiles) { long fileTailOffset = file.getFileFromOffset() + this.mappedFileSize; if (fileTailOffset > offset) { if (offset >= file.getFileFromOffset()) { file.setWrotePosition((int) (offset % this.mappedFileSize)); file.setCommittedPosition((int) (offset % this.mappedFileSize)); } else { // 将文件删除掉 file.destroy(1000); willRemoveFiles.add(file); } } } this.deleteExpiredFile(willRemoveFiles); } /** * 删除文件只能从头开始删 */ private void deleteExpiredFile(List<MappedFile> files) { if (!files.isEmpty()) { try { this.readWriteLock.writeLock().lock(); for (MappedFile file : files) { if (!this.mappedFiles.remove(file)) { log.error("deleteExpiredFile remove failed."); break; } } } catch (Exception e) { log.error("deleteExpiredFile has exception.", e); } finally { this.readWriteLock.writeLock().unlock(); } } } public boolean load() { File[] dirs; if (!this.storePath.contains(",")) { dirs = new File[]{new File(this.storePath)}; } else { String[] storePaths = storePath.split(","); dirs = new File[storePaths.length]; for (int i = 0; i < dirs.length; i++) { dirs[i] = new File(storePaths[i]); } } List<File> files = new ArrayList<File>(); for (File dir : dirs) { File[] commitLogFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { Matcher matcher = MAPPED_FILE_NAME_PATTERN.matcher(name); return matcher.matches(); } }); if (null != commitLogFiles) { files.addAll(Arrays.asList(commitLogFiles)); } } if (!files.isEmpty()) { // ascending order Collections.sort(files, new Comparator<File>() { @Override public int compare(File lhs, File rhs) { return lhs.getName().compareTo(rhs.getName()); } }); for (File file : files) { // 校验文件大小是否匹配 if (file.length() != this.mappedFileSize) { log.warn(file + "\t" + file.length() + " length not matched message store config value, ignore it"); return true; } // 恢复队列 try { MappedFile mapedFile = new MappedFile(file.getPath(), mappedFileSize); mapedFile.setWrotePosition(this.mappedFileSize); mapedFile.setCommittedPosition(this.mappedFileSize); this.mappedFiles.add(mapedFile); log.info("load " + file.getPath() + " OK"); } catch (IOException e) { log.error("load file " + file + " error", e); return false; } } } return true; } /** * 刷盘进度落后了多少 */ public long howMuchFallBehind() { if (this.mappedFiles.isEmpty()) return 0; long committed = this.committedWhere; if (committed != 0) { MappedFile mappedFile = this.getLastMappedFile(); if (mappedFile != null) { return (mappedFile.getFileFromOffset() + mappedFile.getWrotePosition()) - committed; } } return 0; } public MappedFile getLastMappedFile() { return this.getLastMappedFile(0); } /** * 获取最后一个MappedFile对象,如果一个都没有,则新创建一个,如果最后一个写满了,则新创建一个 * * @param startOffset 如果创建新的文件,起始offset * @return */ public MappedFile getLastMappedFile(final long startOffset) { long createOffset = -1; MappedFile mappedFileLast = null; { this.readWriteLock.readLock().lock(); if (this.mappedFiles.isEmpty()) { createOffset = startOffset - (startOffset % this.mappedFileSize); } else { mappedFileLast = this.mappedFiles.get(this.mappedFiles.size() - 1); } this.readWriteLock.readLock().unlock(); } if (mappedFileLast != null && mappedFileLast.isFull()) { createOffset = mappedFileLast.getFileFromOffset() + this.mappedFileSize; } if (createOffset != -1) { String commitLogStorePath = UtilAll.selectPath(this.storePath); String nextFilePath = commitLogStorePath + File.separator + UtilAll.offset2FileName(createOffset); String nextNextFilePath = commitLogStorePath + File.separator + UtilAll.offset2FileName(createOffset + this.mappedFileSize); MappedFile mappedFile = null; if (this.allocateMappedFileService != null) { mappedFile = this.allocateMappedFileService.putRequestAndReturnMappedFile(nextFilePath, nextNextFilePath, this.mappedFileSize); } else { try { mappedFile = new MappedFile(nextFilePath, this.mappedFileSize); } catch (IOException e) { log.error("create mapped file exception", e); } } if (mappedFile != null) { this.readWriteLock.writeLock().lock(); if (this.mappedFiles.isEmpty()) { mappedFile.setFirstCreateInQueue(true); } this.mappedFiles.add(mappedFile); this.readWriteLock.writeLock().unlock(); } return mappedFile; } return mappedFileLast; } /** * 获取队列的最小Offset,如果队列为空,则返回-1 */ public long getMinOffset() { try { this.readWriteLock.readLock().lock(); if (!this.mappedFiles.isEmpty()) { return this.mappedFiles.get(0).getFileFromOffset(); } } catch (Exception e) { log.error("getMinOffset has exception.", e); } finally { this.readWriteLock.readLock().unlock(); } return -1; } public long getMaxOffset() { try { this.readWriteLock.readLock().lock(); if (!this.mappedFiles.isEmpty()) { int lastIndex = this.mappedFiles.size() - 1; MappedFile mappedFile = this.mappedFiles.get(lastIndex); return mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); } } catch (Exception e) { log.error("getMinOffset has exception.", e); } finally { this.readWriteLock.readLock().unlock(); } return 0; } /** * 恢复时调用 */ public void deleteLastMappedFile() { if (!this.mappedFiles.isEmpty()) { int lastIndex = this.mappedFiles.size() - 1; MappedFile mappedFile = this.mappedFiles.get(lastIndex); mappedFile.destroy(1000); this.mappedFiles.remove(mappedFile); log.info("on recover, destroy a logic mapped file " + mappedFile.getFileName()); } } /** * 根据文件过期时间来删除物理队列文件 */ public int deleteExpiredFileByTime(// final long expiredTime, // final int deleteFilesInterval, // final long intervalForcibly,// final boolean cleanImmediately// ) { Object[] mfs = this.copyMappedFiles(0); if (null == mfs) return 0; // 最后一个文件处于写状态,不能删除 int mfsLength = mfs.length - 1; int deleteCount = 0; List<MappedFile> files = new ArrayList<MappedFile>(); for (int i = 0; i < mfsLength; i++) { MappedFile mappedFile = (MappedFile) mfs[i]; long liveMaxTimestamp = mappedFile.getLastModifiedTimestamp() + expiredTime; if (System.currentTimeMillis() >= liveMaxTimestamp// || cleanImmediately) { if (mappedFile.destroy(intervalForcibly)) { files.add(mappedFile); deleteCount++; if (files.size() >= DeleteFilesBatchMax) { break; } if (deleteFilesInterval > 0 && (i + 1) < mfsLength) { try { Thread.sleep(deleteFilesInterval); } catch (InterruptedException e) { } } } else { break; } } } deleteExpiredFile(files); return deleteCount; } /** * 根据物理队列最小offset来删除commit log队列文件. * @param offset physical offset * @return 删除的文件个数 */ public int deleteExpiredFilesByPhysicalOffset(long offset) { if (offset < mappedFileSize) { return 0; } // copy with read lock. Object[] mfs = copyMappedFiles(0); List<MappedFile> files = new ArrayList<>(); int deleteCount = 0; if (null != mfs) { int len = mfs.length - 1; for (int i = 0; i < len; i++) { MappedFile mappedFile = (MappedFile) mfs[i]; if (mappedFile.getFileFromOffset() + mappedFileSize < offset) { if (mappedFile.destroy(60 * 1000)) { // Destroy files files.add(mappedFile); deleteCount++; } } else { break; } } } // remove with write lock. deleteExpiredFile(files); return deleteCount; } /** * 根据物理队列最小Offset来删除逻辑队列 * * @param offset 物理队列最小offset */ public int deleteExpiredFileByOffset(long offset, int unitSize) { Object[] mfs = this.copyMappedFiles(0); List<MappedFile> files = new ArrayList<MappedFile>(); int deleteCount = 0; if (null != mfs) { // 最后一个文件处于写状态,不能删除 int mfsLength = mfs.length - 1; // 这里遍历范围 0 ... last - 1 for (int i = 0; i < mfsLength; i++) { boolean destroy = true; MappedFile mappedFile = (MappedFile) mfs[i]; SelectMappedBufferResult result = mappedFile.selectMappedBuffer(this.mappedFileSize - unitSize); if (result != null) { long maxOffsetInLogicQueue = result.getByteBuffer().getLong(); result.release(); // 当前文件是否可以删除 destroy = (maxOffsetInLogicQueue < offset); if (destroy) { log.info("physic min offset " + offset + ", logics in current mapped file max offset " + maxOffsetInLogicQueue + ", delete it"); } } else { log.warn("this being not executed forever."); if (mappedFile.isCleanupOver()) { // Process dangling file. File file = new File(mappedFile.getFileName()); if (file.exists()) { boolean success = file.delete(); if (!success) { log.error("Unable to delete dangling file: {}", mappedFile.getFileName()); } } } else { break; } } if (destroy && mappedFile.destroy(1000 * 60)) { files.add(mappedFile); deleteCount++; } else { break; } } } deleteExpiredFile(files); return deleteCount; } /** * 返回值表示是否全部刷盘完成 * * @return */ public boolean commit(final int flushLeastPages) { boolean result = true; MappedFile mappedFile = this.findMappedFileByOffset(this.committedWhere, true); if (mappedFile != null) { long tmpTimeStamp = mappedFile.getStoreTimestamp(); int offset = mappedFile.commit(flushLeastPages); long where = mappedFile.getFileFromOffset() + offset; result = (where == this.committedWhere); this.committedWhere = where; if (0 == flushLeastPages) { this.storeTimestamp = tmpTimeStamp; } } return result; } public MappedFile findMappedFileByOffset(final long offset, final boolean returnFirstOnNotFound) { try { this.readWriteLock.readLock().lock(); MappedFile mappedFile = this.getFirstMappedFile(); if (mappedFile != null) { int index = (int) ((offset / this.mappedFileSize) - (mappedFile.getFileFromOffset() / this.mappedFileSize)); if (!returnFirstOnNotFound && (index < 0 || index >= this.mappedFiles.size())) { logError.warn("findMappedFileByOffset offset not matched, request Offset: {}, index: {}, " + "mappedFileSize: {}, mappedFiles count: {}, StackTrace: {}",// offset,// index,// this.mappedFileSize,// this.mappedFiles.size(),// UtilAll.currentStackTrace()); } try { return this.mappedFiles.get(index); } catch (Exception e) { if (returnFirstOnNotFound) { return mappedFile; } } } } catch (Exception e) { log.error("findMappedFileByOffset Exception", e); } finally { this.readWriteLock.readLock().unlock(); } return null; } private MappedFile getFirstMappedFile() { if (this.mappedFiles.isEmpty()) { return null; } return this.mappedFiles.get(0); } public MappedFile getLastMappedFile2() { if (this.mappedFiles.isEmpty()) { return null; } return this.mappedFiles.get(this.mappedFiles.size() - 1); } public MappedFile findMappedFileByOffset(final long offset) { return findMappedFileByOffset(offset, false); } public long getMappedMemorySize() { long size = 0; Object[] mfs = this.copyMappedFiles(0); if (mfs != null) { for (Object mf : mfs) { if (((ReferenceResource) mf).isAvailable()) { size += this.mappedFileSize; } } } return size; } public boolean retryDeleteFirstFile(final long intervalForcibly) { MappedFile mappedFile = this.getFirstMappedFileOnLock(); if (mappedFile != null) { if (!mappedFile.isAvailable()) { log.warn("the mapped file was destroyed once, but still alive, " + mappedFile.getFileName()); boolean result = mappedFile.destroy(intervalForcibly); if (result) { log.warn("the mapped file re-delete OK, " + mappedFile.getFileName()); List<MappedFile> tempMappedFiles = new ArrayList<MappedFile>(); tempMappedFiles.add(mappedFile); this.deleteExpiredFile(tempMappedFiles); } else { log.warn("the mapped file re-delete Failed, " + mappedFile.getFileName()); } return result; } } return false; } public MappedFile getFirstMappedFileOnLock() { try { this.readWriteLock.readLock().lock(); return this.getFirstMappedFile(); } finally { this.readWriteLock.readLock().unlock(); } } /** * 关闭队列,队列数据还在,但是不能访问 */ public void shutdown(final long intervalForcibly) { this.readWriteLock.readLock().lock(); for (MappedFile mf : this.mappedFiles) { mf.shutdown(intervalForcibly); } this.readWriteLock.readLock().unlock(); } /** * 销毁队列,队列数据被删除,此函数有可能不成功 */ public void destroy() { this.readWriteLock.writeLock().lock(); for (MappedFile mf : this.mappedFiles) { mf.destroy(1000 * 3); } this.mappedFiles.clear(); this.committedWhere = 0; // delete parent directory File file = new File(storePath); if (file.isDirectory()) { file.delete(); } this.readWriteLock.writeLock().unlock(); } public long getCommittedWhere() { return committedWhere; } public void setCommittedWhere(long committedWhere) { this.committedWhere = committedWhere; } public long getStoreTimestamp() { return storeTimestamp; } public List<MappedFile> getMappedFiles() { return mappedFiles; } public int getMappedFileSize() { return mappedFileSize; } public void setStorePath(String storePath) { this.storePath = storePath; } }
rocketmq-store/src/main/java/com/alibaba/rocketmq/store/MappedFileQueue.java
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.rocketmq.store; import com.alibaba.rocketmq.common.UtilAll; import com.alibaba.rocketmq.common.constant.LoggerName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 存储队列,数据定时删除,无限增长<br> * 队列是由多个文件组成 * * @author shijia.wxr<[email protected]> * @since 2013-7-21 */ public class MappedFileQueue { private static final Logger log = LoggerFactory.getLogger(LoggerName.StoreLoggerName); private static final Logger logError = LoggerFactory.getLogger(LoggerName.StoreErrorLoggerName); // 每次触发删除文件,最多删除多少个文件 private static final int DeleteFilesBatchMax = 10; // 文件存储位置 private String storePath; // 每个文件的大小 private final int mappedFileSize; // 各个文件 private final List<MappedFile> mappedFiles = new ArrayList<MappedFile>(); // 读写锁(针对mappedFiles) private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); // 预分配MappedFile对象服务 private final AllocateMappedFileService allocateMappedFileService; // 刷盘刷到哪里 private long committedWhere = 0; // 最后一条消息存储时间 private volatile long storeTimestamp = 0; private static final String MAPPED_FILE_NAME_PATTERN_STRING = "\\d+"; private static final Pattern MAPPED_FILE_NAME_PATTERN = Pattern.compile(MAPPED_FILE_NAME_PATTERN_STRING); public MappedFileQueue(final String storePath, int mappedFileSize, AllocateMappedFileService allocateMappedFileService) { this.storePath = storePath; this.mappedFileSize = mappedFileSize; this.allocateMappedFileService = allocateMappedFileService; } public MappedFile getMappedFileByTime(final long timestamp) { Object[] mfs = this.copyMappedFiles(0); if (null == mfs) return null; for (Object mf : mfs) { MappedFile mappedFile = (MappedFile) mf; if (mappedFile.getLastModifiedTimestamp() >= timestamp) { return mappedFile; } } return (MappedFile) mfs[mfs.length - 1]; } private Object[] copyMappedFiles(final int reservedMappedFiles) { Object[] mfs = null; try { this.readWriteLock.readLock().lock(); if (this.mappedFiles.size() <= reservedMappedFiles) { return null; } mfs = this.mappedFiles.toArray(); } catch (Exception e) { e.printStackTrace(); } finally { this.readWriteLock.readLock().unlock(); } return mfs; } /** * recover时调用,不需要加锁 */ public void truncateDirtyFiles(long offset) { List<MappedFile> willRemoveFiles = new ArrayList<MappedFile>(); for (MappedFile file : this.mappedFiles) { long fileTailOffset = file.getFileFromOffset() + this.mappedFileSize; if (fileTailOffset > offset) { if (offset >= file.getFileFromOffset()) { file.setWrotePosition((int) (offset % this.mappedFileSize)); file.setCommittedPosition((int) (offset % this.mappedFileSize)); } else { // 将文件删除掉 file.destroy(1000); willRemoveFiles.add(file); } } } this.deleteExpiredFile(willRemoveFiles); } /** * 删除文件只能从头开始删 */ private void deleteExpiredFile(List<MappedFile> files) { if (!files.isEmpty()) { try { this.readWriteLock.writeLock().lock(); for (MappedFile file : files) { if (!this.mappedFiles.remove(file)) { log.error("deleteExpiredFile remove failed."); break; } } } catch (Exception e) { log.error("deleteExpiredFile has exception.", e); } finally { this.readWriteLock.writeLock().unlock(); } } } public boolean load() { File[] dirs; if (!this.storePath.contains(",")) { dirs = new File[]{new File(this.storePath)}; } else { String[] storePaths = storePath.split(","); dirs = new File[storePaths.length]; for (int i = 0; i < dirs.length; i++) { dirs[i] = new File(storePaths[i]); } } List<File> files = new ArrayList<File>(); for (File dir : dirs) { File[] commitLogFiles = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { Matcher matcher = MAPPED_FILE_NAME_PATTERN.matcher(name); return matcher.matches(); } }); if (null != commitLogFiles) { files.addAll(Arrays.asList(commitLogFiles)); } } if (!files.isEmpty()) { // ascending order Collections.sort(files); for (File file : files) { // 校验文件大小是否匹配 if (file.length() != this.mappedFileSize) { log.warn(file + "\t" + file.length() + " length not matched message store config value, ignore it"); return true; } // 恢复队列 try { MappedFile mapedFile = new MappedFile(file.getPath(), mappedFileSize); mapedFile.setWrotePosition(this.mappedFileSize); mapedFile.setCommittedPosition(this.mappedFileSize); this.mappedFiles.add(mapedFile); log.info("load " + file.getPath() + " OK"); } catch (IOException e) { log.error("load file " + file + " error", e); return false; } } } return true; } /** * 刷盘进度落后了多少 */ public long howMuchFallBehind() { if (this.mappedFiles.isEmpty()) return 0; long committed = this.committedWhere; if (committed != 0) { MappedFile mappedFile = this.getLastMappedFile(); if (mappedFile != null) { return (mappedFile.getFileFromOffset() + mappedFile.getWrotePosition()) - committed; } } return 0; } public MappedFile getLastMappedFile() { return this.getLastMappedFile(0); } /** * 获取最后一个MappedFile对象,如果一个都没有,则新创建一个,如果最后一个写满了,则新创建一个 * * @param startOffset 如果创建新的文件,起始offset * @return */ public MappedFile getLastMappedFile(final long startOffset) { long createOffset = -1; MappedFile mappedFileLast = null; { this.readWriteLock.readLock().lock(); if (this.mappedFiles.isEmpty()) { createOffset = startOffset - (startOffset % this.mappedFileSize); } else { mappedFileLast = this.mappedFiles.get(this.mappedFiles.size() - 1); } this.readWriteLock.readLock().unlock(); } if (mappedFileLast != null && mappedFileLast.isFull()) { createOffset = mappedFileLast.getFileFromOffset() + this.mappedFileSize; } if (createOffset != -1) { String commitLogStorePath = UtilAll.selectPath(this.storePath); String nextFilePath = commitLogStorePath + File.separator + UtilAll.offset2FileName(createOffset); String nextNextFilePath = commitLogStorePath + File.separator + UtilAll.offset2FileName(createOffset + this.mappedFileSize); MappedFile mappedFile = null; if (this.allocateMappedFileService != null) { mappedFile = this.allocateMappedFileService.putRequestAndReturnMappedFile(nextFilePath, nextNextFilePath, this.mappedFileSize); } else { try { mappedFile = new MappedFile(nextFilePath, this.mappedFileSize); } catch (IOException e) { log.error("create mapped file exception", e); } } if (mappedFile != null) { this.readWriteLock.writeLock().lock(); if (this.mappedFiles.isEmpty()) { mappedFile.setFirstCreateInQueue(true); } this.mappedFiles.add(mappedFile); this.readWriteLock.writeLock().unlock(); } return mappedFile; } return mappedFileLast; } /** * 获取队列的最小Offset,如果队列为空,则返回-1 */ public long getMinOffset() { try { this.readWriteLock.readLock().lock(); if (!this.mappedFiles.isEmpty()) { return this.mappedFiles.get(0).getFileFromOffset(); } } catch (Exception e) { log.error("getMinOffset has exception.", e); } finally { this.readWriteLock.readLock().unlock(); } return -1; } public long getMaxOffset() { try { this.readWriteLock.readLock().lock(); if (!this.mappedFiles.isEmpty()) { int lastIndex = this.mappedFiles.size() - 1; MappedFile mappedFile = this.mappedFiles.get(lastIndex); return mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); } } catch (Exception e) { log.error("getMinOffset has exception.", e); } finally { this.readWriteLock.readLock().unlock(); } return 0; } /** * 恢复时调用 */ public void deleteLastMappedFile() { if (!this.mappedFiles.isEmpty()) { int lastIndex = this.mappedFiles.size() - 1; MappedFile mappedFile = this.mappedFiles.get(lastIndex); mappedFile.destroy(1000); this.mappedFiles.remove(mappedFile); log.info("on recover, destroy a logic mapped file " + mappedFile.getFileName()); } } /** * 根据文件过期时间来删除物理队列文件 */ public int deleteExpiredFileByTime(// final long expiredTime, // final int deleteFilesInterval, // final long intervalForcibly,// final boolean cleanImmediately// ) { Object[] mfs = this.copyMappedFiles(0); if (null == mfs) return 0; // 最后一个文件处于写状态,不能删除 int mfsLength = mfs.length - 1; int deleteCount = 0; List<MappedFile> files = new ArrayList<MappedFile>(); for (int i = 0; i < mfsLength; i++) { MappedFile mappedFile = (MappedFile) mfs[i]; long liveMaxTimestamp = mappedFile.getLastModifiedTimestamp() + expiredTime; if (System.currentTimeMillis() >= liveMaxTimestamp// || cleanImmediately) { if (mappedFile.destroy(intervalForcibly)) { files.add(mappedFile); deleteCount++; if (files.size() >= DeleteFilesBatchMax) { break; } if (deleteFilesInterval > 0 && (i + 1) < mfsLength) { try { Thread.sleep(deleteFilesInterval); } catch (InterruptedException e) { } } } else { break; } } } deleteExpiredFile(files); return deleteCount; } /** * 根据物理队列最小offset来删除commit log队列文件. * @param offset physical offset * @return 删除的文件个数 */ public int deleteExpiredFilesByPhysicalOffset(long offset) { if (offset < mappedFileSize) { return 0; } // copy with read lock. Object[] mfs = copyMappedFiles(0); List<MappedFile> files = new ArrayList<>(); int deleteCount = 0; if (null != mfs) { int len = mfs.length - 1; for (int i = 0; i < len; i++) { MappedFile mappedFile = (MappedFile) mfs[i]; if (mappedFile.getFileFromOffset() + mappedFileSize < offset) { if (mappedFile.destroy(60 * 1000)) { // Destroy files files.add(mappedFile); deleteCount++; } } else { break; } } } // remove with write lock. deleteExpiredFile(files); return deleteCount; } /** * 根据物理队列最小Offset来删除逻辑队列 * * @param offset 物理队列最小offset */ public int deleteExpiredFileByOffset(long offset, int unitSize) { Object[] mfs = this.copyMappedFiles(0); List<MappedFile> files = new ArrayList<MappedFile>(); int deleteCount = 0; if (null != mfs) { // 最后一个文件处于写状态,不能删除 int mfsLength = mfs.length - 1; // 这里遍历范围 0 ... last - 1 for (int i = 0; i < mfsLength; i++) { boolean destroy = true; MappedFile mappedFile = (MappedFile) mfs[i]; SelectMappedBufferResult result = mappedFile.selectMappedBuffer(this.mappedFileSize - unitSize); if (result != null) { long maxOffsetInLogicQueue = result.getByteBuffer().getLong(); result.release(); // 当前文件是否可以删除 destroy = (maxOffsetInLogicQueue < offset); if (destroy) { log.info("physic min offset " + offset + ", logics in current mapped file max offset " + maxOffsetInLogicQueue + ", delete it"); } } else { log.warn("this being not executed forever."); if (mappedFile.isCleanupOver()) { // Process dangling file. File file = new File(mappedFile.getFileName()); if (file.exists()) { boolean success = file.delete(); if (!success) { log.error("Unable to delete dangling file: {}", mappedFile.getFileName()); } } } else { break; } } if (destroy && mappedFile.destroy(1000 * 60)) { files.add(mappedFile); deleteCount++; } else { break; } } } deleteExpiredFile(files); return deleteCount; } /** * 返回值表示是否全部刷盘完成 * * @return */ public boolean commit(final int flushLeastPages) { boolean result = true; MappedFile mappedFile = this.findMappedFileByOffset(this.committedWhere, true); if (mappedFile != null) { long tmpTimeStamp = mappedFile.getStoreTimestamp(); int offset = mappedFile.commit(flushLeastPages); long where = mappedFile.getFileFromOffset() + offset; result = (where == this.committedWhere); this.committedWhere = where; if (0 == flushLeastPages) { this.storeTimestamp = tmpTimeStamp; } } return result; } public MappedFile findMappedFileByOffset(final long offset, final boolean returnFirstOnNotFound) { try { this.readWriteLock.readLock().lock(); MappedFile mappedFile = this.getFirstMappedFile(); if (mappedFile != null) { int index = (int) ((offset / this.mappedFileSize) - (mappedFile.getFileFromOffset() / this.mappedFileSize)); if (!returnFirstOnNotFound && (index < 0 || index >= this.mappedFiles.size())) { logError.warn("findMappedFileByOffset offset not matched, request Offset: {}, index: {}, " + "mappedFileSize: {}, mappedFiles count: {}, StackTrace: {}",// offset,// index,// this.mappedFileSize,// this.mappedFiles.size(),// UtilAll.currentStackTrace()); } try { return this.mappedFiles.get(index); } catch (Exception e) { if (returnFirstOnNotFound) { return mappedFile; } } } } catch (Exception e) { log.error("findMappedFileByOffset Exception", e); } finally { this.readWriteLock.readLock().unlock(); } return null; } private MappedFile getFirstMappedFile() { if (this.mappedFiles.isEmpty()) { return null; } return this.mappedFiles.get(0); } public MappedFile getLastMappedFile2() { if (this.mappedFiles.isEmpty()) { return null; } return this.mappedFiles.get(this.mappedFiles.size() - 1); } public MappedFile findMappedFileByOffset(final long offset) { return findMappedFileByOffset(offset, false); } public long getMappedMemorySize() { long size = 0; Object[] mfs = this.copyMappedFiles(0); if (mfs != null) { for (Object mf : mfs) { if (((ReferenceResource) mf).isAvailable()) { size += this.mappedFileSize; } } } return size; } public boolean retryDeleteFirstFile(final long intervalForcibly) { MappedFile mappedFile = this.getFirstMappedFileOnLock(); if (mappedFile != null) { if (!mappedFile.isAvailable()) { log.warn("the mapped file was destroyed once, but still alive, " + mappedFile.getFileName()); boolean result = mappedFile.destroy(intervalForcibly); if (result) { log.warn("the mapped file re-delete OK, " + mappedFile.getFileName()); List<MappedFile> tempMappedFiles = new ArrayList<MappedFile>(); tempMappedFiles.add(mappedFile); this.deleteExpiredFile(tempMappedFiles); } else { log.warn("the mapped file re-delete Failed, " + mappedFile.getFileName()); } return result; } } return false; } public MappedFile getFirstMappedFileOnLock() { try { this.readWriteLock.readLock().lock(); return this.getFirstMappedFile(); } finally { this.readWriteLock.readLock().unlock(); } } /** * 关闭队列,队列数据还在,但是不能访问 */ public void shutdown(final long intervalForcibly) { this.readWriteLock.readLock().lock(); for (MappedFile mf : this.mappedFiles) { mf.shutdown(intervalForcibly); } this.readWriteLock.readLock().unlock(); } /** * 销毁队列,队列数据被删除,此函数有可能不成功 */ public void destroy() { this.readWriteLock.writeLock().lock(); for (MappedFile mf : this.mappedFiles) { mf.destroy(1000 * 3); } this.mappedFiles.clear(); this.committedWhere = 0; // delete parent directory File file = new File(storePath); if (file.isDirectory()) { file.delete(); } this.readWriteLock.writeLock().unlock(); } public long getCommittedWhere() { return committedWhere; } public void setCommittedWhere(long committedWhere) { this.committedWhere = committedWhere; } public long getStoreTimestamp() { return storeTimestamp; } public List<MappedFile> getMappedFiles() { return mappedFiles; } public int getMappedFileSize() { return mappedFileSize; } public void setStorePath(String storePath) { this.storePath = storePath; } }
BugFix: fix file comparing by commit log offset.
rocketmq-store/src/main/java/com/alibaba/rocketmq/store/MappedFileQueue.java
BugFix: fix file comparing by commit log offset.
<ide><path>ocketmq-store/src/main/java/com/alibaba/rocketmq/store/MappedFileQueue.java <ide> import java.io.File; <ide> import java.io.FilenameFilter; <ide> import java.io.IOException; <del>import java.util.ArrayList; <del>import java.util.Arrays; <del>import java.util.Collections; <del>import java.util.List; <add>import java.util.*; <ide> import java.util.concurrent.locks.ReadWriteLock; <ide> import java.util.concurrent.locks.ReentrantReadWriteLock; <ide> import java.util.regex.Matcher; <ide> <ide> if (!files.isEmpty()) { <ide> // ascending order <del> Collections.sort(files); <add> Collections.sort(files, new Comparator<File>() { <add> @Override <add> public int compare(File lhs, File rhs) { <add> return lhs.getName().compareTo(rhs.getName()); <add> } <add> }); <add> <ide> for (File file : files) { <ide> // 校验文件大小是否匹配 <ide> if (file.length() != this.mappedFileSize) {
Java
mit
f771b3352f3e370cc6f724fa2df59bac16bdd99a
0
joansmith/cucumber-jvm,joansmith/cucumber-jvm,sventorben/cucumber-jvm,Draeval/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,sghill/cucumber-jvm,cucumber/cucumber-jvm,danielwegener/cucumber-jvm,sventorben/cucumber-jvm,NickCharsley/cucumber-jvm,joansmith/cucumber-jvm,NickCharsley/cucumber-jvm,hcawebdevelopment/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,ppotanin/cucumber-jvm,DPUkyle/cucumber-jvm,goushijie/cucumber-jvm,hcawebdevelopment/cucumber-jvm,DPUkyle/cucumber-jvm,Draeval/cucumber-jvm,sghill/cucumber-jvm,VivaceVivo/cucumber-mod-DI,andyb-ge/cucumber-jvm,ppotanin/cucumber-jvm,danielwegener/cucumber-jvm,danielwegener/cucumber-jvm,chrishowejones/cucumber-jvm,sghill/cucumber-jvm,Draeval/cucumber-jvm,Draeval/cucumber-jvm,NickCharsley/cucumber-jvm,ushkinaz/cucumber-jvm,joansmith/cucumber-jvm,chiranjith/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,chiranjith/cucumber-jvm,sghill/cucumber-jvm,andyb-ge/cucumber-jvm,Draeval/cucumber-jvm,demos74dx/cucumber-jvm,andyb-ge/cucumber-jvm,chrishowejones/cucumber-jvm,hcawebdevelopment/cucumber-jvm,DPUkyle/cucumber-jvm,dkowis/cucumber-jvm,DPUkyle/cucumber-jvm,chrishowejones/cucumber-jvm,demos74dx/cucumber-jvm,ushkinaz/cucumber-jvm,DPUkyle/cucumber-jvm,flaviuratiu/cucumber-jvm,DPUkyle/cucumber-jvm,dkowis/cucumber-jvm,bartkeizer/cucumber-jvm,cucumber/cucumber-jvm,goushijie/cucumber-jvm,flaviuratiu/cucumber-jvm,demos74dx/cucumber-jvm,paoloambrosio/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,PeterDG/cucumberPro,ppotanin/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,sventorben/cucumber-jvm,goushijie/cucumber-jvm,sghill/cucumber-jvm,joansmith/cucumber-jvm,brasmusson/cucumber-jvm,PeterDG/cucumberPro,paoloambrosio/cucumber-jvm,bartkeizer/cucumber-jvm,PeterDG/cucumberPro,NickCharsley/cucumber-jvm,danielwegener/cucumber-jvm,guardian/cucumber-jvm,HendrikSP/cucumber-jvm,guardian/cucumber-jvm,flaviuratiu/cucumber-jvm,demos74dx/cucumber-jvm,guardian/cucumber-jvm,flaviuratiu/cucumber-jvm,ppotanin/cucumber-jvm,ushkinaz/cucumber-jvm,VivaceVivo/cucumber-mod-DI,chiranjith/cucumber-jvm,guardian/cucumber-jvm,chiranjith/cucumber-jvm,PeterDG/cucumberPro,VivaceVivo/cucumber-mod-DI,hcawebdevelopment/cucumber-jvm,sghill/cucumber-jvm,guardian/cucumber-jvm,dkowis/cucumber-jvm,ushkinaz/cucumber-jvm,ArishArbab/cucumber-jvm,danielwegener/cucumber-jvm,HendrikSP/cucumber-jvm,ushkinaz/cucumber-jvm,chrishowejones/cucumber-jvm,HendrikSP/cucumber-jvm,andyb-ge/cucumber-jvm,HendrikSP/cucumber-jvm,chiranjith/cucumber-jvm,dkowis/cucumber-jvm,Draeval/cucumber-jvm,brasmusson/cucumber-jvm,ArishArbab/cucumber-jvm,hcawebdevelopment/cucumber-jvm,chiranjith/cucumber-jvm,bartkeizer/cucumber-jvm,hcawebdevelopment/cucumber-jvm,joansmith/cucumber-jvm,demos74dx/cucumber-jvm,brasmusson/cucumber-jvm,goushijie/cucumber-jvm,VivaceVivo/cucumber-mod-DI,ushkinaz/cucumber-jvm,paoloambrosio/cucumber-jvm,brasmusson/cucumber-jvm,sventorben/cucumber-jvm,ArishArbab/cucumber-jvm,HendrikSP/cucumber-jvm,chrishowejones/cucumber-jvm,chrishowejones/cucumber-jvm,sventorben/cucumber-jvm,bartkeizer/cucumber-jvm,andyb-ge/cucumber-jvm,goushijie/cucumber-jvm,flaviuratiu/cucumber-jvm,VivaceVivo/cucumber-mod-DI,goushijie/cucumber-jvm,bartkeizer/cucumber-jvm,cucumber/cucumber-jvm,danielwegener/cucumber-jvm,ppotanin/cucumber-jvm,assilzm/cucumber-groovy-seeyon,assilzm/cucumber-groovy-seeyon,ArishArbab/cucumber-jvm,demos74dx/cucumber-jvm,brasmusson/cucumber-jvm,rlagunov-anaplan/cucumber-jvm,dkowis/cucumber-jvm,PeterDG/cucumberPro,flaviuratiu/cucumber-jvm,cucumber/cucumber-jvm,cucumber/cucumber-jvm,dkowis/cucumber-jvm,andyb-ge/cucumber-jvm,ppotanin/cucumber-jvm,sventorben/cucumber-jvm,paoloambrosio/cucumber-jvm,HendrikSP/cucumber-jvm,ArishArbab/cucumber-jvm,ArishArbab/cucumber-jvm,NickCharsley/cucumber-jvm,bartkeizer/cucumber-jvm,NickCharsley/cucumber-jvm,PeterDG/cucumberPro
package cucumber.examples.java.helloworld; import cucumber.api.junit.Cucumber; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @Cucumber.Options(format = {"html:target/cucumber-html-report", "json-pretty:target/cucumber-json-report.json"}) public class RunCukesTest { }
examples/java-helloworld/src/test/java/cucumber/examples/java/helloworld/RunCukesTest.java
package cucumber.examples.java.helloworld; import cucumber.api.junit.Cucumber; import org.junit.runner.RunWith; @RunWith(Cucumber.class) // Run scenarios tagged with @foo OR @bar. Can be overridden with e.g. -Dcucumber.options="--tags @foo" // on the command line. @Cucumber.Options(tags = {"@foo,@bar"}, format = {"html:target/cucumber-html-report", "json-pretty:target/cucumber-json-report.json"}) public class RunCukesTest { }
Don't specify tags in runner
examples/java-helloworld/src/test/java/cucumber/examples/java/helloworld/RunCukesTest.java
Don't specify tags in runner
<ide><path>xamples/java-helloworld/src/test/java/cucumber/examples/java/helloworld/RunCukesTest.java <ide> import org.junit.runner.RunWith; <ide> <ide> @RunWith(Cucumber.class) <del>// Run scenarios tagged with @foo OR @bar. Can be overridden with e.g. -Dcucumber.options="--tags @foo" <del>// on the command line. <del>@Cucumber.Options(tags = {"@foo,@bar"}, format = {"html:target/cucumber-html-report", "json-pretty:target/cucumber-json-report.json"}) <add>@Cucumber.Options(format = {"html:target/cucumber-html-report", "json-pretty:target/cucumber-json-report.json"}) <ide> public class RunCukesTest { <ide> }
Java
lgpl-2.1
0a283f928e329d2578b87b0b874a7c7bdbe56896
0
concord-consortium/datagraph
/* * Copyright (C) 2004 The Concord Consortium, Inc., * 10 Concord Crossing, Concord, MA 01742 * * Web Site: http://www.concord.org * Email: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * END LICENSE */ /* * Last modification information: * $Revision: 1.7 $ * $Date: 2007-08-30 21:16:06 $ * $Author: imoncada $ * * Licence Information * Copyright 2004 The Concord Consortium */ package org.concord.datagraph.state; import org.concord.framework.otrunk.OTObjectInterface; import org.concord.framework.otrunk.OTObjectList; /** * PfDataAxis * Class name and description * * Date created: Nov 18, 2004 * * @author scott<p> * */ public interface OTDataAxis extends OTObjectInterface { public float getMin(); public void setMin(float min); public float getMax(); public void setMax(float max); public void setLabel(String label); public String getLabel(); public void setUnits(String units); public String getUnits(); public void setIntervalWorld(int units); public int getIntervalWorld(); public OTObjectList getGraphables(); }
src/org/concord/datagraph/state/OTDataAxis.java
/* * Copyright (C) 2004 The Concord Consortium, Inc., * 10 Concord Crossing, Concord, MA 01742 * * Web Site: http://www.concord.org * Email: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * END LICENSE */ /* * Last modification information: * $Revision: 1.6 $ * $Date: 2007-03-08 22:10:52 $ * $Author: sfentress $ * * Licence Information * Copyright 2004 The Concord Consortium */ package org.concord.datagraph.state; import org.concord.framework.otrunk.OTObjectInterface; import org.concord.framework.otrunk.OTObjectList; /** * PfDataAxis * Class name and description * * Date created: Nov 18, 2004 * * @author scott<p> * */ public interface OTDataAxis extends OTObjectInterface { public float getMin(); public void setMin(float min); public float getMax(); public void setMax(float max); public void setLabel(String label); public String getLabel(); public void setUnits(String units); public String getUnits(); public OTObjectList getGraphables(); }
Added possibility to specify in the axis a FIXED interval in world coordinates explicitly git-svn-id: a0d2519504059b70a86a1ce51b726c2279190bad@8101 6e01202a-0783-4428-890a-84243c50cc2b
src/org/concord/datagraph/state/OTDataAxis.java
Added possibility to specify in the axis a FIXED interval in world coordinates explicitly
<ide><path>rc/org/concord/datagraph/state/OTDataAxis.java <ide> <ide> /* <ide> * Last modification information: <del> * $Revision: 1.6 $ <del> * $Date: 2007-03-08 22:10:52 $ <del> * $Author: sfentress $ <add> * $Revision: 1.7 $ <add> * $Date: 2007-08-30 21:16:06 $ <add> * $Author: imoncada $ <ide> * <ide> * Licence Information <ide> * Copyright 2004 The Concord Consortium <ide> public void setUnits(String units); <ide> public String getUnits(); <ide> <add> public void setIntervalWorld(int units); <add> public int getIntervalWorld(); <add> <ide> public OTObjectList getGraphables(); <ide> }
Java
mpl-2.0
dfe273ac764459966a13521273d28e0552faffcf
0
MozillaCZ/MozStumbler,crankycoder/MozStumbler,priyankvex/MozStumbler,petercpg/MozStumbler,crankycoder/MozStumbler,dougt/MozStumbler,priyankvex/MozStumbler,garvankeeley/MozStumbler,cascheberg/MozStumbler,garvankeeley/MozStumbler,petercpg/MozStumbler,priyankvex/MozStumbler,garvankeeley/MozStumbler,cascheberg/MozStumbler,MozillaCZ/MozStumbler,MozillaCZ/MozStumbler,cascheberg/MozStumbler,petercpg/MozStumbler,crankycoder/MozStumbler
package org.mozilla.mozstumbler; import android.net.wifi.ScanResult; final class SSIDBlockList { private static final String[] PREFIX_LIST = { // Mobile devices "AndroidAP", "AndroidHotspot", "Android Hotspot", "barnacle", // Android tether app "Galaxy Note", "Galaxy S", "Galaxy Tab", "HTC ", "iPhone", "LG-MS770", "LG-MS870", "LG VS910 4G", "LG Vortex", "MIFI", "MiFi", "myLGNet", "myTouch 4G Hotspot", "NOKIA Lumia", "PhoneAP", "SCH-I", "Sprint MiFi", "Verizon ", "Verizon-", "VirginMobile MiFi", "VodafoneMobileWiFi-", "FirefoxHotspot", "Mobile Hotspot", // BlackBerry OS 10 // Transportation Wi-Fi "ac_transit_wifi_bus", "AmtrakConnect", "Amtrak_", "amtrak_", "arriva", //Arriva Nederland on-train Wifi (Netherlands) "CapitalBus", // Capital Bus on-bus WiFi (Taiwan) "CDWiFi", // Ceske drahy (Czech railways): http://www.cd.cz/cd-online/-15765/ "csadplzen_bus", // CSAD Plzen bus hotspots: http://www.csadplzen.cz/?ob=aktuality#wifi7 "GBUS", "GBusWifi", "gogoinflight", // Gogo in-flight WiFi "Hot-Spot-KS", // Koleje Slaskie transportation services (Poland) "wifi_rail", // BART "egged.co.il", // Egged transportation services (Israel) "gb-tours.com", // GB Tours transportation services (Israel) "ISRAEL-RAILWAYS", "MAVSTART-WiFi", // Hungarian State Railways onboard hotspot on InterCity trains (Hungary) "Omni-WiFi", // Omnibus transportation services (Israel) "QbuzzWIFI", //Qbuzz on-bus WiFi (Netherlands) "SF Shuttle Wireless", "ShuttleWiFi", "Southwest WiFi", // Southwest Airlines in-flight WiFi "SST-PR-1", // Sears Home Service van hotspot?! "Telekom_ICE", // Deutsche Bahn on-train WiFi "TPE-Free Bus", // Taipei City on-bus WiFi (Taiwan) "THSR-VeeTIME", // Taiwan High Speed Rail on-train WiFi "tmobile", //Nederlandse Spoorwegen on-train WiFi by T-Mobile (Netherlands) "VR-junaverkko", // VR on-train WiFi (Finland) }; private static final String[] SUFFIX_LIST = { // Mobile devices "iPhone", "iphone", "MIFI", "MIFI", "MiFi", "Mifi", "mifi", "mi-fi", "MyWi", "Phone", "Portable Hotspot", "Tether", "tether", // Google's SSID opt-out "_nomap", }; private SSIDBlockList() { } static boolean contains(ScanResult scanResult) { String SSID = scanResult.SSID; if (SSID == null) { return true; // no SSID? } for (String prefix : PREFIX_LIST) { if (SSID.startsWith(prefix)) { return true; // blocked! } } for (String suffix : SUFFIX_LIST) { if (SSID.endsWith(suffix)) { return true; // blocked! } } return false; // OK } }
src/org/mozilla/mozstumbler/SSIDBlockList.java
package org.mozilla.mozstumbler; import android.net.wifi.ScanResult; final class SSIDBlockList { private static final String[] PREFIX_LIST = { // Mobile devices "AndroidAP", "AndroidHotspot", "Android Hotspot", "barnacle", // Android tether app "Galaxy Note", "Galaxy S", "Galaxy Tab", "HTC ", "iPhone", "LG-MS770", "LG-MS870", "LG VS910 4G", "LG Vortex", "MIFI", "MiFi", "myLGNet", "myTouch 4G Hotspot", "NOKIA Lumia", "PhoneAP", "SCH-I", "Sprint MiFi", "Verizon ", "Verizon-", "VirginMobile MiFi", "VodafoneMobileWiFi-", "FirefoxHotspot", "Mobile Hotspot", // BlackBerry OS 10 // Transportation Wi-Fi "ac_transit_wifi_bus", "AmtrakConnect", "Amtrak_", "amtrak_", "arriva", //Arriva Nederland on-train Wifi (Netherlands) "CapitalBus", // Capital Bus on-bus WiFi (Taiwan) "CDWiFi", // Ceske drahy (Czech railways): http://www.cd.cz/cd-online/-15765/ "csadplzen_bus", // CSAD Plzen bus hotspots: http://www.csadplzen.cz/?ob=aktuality#wifi7 "GBUS", "GBusWifi", "gogoinflight", // Gogo in-flight WiFi "Hot-Spot-KS", // Koleje Slaskie transportation services (Poland) "wifi_rail", // BART "egged.co.il", // Egged transportation services (Israel) "gb-tours.com", // GB Tours transportation services (Israel) "ISRAEL-RAILWAYS", "Omni-WiFi", // Omnibus transportation services (Israel) "QbuzzWIFI", //Qbuzz on-bus WiFi (Netherlands) "SF Shuttle Wireless", "ShuttleWiFi", "Southwest WiFi", // Southwest Airlines in-flight WiFi "SST-PR-1", // Sears Home Service van hotspot?! "Telekom_ICE", // Deutsche Bahn on-train WiFi "TPE-Free Bus", // Taipei City on-bus WiFi (Taiwan) "THSR-VeeTIME", // Taiwan High Speed Rail on-train WiFi "tmobile", //Nederlandse Spoorwegen on-train WiFi by T-Mobile (Netherlands) "VR-junaverkko", // VR on-train WiFi (Finland) }; private static final String[] SUFFIX_LIST = { // Mobile devices "iPhone", "iphone", "MIFI", "MIFI", "MiFi", "Mifi", "mifi", "mi-fi", "MyWi", "Phone", "Portable Hotspot", "Tether", "tether", // Google's SSID opt-out "_nomap", }; private SSIDBlockList() { } static boolean contains(ScanResult scanResult) { String SSID = scanResult.SSID; if (SSID == null) { return true; // no SSID? } for (String prefix : PREFIX_LIST) { if (SSID.startsWith(prefix)) { return true; // blocked! } } for (String suffix : SUFFIX_LIST) { if (SSID.endsWith(suffix)) { return true; // blocked! } } return false; // OK } }
Add MÁV (Hungarian State Railways) InterCity train hot-spots to blocklist
src/org/mozilla/mozstumbler/SSIDBlockList.java
Add MÁV (Hungarian State Railways) InterCity train hot-spots to blocklist
<ide><path>rc/org/mozilla/mozstumbler/SSIDBlockList.java <ide> "egged.co.il", // Egged transportation services (Israel) <ide> "gb-tours.com", // GB Tours transportation services (Israel) <ide> "ISRAEL-RAILWAYS", <add> "MAVSTART-WiFi", // Hungarian State Railways onboard hotspot on InterCity trains (Hungary) <ide> "Omni-WiFi", // Omnibus transportation services (Israel) <ide> "QbuzzWIFI", //Qbuzz on-bus WiFi (Netherlands) <ide> "SF Shuttle Wireless",
Java
apache-2.0
a28c3cd952ecad18cc871eed166fd76df4a690f6
0
EvilMcJerkface/atlasdb,palantir/atlasdb,palantir/atlasdb,EvilMcJerkface/atlasdb,palantir/atlasdb,EvilMcJerkface/atlasdb
atlasdb-dbkvs/src/main/java/com/palantir/atlasdb/keyvalue/dbkvs/TableNameMapper.java
/** * Copyright 2016 Palantir Technologies * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.keyvalue.dbkvs; import com.palantir.atlasdb.keyvalue.api.TableReference; /** * This is the mapper to shorten table names. The mapping should keep table names already meeting * length limits unchanged. */ public interface TableNameMapper { String getShortPrefixedTableName(String tablePrefix, TableReference tableRef); }
remove unused TableMapper interface
atlasdb-dbkvs/src/main/java/com/palantir/atlasdb/keyvalue/dbkvs/TableNameMapper.java
remove unused TableMapper interface
<ide><path>tlasdb-dbkvs/src/main/java/com/palantir/atlasdb/keyvalue/dbkvs/TableNameMapper.java <del>/** <del> * Copyright 2016 Palantir Technologies <del> * <del> * Licensed under the BSD-3 License (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://opensource.org/licenses/BSD-3-Clause <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package com.palantir.atlasdb.keyvalue.dbkvs; <del> <del>import com.palantir.atlasdb.keyvalue.api.TableReference; <del> <del>/** <del> * This is the mapper to shorten table names. The mapping should keep table names already meeting <del> * length limits unchanged. <del> */ <del>public interface TableNameMapper { <del> String getShortPrefixedTableName(String tablePrefix, TableReference tableRef); <del>}