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
JavaScript
bsd-3-clause
4cc5257bca46def222020968ef12f7b73c3f14b3
0
SalesforceFoundation/HEDAP,SalesforceFoundation/HEDAP,SalesforceFoundation/HEDAP
import { LightningElement, api, track } from "lwc"; import stgHealthCheckLoadingIndicator from "@salesforce/label/c.stgHealthCheckLoadingIndicator"; //Account Model Settings Labels import stgAccountModelSettingsTitle from "@salesforce/label/c.stgAccountModelSettingsTitle"; import stgAccModelTitle from "@salesforce/label/c.stgAccModelTitle"; import stgAdminAccountRecordType from "@salesforce/label/c.stgAdminAccountRecordType"; import stgAccountRecordTypeSupportsHHAddress from "@salesforce/label/c.stgAccountRecordTypeSupportsHHAddress"; import stgAccoutTypesWithoutContactsDelete from "@salesforce/label/c.stgAccoutTypesWithoutContactsDelete"; import stgLeadConversionAccountNaming from "@salesforce/label/c.stgLeadConversionAccountNaming"; //Contact Information Settings Labels import stgContactInformationSettingsTitle from "@salesforce/label/c.stgContactInformationSettingsTitle"; import stgDefaultContactLanguageFluency from "@salesforce/label/c.stgDefaultContactLanguageFluency"; import stgDisablePreferredEmailEnforcement from "@salesforce/label/c.stgDisablePreferredEmailEnforcement"; import stgEnablePreferredPhoneSync from "@salesforce/label/c.stgEnablePreferredPhoneSync"; import stgPreferredPhoneDefault from "@salesforce/label/c.stgPreferredPhoneDefault"; //Address Settings Labels import stgAccountTypesMultiAddressesEnabled from "@salesforce/label/c.stgAccountTypesMultiAddressesEnabled"; import stgAddressSettingsTitle from "@salesforce/label/c.stgAddressSettingsTitle"; import stgContactMultiAddressesEnabled from "@salesforce/label/c.stgContactMultiAddressesEnabled"; import stgSimpleAddressChangeUpdate from "@salesforce/label/c.stgSimpleAddressChangeUpdate"; //Affiliation Settings Labels import stgTabAfflMappings from "@salesforce/label/c.stgTabAfflMappings"; import stgAffiliationsSettingsNav from "@salesforce/label/c.stgAffiliationsSettingsNav"; import afflTypeEnforced from "@salesforce/label/c.afflTypeEnforced"; //Course Enrollment Labels import stgCoursesAndEnrollmentsNav from "@salesforce/label/c.stgCoursesAndEnrollmentsNav"; import stgProgramsSettingsNav from "@salesforce/label/c.stgProgramsSettingsNav"; //System Settings Labels import stgSystemSettingsNav from "@salesforce/label/c.stgSystemSettingsNav"; //System Tools SettingsLabels import stgSystemSettingsTitle from "@salesforce/label/c.stgSystemSettingsTitle"; //Error Settings Labels import stgErrorSettingsNav from "@salesforce/label/c.stgErrorSettingsNav"; import stgStoreErrorsTitle from "@salesforce/label/c.stgStoreErrorsTitle"; import stgEnableDebugTitle from "@salesforce/label/c.stgEnableDebugTitle"; import stgDisableErrorHandlingTitle from "@salesforce/label/c.stgDisableErrorHandlingTitle"; export default class EdaSettingsNavigation extends LightningElement { labelReference = { peopleAndGroups: "People and Groups", setupHome: "Setup Home", spinnerLoadingAltText: stgHealthCheckLoadingIndicator, systemSettings: stgSystemSettingsNav, accountModel: { accountAutoDeletionModel: stgAccoutTypesWithoutContactsDelete, accountModelSettings: stgAccountModelSettingsTitle, adminAccountModel: stgAdminAccountRecordType, defaultAccountModel: stgAccModelTitle, hhAccountModel: stgAccountRecordTypeSupportsHHAddress, adminAccountNaming: "Administrative Account Name Format", hhAccountNaming: "Household Account Name Format", autoHHAccountNaming: "Automatically Rename Household Accounts", leadConversionAutoAccountNaming: stgLeadConversionAccountNaming, }, addressSettings: { addressAccountRecordTypes: stgAccountTypesMultiAddressesEnabled, addressSettings: stgAddressSettingsTitle, contactMultipleAddresses: stgContactMultiAddressesEnabled, simpleAddressChangeIsUpdate: stgSimpleAddressChangeUpdate, }, affiliationSettings: { affiliationMappings: stgTabAfflMappings, affiliationSettings: stgAffiliationsSettingsNav, enforceRecordTypeValidation: afflTypeEnforced, }, contactInformation: { contactInformation: stgContactInformationSettingsTitle, defaultContactLanguageFluency: stgDefaultContactLanguageFluency, defaultPreferredPhone: stgPreferredPhoneDefault, enhancedPhoneFunctionality: stgEnablePreferredPhoneSync, requirePreferredEmail: stgDisablePreferredEmailEnforcement, }, coursesAndEnrollmentsSettings: { coursesAndEnrollmentsSettings: stgCoursesAndEnrollmentsNav, }, errorSettings: { enableDebug: stgEnableDebugTitle, enableErrorHandling: stgDisableErrorHandlingTitle, errorSettings: stgErrorSettingsNav, sendErrorNotifications: "Send Error Notifications", storeErrors: stgStoreErrorsTitle, }, programSettings: { programSettings: stgProgramsSettingsNav, programAutoEnrollmentMappings: stgAutoEnrollmentMappingsNav, programEnrollmentDeletions: "Program Enrollment Deletions", }, relationshipSettings: { preventAutoCreatedDuplicateRelationships: "Prevent Auto-Created Duplicate Relations", reciprocalMethod: "Reciprocal Method", reciprocalRelationshipMappings: "Reciprocal Relationship mappings", relationshipAutocreateCampaignMappings: "Autocreate Campaign Mappings", relationshipAutocreateContactMappings: "Autocreate Contact Mappings", relationshipSettings: "Relationships", }, systemTools: { courseConnectionBackfill: "Course Connection Backfill", courseDescriptionMigration: "Course Description Migration", ethnicityAndRaceBackfill: "Ethnicity and Race Backfill", preferredEmailCleanup: "Preferred Email and Phone Cleanup", systemTools: stgSystemSettingsTitle, refreshAdministrativeAccountNames: "Refresh Administrative Account Names", refreshHouseholdAccountNames: "Refresh Household Account Names", }, }; @api activePage; @track viewModel = { navigationSections: [ { label: this.labelReference.setupHome, page: "setupHome", id: "setupHome", }, { label: this.labelReference.peopleAndGroups, id: "peopleAndGroups", navigationSubSections: [ { label: this.labelReference.accountModel.accountModelSettings, page: "accountModelSettings", id: "accountModelSettings", menuItems: [ { label: this.labelReference.accountModel.defaultAccountModel, id: "defaultAccountModel" }, { label: this.labelReference.accountModel.adminAccountModel, id: "adminAccountModel", }, { label: this.labelReference.accountModel.hhAccountModel, id: "hhAccountModel" }, { label: this.labelReference.accountModel.accountAutoDeletionModel, id: "accountAutoDeletionModel", }, { label: this.labelReference.accountModel.adminAccountNaming, id: "adminAccountNaming" }, { label: this.labelReference.accountModel.hhAccountNaming, id: "hhAccountNaming" }, { label: this.labelReference.accountModel.autoHHAccountNaming, id: "autoHHAccountNaming" }, { label: this.labelReference.accountModel.leadConversionAutoAccountNaming, id: "leadConversionAutoAccountNaming", }, ], isActive: true, }, { label: this.labelReference.contactInformation.contactInformation, page: "contactInformationSettings", id: "contactInformation", menuItems: [ { label: this.labelReference.contactInformation.defaultContactLanguageFluency, id: "defaultContactLanguageFluency", }, { label: this.labelReference.contactInformation.requirePreferredEmail, id: "requirePreferredEmail", }, { label: this.labelReference.contactInformation.enhancedPhoneFunctionality, id: "enhancedPhoneFunctionality", }, { label: this.labelReference.contactInformation.defaultPreferredPhone, id: "defaultPreferredPhone", }, ], }, { label: this.labelReference.addressSettings.addressSettings, page: "addressSettings", id: "addresses", menuItems: [ { label: this.labelReference.addressSettings.contactMultipleAddresses, id: "contactMultipleAddresses", }, { label: this.labelReference.addressSettings.simpleAddressChangeIsUpdate, id: "addressAccountRecordTypes", }, { label: this.labelReference.addressSettings.addressAccountRecordTypes, id: "simpleAddressChangeIsUpdate", }, ], }, ], }, { label: this.labelReference.affiliationSettings.affiliationSettings, page: "affiliationSettings", id: "affiliations", menuItems: [ { label: this.labelReference.affiliationSettings.enforceRecordTypeValidation, id: "enforceRecordTypeValidation", }, { label: this.labelReference.affiliationSettings.affiliationMappings, id: "affiliationMappings", }, ], }, { label: this.labelReference.relationshipSettings.relationshipSettings, page: "relationshipSettings", id: "relationshipSettings", menuItems: [ { label: this.labelReference.relationshipSettings.reciprocalMethod, id: "reciprocalMethod", }, { label: this.labelReference.relationshipSettings.preventAutoCreatedDuplicateRelationships, id: "preventAutoCreatedDuplicateRelationships", }, { label: this.labelReference.relationshipSettings.preventAutoCreatedDuplicateRelationships, id: "preventAutoCreatedDuplicateRelationships", }, { label: this.labelReference.relationshipSettings.reciprocalRelationshipMappings, id: "reciprocalRelationshipMappings", }, { label: this.labelReference.relationshipSettings.relationshipAutocreateCampaignMappings, id: "relationshipAutocreateCampaignMappings", }, { label: this.labelReference.relationshipSettings.relationshipAutocreateContactMappings, id: "relationshipAutocreateContactMappings", }, ], }, { label: this.labelReference.coursesAndEnrollmentsSettings.coursesAndEnrollmentsSettings, id: "coursesAndEnrollments", navigationSubSections: [ { label: this.labelReference.programSettings.programSettings, page: "programSettings", id: "programSettings", menuItems: [ { label: this.labelReference.programSettings.programAutoEnrollmentMappings, id: "programAutoEnrollmentMappings", }, { label: this.labelReference.programSettings.programEnrollmentDeletions, id: "programEnrollmentDeletions", }, ], }, ], }, { label: this.labelReference.systemSettings, id: "systemSettings", navigationSubSections: [ { label: this.labelReference.errorSettings.errorSettings, page: "errorSettings", id: "errorSettings", menuItems: [ { label: this.labelReference.errorSettings.storeErrors, id: "storeErrors" }, { label: this.labelReference.errorSettings.sendErrorNotifications, id: "sendErrorNotifications", }, { label: this.labelReference.errorSettings.enableErrorHandling, id: "enableErrorHandling", }, { label: this.labelReference.errorSettings.enableDebug, id: "enableDebug" }, ], }, { label: this.labelReference.systemTools.systemTools, page: "systemTools", id: "systemTools", menuItems: [ { label: this.labelReference.systemTools.refreshAdministrativeAccountNames, id: "refreshAdministrativeAccountNames", }, { label: this.labelReference.systemTools.refreshHouseholdAccountNames, id: "refreshHouseholdAccountNames", }, { label: this.labelReference.systemTools.preferredEmailCleanup, id: "preferredEmailCleanup", }, { label: this.labelReference.systemTools.ethnicityAndRaceBackfill, id: "ethnicityAndRaceBackfill", }, { label: this.labelReference.systemTools.courseConnectionBackfill, id: "courseConnectionBackfill", }, { label: this.labelReference.systemTools.courseDescriptionMigration, id: "courseDescriptionMigration", }, ], }, ], }, ], }; }
force-app/main/default/lwc/edaSettingsNavigation/edaSettingsNavigation.js
import { LightningElement, api, track } from "lwc"; import stgHealthCheckLoadingIndicator from "@salesforce/label/c.stgHealthCheckLoadingIndicator"; //Account Model Settings Labels import stgAccountModelSettingsTitle from "@salesforce/label/c.stgAccountModelSettingsTitle"; import stgAccModelTitle from "@salesforce/label/c.stgAccModelTitle"; import stgAdminAccountRecordType from "@salesforce/label/c.stgAdminAccountRecordType"; import stgAccountRecordTypeSupportsHHAddress from "@salesforce/label/c.stgAccountRecordTypeSupportsHHAddress"; import stgAccoutTypesWithoutContactsDelete from "@salesforce/label/c.stgAccoutTypesWithoutContactsDelete"; import stgLeadConversionAccountNaming from "@salesforce/label/c.stgLeadConversionAccountNaming"; //Contact Information Settings Labels import stgContactInformationSettingsTitle from "@salesforce/label/c.stgContactInformationSettingsTitle"; import stgDefaultContactLanguageFluency from "@salesforce/label/c.stgDefaultContactLanguageFluency"; import stgDisablePreferredEmailEnforcement from "@salesforce/label/c.stgDisablePreferredEmailEnforcement"; import stgEnablePreferredPhoneSync from "@salesforce/label/c.stgEnablePreferredPhoneSync"; import stgPreferredPhoneDefault from "@salesforce/label/c.stgPreferredPhoneDefault"; //Address Settings Labels import stgAccountTypesMultiAddressesEnabled from "@salesforce/label/c.stgAccountTypesMultiAddressesEnabled"; import stgAddressSettingsTitle from "@salesforce/label/c.stgAddressSettingsTitle"; import stgContactMultiAddressesEnabled from "@salesforce/label/c.stgContactMultiAddressesEnabled"; import stgSimpleAddressChangeUpdate from "@salesforce/label/c.stgSimpleAddressChangeUpdate"; //Affiliation Settings Labels import stgTabAfflMappings from "@salesforce/label/c.stgTabAfflMappings"; import stgAffiliationsSettingsNav from "@salesforce/label/c.stgAffiliationsSettingsNav"; import afflTypeEnforced from "@salesforce/label/c.afflTypeEnforced"; //Course Enrollment Labels import stgCoursesAndEnrollmentsNav from "@salesforce/label/c.stgCoursesAndEnrollmentsNav"; import stgProgramsSettingsNav from "@salesforce/label/c.stgProgramsSettingsNav"; //System Settings Labels import stgSystemSettingsNav from "@salesforce/label/c.stgSystemSettingsNav"; //System Tools SettingsLabels import stgSystemSettingsTitle from "@salesforce/label/c.stgSystemSettingsTitle"; //Error Settings Labels import stgErrorSettingsNav from "@salesforce/label/c.stgErrorSettingsNav"; import stgStoreErrorsTitle from "@salesforce/label/c.stgStoreErrorsTitle"; import stgEnableDebugTitle from "@salesforce/label/c.stgEnableDebugTitle"; import stgDisableErrorHandlingTitle from "@salesforce/label/c.stgDisableErrorHandlingTitle"; export default class EdaSettingsNavigation extends LightningElement { labelReference = { peopleAndGroups: "People and Groups", setupHome: "Setup Home", spinnerLoadingAltText: stgHealthCheckLoadingIndicator, systemSettings: stgSystemSettingsNav, accountModel: { accountAutoDeletionModel: stgAccoutTypesWithoutContactsDelete, accountModelSettings: stgAccountModelSettingsTitle, adminAccountModel: stgAdminAccountRecordType, defaultAccountModel: stgAccModelTitle, hhAccountModel: stgAccountRecordTypeSupportsHHAddress, adminAccountNaming: "Administrative Account Name Format", hhAccountNaming: "Household Account Name Format", autoHHAccountNaming: "Automatically Rename Household Accounts", leadConversionAutoAccountNaming: stgLeadConversionAccountNaming, }, addressSettings: { addressAccountRecordTypes: stgAccountTypesMultiAddressesEnabled, addressSettings: stgAddressSettingsTitle, contactMultipleAddresses: stgContactMultiAddressesEnabled, simpleAddressChangeIsUpdate: stgSimpleAddressChangeUpdate, }, affiliationSettings: { affiliationMappings: stgTabAfflMappings, affiliationSettings: stgAffiliationsSettingsNav, enforceRecordTypeValidation: afflTypeEnforced, }, contactInformation: { contactInformation: stgContactInformationSettingsTitle, defaultContactLanguageFluency: stgDefaultContactLanguageFluency, defaultPreferredPhone: stgPreferredPhoneDefault, enhancedPhoneFunctionality: stgEnablePreferredPhoneSync, requirePreferredEmail: stgDisablePreferredEmailEnforcement, }, coursesAndEnrollmentsSettings: { coursesAndEnrollmentsSettings: stgCoursesAndEnrollmentsNav, }, errorSettings: { enableDebug: stgEnableDebugTitle, enableErrorHandling: stgDisableErrorHandlingTitle, errorSettings: stgErrorSettingsNav, sendErrorNotifications: "Send Error Notifications", storeErrors: stgStoreErrorsTitle, }, programSettings: { programSettings: stgProgramsSettingsNav, programAutoEnrollmentMappings: "Program Auto-Enrollment Mappings", programEnrollmentDeletions: "Program Enrollment Deletions", }, relationshipSettings: { preventAutoCreatedDuplicateRelationships: "Prevent Auto-Created Duplicate Relations", reciprocalMethod: "Reciprocal Method", reciprocalRelationshipMappings: "Reciprocal Relationship mappings", relationshipAutocreateCampaignMappings: "Autocreate Campaign Mappings", relationshipAutocreateContactMappings: "Autocreate Contact Mappings", relationshipSettings: "Relationships", }, systemTools: { courseConnectionBackfill: "Course Connection Backfill", courseDescriptionMigration: "Course Description Migration", ethnicityAndRaceBackfill: "Ethnicity and Race Backfill", preferredEmailCleanup: "Preferred Email and Phone Cleanup", systemTools: stgSystemSettingsTitle, refreshAdministrativeAccountNames: "Refresh Administrative Account Names", refreshHouseholdAccountNames: "Refresh Household Account Names", }, }; @api activePage; @track viewModel = { navigationSections: [ { label: this.labelReference.setupHome, page: "setupHome", id: "setupHome", }, { label: this.labelReference.peopleAndGroups, id: "peopleAndGroups", navigationSubSections: [ { label: this.labelReference.accountModel.accountModelSettings, page: "accountModelSettings", id: "accountModelSettings", menuItems: [ { label: this.labelReference.accountModel.defaultAccountModel, id: "defaultAccountModel" }, { label: this.labelReference.accountModel.adminAccountModel, id: "adminAccountModel", }, { label: this.labelReference.accountModel.hhAccountModel, id: "hhAccountModel" }, { label: this.labelReference.accountModel.accountAutoDeletionModel, id: "accountAutoDeletionModel", }, { label: this.labelReference.accountModel.adminAccountNaming, id: "adminAccountNaming" }, { label: this.labelReference.accountModel.hhAccountNaming, id: "hhAccountNaming" }, { label: this.labelReference.accountModel.autoHHAccountNaming, id: "autoHHAccountNaming" }, { label: this.labelReference.accountModel.leadConversionAutoAccountNaming, id: "leadConversionAutoAccountNaming", }, ], isActive: true, }, { label: this.labelReference.contactInformation.contactInformation, page: "contactInformationSettings", id: "contactInformation", menuItems: [ { label: this.labelReference.contactInformation.defaultContactLanguageFluency, id: "defaultContactLanguageFluency", }, { label: this.labelReference.contactInformation.requirePreferredEmail, id: "requirePreferredEmail", }, { label: this.labelReference.contactInformation.enhancedPhoneFunctionality, id: "enhancedPhoneFunctionality", }, { label: this.labelReference.contactInformation.defaultPreferredPhone, id: "defaultPreferredPhone", }, ], }, { label: this.labelReference.addressSettings.addressSettings, page: "addressSettings", id: "addresses", menuItems: [ { label: this.labelReference.addressSettings.contactMultipleAddresses, id: "contactMultipleAddresses", }, { label: this.labelReference.addressSettings.simpleAddressChangeIsUpdate, id: "addressAccountRecordTypes", }, { label: this.labelReference.addressSettings.addressAccountRecordTypes, id: "simpleAddressChangeIsUpdate", }, ], }, ], }, { label: this.labelReference.affiliationSettings.affiliationSettings, page: "affiliationSettings", id: "affiliations", menuItems: [ { label: this.labelReference.affiliationSettings.enforceRecordTypeValidation, id: "enforceRecordTypeValidation", }, { label: this.labelReference.affiliationSettings.affiliationMappings, id: "affiliationMappings", }, ], }, { label: this.labelReference.relationshipSettings.relationshipSettings, page: "relationshipSettings", id: "relationshipSettings", menuItems: [ { label: this.labelReference.relationshipSettings.reciprocalMethod, id: "reciprocalMethod", }, { label: this.labelReference.relationshipSettings.preventAutoCreatedDuplicateRelationships, id: "preventAutoCreatedDuplicateRelationships", }, { label: this.labelReference.relationshipSettings.preventAutoCreatedDuplicateRelationships, id: "preventAutoCreatedDuplicateRelationships", }, { label: this.labelReference.relationshipSettings.reciprocalRelationshipMappings, id: "reciprocalRelationshipMappings", }, { label: this.labelReference.relationshipSettings.relationshipAutocreateCampaignMappings, id: "relationshipAutocreateCampaignMappings", }, { label: this.labelReference.relationshipSettings.relationshipAutocreateContactMappings, id: "relationshipAutocreateContactMappings", }, ], }, { label: this.labelReference.coursesAndEnrollmentsSettings.coursesAndEnrollmentsSettings, id: "coursesAndEnrollments", navigationSubSections: [ { label: this.labelReference.programSettings.programSettings, page: "programSettings", id: "programSettings", menuItems: [ { label: this.labelReference.programSettings.programAutoEnrollmentMappings, id: "programAutoEnrollmentMappings", }, { label: this.labelReference.programSettings.programEnrollmentDeletions, id: "programEnrollmentDeletions", }, ], }, ], }, { label: this.labelReference.systemSettings, id: "systemSettings", navigationSubSections: [ { label: this.labelReference.errorSettings.errorSettings, page: "errorSettings", id: "errorSettings", menuItems: [ { label: this.labelReference.errorSettings.storeErrors, id: "storeErrors" }, { label: this.labelReference.errorSettings.sendErrorNotifications, id: "sendErrorNotifications", }, { label: this.labelReference.errorSettings.enableErrorHandling, id: "enableErrorHandling", }, { label: this.labelReference.errorSettings.enableDebug, id: "enableDebug" }, ], }, { label: this.labelReference.systemTools.systemTools, page: "systemTools", id: "systemTools", menuItems: [ { label: this.labelReference.systemTools.refreshAdministrativeAccountNames, id: "refreshAdministrativeAccountNames", }, { label: this.labelReference.systemTools.refreshHouseholdAccountNames, id: "refreshHouseholdAccountNames", }, { label: this.labelReference.systemTools.preferredEmailCleanup, id: "preferredEmailCleanup", }, { label: this.labelReference.systemTools.ethnicityAndRaceBackfill, id: "ethnicityAndRaceBackfill", }, { label: this.labelReference.systemTools.courseConnectionBackfill, id: "courseConnectionBackfill", }, { label: this.labelReference.systemTools.courseDescriptionMigration, id: "courseDescriptionMigration", }, ], }, ], }, ], }; }
adding custom label to navigation
force-app/main/default/lwc/edaSettingsNavigation/edaSettingsNavigation.js
adding custom label to navigation
<ide><path>orce-app/main/default/lwc/edaSettingsNavigation/edaSettingsNavigation.js <ide> }, <ide> programSettings: { <ide> programSettings: stgProgramsSettingsNav, <del> programAutoEnrollmentMappings: "Program Auto-Enrollment Mappings", <add> programAutoEnrollmentMappings: stgAutoEnrollmentMappingsNav, <ide> programEnrollmentDeletions: "Program Enrollment Deletions", <ide> }, <ide> relationshipSettings: {
Java
bsd-2-clause
62faf38f87aeeff8a2d5a309175fcdfd13928255
0
Periodicraft-Dev/Periodicraft-Minecraft-Mod
package org.periodicraft.periodicraft; import org.periodicraft.periodicraft.block.PeriodicraftOre; import org.periodicraft.periodicraft.item.PeriodicraftArmor; import org.periodicraft.periodicraft.item.PeriodicraftAxe; import org.periodicraft.periodicraft.item.PeriodicraftEntityBullet; import org.periodicraft.periodicraft.item.PeriodicraftGun; import org.periodicraft.periodicraft.item.PeriodicraftHoe; import org.periodicraft.periodicraft.item.PeriodicraftIngot; import org.periodicraft.periodicraft.item.PeriodicraftItem; import org.periodicraft.periodicraft.item.PeriodicraftPickaxe; import org.periodicraft.periodicraft.item.PeriodicraftSpade; import org.periodicraft.periodicraft.item.PeriodicraftSword; import org.periodicraft.periodicraft.world.PeriodicraftGenerator; import scala.tools.nsc.doc.model.Public; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.item.ItemArmor.ArmorMaterial; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.EnumHelper; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; @Mod(modid = Periodicraft.MODID, name = Periodicraft.NAME, version = Periodicraft.VERSION) public class Periodicraft { public static final String MODID = "org.periodicraft.periodicraft"; public static final String VERSION = "0.0.1"; public static final String NAME = "Periodicraft"; public static CreativeTabs tabBlocks = new CreativeTabs("PeriodicraftBlocks") { @Override public Item getTabIconItem() { return Item.getItemFromBlock(Periodicraft.BlockCopperOre); } }; public static CreativeTabs tabWeapons = new CreativeTabs("PeriodicraftWeapons") { @Override public Item getTabIconItem() { return Periodicraft.ItemCopperSword; } }; public static CreativeTabs tabTools = new CreativeTabs("PeriodicraftTools") { @Override public Item getTabIconItem() { return Periodicraft.ItemCopperPickaxe; } }; public static CreativeTabs tabMaterials = new CreativeTabs("PeriodicraftMaterials") { @Override public Item getTabIconItem() { return Periodicraft.ItemCopperIngot; } }; public static CreativeTabs tabArmor = new CreativeTabs("PeriodicraftArmor") { @Override public Item getTabIconItem() { return Periodicraft.ItemCopperHelmet; } }; // World Gen public static PeriodicraftGenerator Generator; //========================================================================================================================================= //COPPER public static Block BlockCopperOre; public static ToolMaterial ToolMaterialCopper; public static Item ItemCopperIngot; public static Item ItemCopperPickaxe; public static Item ItemCopperSword; public static Item ItemCopperSpade; public static Item ItemCopperAxe; public static Item ItemCopperHoe; public static ArmorMaterial ArmorMaterialCopper; public static Item ItemCopperHelmet; public static Item ItemCopperChestplate; public static Item ItemCopperLeggings; public static Item ItemCopperBoots; //BONE public static ToolMaterial ToolMaterialBone; public static Item ItemBoneSword; public static Item ItemBoneAxe; //Blazing BONE public static ToolMaterial ToolMaterialBlazingBone; public static Item ItemBlazingBoneShard; public static Item ItemBlazingBoneSword; //BLAZING public static ToolMaterial ToolMaterialBlazing; public static ArmorMaterial ArmorMaterialBlazing; public static Item ItemBlazingIngot; public static Block BlockBlazingOre; public static Item ItemBlazingHelmet; public static Item ItemBlazingChestplate; public static Item ItemBlazingLeggings; public static Item ItemBlazingBoots; public static Item ItemBlazingSword; public static Item ItemBlazingAxe; public static Item ItemBlazingPickaxe; //EMERALD public static ToolMaterial ToolMaterialEmerald; public static ArmorMaterial ArmorMaterialEmerald; public static Item ItemEmeraldSword; public static Item ItemEmeraldPickaxe; public static Item ItemEmeraldSpade; public static Item ItemEmeraldAxe; public static Item ItemEmeraldHoe; public static Item ItemEmeraldHelmet; public static Item ItemEmeraldChestplate; public static Item ItemEmeraldLeggings; public static Item ItemEmeraldBoots; public static Item ItemEmeraldChunk; public static Item ItemEmeraldShard; //OBSIDIAN public static ToolMaterial ToolMaterialObsidian; public static ArmorMaterial ArmorMaterialObsidian; public static Item ItemObsidianSword; public static Item ItemObsidianChunk; public static Item ItemObsidianPickaxe; public static Item ItemObsidianSpade; public static Item ItemObsidianAxe; public static Item ItemObsidianHoe; public static Item ItemObsidianHelmet; public static Item ItemObsidianChestplate; public static Item ItemObsidianleggings; public static Item ItemObsidianBoots; public static Item ItemObsidianShard; //TITIANUM public static ToolMaterial ToolMaterialTitianum; public static ArmorMaterial ArmorMaterialTitianum; public static Block BlockTitianumOre; public static Item ItemTitanumIngot; public static Item ItemTitianumPickaxe; public static Item ItemTitianumHelmet; //GUNS public static Item ItemAKGun; public static Item ItemM4A1Gun; public static Item ItemUZIGun; public static Item ItemHunterRifelGun; //========================================================================================================================================= @EventHandler public void init(FMLInitializationEvent event) { Periodicraft.Generator = new PeriodicraftGenerator(); //OBSIDIAN ToolMaterialObsidian = EnumHelper.addToolMaterial("Obsidian", 2, 200, 14.0F, 4.7F, 25); ArmorMaterialObsidian = EnumHelper.addArmorMaterial("Obsidian", 15, new int[] {2, 5, 4, 2}, 25); ItemObsidianShard = new PeriodicraftItem("ObsidianShard", tabMaterials); ItemObsidianChunk = new PeriodicraftItem("ObsidianChunk", tabMaterials); ItemObsidianSword = new PeriodicraftSword(ToolMaterialObsidian, "ObsidianSword", tabWeapons, ItemObsidianChunk); ItemObsidianPickaxe = new PeriodicraftPickaxe(ToolMaterialObsidian, "ObsidainPickaxe", tabTools, ItemObsidianChunk); //BONE ToolMaterialBone = EnumHelper.addToolMaterial("Bone", 1, 100, 14.0F, 3.0F, 35); ItemBoneSword = new PeriodicraftSword(ToolMaterialBone, "BoneSword", tabWeapons); //Blazing ToolMaterialBlazing = EnumHelper.addToolMaterial("Blazing", 2, 300, 5.3F, 3.0F, 27); ArmorMaterialBlazing = EnumHelper.addArmorMaterial("Blazing", 15, new int[] {3, 6, 5, 3}, 27); BlockBlazingOre = new PeriodicraftOre(Material.rock, 4.0F, 2.9F, Block.soundTypeStone, "BlazeingOre", tabBlocks, 1, ItemBlazingIngot, 2.6F); Generator.addBlockNether(BlockBlazingOre, 100, 5, 10); ItemBlazingIngot = new PeriodicraftIngot("BlazingIngot", tabMaterials); ItemBlazingSword = new PeriodicraftSword(ToolMaterialBlazing, "BlazingSword", tabArmor); ItemBlazingHelmet = new PeriodicraftArmor(ArmorMaterialBlazing, 0, "BlazingHelmet", tabArmor); ItemBlazingChestplate = new PeriodicraftArmor(ArmorMaterialBlazing, 1, "BlazingChestplate", tabArmor); ItemBlazingLeggings = new PeriodicraftArmor(ArmorMaterialBlazing, 2, "BlazingLeggings", tabArmor); ItemBlazingBoots = new PeriodicraftArmor(ArmorMaterialBlazing, 3, "BlazingBoots", tabArmor); ItemBlazingPickaxe = new PeriodicraftPickaxe(ToolMaterialBlazing, "BlazingPickaxe", tabTools, ItemBlazingIngot); //Blazing BONE ToolMaterialBlazingBone = EnumHelper.addToolMaterial("BlazingBone", 2, 125, 14.0F, 4.9F, 35); ItemBlazingBoneSword = new PeriodicraftSword(ToolMaterialBlazingBone, "BlazingBoneSword", tabWeapons); //EMERALD ToolMaterialEmerald = EnumHelper.addToolMaterial("Emerald", 4, 2000, 10.0F, 4.4F, 15); ArmorMaterialEmerald = EnumHelper.addArmorMaterial("Emerald", 37, new int[] {7, 10, 7, 4}, 15); ItemEmeraldShard = new PeriodicraftItem("EmeraldShard", tabMaterials); ItemEmeraldChunk = new PeriodicraftItem("EmeraldChunk", tabMaterials); ItemEmeraldSword = new PeriodicraftSword(ToolMaterialEmerald, "EmeraldSword", tabWeapons, ItemEmeraldChunk); ItemEmeraldSpade = new PeriodicraftSpade(ToolMaterialEmerald, "EmeraldSpade", tabTools, ItemEmeraldChunk); //ItemEmerald ItemEmeraldHelmet = new PeriodicraftArmor(ArmorMaterialEmerald, 0, "EmeraldHelmet", tabArmor); ItemEmeraldChestplate = new PeriodicraftArmor(ArmorMaterialEmerald, 1, "EmeraldChestplate", tabArmor); ItemEmeraldLeggings = new PeriodicraftArmor(ArmorMaterialEmerald, 2, "EmeraldLeggings", tabArmor); ItemEmeraldBoots = new PeriodicraftArmor(ArmorMaterialEmerald, 3, "EmeraldBoots", tabArmor); // COPPER ToolMaterialCopper = EnumHelper.addToolMaterial("Copper", 2, 175, 5.2F, 1.6F, 10); ArmorMaterialCopper = EnumHelper.addArmorMaterial("Copper", 13, new int[] {2, 5, 5, 2}, 10); ItemCopperIngot = new PeriodicraftIngot("CopperIngot", tabMaterials); BlockCopperOre = new PeriodicraftOre(Material.rock, 4.0F, 2.2F, Block.soundTypeStone, "CopperOre", tabBlocks, 1, ItemCopperIngot, 2.6F); Generator.addBlockSurface(BlockCopperOre, 60, 7, 27); ItemCopperPickaxe = new PeriodicraftPickaxe(ToolMaterialCopper, "CopperPickaxe", tabTools, ItemCopperIngot); ItemCopperSword = new PeriodicraftSword(ToolMaterialCopper, "CopperSword", tabWeapons, ItemCopperIngot); ItemCopperSpade = new PeriodicraftSpade(ToolMaterialCopper, "CopperSpade", tabTools, ItemCopperIngot); ItemCopperAxe = new PeriodicraftAxe(ToolMaterialCopper, "CopperAxe", tabTools, ItemCopperIngot); ItemCopperHoe = new PeriodicraftHoe(ToolMaterialCopper, "CopperHoe", tabTools, ItemCopperIngot); ItemCopperHelmet = new PeriodicraftArmor(ArmorMaterialCopper, 0, "CopperHelmet", tabArmor); ItemCopperChestplate = new PeriodicraftArmor(ArmorMaterialCopper, 1, "CopperChestplate", tabArmor); ItemCopperLeggings = new PeriodicraftArmor(ArmorMaterialCopper, 2, "CopperLeggings", tabArmor); ItemCopperBoots = new PeriodicraftArmor(ArmorMaterialCopper, 3, "CopperBoots", tabArmor); GameRegistry.addShapedRecipe(new ItemStack(ItemEmeraldShard), "xxx", "xxx", "xxx", 'x', Items.emerald); GameRegistry.addSmelting(ItemEmeraldShard, new ItemStack(ItemEmeraldChunk), 4.0F); GameRegistry.addShapedRecipe(new ItemStack(ItemObsidianShard), "xxx", "xxx", "xxx", 'x', Blocks.obsidian); GameRegistry.addSmelting(ItemObsidianShard, new ItemStack(ItemObsidianChunk), 3.0F); GameRegistry.addShapedRecipe(new ItemStack(ItemBlazingBoneSword), "xix", "xix", " y ", 'x', ItemBlazingIngot, 'i', Items.bone, 'y', Items.blaze_rod); ItemAKGun = new PeriodicraftGun("AK-47", tabWeapons, PeriodicraftEntityBullet.class); ItemM4A1Gun = new PeriodicraftGun("M4A1", tabWeapons, PeriodicraftEntityBullet.class); ItemUZIGun = new PeriodicraftGun("UZI", tabWeapons, PeriodicraftEntityBullet.class); ItemHunterRifelGun = new PeriodicraftGun("HunterRifel", tabWeapons, PeriodicraftEntityBullet.class); } }
main/java/org/periodicraft/periodicraft/Periodicraft.java
package org.periodicraft.periodicraft; import org.periodicraft.periodicraft.block.PeriodicraftOre; import org.periodicraft.periodicraft.item.PeriodicraftArmor; import org.periodicraft.periodicraft.item.PeriodicraftAxe; import org.periodicraft.periodicraft.item.PeriodicraftEntityBullet; import org.periodicraft.periodicraft.item.PeriodicraftGun; import org.periodicraft.periodicraft.item.PeriodicraftHoe; import org.periodicraft.periodicraft.item.PeriodicraftIngot; import org.periodicraft.periodicraft.item.PeriodicraftItem; import org.periodicraft.periodicraft.item.PeriodicraftPickaxe; import org.periodicraft.periodicraft.item.PeriodicraftSpade; import org.periodicraft.periodicraft.item.PeriodicraftSword; import org.periodicraft.periodicraft.world.PeriodicraftGenerator; import scala.tools.nsc.doc.model.Public; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.item.ItemArmor.ArmorMaterial; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.EnumHelper; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; @Mod(modid = Periodicraft.MODID, name = Periodicraft.NAME, version = Periodicraft.VERSION) public class Periodicraft { public static final String MODID = "org.periodicraft.periodicraft"; public static final String VERSION = "0.0.1"; public static final String NAME = "Periodicraft"; public static CreativeTabs tabBlocks = new CreativeTabs("PeriodicraftBlocks") { @Override public Item getTabIconItem() { return Item.getItemFromBlock(Periodicraft.BlockCopperOre); } }; public static CreativeTabs tabWeapons = new CreativeTabs("PeriodicraftWeapons") { @Override public Item getTabIconItem() { return Periodicraft.ItemCopperSword; } }; public static CreativeTabs tabTools = new CreativeTabs("PeriodicraftTools") { @Override public Item getTabIconItem() { return Periodicraft.ItemCopperPickaxe; } }; public static CreativeTabs tabMaterials = new CreativeTabs("PeriodicraftMaterials") { @Override public Item getTabIconItem() { return Periodicraft.ItemCopperIngot; } }; public static CreativeTabs tabArmor = new CreativeTabs("PeriodicraftArmor") { @Override public Item getTabIconItem() { return Periodicraft.ItemCopperHelmet; } }; // World Gen public static PeriodicraftGenerator Generator; //========================================================================================================================================= //COPPER public static Block BlockCopperOre; public static ToolMaterial ToolMaterialCopper; public static Item ItemCopperIngot; public static Item ItemCopperPickaxe; public static Item ItemCopperSword; public static Item ItemCopperSpade; public static Item ItemCopperAxe; public static Item ItemCopperHoe; public static ArmorMaterial ArmorMaterialCopper; public static Item ItemCopperHelmet; public static Item ItemCopperChestplate; public static Item ItemCopperLeggings; public static Item ItemCopperBoots; //BONE public static ToolMaterial ToolMaterialBone; public static Item ItemBoneSword; public static Item ItemBoneAxe; //Blazing BONE public static ToolMaterial ToolMaterialBlazingBone; public static Item ItemBlazingBoneShard; public static Item ItemBlazingBoneSword; //BLAZING public static ToolMaterial ToolMaterialBlazing; public static ArmorMaterial ArmorMaterialBlazing; public static Item ItemBlazingIngot; public static Block BlockBlazingOre; public static Item ItemBlazingHelmet; public static Item ItemBlazingChestplate; public static Item ItemBlazingLeggings; public static Item ItemBlazingBoots; public static Item ItemBlazingSword; public static Item ItemBlazingAxe; public static Item ItemBlazingPickaxe; //EMERALD public static ToolMaterial ToolMaterialEmerald; public static ArmorMaterial ArmorMaterialEmerald; public static Item ItemEmeraldSword; public static Item ItemEmeraldPickaxe; public static Item ItemEmeraldSpade; public static Item ItemEmeraldAxe; public static Item ItemEmeraldHoe; public static Item ItemEmeraldHelmet; public static Item ItemEmeraldChestplate; public static Item ItemEmeraldLeggings; public static Item ItemEmeraldBoots; public static Item ItemEmeraldChunk; public static Item ItemEmeraldShard; //OBSIDIAN public static ToolMaterial ToolMaterialObsidian; public static ArmorMaterial ArmorMaterialObsidian; public static Item ItemObsidianSword; public static Item ItemObsidianChunk; public static Item ItemObsidianPickaxe; public static Item ItemObsidianSpade; public static Item ItemObsidianAxe; public static Item ItemObsidianHoe; public static Item ItemObsidianHelmet; public static Item ItemObsidianChestplate; public static Item ItemObsidianleggings; public static Item ItemObsidianBoots; public static Item ItemObsidianShard; //TITIANUM public static ToolMaterial ToolMaterialTitianum; public static ArmorMaterial ArmorMaterialTitianum; public static Block BlockTitianumOre; public static Item ItemTitanumIngot; public static Item ItemTitianumPickaxe; public static Item ItemTitianumHelmet; //GUNS public static Item ItemAKGun; public static Item ItemM4A1Gun; public static Item ItemUZIGun; public static Item ItemHunterRifelGun; //========================================================================================================================================= @EventHandler public void init(FMLInitializationEvent event) { Periodicraft.Generator = new PeriodicraftGenerator(); //OBSIDIAN ToolMaterialObsidian = EnumHelper.addToolMaterial("Obsidian", 2, 200, 14.0F, 4.7F, 25); ArmorMaterialObsidian = EnumHelper.addArmorMaterial("Obsidian", 15, new int[] {2, 5, 4, 2}, 25); ItemObsidianShard = new PeriodicraftItem("ObsidianShard", tabMaterials); ItemObsidianChunk = new PeriodicraftItem("ObsidianChunk", tabMaterials); ItemObsidianSword = new PeriodicraftSword(ToolMaterialObsidian, "ObsidianSword", tabWeapons, ItemObsidianChunk); ItemObsidianPickaxe = new PeriodicraftPickaxe(ToolMaterialObsidian, "ObsidainPickaxe", tabTools, ItemObsidianChunk); //BONE ToolMaterialBone = EnumHelper.addToolMaterial("Bone", 1, 100, 14.0F, 3.0F, 35); ItemBoneSword = new PeriodicraftSword(ToolMaterialBone, "BoneSword", tabWeapons); //Blazing ToolMaterialBlazing = EnumHelper.addToolMaterial("Blazing", 2, 300, 5.3F, 3.0F, 27); ArmorMaterialBlazing = EnumHelper.addArmorMaterial("Blazing", 15, new int[] {3, 6, 5, 3}, 27); // BlockBlazingOre = new PeriodicraftOre(Material.rock, 4.0F, ); // Generator.addBlockNether(BlockBlazingOre, 100, 5, 10); ItemBlazingIngot = new PeriodicraftIngot("BlazingIngot", tabMaterials); ItemBlazingSword = new PeriodicraftSword(ToolMaterialBlazing, "BlazingSword", tabArmor); ItemBlazingHelmet = new PeriodicraftArmor(ArmorMaterialBlazing, 0, "BlazingHelmet", tabArmor); ItemBlazingChestplate = new PeriodicraftArmor(ArmorMaterialBlazing, 1, "BlazingChestplate", tabArmor); ItemBlazingLeggings = new PeriodicraftArmor(ArmorMaterialBlazing, 2, "BlazingLeggings", tabArmor); ItemBlazingBoots = new PeriodicraftArmor(ArmorMaterialBlazing, 3, "BlazingBoots", tabArmor); ItemBlazingPickaxe = new PeriodicraftPickaxe(ToolMaterialBlazing, "BlazingPickaxe", tabTools, ItemBlazingIngot); //Blazing BONE ToolMaterialBlazingBone = EnumHelper.addToolMaterial("BlazingBone", 2, 125, 14.0F, 4.9F, 35); ItemBlazingBoneSword = new PeriodicraftItem("BlazingBoneSword", tabWeapons); //EMERALD ToolMaterialEmerald = EnumHelper.addToolMaterial("Emerald", 4, 2000, 10.0F, 4.4F, 15); ArmorMaterialEmerald = EnumHelper.addArmorMaterial("Emerald", 37, new int[] {7, 10, 7, 4}, 15); ItemEmeraldShard = new PeriodicraftItem("EmeraldShard", tabMaterials); ItemEmeraldChunk = new PeriodicraftItem("EmeraldChunk", tabMaterials); ItemEmeraldSword = new PeriodicraftSword(ToolMaterialEmerald, "EmeraldSword", tabWeapons, ItemEmeraldChunk); // COPPER ToolMaterialCopper = EnumHelper.addToolMaterial("Copper", 2, 175, 5.2F, 1.6F, 10); ArmorMaterialCopper = EnumHelper.addArmorMaterial("Copper", 13, new int[] {2, 5, 5, 2}, 10); ItemCopperIngot = new PeriodicraftIngot("CopperIngot", tabMaterials); BlockCopperOre = new PeriodicraftOre(Material.rock, 4.0F, 2.2F, Block.soundTypeStone, "CopperOre", tabBlocks, 1, ItemCopperIngot, 2.6F); Generator.addBlockSurface(BlockCopperOre, 60, 7, 27); ItemCopperPickaxe = new PeriodicraftPickaxe(ToolMaterialCopper, "CopperPickaxe", tabTools, ItemCopperIngot); ItemCopperSword = new PeriodicraftSword(ToolMaterialCopper, "CopperSword", tabWeapons, ItemCopperIngot); ItemCopperSpade = new PeriodicraftSpade(ToolMaterialCopper, "CopperSpade", tabTools, ItemCopperIngot); ItemCopperAxe = new PeriodicraftAxe(ToolMaterialCopper, "CopperAxe", tabTools, ItemCopperIngot); ItemCopperHoe = new PeriodicraftHoe(ToolMaterialCopper, "CopperHoe", tabTools, ItemCopperIngot); ItemCopperHelmet = new PeriodicraftArmor(ArmorMaterialCopper, 0, "CopperHelmet", tabArmor); ItemCopperChestplate = new PeriodicraftArmor(ArmorMaterialCopper, 1, "CopperChestplate", tabArmor); ItemCopperLeggings = new PeriodicraftArmor(ArmorMaterialCopper, 2, "CopperLeggings", tabArmor); ItemCopperBoots = new PeriodicraftArmor(ArmorMaterialCopper, 3, "CopperBoots", tabArmor); GameRegistry.addShapedRecipe(new ItemStack(ItemEmeraldShard), "xxx", "xxx", "xxx", 'x', Items.emerald); GameRegistry.addSmelting(ItemEmeraldShard, new ItemStack(ItemEmeraldChunk), 4.0F); GameRegistry.addShapedRecipe(new ItemStack(ItemObsidianShard), "xxx", "xxx", "xxx", 'x', Blocks.obsidian); GameRegistry.addSmelting(ItemObsidianShard, new ItemStack(ItemObsidianChunk), 3.0F); GameRegistry.addShapedRecipe(new ItemStack(ItemBlazingSword), "xix", "xix", " y ", 'x', ItemBlazeingIngot, 'i', Items.bone, 'y', Items.blaze_rod); ItemAKGun = new PeriodicraftGun("AK-47", tabWeapons, PeriodicraftEntityBullet.class); ItemM4A1Gun = new PeriodicraftGun("M4A1", tabWeapons, PeriodicraftEntityBullet.class); ItemUZIGun = new PeriodicraftGun("UZI", tabWeapons, PeriodicraftEntityBullet.class); ItemHunterRifelGun = new PeriodicraftGun("HunterRifel", tabWeapons, PeriodicraftEntityBullet.class); } }
Preped for presentation
main/java/org/periodicraft/periodicraft/Periodicraft.java
Preped for presentation
<ide><path>ain/java/org/periodicraft/periodicraft/Periodicraft.java <ide> //Blazing <ide> ToolMaterialBlazing = EnumHelper.addToolMaterial("Blazing", 2, 300, 5.3F, 3.0F, 27); <ide> ArmorMaterialBlazing = EnumHelper.addArmorMaterial("Blazing", 15, new int[] {3, 6, 5, 3}, 27); <del> // BlockBlazingOre = new PeriodicraftOre(Material.rock, 4.0F, ); <del> // Generator.addBlockNether(BlockBlazingOre, 100, 5, 10); <add> BlockBlazingOre = new PeriodicraftOre(Material.rock, 4.0F, 2.9F, Block.soundTypeStone, "BlazeingOre", tabBlocks, 1, ItemBlazingIngot, 2.6F); <add> Generator.addBlockNether(BlockBlazingOre, 100, 5, 10); <ide> ItemBlazingIngot = new PeriodicraftIngot("BlazingIngot", tabMaterials); <ide> ItemBlazingSword = new PeriodicraftSword(ToolMaterialBlazing, "BlazingSword", tabArmor); <ide> ItemBlazingHelmet = new PeriodicraftArmor(ArmorMaterialBlazing, 0, "BlazingHelmet", tabArmor); <ide> <ide> //Blazing BONE <ide> ToolMaterialBlazingBone = EnumHelper.addToolMaterial("BlazingBone", 2, 125, 14.0F, 4.9F, 35); <del> ItemBlazingBoneSword = new PeriodicraftItem("BlazingBoneSword", tabWeapons); <add> ItemBlazingBoneSword = new PeriodicraftSword(ToolMaterialBlazingBone, "BlazingBoneSword", tabWeapons); <ide> <ide> //EMERALD <ide> ToolMaterialEmerald = EnumHelper.addToolMaterial("Emerald", 4, 2000, 10.0F, 4.4F, 15); <ide> ItemEmeraldShard = new PeriodicraftItem("EmeraldShard", tabMaterials); <ide> ItemEmeraldChunk = new PeriodicraftItem("EmeraldChunk", tabMaterials); <ide> ItemEmeraldSword = new PeriodicraftSword(ToolMaterialEmerald, "EmeraldSword", tabWeapons, ItemEmeraldChunk); <add> ItemEmeraldSpade = new PeriodicraftSpade(ToolMaterialEmerald, "EmeraldSpade", tabTools, ItemEmeraldChunk); <add> //ItemEmerald <add> ItemEmeraldHelmet = new PeriodicraftArmor(ArmorMaterialEmerald, 0, "EmeraldHelmet", tabArmor); <add> ItemEmeraldChestplate = new PeriodicraftArmor(ArmorMaterialEmerald, 1, "EmeraldChestplate", tabArmor); <add> ItemEmeraldLeggings = new PeriodicraftArmor(ArmorMaterialEmerald, 2, "EmeraldLeggings", tabArmor); <add> ItemEmeraldBoots = new PeriodicraftArmor(ArmorMaterialEmerald, 3, "EmeraldBoots", tabArmor); <ide> <ide> // COPPER <ide> ToolMaterialCopper = EnumHelper.addToolMaterial("Copper", 2, 175, 5.2F, 1.6F, 10); <ide> GameRegistry.addSmelting(ItemEmeraldShard, new ItemStack(ItemEmeraldChunk), 4.0F); <ide> GameRegistry.addShapedRecipe(new ItemStack(ItemObsidianShard), "xxx", "xxx", "xxx", 'x', Blocks.obsidian); <ide> GameRegistry.addSmelting(ItemObsidianShard, new ItemStack(ItemObsidianChunk), 3.0F); <del> GameRegistry.addShapedRecipe(new ItemStack(ItemBlazingSword), "xix", "xix", " y ", 'x', ItemBlazeingIngot, 'i', Items.bone, 'y', Items.blaze_rod); <add> GameRegistry.addShapedRecipe(new ItemStack(ItemBlazingBoneSword), "xix", "xix", " y ", 'x', ItemBlazingIngot, 'i', Items.bone, 'y', Items.blaze_rod); <ide> <ide> ItemAKGun = new PeriodicraftGun("AK-47", tabWeapons, PeriodicraftEntityBullet.class); <ide> ItemM4A1Gun = new PeriodicraftGun("M4A1", tabWeapons, PeriodicraftEntityBullet.class);
JavaScript
mit
f58dcd1df1b52c4ff92752590fc7d14cbe835fab
0
Baqend/js-sdk,Baqend/js-sdk
"use strict"; var message = require('./message'); var error = require('./error'); var binding = require('./binding'); var util = require('./util'); var query = require('./query'); var UserFactory = require('./binding/UserFactory'); var EntityTransaction = require('./EntityTransaction'); var Metadata = require('./util/Metadata'); var Message = require('./connector/Message'); var BloomFilter = require('./caching/BloomFilter'); var StatusCode = Message.StatusCode; /** * @alias EntityManager * @extends util.Lockable */ class EntityManager extends util.Lockable { /** * Determine whether the entity manager is open. * true until the entity manager has been closed * @type boolean */ get isOpen() { return !!this._connector; } /** * The authentication token if the user is logged in currently * @type String */ get token() { return this.tokenStorage.token; } get isCachingDisabled() { return !this.bloomFilter; } /** * The authentication token if the user is logged in currently * @param {String} value */ set token(value) { this.tokenStorage.update(value); } /** * @param {EntityManagerFactory} entityManagerFactory The factory which of this entityManager instance */ constructor(entityManagerFactory) { super(); /** * Log messages can created by calling log directly as function, with a specific log level or with the helper * methods, which a members of the log method. * * Logs will be filtered by the client logger and the before they persisted. The default log level is * 'info' therefore all log messages below the given message aren't persisted. * * Examples: * <pre class="prettyprint"> // default log level ist info db.log('test message %s', 'my string'); // info: test message my string // pass a explicit log level as the first argument, one of ('trace', 'debug', 'info', 'warn', 'error') db.log('warn', 'test message %d', 123); // warn: test message 123 // debug log level will not be persisted by default, since the default logging level is info db.log('debug', 'test message %j', {number: 123}, {}); // debug: test message {"number":123} // data = {} // One additional json object can be provided, which will be persisted together with the log entry db.log('info', 'test message %s, %s', 'first', 'second', {number: 123}); // info: test message first, second // data = {number: 123} //use the log level helper db.log.info('test message', 'first', 'second', {number: 123}); // info: test message first second // data = {number: 123} //change the default log level to trace, i.e. all log levels will be persisted, note that the log level can be //additionally configured in the baqend db.log.level = 'trace'; //trace will be persisted now db.log.trace('test message', 'first', 'second', {number: 123}); // info: test message first second // data = {number: 123} * </pre> * * @type util.Logger */ this.log = util.Logger.create(this); /** * The connector used for requests * @type connector.Connector * @private */ this._connector = null; /** * All managed and cached entity instances * @type Map<String,binding.Entity> */ this._entities = null; /** @type EntityManagerFactory */ this.entityManagerFactory = entityManagerFactory; /** @type metamodel.Metamodel */ this.metamodel = entityManagerFactory.metamodel; /** @type util.Code */ this.code = entityManagerFactory.code; /** @type util.Modules */ this.modules = null; /** * The current logged in user object * @type model.User */ this.me = null; /** * Returns true if the device token is already registered, otherwise false. * @type boolean */ this.isDeviceRegistered = false; /** * Returns the tokenStorage which will be used to authorize all requests. * @type {util.TokenStorage} */ this.tokenStorage = null; /** * @type {caching.BloomFilter} */ this.bloomFilter = null; /** * Set of object ids that were revalidated after the Bloom filter was loaded. */ this.cacheWhiteList = null; /** * Set of object ids that were updated but are not yet included in the bloom filter. * This set essentially implements revalidation by side effect which does not work in Chrome. */ this.cacheBlackList = null; /** * Bloom filter refresh interval in seconds. * * @type {number} */ this.bloomFilterRefresh = 60; /** * Bloom filter refresh Promise * */ this._bloomFilterLock = new util.Lockable(); } /** * Connects this entityManager, used for synchronous and asynchronous initialization * @param {connector.Connector} connector * @param {Object} connectData * @param {util.TokenStorage} tokenStorage The used tokenStorage for token persistence */ connected(connector, connectData, tokenStorage) { this._connector = connector; this.tokenStorage = tokenStorage; this.bloomFilterRefresh = this.entityManagerFactory.staleness; this._entities = {}; this.File = binding.FileFactory.create(this); this._createObjectFactory(this.metamodel.embeddables); this._createObjectFactory(this.metamodel.entities); this.transaction = new EntityTransaction(this); this.modules = new util.Modules(this, connector); if (connectData) { this.isDeviceRegistered = !!connectData.device; if (connectData.user && connectData.token == tokenStorage.token) this._updateUser(connectData.user, true); if (this.bloomFilterRefresh > 0 && connectData.bloomFilter && util.atob && !util.isNode) { this.updateBloomFilter(connectData.bloomFilter); } } } /** * @param {metamodel.ManagedType[]} types * @return {binding.ManagedFactory} * @private */ _createObjectFactory(types) { Object.keys(types).forEach(function(ref) { var type = this.metamodel.managedType(ref); var name = type.name; if (this[name]) { type.typeConstructor = this[name]; Object.defineProperty(this, name, { value: type.createObjectFactory(this) }); } else { Object.defineProperty(this, name, { get() { Object.defineProperty(this, name, { value: type.createObjectFactory(this) }); return this[name]; }, set(typeConstructor) { type.typeConstructor = typeConstructor; }, configurable: true }); } }, this); } _sendOverSocket(message) { message.token = this.token; this._connector.sendOverSocket(message); } _subscribe(topic, cb) { this._connector.subscribe(topic, cb); } _unsubscribe(topic, cb) { this._connector.unsubscribe(topic, cb); } send(message) { message.tokenStorage = this.tokenStorage; return this._connector.send(message).catch((e) => { if (e.status == StatusCode.BAD_CREDENTIALS) { this._logout(); } throw e; }); } /** * Get an instance, whose state may be lazily fetched. If the requested instance does not exist * in the database, the EntityNotFoundError is thrown when the instance state is first accessed. * The application should not expect that the instance state will be available upon detachment, * unless it was accessed by the application while the entity manager was open. * * @param {(Class<binding.Entity>|string)} entityClass * @param {string=} key */ getReference(entityClass, key) { var id, type; if (key) { type = this.metamodel.entity(entityClass); if (key.indexOf('/db/') == 0) { id = key; } else { id = type.ref + '/' + encodeURIComponent(key); } } else { id = entityClass; type = this.metamodel.entity(id.substring(0, id.indexOf('/', 4))); //skip /db/ } var entity = this._entities[id]; if (!entity) { entity = type.create(); var metadata = Metadata.get(entity); metadata.id = id; metadata.setUnavailable(); this._attach(entity); } return entity; } /** * Creates an instance of Query.Builder for query creation and execution. The Query results are instances of the * resultClass argument. * @param {Class<*>=} resultClass - the type of the query result * @return {query.Builder<*>} A query builder to create one ore more queries for the specified class */ createQueryBuilder(resultClass) { return new query.Builder(this, resultClass); } /** * Clear the persistence context, causing all managed entities to become detached. * Changes made to entities that have not been flushed to the database will not be persisted. */ clear() { this._entities = {}; } /** * Close an application-managed entity manager. After the close method has been invoked, * all methods on the EntityManager instance and any Query and TypedQuery objects obtained from it * will throw the IllegalStateError except for transaction, and isOpen (which will return false). * If this method is called when the entity manager is associated with an active transaction, * the persistence context remains managed until the transaction completes. */ close() { this._connector = null; return this.clear(); } /** * Check if the instance is a managed entity instance belonging to the current persistence context. * @param {binding.Entity} entity - entity instance * @returns {boolean} boolean indicating if entity is in persistence context */ contains(entity) { return !!entity && this._entities[entity.id] === entity; } /** * Check if an object with the id from the given entity is already attached. * @param {binding.Entity} entity - entity instance * @returns {boolean} boolean indicating if entity with same id is attached */ containsById(entity) { return !!(entity && this._entities[entity.id]); } /** * Remove the given entity from the persistence context, causing a managed entity to become detached. * Unflushed changes made to the entity if any (including removal of the entity), * will not be synchronized to the database. Entities which previously referenced the detached entity will continue to reference it. * @param {binding.Entity} entity - entity instance */ detach(entity) { var state = Metadata.get(entity); return state.withLock(() => { this.removeReference(entity); return Promise.resolve(entity); }); } /** * Resolve the depth by loading the referenced objects of the given entity. * * @param {binding.Entity} entity - entity instance * @param {Object} [options] The load options * @return {Promise<binding.Entity>} */ resolveDepth(entity, options) { if (!options || !options.depth) return Promise.resolve(entity); options.resolved = options.resolved || []; var promises = []; var subOptions = Object.assign({}, options, { depth: options.depth === true ? true : options.depth - 1 }); this.getSubEntities(entity, 1).forEach((subEntity) => { if (subEntity != null && !~options.resolved.indexOf(subEntity)) { options.resolved.push(subEntity); promises.push(this.load(subEntity.id, null, subOptions)); } }); return Promise.all(promises).then(function() { return entity; }); } /** * Search for an entity of the specified oid. * If the entity instance is contained in the persistence context, it is returned from there. * @param {(Class<binding.Entity>|string)} entityClass - entity class * @param {String} oid - Object ID * @param {Object} [options] The load options. * @return {Promise<binding.Entity>} the loaded entity or null */ load(entityClass, oid, options) { options = options || {}; var entity = this.getReference(entityClass, oid); var state = Metadata.get(entity); if (!options.refresh && options.local && state.isAvailable) { return this.resolveDepth(entity, options); } var msg = new message.GetObject(state.bucket, state.key); this.ensureCacheHeader(entity.id, msg, options.refresh); return this.send(msg).then((response) => { // refresh object if loaded older version from cache // chrome doesn't using cache when ifNoneMatch is set if (entity.version > response.entity.version) { options.refresh = true; return this.load(entityClass, oid, options) } this.addToWhiteList(response.entity.id); if (response.status != StatusCode.NOT_MODIFIED) { state.setJson(response.entity); } state.setPersistent(); return this.resolveDepth(entity, options); }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { this.removeReference(entity); state.setRemoved(); return null; } else { throw e; } }); } /** * @param {binding.Entity} entity * @param {Object} options * @return {Promise<binding.Entity>} */ insert(entity, options) { options = options || {}; var isNew; return this._save(entity, options, function(state, json) { if (state.version) throw new error.PersistentError('Existing objects can\'t be inserted.'); isNew = !state.id; return new message.CreateObject(state.bucket, json); }).then((val) => { if (isNew) this._attach(entity); return val; }); } /** * @param {binding.Entity} entity * @param {Object} options * @return {Promise<binding.Entity>} */ update(entity, options) { options = options || {}; return this._save(entity, options, function(state, json) { if (!state.version) throw new error.PersistentError("New objects can't be inserted."); if (options.force) { delete json.version; return new message.ReplaceObject(state.bucket, state.key, json) .ifMatch('*'); } else { return new message.ReplaceObject(state.bucket, state.key, json) .ifMatch(state.version); } }); } /** * @param {binding.Entity} entity * @param {Object} options The save options * @param {boolean=} withoutLock Set true to save the entity without locking * @return {Promise<binding.Entity>} */ save(entity, options, withoutLock) { options = options || {}; var msgFactory = function(state, json) { if (options.force) { if (!state.id) throw new error.PersistentError("New special objects can't be forcedly saved."); delete json.version; return new message.ReplaceObject(state.bucket, state.key, json); } else if (state.version) { return new message.ReplaceObject(state.bucket, state.key, json) .ifMatch(state.version); } else { return new message.CreateObject(state.bucket, json); } }; return withoutLock ? this._locklessSave(entity, options, msgFactory) : this._save(entity, options, msgFactory) } /** * @param {binding.Entity} entity * @param {Function} cb pre-safe callback * @return {Promise<binding.Entity>} */ optimisticSave(entity, cb) { return Metadata.get(entity).withLock(() => { return this._optimisticSave(entity, cb); }); } /** * @param {binding.Entity} entity * @param {Function} cb pre-safe callback * @return {Promise<binding.Entity>} * @private */ _optimisticSave(entity, cb) { var abort = false; var abortFn = function() { abort = true; }; var promise = Promise.resolve(cb(entity, abortFn)); if (abort) return Promise.resolve(entity); return promise.then(() => { return this.save(entity, {}, true).catch((e) => { if (e.status == 412) { return this.refresh(entity, {}).then(() => { return this._optimisticSave(entity, cb); }); } else { throw e; } }); }); } /** * Save the object state without locking * @param {binding.Entity} entity * @param {Object} options * @param {Function} msgFactory * @return {Promise.<binding.Entity>} * @private */ _locklessSave(entity, options, msgFactory) { this.attach(entity); var state = Metadata.get(entity); var refPromises; var json; if (state.isAvailable) { //getting json will check all collections changes, therefore we must do it before proofing the dirty state json = state.getJson(); } if (state.isDirty) { if (!options.refresh) { state.setPersistent(); } var sendPromise = this.send(msgFactory(state, json)).then((response) => { if (options.refresh) { state.setJson(response.entity); state.setPersistent(); } else { state.setJsonMetadata(response.entity); } return entity; }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { this.removeReference(entity); state.setRemoved(); return null; } else { state.setDirty(); throw e; } }); refPromises = [sendPromise]; } else { refPromises = [Promise.resolve(entity)]; } var subOptions = Object.assign({}, options); subOptions.depth = 0; this.getSubEntities(entity, options.depth).forEach((sub) => { refPromises.push(this._save(sub, subOptions, msgFactory)); }); return Promise.all(refPromises).then(() => entity); } /** * Save and lock the object state * @param {binding.Entity} entity * @param {Object} options * @param {Function} msgFactory * @return {Promise.<binding.Entity>} * @private */ _save(entity, options, msgFactory) { this.ensureBloomFilterFreshness(); var state = Metadata.get(entity); if (state.version) { this.addToBlackList(entity.id); } return state.withLock(() => { return this._locklessSave(entity, options, msgFactory); }); } /** * Returns all referenced sub entities for the given depth and root entity * @param {binding.Entity} entity * @param {boolean|number} depth * @param {binding.Entity[]} [resolved] * @param {binding.Entity=} initialEntity * @returns {binding.Entity[]} */ getSubEntities(entity, depth, resolved, initialEntity) { resolved = resolved || []; if (!depth) { return resolved; } initialEntity = initialEntity || entity; var state = Metadata.get(entity); for (let value of state.type.references()) { this.getSubEntitiesByPath(entity, value.path).forEach((subEntity) => { if (!~resolved.indexOf(subEntity) && subEntity != initialEntity) { resolved.push(subEntity); resolved = this.getSubEntities(subEntity, depth === true ? depth : depth - 1, resolved, initialEntity); } }); } return resolved; } /** * Returns all referenced one level sub entities for the given path * @param {binding.Entity} entity * @param {Array<string>} path * @returns {binding.Entity[]} */ getSubEntitiesByPath(entity, path) { var subEntities = [entity]; path.forEach((attributeName) => { var tmpSubEntities = []; subEntities.forEach((subEntity) => { var curEntity = subEntity[attributeName]; if (!curEntity) return; var attribute = this.metamodel.managedType(subEntity.constructor).getAttribute(attributeName); if (attribute.isCollection) { for (let entry of curEntity.entries()) { tmpSubEntities.push(entry[1]); attribute.keyType && attribute.keyType.isEntity && tmpSubEntities.push(entry[0]); } } else { tmpSubEntities.push(curEntity); } }); subEntities = tmpSubEntities; }); return subEntities; } /** * Delete the entity instance. * @param {binding.Entity} entity * @param {Object} options The delete options * @return {Promise<binding.Entity>} */ 'delete'(entity, options) { options = options || {}; this.attach(entity); var state = Metadata.get(entity); return state.withLock(() => { if (!state.version && !options.force) throw new error.IllegalEntityError(entity); var msg = new message.DeleteObject(state.bucket, state.key); this.addToBlackList(entity.id); if (!options.force) msg.ifMatch(state.version); var refPromises = [this.send(msg).then(() => { this.removeReference(entity); state.setRemoved(); return entity; })]; var subOptions = Object.assign({}, options); subOptions.depth = 0; this.getSubEntities(entity, options.depth).forEach((sub) => { refPromises.push(this.delete(sub, subOptions)); }); return Promise.all(refPromises).then(function() { return entity; }); }); } /** * Synchronize the persistence context to the underlying database. * * @returns {Promise<*>} */ flush(doneCallback, failCallback) { // TODO: implement this } /** * Make an instance managed and persistent. * @param {binding.Entity} entity - entity instance */ persist(entity) { this.attach(entity); } /** * Refresh the state of the instance from the database, overwriting changes made to the entity, if any. * @param {binding.Entity} entity - entity instance * @param {Object} options The refresh options * @return {Promise<binding.Entity>} */ refresh(entity, options) { options = options || {}; options.refresh = true; return this.load(entity.id, null, options); } /** * Attach the instance to this database context, if it is not already attached * @param {binding.Entity} entity The entity to attach */ attach(entity) { if (!this.contains(entity)) { var type = this.metamodel.entity(entity.constructor); if (!type) throw new error.IllegalEntityError(entity); if (this.containsById(entity)) throw new error.EntityExistsError(entity); this._attach(entity); } } _attach(entity) { var metadata = Metadata.get(entity); if (metadata.isAttached) { if (metadata.db != this) { throw new error.EntityExistsError(entity); } } else { metadata.db = this; } if (!metadata.id) { if (metadata.type.name != 'User' && metadata.type.name != 'Role' && metadata.type.name != 'logs.AppLog') { metadata.id = '/db/' + metadata.type.name + '/' + util.uuid(); } } if (metadata.id) { this._entities[metadata.id] = entity; } } removeReference(entity) { var state = Metadata.get(entity); if (!state) throw new error.IllegalEntityError(entity); delete this._entities[state.id]; } register(user, password, loginOption) { let login = loginOption > UserFactory.LoginOption.NO_LOGIN; if (this.me && login) { throw new error.PersistentError('User is already logged in.'); } return this.withLock(() => { var msg = new message.Register({ user: user, password: password, login: login }); return this._userRequest(msg, loginOption); }); } login(username, password, loginOption) { if (this.me) throw new error.PersistentError('User is already logged in.'); return this.withLock(() => { let msg = new message.Login({ username: username, password: password }); return this._userRequest(msg, loginOption); }); } logout() { return this.withLock(() => { return this.send(new message.Logout()).then(this._logout.bind(this)); }); } loginWithOAuth(provider, clientID, options) { if (this.me) throw new error.PersistentError('User is already logged in.'); options = Object.assign({ title: "Login with " + provider, timeout: 5 * 60 * 1000, state: {}, loginOption: true }, options); var msg; if (Message[provider + 'OAuth']) { msg = new Message[provider + 'OAuth'](clientID, options.scope, JSON.stringify(options.state)); } else { throw new Error('OAuth provider ' + provider + ' not supported.'); } var req = this._userRequest(msg, options.loginOption); var w = open(msg.request.path, options.title, 'width=' + options.width + ',height=' + options.height); return new Promise((resolve, reject) => { var timeout = setTimeout(() => { reject(new error.PersistentError('OAuth login timeout.')); }, options.timeout); req.then(resolve, reject).then(() => { clearTimeout(timeout); }); }); } renew() { return this.withLock(() => { var msg = new message.Me(); return this._userRequest(msg, true); }); } newPassword(username, password, newPassword) { return this.withLock(() => { var msg = new message.NewPassword({ username: username, password: password, newPassword: newPassword }); return this.send(msg).then((response) => { return this._updateUser(response.entity); }); }); } _updateUser(obj, updateMe) { var user = this.getReference(obj.id); var metadata = Metadata.get(user); metadata.setJson(obj); metadata.setPersistent(); if (updateMe) this.me = user; return user; } _logout() { this.me = null; this.token = null; } _userRequest(msg, loginOption) { let login = loginOption > UserFactory.LoginOption.NO_LOGIN; if (login) { this.tokenStorage.temporary = loginOption < UserFactory.LoginOption.PERSIST_LOGIN; } return this.send(msg).then((response) => { if (response.entity) { return this._updateUser(response.entity, login); } }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { if (login) this._logout(); return null; } else { throw e; } }); } registerDevice(os, token, device) { var msg = new message.DeviceRegister({ token: token, devicetype: os, device: device }); msg.withCredentials = true; return this.send(msg); } checkDeviceRegistration() { return this.send(new message.DeviceRegistered()).then(() => { return this.isDeviceRegistered = true; }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { return this.isDeviceRegistered = false; } else { throw e; } }); } pushDevice(pushMessage) { return this.send(new message.DevicePush(pushMessage)); } /** * The given entity will be checked by the validation code of the entity type. * * @param {binding.Entity} entity * @returns {util.ValidationResult} result */ validate(entity) { var type = Metadata.get(entity).type; var result = new util.ValidationResult(); for (var iter = type.attributes(), item; !(item = iter.next()).done;) { var validate = new util.Validator(item.value.name, entity); result.fields[validate.key] = validate; } var validationCode = type.validationCode; if (validationCode) { validationCode(result.fields); } return result; } /** * Adds the given object id to the cacheWhiteList if needed. * @param {string} objectId The id to add. */ addToWhiteList(objectId) { if (!this.isCachingDisabled) { if (this.bloomFilter.contains(objectId)) { this.cacheWhiteList.add(objectId); } this.cacheBlackList.delete(objectId); } } /** * Adds the given object id to the cacheBlackList if needed. * @param {string} objectId The id to add. */ addToBlackList(objectId) { if (!this.isCachingDisabled) { if (!this.bloomFilter.contains(objectId)) { this.cacheBlackList.add(objectId); } this.cacheWhiteList.delete(objectId); } } refreshBloomFilter() { if (this.isCachingDisabled) return Promise.resolve(); var msg = new message.GetBloomFilter(); return this.send(msg).then((response) => { this.updateBloomFilter(response.entity); return this.bloomFilter; }); } updateBloomFilter(bloomFilter) { this.bloomFilter = new BloomFilter(bloomFilter); this.cacheWhiteList = new Set(); this.cacheBlackList = new Set(); } /** * Checks the freshness of the bloom filter and does a reload if necessary */ ensureBloomFilterFreshness() { if (this.isCachingDisabled) return; var now = new Date().getTime(); var refreshRate = this.bloomFilterRefresh * 1000; if (this._bloomFilterLock.isReady && now - this.bloomFilter.creation > refreshRate) { this._bloomFilterLock.withLock(() => this.refreshBloomFilter()); } } /** * Checks for a given id, if revalidation is required, the resource is stale or caching was disabled * @param {string} id The object id to check * @returns {boolean} Indicates if the resource must be revalidated */ mustRevalidate(id) { if (util.isNode) return false; this.ensureBloomFilterFreshness(); var refresh = this.isCachingDisabled || !this._bloomFilterLock.isReady; refresh = refresh || (!this.cacheWhiteList.has(id) && (this.cacheBlackList.has(id) || this.bloomFilter.contains(id))); return refresh; } /** * * @param {string} id To check the bloom filter * @param {connector.Message} message To attach the headers * @param {boolean} refresh To force the reload headers */ ensureCacheHeader(id, message, refresh) { refresh = refresh || this.mustRevalidate(id); if (refresh) { message.noCache(); } } /** * Creates a absolute url for the given relative one * @param {string} relativePath the relative url * @param {boolean=} authorize indicates if authorization credentials should be generated and be attached to the url * @return {string} a absolute url wich is optionaly signed with a resource token which authenticates the currently * logged in user */ createURL(relativePath, authorize) { var path = this._connector.basePath + relativePath; var append = false; if (authorize && this.me) { path = this.tokenStorage.signPath(path); append = true; } else { path = path.split('/').map(encodeURIComponent).join('/'); } if (this.mustRevalidate(relativePath)) { path = path + (append ? '&' : '?') + 'BCB'; } return this._connector.origin + path; } } /** * Constructor for a new List collection * @function * @param {...*} args Same arguments can be passed as the Array constructor takes * @return {void} The new created List */ EntityManager.prototype.List = Array; /** * Constructor for a new Set collection * @function * @param {Iterable<*>=} collection The initial array or collection to initialize the new Set * @return {void} The new created Set */ EntityManager.prototype.Set = Set; /** * Constructor for a new Map collection * @function * @param {Iterable<*>=} collection The initial array or collection to initialize the new Map * @return {void} The new created Map */ EntityManager.prototype.Map = Map; /** * Constructor for a new GeoPoint * @function * @param {string|number|Object|Array<number>} [latitude] A coordinate pair (latitude first), a GeoPoint like object or the GeoPoint's latitude * @param {number=} longitude The GeoPoint's longitude * @return {void} The new created GeoPoint */ EntityManager.prototype.GeoPoint = require('./GeoPoint'); /** * An User factory for user objects. * The User factory can be called to create new instances of users or can be used to register/login/logout users. * The created instances implements the {@link model.User} interface * @name User * @type binding.UserFactory * @memberOf EntityManager.prototype */ /** * An Role factory for role objects. * The Role factory can be called to create new instances of roles, later on users can be attached to roles to manage the * access permissions through this role * The created instances implements the {@link model.Role} interface * @name Role * @memberOf EntityManager.prototype * @type binding.EntityFactory<model.Role> */ /** * An Device factory for user objects. * The Device factory can be called to create new instances of devices or can be used to register, push to and * check registration status of devices. * @name Device * @memberOf EntityManager.prototype * @type binding.DeviceFactory */ /** * An Object factory for entity or embedded objects, * that can be accessed by the type name of the entity type. * An object factory can be called to create new instances of the type. * The created instances implements the {@link binding.Entity} or the {@link binding.Managed} interface * whenever the class is an entity or embedded object * @name [YourEntityClass: string] * @memberOf EntityManager.prototype * @type {*} */ /** * A File factory for file objects. * The file factory can be called to create new instances for files. * The created instances implements the {@link binding.File} interface * @name File * @memberOf EntityManager.prototype * @type binding.FileFactory */ module.exports = EntityManager;
lib/EntityManager.js
"use strict"; var message = require('./message'); var error = require('./error'); var binding = require('./binding'); var util = require('./util'); var query = require('./query'); var UserFactory = require('./binding/UserFactory'); var EntityTransaction = require('./EntityTransaction'); var Metadata = require('./util/Metadata'); var Message = require('./connector/Message'); var BloomFilter = require('./caching/BloomFilter'); var StatusCode = Message.StatusCode; /** * @alias EntityManager * @extends util.Lockable */ class EntityManager extends util.Lockable { /** * Determine whether the entity manager is open. * true until the entity manager has been closed * @type boolean */ get isOpen() { return !!this._connector; } /** * The authentication token if the user is logged in currently * @type String */ get token() { return this.tokenStorage.token; } get isCachingDisabled() { return !this.bloomFilter; } /** * The authentication token if the user is logged in currently * @param {String} value */ set token(value) { this.tokenStorage.update(value); } /** * @param {EntityManagerFactory} entityManagerFactory The factory which of this entityManager instance */ constructor(entityManagerFactory) { super(); /** * Log messages can created by calling log directly as function, with a specific log level or with the helper * methods, which a members of the log method. * * Logs will be filtered by the client logger and the before they persisted. The default log level is * 'info' therefore all log messages below the given message aren't persisted. * * Examples: * <pre class="prettyprint"> // default log level ist info db.log('test message %s', 'my string'); // info: test message my string // pass a explicit log level as the first argument, one of ('trace', 'debug', 'info', 'warn', 'error') db.log('warn', 'test message %d', 123); // warn: test message 123 // debug log level will not be persisted by default, since the default logging level is info db.log('debug', 'test message %j', {number: 123}, {}); // debug: test message {"number":123} // data = {} // One additional json object can be provided, which will be persisted together with the log entry db.log('info', 'test message %s, %s', 'first', 'second', {number: 123}); // info: test message first, second // data = {number: 123} //use the log level helper db.log.info('test message', 'first', 'second', {number: 123}); // info: test message first second // data = {number: 123} //change the default log level to trace, i.e. all log levels will be persisted, note that the log level can be //additionally configured in the baqend db.log.level = 'trace'; //trace will be persisted now db.log.trace('test message', 'first', 'second', {number: 123}); // info: test message first second // data = {number: 123} * </pre> * * @type util.Logger */ this.log = util.Logger.create(this); /** * The connector used for requests * @type connector.Connector * @private */ this._connector = null; /** * All managed and cached entity instances * @type Map<String,binding.Entity> */ this._entities = null; /** @type EntityManagerFactory */ this.entityManagerFactory = entityManagerFactory; /** @type metamodel.Metamodel */ this.metamodel = entityManagerFactory.metamodel; /** @type util.Code */ this.code = entityManagerFactory.code; /** @type util.Modules */ this.modules = null; /** * The current logged in user object * @type model.User */ this.me = null; /** * Returns true if the device token is already registered, otherwise false. * @type boolean */ this.isDeviceRegistered = false; /** * Returns the tokenStorage which will be used to authorize all requests. * @type {util.TokenStorage} */ this.tokenStorage = null; /** * @type {caching.BloomFilter} */ this.bloomFilter = null; /** * Set of object ids that were revalidated after the Bloom filter was loaded. */ this.cacheWhiteList = null; /** * Set of object ids that were updated but are not yet included in the bloom filter. * This set essentially implements revalidation by side effect which does not work in Chrome. */ this.cacheBlackList = null; /** * Bloom filter refresh interval in seconds. * * @type {number} */ this.bloomFilterRefresh = 60; /** * Bloom filter refresh Promise * */ this._bloomFilterLock = new util.Lockable(); } /** * Connects this entityManager, used for synchronous and asynchronous initialization * @param {connector.Connector} connector * @param {Object} connectData * @param {util.TokenStorage} tokenStorage The used tokenStorage for token persistence */ connected(connector, connectData, tokenStorage) { this._connector = connector; this.tokenStorage = tokenStorage; this.bloomFilterRefresh = this.entityManagerFactory.staleness; this._entities = {}; this.File = binding.FileFactory.create(this); this._createObjectFactory(this.metamodel.embeddables); this._createObjectFactory(this.metamodel.entities); this.transaction = new EntityTransaction(this); this.modules = new util.Modules(this, connector); if (connectData) { this.isDeviceRegistered = !!connectData.device; if (connectData.user && connectData.token == tokenStorage.token) this._updateUser(connectData.user, true); if (this.bloomFilterRefresh > 0 && connectData.bloomFilter && util.atob && !util.isNode) { this.updateBloomFilter(connectData.bloomFilter); } } } /** * @param {metamodel.ManagedType[]} types * @return {binding.ManagedFactory} * @private */ _createObjectFactory(types) { Object.keys(types).forEach(function(ref) { var type = this.metamodel.managedType(ref); var name = type.name; if (this[name]) { type.typeConstructor = this[name]; Object.defineProperty(this, name, { value: type.createObjectFactory(this) }); } else { Object.defineProperty(this, name, { get() { Object.defineProperty(this, name, { value: type.createObjectFactory(this) }); return this[name]; }, set(typeConstructor) { type.typeConstructor = typeConstructor; }, configurable: true }); } }, this); } _sendOverSocket(message) { message.token = this.token; this._connector.sendOverSocket(message); } _subscribe(topic, cb) { this._connector.subscribe(topic, cb); } _unsubscribe(topic, cb) { this._connector.unsubscribe(topic, cb); } send(message) { message.tokenStorage = this.tokenStorage; return this._connector.send(message).catch((e) => { if (e.status == StatusCode.BAD_CREDENTIALS) { this._logout(); } throw e; }); } /** * Get an instance, whose state may be lazily fetched. If the requested instance does not exist * in the database, the EntityNotFoundError is thrown when the instance state is first accessed. * The application should not expect that the instance state will be available upon detachment, * unless it was accessed by the application while the entity manager was open. * * @param {(Class<binding.Entity>|string)} entityClass * @param {string=} key */ getReference(entityClass, key) { var id, type; if (key) { type = this.metamodel.entity(entityClass); if (key.indexOf('/db/') == 0) { id = key; } else { id = type.ref + '/' + encodeURIComponent(key); } } else { id = entityClass; type = this.metamodel.entity(id.substring(0, id.indexOf('/', 4))); //skip /db/ } var entity = this._entities[id]; if (!entity) { entity = type.create(); var metadata = Metadata.get(entity); metadata.id = id; metadata.setUnavailable(); this._attach(entity); } return entity; } /** * Creates an instance of Query.Builder for query creation and execution. The Query results are instances of the * resultClass argument. * @param {Class<*>=} resultClass - the type of the query result * @return {query.Builder<*>} A query builder to create one ore more queries for the specified class */ createQueryBuilder(resultClass) { return new query.Builder(this, resultClass); } /** * Clear the persistence context, causing all managed entities to become detached. * Changes made to entities that have not been flushed to the database will not be persisted. */ clear() { this._entities = {}; } /** * Close an application-managed entity manager. After the close method has been invoked, * all methods on the EntityManager instance and any Query and TypedQuery objects obtained from it * will throw the IllegalStateError except for transaction, and isOpen (which will return false). * If this method is called when the entity manager is associated with an active transaction, * the persistence context remains managed until the transaction completes. */ close() { this._connector = null; return this.clear(); } /** * Check if the instance is a managed entity instance belonging to the current persistence context. * @param {binding.Entity} entity - entity instance * @returns {boolean} boolean indicating if entity is in persistence context */ contains(entity) { return !!entity && this._entities[entity.id] === entity; } /** * Check if an object with the id from the given entity is already attached. * @param {binding.Entity} entity - entity instance * @returns {boolean} boolean indicating if entity with same id is attached */ containsById(entity) { return !!(entity && this._entities[entity.id]); } /** * Remove the given entity from the persistence context, causing a managed entity to become detached. * Unflushed changes made to the entity if any (including removal of the entity), * will not be synchronized to the database. Entities which previously referenced the detached entity will continue to reference it. * @param {binding.Entity} entity - entity instance */ detach(entity) { var state = Metadata.get(entity); return state.withLock(() => { this.removeReference(entity); return Promise.resolve(entity); }); } /** * Resolve the depth by loading the referenced objects of the given entity. * * @param {binding.Entity} entity - entity instance * @param {Object} [options] The load options * @return {Promise<binding.Entity>} */ resolveDepth(entity, options) { if (!options || !options.depth) return Promise.resolve(entity); options.resolved = options.resolved || []; var promises = []; var subOptions = Object.assign({}, options, { depth: options.depth === true ? true : options.depth - 1 }); this.getSubEntities(entity, 1).forEach((subEntity) => { if (subEntity != null && !~options.resolved.indexOf(subEntity)) { options.resolved.push(subEntity); promises.push(this.load(subEntity.id, null, subOptions)); } }); return Promise.all(promises).then(function() { return entity; }); } /** * Search for an entity of the specified oid. * If the entity instance is contained in the persistence context, it is returned from there. * @param {(Class<binding.Entity>|string)} entityClass - entity class * @param {String} oid - Object ID * @param {Object} [options] The load options. * @return {Promise<binding.Entity>} the loaded entity or null */ load(entityClass, oid, options) { options = options || {}; var entity = this.getReference(entityClass, oid); var state = Metadata.get(entity); if (!options.refresh && options.local && state.isAvailable) { return this.resolveDepth(entity, options); } var msg = new message.GetObject(state.bucket, state.key); this.ensureCacheHeader(entity.id, msg, options.refresh); return this.send(msg).then((response) => { // refresh object if loaded older version from cache // chrome doesn't using cache when ifNoneMatch is set if (entity.version > response.entity.version) { options.refresh = true; return this.load(entityClass, oid, options) } this.addToWhiteList(response.entity.id); if (response.status != StatusCode.NOT_MODIFIED) { state.setJson(response.entity); } state.setPersistent(); return this.resolveDepth(entity, options); }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { this.removeReference(entity); state.setRemoved(); return null; } else { throw e; } }); } /** * @param {binding.Entity} entity * @param {Object} options * @return {Promise<binding.Entity>} */ insert(entity, options) { options = options || {}; var isNew; return this._save(entity, options, function(state, json) { if (state.version) throw new error.PersistentError('Existing objects can\'t be inserted.'); isNew = !state.id; return new message.CreateObject(state.bucket, json); }).then((val) => { if (isNew) this._attach(entity); return val; }); } /** * @param {binding.Entity} entity * @param {Object} options * @return {Promise<binding.Entity>} */ update(entity, options) { options = options || {}; return this._save(entity, options, function(state, json) { if (!state.version) throw new error.PersistentError("New objects can't be inserted."); if (options.force) { delete json.version; return new message.ReplaceObject(state.bucket, state.key, json) .ifMatch('*'); } else { return new message.ReplaceObject(state.bucket, state.key, json) .ifMatch(state.version); } }); } /** * @param {binding.Entity} entity * @param {Object} options The save options * @param {boolean=} withoutLock Set true to save the entity without locking * @return {Promise<binding.Entity>} */ save(entity, options, withoutLock) { options = options || {}; var msgFactory = function(state, json) { if (options.force) { if (!state.id) throw new error.PersistentError("New special objects can't be forcedly saved."); delete json.version; return new message.ReplaceObject(state.bucket, state.key, json); } else if (state.version) { return new message.ReplaceObject(state.bucket, state.key, json) .ifMatch(state.version); } else { return new message.CreateObject(state.bucket, json); } }; return withoutLock ? this._locklessSave(entity, options, msgFactory) : this._save(entity, options, msgFactory) } /** * @param {binding.Entity} entity * @param {Function} cb pre-safe callback * @return {Promise<binding.Entity>} */ optimisticSave(entity, cb) { return Metadata.get(entity).withLock(() => { return this._optimisticSave(entity, cb); }); } /** * @param {binding.Entity} entity * @param {Function} cb pre-safe callback * @return {Promise<binding.Entity>} * @private */ _optimisticSave(entity, cb) { var abort = false; var abortFn = function() { abort = true; }; var promise = Promise.resolve(cb(entity, abortFn)); if (abort) return Promise.resolve(entity); return promise.then(() => { return this.save(entity, {}, true).catch((e) => { if (e.status == 412) { return this.refresh(entity, {}).then(() => { return this._optimisticSave(entity, cb); }); } else { throw e; } }); }); } /** * Save the object state without locking * @param {binding.Entity} entity * @param {Object} options * @param {Function} msgFactory * @return {Promise.<binding.Entity>} * @private */ _locklessSave(entity, options, msgFactory) { this.attach(entity); var state = Metadata.get(entity); var refPromises; var json; if (state.isAvailable) { //getting json will check all collections changes, therefore we must do it before proofing the dirty state json = state.getJson(); } if (state.isDirty) { if (!options.refresh) { state.setPersistent(); } var sendPromise = this.send(msgFactory(state, json)).then((response) => { if (options.refresh) { state.setJson(response.entity); state.setPersistent(); } else { state.setJsonMetadata(response.entity); } return entity; }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { this.removeReference(entity); state.setRemoved(); return null; } else { state.setDirty(); throw e; } }); refPromises = [sendPromise]; } else { refPromises = [Promise.resolve(entity)]; } var subOptions = Object.assign({}, options); subOptions.depth = 0; this.getSubEntities(entity, options.depth).forEach((sub) => { refPromises.push(this._save(sub, subOptions, msgFactory)); }); return Promise.all(refPromises).then(() => entity); } /** * Save and lock the object state * @param {binding.Entity} entity * @param {Object} options * @param {Function} msgFactory * @return {Promise.<binding.Entity>} * @private */ _save(entity, options, msgFactory) { this.ensureBloomFilterFreshness(); var state = Metadata.get(entity); if (state.version) { this.addToBlackList(entity.id); } return state.withLock(() => { return this._locklessSave(entity, options, msgFactory); }); } /** * Returns all referenced sub entities for the given depth and root entity * @param {binding.Entity} entity * @param {boolean|number} depth * @param {binding.Entity[]} [resolved] * @param {binding.Entity=} initialEntity * @returns {binding.Entity[]} */ getSubEntities(entity, depth, resolved, initialEntity) { resolved = resolved || []; if (!depth) { return resolved; } initialEntity = initialEntity || entity; var state = Metadata.get(entity); for (let value of state.type.references()) { this.getSubEntitiesByPath(entity, value.path).forEach((subEntity) => { if (!~resolved.indexOf(subEntity) && subEntity != initialEntity) { resolved.push(subEntity); resolved = this.getSubEntities(subEntity, depth === true ? depth : depth - 1, resolved, initialEntity); } }); } return resolved; } /** * Returns all referenced one level sub entities for the given path * @param {binding.Entity} entity * @param {Array<string>} path * @returns {binding.Entity[]} */ getSubEntitiesByPath(entity, path) { var subEntities = [entity]; path.forEach((attributeName) => { var tmpSubEntities = []; subEntities.forEach((subEntity) => { var curEntity = subEntity[attributeName]; if (!curEntity) return; var attribute = this.metamodel.managedType(subEntity.constructor).getAttribute(attributeName); if (attribute.isCollection) { for (let entry of curEntity.entries()) { tmpSubEntities.push(entry[1]); attribute.keyType && attribute.keyType.isEntity && tmpSubEntities.push(entry[0]); } } else { tmpSubEntities.push(curEntity); } }); subEntities = tmpSubEntities; }); return subEntities; } /** * Delete the entity instance. * @param {binding.Entity} entity * @param {Object} options The delete options * @return {Promise<binding.Entity>} */ 'delete'(entity, options) { options = options || {}; this.attach(entity); var state = Metadata.get(entity); return state.withLock(() => { if (!state.version && !options.force) throw new error.IllegalEntityError(entity); var msg = new message.DeleteObject(state.bucket, state.key); this.addToBlackList(entity.id); if (!options.force) msg.ifMatch(state.version); var refPromises = [this.send(msg).then(() => { this.removeReference(entity); state.setRemoved(); return entity; })]; var subOptions = Object.assign({}, options); subOptions.depth = 0; this.getSubEntities(entity, options.depth).forEach((sub) => { refPromises.push(this.delete(sub, subOptions)); }); return Promise.all(refPromises).then(function() { return entity; }); }); } /** * Synchronize the persistence context to the underlying database. * * @returns {Promise<*>} */ flush(doneCallback, failCallback) { // TODO: implement this } /** * Make an instance managed and persistent. * @param {binding.Entity} entity - entity instance */ persist(entity) { this.attach(entity); } /** * Refresh the state of the instance from the database, overwriting changes made to the entity, if any. * @param {binding.Entity} entity - entity instance * @param {Object} options The refresh options * @return {Promise<binding.Entity>} */ refresh(entity, options) { options = options || {}; options.refresh = true; return this.load(entity.id, null, options); } /** * Attach the instance to this database context, if it is not already attached * @param {binding.Entity} entity The entity to attach */ attach(entity) { if (!this.contains(entity)) { var type = this.metamodel.entity(entity.constructor); if (!type) throw new error.IllegalEntityError(entity); if (this.containsById(entity)) throw new error.EntityExistsError(entity); this._attach(entity); } } _attach(entity) { var metadata = Metadata.get(entity); if (metadata.isAttached) { if (metadata.db != this) { throw new error.EntityExistsError(entity); } } else { metadata.db = this; } if (!metadata.id) { if (metadata.type.name != 'User' && metadata.type.name != 'Role' && metadata.type.name != 'logs.AppLog') { metadata.id = '/db/' + metadata.type.name + '/' + util.uuid(); } } if (metadata.id) { this._entities[metadata.id] = entity; } } removeReference(entity) { var state = Metadata.get(entity); if (!state) throw new error.IllegalEntityError(entity); delete this._entities[state.id]; } register(user, password, loginOption) { let login = loginOption > UserFactory.LoginOption.NO_LOGIN; if (this.me && login) { throw new error.PersistentError('User is already logged in.'); } return this.withLock(() => { var msg = new message.Register({ user: user, password: password, login: login }); return this._userRequest(msg, loginOption); }); } login(username, password, loginOption) { if (this.me) throw new error.PersistentError('User is already logged in.'); return this.withLock(() => { let msg = new message.Login({ username: username, password: password }); return this._userRequest(msg, loginOption); }); } logout() { return this.withLock(() => { return this.send(new message.Logout()).then(this._logout.bind(this)); }); } loginWithOAuth(provider, clientID, options) { if (this.me) throw new error.PersistentError('User is already logged in.'); options = Object.assign({ title: "Login with " + provider, timeout: 5 * 60 * 1000, state: {}, loginOption: true }, options); var msg; if (Message[provider + 'OAuth']) { msg = new Message[provider + 'OAuth'](clientID, options.scope, JSON.stringify(options.state)); } else { throw new Error('OAuth provider ' + provider + ' not supported.'); } var req = this._userRequest(msg, options.loginOption); var w = open(msg.request.path, options.title, 'width=' + options.width + ',height=' + options.height); return new Promise((resolve, reject) => { var timeout = setTimeout(() => { reject(new error.PersistentError('OAuth login timeout.')); }, options.timeout); req.then(resolve, reject).then(() => { clearTimeout(timeout); }); }); } renew() { return this.withLock(() => { var msg = new message.Me(); return this._userRequest(msg, true); }); } newPassword(username, password, newPassword) { return this.withLock(() => { var msg = new message.NewPassword({ username: username, password: password, newPassword: newPassword }); return this.send(msg).then((response) => { this._updateUser(response.entity); }); }); } _updateUser(obj, updateMe) { var user = this.getReference(obj.id); var metadata = Metadata.get(user); metadata.setJson(obj); metadata.setPersistent(); if (updateMe) this.me = user; return user; } _logout() { this.me = null; this.token = null; } _userRequest(msg, loginOption) { let login = loginOption > UserFactory.LoginOption.NO_LOGIN; if (login) { this.tokenStorage.temporary = loginOption < UserFactory.LoginOption.PERSIST_LOGIN; } return this.send(msg).then((response) => { if (response.entity) { return this._updateUser(response.entity, login); } }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { if (login) this._logout(); return null; } else { throw e; } }); } registerDevice(os, token, device) { var msg = new message.DeviceRegister({ token: token, devicetype: os, device: device }); msg.withCredentials = true; return this.send(msg); } checkDeviceRegistration() { return this.send(new message.DeviceRegistered()).then(() => { return this.isDeviceRegistered = true; }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { return this.isDeviceRegistered = false; } else { throw e; } }); } pushDevice(pushMessage) { return this.send(new message.DevicePush(pushMessage)); } /** * The given entity will be checked by the validation code of the entity type. * * @param {binding.Entity} entity * @returns {util.ValidationResult} result */ validate(entity) { var type = Metadata.get(entity).type; var result = new util.ValidationResult(); for (var iter = type.attributes(), item; !(item = iter.next()).done;) { var validate = new util.Validator(item.value.name, entity); result.fields[validate.key] = validate; } var validationCode = type.validationCode; if (validationCode) { validationCode(result.fields); } return result; } /** * Adds the given object id to the cacheWhiteList if needed. * @param {string} objectId The id to add. */ addToWhiteList(objectId) { if (!this.isCachingDisabled) { if (this.bloomFilter.contains(objectId)) { this.cacheWhiteList.add(objectId); } this.cacheBlackList.delete(objectId); } } /** * Adds the given object id to the cacheBlackList if needed. * @param {string} objectId The id to add. */ addToBlackList(objectId) { if (!this.isCachingDisabled) { if (!this.bloomFilter.contains(objectId)) { this.cacheBlackList.add(objectId); } this.cacheWhiteList.delete(objectId); } } refreshBloomFilter() { if (this.isCachingDisabled) return Promise.resolve(); var msg = new message.GetBloomFilter(); return this.send(msg).then((response) => { this.updateBloomFilter(response.entity); return this.bloomFilter; }); } updateBloomFilter(bloomFilter) { this.bloomFilter = new BloomFilter(bloomFilter); this.cacheWhiteList = new Set(); this.cacheBlackList = new Set(); } /** * Checks the freshness of the bloom filter and does a reload if necessary */ ensureBloomFilterFreshness() { if (this.isCachingDisabled) return; var now = new Date().getTime(); var refreshRate = this.bloomFilterRefresh * 1000; if (this._bloomFilterLock.isReady && now - this.bloomFilter.creation > refreshRate) { this._bloomFilterLock.withLock(() => this.refreshBloomFilter()); } } /** * Checks for a given id, if revalidation is required, the resource is stale or caching was disabled * @param {string} id The object id to check * @returns {boolean} Indicates if the resource must be revalidated */ mustRevalidate(id) { if (util.isNode) return false; this.ensureBloomFilterFreshness(); var refresh = this.isCachingDisabled || !this._bloomFilterLock.isReady; refresh = refresh || (!this.cacheWhiteList.has(id) && (this.cacheBlackList.has(id) || this.bloomFilter.contains(id))); return refresh; } /** * * @param {string} id To check the bloom filter * @param {connector.Message} message To attach the headers * @param {boolean} refresh To force the reload headers */ ensureCacheHeader(id, message, refresh) { refresh = refresh || this.mustRevalidate(id); if (refresh) { message.noCache(); } } /** * Creates a absolute url for the given relative one * @param {string} relativePath the relative url * @param {boolean=} authorize indicates if authorization credentials should be generated and be attached to the url * @return {string} a absolute url wich is optionaly signed with a resource token which authenticates the currently * logged in user */ createURL(relativePath, authorize) { var path = this._connector.basePath + relativePath; var append = false; if (authorize && this.me) { path = this.tokenStorage.signPath(path); append = true; } else { path = path.split('/').map(encodeURIComponent).join('/'); } if (this.mustRevalidate(relativePath)) { path = path + (append ? '&' : '?') + 'BCB'; } return this._connector.origin + path; } } /** * Constructor for a new List collection * @function * @param {...*} args Same arguments can be passed as the Array constructor takes * @return {void} The new created List */ EntityManager.prototype.List = Array; /** * Constructor for a new Set collection * @function * @param {Iterable<*>=} collection The initial array or collection to initialize the new Set * @return {void} The new created Set */ EntityManager.prototype.Set = Set; /** * Constructor for a new Map collection * @function * @param {Iterable<*>=} collection The initial array or collection to initialize the new Map * @return {void} The new created Map */ EntityManager.prototype.Map = Map; /** * Constructor for a new GeoPoint * @function * @param {string|number|Object|Array<number>} [latitude] A coordinate pair (latitude first), a GeoPoint like object or the GeoPoint's latitude * @param {number=} longitude The GeoPoint's longitude * @return {void} The new created GeoPoint */ EntityManager.prototype.GeoPoint = require('./GeoPoint'); /** * An User factory for user objects. * The User factory can be called to create new instances of users or can be used to register/login/logout users. * The created instances implements the {@link model.User} interface * @name User * @type binding.UserFactory * @memberOf EntityManager.prototype */ /** * An Role factory for role objects. * The Role factory can be called to create new instances of roles, later on users can be attached to roles to manage the * access permissions through this role * The created instances implements the {@link model.Role} interface * @name Role * @memberOf EntityManager.prototype * @type binding.EntityFactory<model.Role> */ /** * An Device factory for user objects. * The Device factory can be called to create new instances of devices or can be used to register, push to and * check registration status of devices. * @name Device * @memberOf EntityManager.prototype * @type binding.DeviceFactory */ /** * An Object factory for entity or embedded objects, * that can be accessed by the type name of the entity type. * An object factory can be called to create new instances of the type. * The created instances implements the {@link binding.Entity} or the {@link binding.Managed} interface * whenever the class is an entity or embedded object * @name [YourEntityClass: string] * @memberOf EntityManager.prototype * @type {*} */ /** * A File factory for file objects. * The file factory can be called to create new instances for files. * The created instances implements the {@link binding.File} interface * @name File * @memberOf EntityManager.prototype * @type binding.FileFactory */ module.exports = EntityManager;
Fix empty promise in newPassword
lib/EntityManager.js
Fix empty promise in newPassword
<ide><path>ib/EntityManager.js <ide> }); <ide> <ide> return this.send(msg).then((response) => { <del> this._updateUser(response.entity); <add> return this._updateUser(response.entity); <ide> }); <ide> }); <ide> }
Java
agpl-3.0
36a2cade1ad0621c8cd867f07ffa35849f566595
0
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
/* * DataImportOptionsUiSav.java * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.environment.dataimport; import org.rstudio.core.client.widget.Operation; import org.rstudio.studio.client.common.HelpLink; import org.rstudio.studio.client.workbench.views.environment.dataimport.model.DataImportAssembleResponse; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Widget; public class DataImportOptionsUiSav extends DataImportOptionsUi { private static DataImportOptionsUiSavUiBinder uiBinder = GWT .create(DataImportOptionsUiSavUiBinder.class); interface DataImportOptionsUiSavUiBinder extends UiBinder<Widget, DataImportOptionsUiSav> { } public DataImportOptionsUiSav(DataImportModes mode) { initWidget(uiBinder.createAndBindUi(this)); initDefaults(mode); initEvents(); } void initDefaults(DataImportModes mode) { formatListBox_.addItem("SAV", "sav"); formatListBox_.addItem("DTA", "dta"); formatListBox_.addItem("POR", "por"); formatListBox_.addItem("SAS", "sas"); formatListBox_.addItem("Stata", "stata"); switch(mode) { case SAS: formatListBox_.setSelectedIndex(3); break; case Stata: formatListBox_.setSelectedIndex(4); break; default: formatListBox_.setSelectedIndex(0); break; } openDataViewerCheckBox_.setValue(true); updateEnabled(); } @Override public DataImportOptionsSav getOptions() { return DataImportOptionsSav.create( nameTextBox_.getValue(), !fileChooser_.getText().isEmpty() ? fileChooser_.getText() : null, formatListBox_.getSelectedValue(), openDataViewerCheckBox_.getValue().booleanValue() ); } @Override public void setAssembleResponse(DataImportAssembleResponse response) { nameTextBox_.setText(response.getDataName()); updateEnabled(); } @Override public void clearOptions() { nameTextBox_.setText(""); updateEnabled(); } @Override public void setImportLocation(String importLocation) { nameTextBox_.setText(""); String[] components = importLocation.split("\\."); if (components.length > 0) { String extension = components[components.length - 1].toLowerCase(); for (int idx = 0; idx < formatListBox_.getItemCount(); idx++) { if (formatListBox_.getValue(idx) == extension) { formatListBox_.setSelectedIndex(idx); } } } } @Override public HelpLink getHelpLink() { return new HelpLink( "Reading data using haven", "import_haven", false, true); } @UiFactory DataImportFileChooser makeLocationChooser() { DataImportFileChooser dataImportFileChooser = new DataImportFileChooser( new Operation() { @Override public void execute() { updateEnabled(); triggerChange(); } }, false); return dataImportFileChooser; } void initEvents() { ValueChangeHandler<String> valueChangeHandler = new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> arg0) { updateEnabled(); triggerChange(); } }; ChangeHandler changeHandler = new ChangeHandler() { @Override public void onChange(ChangeEvent arg0) { updateEnabled(); triggerChange(); } }; ValueChangeHandler<Boolean> booleanValueChangeHandler = new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> arg0) { updateEnabled(); triggerChange(); } }; nameTextBox_.addValueChangeHandler(valueChangeHandler); formatListBox_.addChangeHandler(changeHandler); openDataViewerCheckBox_.addValueChangeHandler(booleanValueChangeHandler); } void updateEnabled() { if (formatListBox_.getSelectedValue() == "sas") { fileChooser_.setEnabled(true); } else { fileChooser_.setEnabled(false); } } @UiField ListBox formatListBox_; @UiField DataImportFileChooser fileChooser_; @UiField CheckBox openDataViewerCheckBox_; }
src/gwt/src/org/rstudio/studio/client/workbench/views/environment/dataimport/DataImportOptionsUiSav.java
/* * DataImportOptionsUiSav.java * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.environment.dataimport; import org.rstudio.core.client.widget.Operation; import org.rstudio.studio.client.common.HelpLink; import org.rstudio.studio.client.workbench.views.environment.dataimport.model.DataImportAssembleResponse; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Widget; public class DataImportOptionsUiSav extends DataImportOptionsUi { private static DataImportOptionsUiSavUiBinder uiBinder = GWT .create(DataImportOptionsUiSavUiBinder.class); interface DataImportOptionsUiSavUiBinder extends UiBinder<Widget, DataImportOptionsUiSav> { } public DataImportOptionsUiSav(DataImportModes mode) { initWidget(uiBinder.createAndBindUi(this)); initDefaults(mode); initEvents(); } void initDefaults(DataImportModes mode) { formatListBox_.addItem("SAV", "sav"); formatListBox_.addItem("DTA", "dta"); formatListBox_.addItem("POR", "por"); formatListBox_.addItem("SAS", "sas"); formatListBox_.addItem("Stata", "stata"); switch(mode) { case SAS: formatListBox_.setSelectedIndex(3); break; case Stata: formatListBox_.setSelectedIndex(4); break; default: formatListBox_.setSelectedIndex(0); break; } openDataViewerCheckBox_.setValue(true); updateEnabled(); } @Override public DataImportOptionsSav getOptions() { return DataImportOptionsSav.create( nameTextBox_.getValue(), !fileChooser_.getText().isEmpty() ? fileChooser_.getText() : null, formatListBox_.getSelectedValue(), openDataViewerCheckBox_.getValue().booleanValue() ); } @Override public void setAssembleResponse(DataImportAssembleResponse response) { nameTextBox_.setText(response.getDataName()); updateEnabled(); } @Override public void clearOptions() { nameTextBox_.setText(""); updateEnabled(); } @Override public void setImportLocation(String importLocation) { nameTextBox_.setText(""); String[] components = importLocation.split("\\."); if (components.length > 0) { String extension = components[components.length - 1].toLowerCase(); for (int idx = 0; idx < formatListBox_.getItemCount(); idx++) { if (formatListBox_.getValue(idx) == extension) { formatListBox_.setSelectedIndex(idx); } } } } @Override public HelpLink getHelpLink() { return new HelpLink( "Reading statistical data using haven", "import_haven", false, true); } @UiFactory DataImportFileChooser makeLocationChooser() { DataImportFileChooser dataImportFileChooser = new DataImportFileChooser( new Operation() { @Override public void execute() { updateEnabled(); triggerChange(); } }, false); return dataImportFileChooser; } void initEvents() { ValueChangeHandler<String> valueChangeHandler = new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> arg0) { updateEnabled(); triggerChange(); } }; ChangeHandler changeHandler = new ChangeHandler() { @Override public void onChange(ChangeEvent arg0) { updateEnabled(); triggerChange(); } }; ValueChangeHandler<Boolean> booleanValueChangeHandler = new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> arg0) { updateEnabled(); triggerChange(); } }; nameTextBox_.addValueChangeHandler(valueChangeHandler); formatListBox_.addChangeHandler(changeHandler); openDataViewerCheckBox_.addValueChangeHandler(booleanValueChangeHandler); } void updateEnabled() { if (formatListBox_.getSelectedValue() == "sas") { fileChooser_.setEnabled(true); } else { fileChooser_.setEnabled(false); } } @UiField ListBox formatListBox_; @UiField DataImportFileChooser fileChooser_; @UiField CheckBox openDataViewerCheckBox_; }
address pr feedback
src/gwt/src/org/rstudio/studio/client/workbench/views/environment/dataimport/DataImportOptionsUiSav.java
address pr feedback
<ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/environment/dataimport/DataImportOptionsUiSav.java <ide> public HelpLink getHelpLink() <ide> { <ide> return new HelpLink( <del> "Reading statistical data using haven", <add> "Reading data using haven", <ide> "import_haven", <ide> false, <ide> true);
JavaScript
agpl-3.0
1361ce2b2bcf9cce55fed68876d0c6c44fb4923f
0
manuel/edgelisp,manuel/edgelisp
/* CyberLisp: A Lisp that compiles to JavaScript 1.5. Copyright (C) 2008, 2011 by Manuel Simoni. CyberLisp 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, or (at your option) any later version. CyberLisp 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 GNU Emacs; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Lisp runtime: this file should contain all functions needed to run compiled Lisp code. At the moment, it does have dependencies on name mangling functions in `compiler.js', though. Lisp code that does use `eval' will always need to include the compiler too. */ /*** Strings ***/ function Lisp_string(s) { this.s = s; } /*** Numbers ***/ function lisp_number(numrepr) { return jsnums.fromString(numrepr); } /*** Functions ***/ function lisp_bif_fast_apply(_key_, fun, _arguments) { return fun.apply(null, _arguments); } /*** Forms ***/ function Lisp_number_form(sign, integral_digits, fractional_digits) { this.formt = "number"; this.sign = sign; this.integral_digits = integral_digits; this.fractional_digits = fractional_digits; } function Lisp_string_form(s) { this.formt = "string"; this.s = s; } function Lisp_symbol_form(name) { this.formt = "symbol"; this.name = name; } function Lisp_compound_form(elts) { this.formt = "compound"; this.elts = elts; } /* This whole comments-as-forms business is silly, but atm I don't know another way to have comments ignored. */ function Lisp_comment_form(contents) { this.formt = "comment"; this.contents = contents; } /*** Utilities for generated code. ***/ function lisp_undefined_identifier(name, namespace) { return lisp_error("Undefined " + namespace, name); } /* Used inside lambdas. */ function lisp_arity_min(length, min) { if (length < min) throw Error("Too few arguments "); } function lisp_arity_min_max(length, min, max) { lisp_arity_min(length, min); if (length > max) throw Error("Too many arguments "); } /* Returns the sequence of arguments to which the rest parameter is bound; called with a function's arguments and the count of positional (required and optional) parameters of the function. */ function lisp_rest_param(_arguments, max) { var args = []; var offset = 1 + max; // Skip calling convention argument. var len = _arguments.length; for (var i = offset; i < len; i++) { args[i - offset] = _arguments[i]; } return args; } /* Used inside lambdas for checking arguments against their types, if any. */ function lisp_check_type(obj, type) { if (!lisp_subtypep(lisp_type_of(obj), type)) lisp_error("Type error", obj); } function lisp_show(obj) { // show is defined as a generic function in boot.lisp if (typeof(_lisp_function_show) !== "undefined") return _lisp_function_show(null, obj); else return JSON.stringify(obj); } function lisp_array_contains(array, elt) { for (var i in array) { if (array[i] == elt) return true; } return false; } function lisp_iter_dict(dict, fun) { for (var k in dict) { if (dict.hasOwnProperty(k)) fun(k); } } function lisp_lists_equal(list1, list2) { if (list1.length != list2.length) return false; for (var i = 0, len = list1.length; i < len; i++) { if (list1[i] !== list2[i]) return false; } return true; } // fixme: should SIGNAL error function lisp_error(message, arg) { throw Error(message + ": " + JSON.stringify(arg)); } function lisp_assert(value, message, arg) { if (!value) lisp_error(message, arg); return value; } function lisp_assert_not_null(value, message, arg) { lisp_assert(value != null, message, arg); return value; } function lisp_assert_number(value, message, arg) { // fixme lisp_assert(typeof value == "number", message, arg); return value; k} function lisp_assert_string(value, message, arg) { lisp_assert(typeof value == "string", message, arg); return value; } function lisp_assert_nonempty_string(value, message, arg) { lisp_assert_string(value, message, arg); lisp_assert(value.length > 0, message, arg); return value; } function lisp_assert_function(value, message, arg) { lisp_assert(typeof value == "function", message, arg); return value; } function lisp_assert_symbol_form(value, message, arg) { lisp_assert(typeof value == "object", message, arg); lisp_assert(value.formt == "symbol", message, arg); lisp_assert_nonempty_string(value.name, message, arg); return value; } function lisp_assert_compound_form(value, message, arg) { lisp_assert(typeof value == "object", message, arg); lisp_assert(value.formt == "compound", message, arg); lisp_assert_not_null(value.elts, message, arg); lisp_assert_not_null(value.elts.length, message, arg); return value; } /*** Built-in form manipulation functions ***/ /* Applies a Lisp function to the elements of a compound form, a simple form of destructuring. The form's elements are simply supplied as the function's positional arguments. */ function lisp_bif_compound_apply(_key_, fun, form) { var _key_ = null; var args = [ _key_ ].concat(form.elts); var thisArg = null; return fun.apply(thisArg, args); } /* Creates a compound form from all positional arguments, which must be forms. */ function lisp_bif_make_compound(_key_) { var elts = []; for (var i = 1; i < arguments.length; i++) { var elt = arguments[i]; lisp_assert(elt && elt.formt, "make-compound", elt); elts = elts.concat(elt); } return new Lisp_compound_form(elts); } /* Creates a compound form by appending all positional arguments, which must be compound forms or lists. This fuzzyness in accepting both compound forms and lists enables the splicing in of forms supplied via the rest parameter. */ function lisp_bif_append_compounds(_key_) { var elts = []; for (var i = 1; i < arguments.length; i++) { var elt = arguments[i]; if (elt.formt == "compound") { elts = elts.concat(elt.elts); } else { lisp_assert(elt.length != null, "append-compounds", elt); elts = elts.concat(elt); } } return new Lisp_compound_form(elts); } function lisp_bif_compound_map(_key_, fun, compound) { function js_fun(elt) { return fun(null, elt); } lisp_assert_not_null(fun); lisp_assert_compound_form(compound); return new Lisp_compound_form(compound.elts.map(js_fun)); } function lisp_bif_compound_elt(_key_, compound, i) { lisp_assert_compound_form(compound, "compound-elt", compound); var elt = compound.elts[i]; return elt; } function lisp_bif_compound_len(_key_, compound) { lisp_assert_compound_form(compound, "compound-len", compound); return compound.elts.length; } function lisp_bif_compound_elts(_key_, compound) { lisp_assert_compound_form(compound, "compound-elts", compound); return compound.elts; } function lisp_bif_compound_slice(_key_, compound, start) { lisp_assert_compound_form(compound, "compound-slice", compound); return new Lisp_compound_form(compound.elts.slice(start)); } function lisp_bif_compound_emptyp(_key_, compound) { lisp_assert_compound_form(compound, "compound-empty?", compound); return compound.elts.length === 0; } /*** Built-in string dictionaries ***/ /* This is the type of dictionaries used to hold keyword arguments, i.e. the one a function with an `&all-keys' signature keyword receives. They're called string dictionaries because their keys can only be strings. By convention, all keys are prefixed with "%" (but not transformed like variables), so we never get in conflict with JS's special names, such as "prototype". */ function lisp_mangle_string_dict_key(name) { lisp_assert_string(name); return "%" + name; } function lisp_is_string_dict_key(k) { return k[0] == "%"; } function Lisp_string_dict() { } /* Turns an ordinary dictionary into a string dictionary. May only be called if the caller has ensured that all keys are properly mangled, or that the dictionary is empty. */ function lisp_fast_string_dict(js_dict) { js_dict.__proto__ = Lisp_string_dict.prototype; return js_dict; } function lisp_bif_string_dict_get(_key_, dict, key) { return dict[lisp_mangle_string_dict_key(key)]; } function lisp_bif_string_dict_put(_key_, dict, key, value) { dict[lisp_mangle_string_dict_key(key)] = value; } function lisp_bif_string_dict_has_key(_key_, dict, key) { return lisp_mangle_string_dict_key(key) in dict; } /*** Control Flow and Conditions ***/ /* CyberLisp uses the same exception system as Dylan and Goo (which is basically Common Lisp's but with exception handlers and restarts unified into a single concept). What's noteworthy about this system is that signaling an exception does not unwind the stack -- an exception handler runs as a subroutine of the signaler, and thus may advise the signaler on different ways to handle an exceptional situation. Unwinding the stack, if desired, has to be done manually through the use of a non-local exit. Together with `unwind-protect' ("finally"), this system is strictly more powerful than the exception systems of languages like Java and Python. It should also be noted that non-unwinding, restartable exceptions pose no algorithmic or implementational complexity over ordinary, automatically unwinding exceptions. */ /* CyberLisp maintains a stack of exception handler frames, because it cannot use JavaScript's try/catch construct. The handler stack grows downward, so that the most recently established exception handlers reside in the bottom-most, deepest frame. An exception handler frame is an object: { handlers: <list>, parent_frame: <handler_frame> } handlers: a list of handler objects; parent_frame: the parent of the current frame or null if it is the top-most frame. A handler object: [ <type>, <fun> ] type: type of exception handled by this handler; fun: handler function. A handler function is called with two arguments: an exception and a next-handler function. It has three possibilities: (1) return a value -- this will be the result of the `signal' that invoked the handler; (2) take a non-local exit, aborting execution of the signaler; (3) decline handling the exception by calling the next-handler function (without arguments), which will continue the search for an applicable handler stack-upwards. */ var lisp_handler_frame = null; // bottom-most frame or null function lisp_bif_bind_handlers(_key_, handlers, fun) { try { var orig_frame = lisp_handler_frame; lisp_handler_frame = { handlers: handlers, parent_frame: orig_frame }; return fun(null); } finally { lisp_handler_frame = orig_frame; } } function lisp_bif_signal(_key_, exception) { function handler_type(handler) { return handler[0]; } function handler_fun(handler) { return handler[1]; } function find_handler(exception, handler_frame) { if (!handler_frame) return null; var handlers = handler_frame.handlers; var type = lisp_type_of(exception); for (var i = 0, len = handlers.length; i < len; i++) { var handler = handlers[i]; if (lisp_subtypep(type, handler_type(handler))) { return [handler, handler_frame]; } } return find_handler(exception, handler_frame.parent_frame); } function do_signal(exception, handler_frame) { var handler_and_frame = find_handler(exception, handler_frame); if (handler_and_frame) { var handler = handler_and_frame[0]; var frame = handler_and_frame[1]; function next_handler(_key_) { return do_signal(exception, frame.parent_frame); } return (handler_fun(handler))(null, exception, next_handler); } else { lisp_error("No applicable handler", exception); } } return do_signal(exception, lisp_handler_frame); } function lisp_bif_call_with_escape_function(_key_, fun) { var token = {}; var escape_function = function(_key_, result) { token.result = result; throw token; }; try { return fun(null, escape_function); } catch(obj) { if (obj === token) { return token.result; } else { throw obj; } } } function lisp_bif_call_unwind_protected(_key_, protected_fun, cleanup_fun) { try { return protected_fun(null); } finally { cleanup_fun(null); } } function lisp_bif_call_while(_key_, test_fun, body_fun) { while(test_fun(null)) { body_fun(null); } return null; } /*** Multiple Dispatch ***/ function Lisp_generic() { this.method_entries = []; } function Lisp_method_entry(method, specializers) { this.method = method; this.specializers = specializers; } function lisp_bif_make_generic(_key_) { return new Lisp_generic(); } function lisp_make_method_entry(method, specializers) { return new Lisp_method_entry(method, specializers); } function lisp_bif_put_method(_key_, generic, specializers, method) { for (var i = 0, len = generic.method_entries; i < len; i++) { var me = generic.method_entries[i]; if (lisp_lists_equal(me.specializers, specializers)) { me.method = method; return; } } generic.method_entries.push(lisp_make_method_entry(method, specializers)); } function lisp_bif_params_specializers(_key_, params) { var specializers = []; var sig = lisp_compile_sig(params.elts); for (var i = 0, len = sig.req_params.length; i < len; i++) { var param = sig.req_params[i]; var specializer = param.specializer ? param.specializer : "object"; var specs = [ new Lisp_symbol_form("%%identifier"), new Lisp_symbol_form(specializer), new Lisp_symbol_form("class") ]; specializers.push(new Lisp_compound_form(specs)); } return new Lisp_compound_form(specializers); } function lisp_bif_find_method(_key_, generic, arguments) { var applicable_mes = lisp_find_applicable_method_entries(generic, arguments); if (applicable_mes.length == 0) return lisp_no_applicable_method(generic, arguments); var me = lisp_most_specific_method_entry(generic, applicable_mes); if (me) return me.method; else return lisp_no_most_specific_method(generic, arguments, applicable_mes); } function lisp_find_applicable_method_entries(generic, arguments) { var actual_specializers = []; // start at 1 to skip over calling convention argument for (var i = 1, len = arguments.length; i < len; i++) actual_specializers.push(lisp_type_of(arguments[i])); var applicable_mes = []; var mes = generic.method_entries; for (var i = 0, len = mes.length; i < len; i++) { if (lisp_specializers_lists_agree(actual_specializers, mes[i].specializers)) { applicable_mes.push(mes[i]); } } return applicable_mes; } function lisp_specializers_lists_agree(actuals, formals) { if (actuals.length != formals.length) return false; for (var i = 0, len = actuals.length; i < len; i++) if (!lisp_subtypep(actuals[i], formals[i])) return false; return true; } function lisp_most_specific_method_entry(generic, applicable_mes) { if (applicable_mes.length == 1) return applicable_mes[0]; for (var i = 0, len = applicable_mes.length; i < len; i++) if (lisp_least_method_entry(applicable_mes[i], applicable_mes)) return applicable_mes[i]; return null; } function lisp_least_method_entry(me, mes) { for (var i = 0, len = mes.length; i < len; i++) { if (me === mes[i]) continue; if (!lisp_smaller_method_entry(me, mes[i])) return false; } return true; } function lisp_smaller_method_entry(me1, me2) { if (me1.specializers.length != me2.specializers.length) return false; for (var i = 0, len = me1.specializers.length; i < len; i++) if ((!lisp_classes_comparable(me1.specializers[i], me2.specializers[i])) || (!lisp_subtypep(me1.specializers[i], me2.specializers[i]))) return false; return true; } function lisp_classes_comparable(class1, class2) { return ((lisp_subtypep(class1, class2)) || (lisp_subtypep(class2, class1))) } function lisp_no_applicable_method(generic, arguments) { lisp_error("No applicable method", generic); } function lisp_no_most_specific_method(generic, arguments, applicable_mes) { lisp_error("No most specific method", generic); } /*** Classes ***/ function lisp_type_of(obj) { if (obj === null) return lisp_nil_class; else return obj.__proto__; } function lisp_bif_type_of(_key_, obj) { return lisp_type_of(obj); } /* Returns true iff type1 is a general subtype of type2, meaning either equal to type2, or a subtype of type2. */ function lisp_subtypep(type1, type2) { if (type1 == type2) return true; var supertype = type1.lisp_superclass; if (supertype) return lisp_subtypep(supertype, type2); return false; } function lisp_bif_subtypep(_key_, type1, type2) { return lisp_subtypep(type1, type2); } function lisp_bif_make_class(_key_) { return {}; } function lisp_bif_set_superclass(_key_, clsA, clsB) { clsA.lisp_superclass = clsB; } function lisp_bif_make_instance(_key_, cls) { var obj = {}; obj.__proto__ = cls; return obj; } function lisp_bif_is_typename(_key_, string) { return lisp_is_type_name(string); } /*** Slots ***/ function lisp_bif_slot(_key_, obj, name) { lisp_assert_string(name); return obj[lisp_mangle_slot(name)]; } function lisp_bif_set_slot(_key_, obj, name, value) { lisp_assert_string(name); return obj[lisp_mangle_slot(name)] = value; } function lisp_bif_has_slot(_key_, obj, name) { lisp_assert_string(name); return obj.hasOwnProperty(lisp_mangle_slot(name)); } /*** Utilities ***/ function lisp_bif_macroexpand_1(_key_, form) { var macro = lisp_macro_function(form.elts[0].name); return macro(null, form); } function lisp_bif_print(_key_, object) { lisp_print(object); // defined in REPL } function lisp_bif_eq(_key_, a, b) { return a === b; } function lisp_bif_symbol_name(_key_, symbol) { lisp_assert_symbol_form(symbol); return symbol.name; } function lisp_bif_symbolp(_key_, form) { return form.formt == "symbol"; } function lisp_bif_compoundp(_key_, form) { return form.formt == "compound"; } function lisp_bif_list(_key_) { var elts = []; for (var i = 1; i < arguments.length; i++) { elts.push(arguments[i]); } return elts; } function lisp_bif_list_elt(_key_, list, i) { return list[i]; } function lisp_bif_list_len(_key_, list, i) { return list.length; } function lisp_bif_list_add(_key_, list, elt) { list.push(elt); return list; } function lisp_bif_string_concat(_key_, s1, s2) { return s1.concat(s2); } function lisp_bif_string_to_form(_key_, string) { return new Lisp_string_form(string); } function lisp_bif_string_to_symbol(_key_, string) { return new Lisp_symbol_form(string); } function lisp_bif_apply(_key_, fun, args, keys) { return fun.apply(null, [ keys ].concat(args)); } function lisp_is_true(obj) // T { return (obj !== false) && (obj !== null); } /*** Export to Lisp ***/ lisp_set("#t", "true"); lisp_set("#f", "false"); lisp_set_class("object", "Object.prototype"); lisp_set_class("<boolean>", "Boolean.prototype"); lisp_set_class("<function>", "Function.prototype"); lisp_set_class("<compound-form>", "Lisp_compound_form.prototype"); lisp_set_class("<list>", "Array.prototype"); lisp_set_class("<number-form>", "Lisp_number_form.prototype"); lisp_set_class("<string-dict>", "Lisp_string_dict.prototype"); lisp_set_class("<string-form>", "Lisp_string_form.prototype"); lisp_set_class("<string>", "String.prototype"); lisp_set_class("<symbol-form>", "Lisp_symbol_form.prototype"); var lisp_nil_class = lisp_bif_make_class(null); lisp_set_class("nil", "lisp_nil_class"); lisp_set("nil", "null"); // Numbers lisp_set_class("small-integer", "Number.prototype"); lisp_set_class("big-integer", "jsnums.BigInteger.prototype") lisp_set_class("real", "jsnums.FloatPoint.prototype"); lisp_set_class("rational", "jsnums.Rational.prototype"); lisp_set_function("append-compounds", "lisp_bif_append_compounds"); lisp_set_function("apply", "lisp_bif_apply"); lisp_set_function("bind-handlers", "lisp_bif_bind_handlers"); lisp_set_function("call-unwind-protected", "lisp_bif_call_unwind_protected"); lisp_set_function("call-while", "lisp_bif_call_while"); lisp_set_function("call-with-escape-function", "lisp_bif_call_with_escape_function"); lisp_set_function("compound-apply", "lisp_bif_compound_apply"); lisp_set_function("compound-elt", "lisp_bif_compound_elt"); lisp_set_function("compound-elts", "lisp_bif_compound_elts"); lisp_set_function("compound-empty?", "lisp_bif_compound_emptyp"); lisp_set_function("compound-len", "lisp_bif_compound_len"); lisp_set_function("compound-map", "lisp_bif_compound_map"); lisp_set_function("compound-slice", "lisp_bif_compound_slice"); lisp_set_function("compound?", "lisp_bif_compoundp"); lisp_set_function("eq", "lisp_bif_eq"); lisp_set_function("fast-apply", "lisp_bif_fast_apply"); lisp_set_function("find-method", "lisp_bif_find_method"); lisp_set_function("has-slot", "lisp_bif_has_slot"); lisp_set_function("list", "lisp_bif_list"); lisp_set_function("list-add", "lisp_bif_list_add"); lisp_set_function("list-elt", "lisp_bif_list_elt"); lisp_set_function("list-len", "lisp_bif_list_len"); lisp_set_function("macroexpand-1", "lisp_bif_macroexpand_1"); lisp_set_function("make-class", "lisp_bif_make_class"); lisp_set_function("make-compound", "lisp_bif_make_compound"); lisp_set_function("make-generic", "lisp_bif_make_generic"); lisp_set_function("make-instance", "lisp_bif_make_instance"); lisp_set_function("params-specializers", "lisp_bif_params_specializers"); lisp_set_function("print", "lisp_bif_print"); lisp_set_function("put-method", "lisp_bif_put_method"); lisp_set_function("set-slot", "lisp_bif_set_slot"); lisp_set_function("set-superclass", "lisp_bif_set_superclass"); lisp_set_function("signal", "lisp_bif_signal"); lisp_set_function("slot", "lisp_bif_slot"); lisp_set_function("string-concat", "lisp_bif_string_concat"); lisp_set_function("string-dict-get", "lisp_bif_string_dict_get"); lisp_set_function("string-dict-has-key", "lisp_bif_string_dict_has_key"); lisp_set_function("string-dict-put", "lisp_bif_string_dict_put"); lisp_set_function("string-to-form", "lisp_bif_string_to_form"); lisp_set_function("string-to-symbol", "lisp_bif_string_to_symbol"); lisp_set_function("subtype?", "lisp_bif_subtypep"); lisp_set_function("symbol-name", "lisp_bif_symbol_name"); lisp_set_function("symbol?", "lisp_bif_symbolp"); lisp_set_function("type-of", "lisp_bif_type_of"); /*** Utilities ***/ function lisp_set(lisp_name, js_object) { eval(lisp_mangle_var(lisp_name) + " = " + js_object); } function lisp_set_function(lisp_name, js_function) { eval(lisp_mangle_function(lisp_name) + " = " + js_function); } function lisp_set_class(lisp_name, js_class) { eval(lisp_mangle_class(lisp_name) + " = " + js_class); }
runtime.js
/* CyberLisp: A Lisp that compiles to JavaScript 1.5. Copyright (C) 2008, 2011 by Manuel Simoni. CyberLisp 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, or (at your option) any later version. CyberLisp 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 GNU Emacs; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Lisp runtime: this file should contain all functions needed to run compiled Lisp code. At the moment, it does have dependencies on name mangling functions in `compiler.js', though. Lisp code that does use `eval' will always need to include the compiler too. */ /*** Strings ***/ function Lisp_string(s) { this.s = s; } /*** Numbers ***/ function lisp_number(numrepr) { return jsnums.fromString(numrepr); } /*** Functions ***/ function lisp_bif_fast_apply(_key_, fun, _arguments) { return fun.apply(null, _arguments); } /*** Forms ***/ function Lisp_number_form(sign, integral_digits, fractional_digits) { this.formt = "number"; this.sign = sign; this.integral_digits = integral_digits; this.fractional_digits = fractional_digits; } function Lisp_string_form(s) { this.formt = "string"; this.s = s; } function Lisp_symbol_form(name) { this.formt = "symbol"; this.name = name; } function Lisp_compound_form(elts) { this.formt = "compound"; this.elts = elts; } /* This whole comments-as-forms business is silly, but atm I don't know another way to have comments ignored. */ function Lisp_comment_form(contents) { this.formt = "comment"; this.contents = contents; } /*** Utilities for generated code. ***/ function lisp_undefined_identifier(name, namespace) { return lisp_error("Undefined " + namespace, name); } /* Used inside lambdas. */ function lisp_arity_min(length, min) { if (length < min) throw Error("Too few arguments "); } function lisp_arity_min_max(length, min, max) { lisp_arity_min(length, min); if (length > max) throw Error("Too many arguments "); } /* Returns the sequence of arguments to which the rest parameter is bound; called with a function's arguments and the count of positional (required and optional) parameters of the function. */ function lisp_rest_param(_arguments, max) { var args = []; var offset = 1 + max; // Skip calling convention argument. var len = _arguments.length; for (var i = offset; i < len; i++) { args[i - offset] = _arguments[i]; } return args; } /* Used inside lambdas for checking arguments against their types, if any. */ function lisp_check_type(obj, type) { if (!lisp_subtypep(lisp_type_of(obj), type)) lisp_error("Type error", obj); } function lisp_show(obj) { // show is defined as a generic function in boot.lisp if (typeof(_lisp_function_show) !== "undefined") return _lisp_function_show(null, obj); else return JSON.stringify(obj); } function lisp_array_contains(array, elt) { for (var i in array) { if (array[i] == elt) return true; } return false; } function lisp_iter_dict(dict, fun) { for (var k in dict) { if (dict.hasOwnProperty(k)) fun(k); } } function lisp_lists_equal(list1, list2) { if (list1.length != list2.length) return false; for (var i = 0, len = list1.length; i < len; i++) { if (list1[i] !== list2[i]) return false; } return true; } // fixme: should SIGNAL error function lisp_error(message, arg) { throw Error(message + ": " + JSON.stringify(arg)); } function lisp_assert(value, message, arg) { if (!value) lisp_error(message, arg); return value; } function lisp_assert_not_null(value, message, arg) { lisp_assert(value != null, message, arg); return value; } function lisp_assert_number(value, message, arg) { // fixme lisp_assert(typeof value == "number", message, arg); return value; k} function lisp_assert_string(value, message, arg) { lisp_assert(typeof value == "string", message, arg); return value; } function lisp_assert_nonempty_string(value, message, arg) { lisp_assert_string(value, message, arg); lisp_assert(value.length > 0, message, arg); return value; } function lisp_assert_function(value, message, arg) { lisp_assert(typeof value == "function", message, arg); return value; } function lisp_assert_symbol_form(value, message, arg) { lisp_assert(typeof value == "object", message, arg); lisp_assert(value.formt == "symbol", message, arg); lisp_assert_nonempty_string(value.name, message, arg); return value; } function lisp_assert_compound_form(value, message, arg) { lisp_assert(typeof value == "object", message, arg); lisp_assert(value.formt == "compound", message, arg); lisp_assert_not_null(value.elts, message, arg); lisp_assert_not_null(value.elts.length, message, arg); return value; } /*** Built-in form manipulation functions ***/ /* Applies a Lisp function to the elements of a compound form, a simple form of destructuring. The form's elements are simply supplied as the function's positional arguments. */ function lisp_bif_compound_apply(_key_, fun, form) { var _key_ = null; var args = [ _key_ ].concat(form.elts); var thisArg = null; return fun.apply(thisArg, args); } /* Creates a compound form from all positional arguments, which must be forms. */ function lisp_bif_make_compound(_key_) { var elts = []; for (var i = 1; i < arguments.length; i++) { var elt = arguments[i]; lisp_assert(elt && elt.formt, "make-compound", elt); elts = elts.concat(elt); } return new Lisp_compound_form(elts); } /* Creates a compound form by appending all positional arguments, which must be compound forms or lists. This fuzzyness in accepting both compound forms and lists enables the splicing in of forms supplied via the rest parameter. */ function lisp_bif_append_compounds(_key_) { var elts = []; for (var i = 1; i < arguments.length; i++) { var elt = arguments[i]; if (elt.formt == "compound") { elts = elts.concat(elt.elts); } else { lisp_assert(elt.length != null, "append-compounds", elt); elts = elts.concat(elt); } } return new Lisp_compound_form(elts); } function lisp_bif_compound_map(_key_, fun, compound) { function js_fun(elt) { return fun(null, elt); } lisp_assert_not_null(fun); lisp_assert_compound_form(compound); return new Lisp_compound_form(compound.elts.map(js_fun)); } function lisp_bif_compound_elt(_key_, compound, i) { lisp_assert_compound_form(compound, "compound-elt", compound); var elt = compound.elts[i]; return elt; } function lisp_bif_compound_len(_key_, compound) { lisp_assert_compound_form(compound, "compound-len", compound); return compound.elts.length; } function lisp_bif_compound_elts(_key_, compound) { lisp_assert_compound_form(compound, "compound-elts", compound); return compound.elts; } function lisp_bif_compound_slice(_key_, compound, start) { lisp_assert_compound_form(compound, "compound-slice", compound); return new Lisp_compound_form(compound.elts.slice(start)); } function lisp_bif_compound_emptyp(_key_, compound) { lisp_assert_compound_form(compound, "compound-empty?", compound); return compound.elts.length === 0; } /*** Built-in string dictionaries ***/ /* This is the type of dictionaries used to hold keyword arguments, i.e. the one a function with an `&all-keys' signature keyword receives. They're called string dictionaries because their keys can only be strings. By convention, all keys are prefixed with "%" (but not transformed like variables), so we never get in conflict with JS's special names, such as "prototype". */ function lisp_mangle_string_dict_key(name) { lisp_assert_string(name); return "%" + name; } function lisp_is_string_dict_key(k) { return k[0] == "%"; } function Lisp_string_dict() { } /* Turns an ordinary dictionary into a string dictionary. May only be called if the caller has ensured that all keys are properly mangled, or that the dictionary is empty. */ function lisp_fast_string_dict(js_dict) { js_dict.__proto__ = Lisp_string_dict.prototype; return js_dict; } function lisp_bif_string_dict_get(_key_, dict, key) { return dict[lisp_mangle_string_dict_key(key)]; } function lisp_bif_string_dict_put(_key_, dict, key, value) { dict[lisp_mangle_string_dict_key(key)] = value; } function lisp_bif_string_dict_has_key(_key_, dict, key) { return lisp_mangle_string_dict_key(key) in dict; } /*** Control Flow and Conditions ***/ /* CyberLisp uses the same exception system as Dylan and Goo (which is basically Common Lisp's but with exception handlers and restarts unified into a single concept). What's noteworthy about this system is that signaling an exception does not unwind the stack -- an exception handler runs as a subroutine of the signaler, and thus may advise the signaler on different ways to handle an exceptional situation. Unwinding the stack, if desired, has to be done manually through the use of a non-local exit. Together with `unwind-protect' ("finally"), this system is strictly more powerful than the exception systems of languages like Java and Python. It should also be noted that non-unwinding, restartable exceptions pose no algorithmic or implementational complexity over ordinary, automatically unwinding exceptions. */ /* CyberLisp maintains a stack of exception handler frames, because it cannot use JavaScript's try/catch construct. The handler stack grows downward, so that the most recently established exception handlers reside in the bottom-most, deepest frame. An exception handler frame is an object: { handlers: <list>, parent_frame: <handler_frame> } handlers: a list of handler objects; parent_frame: the parent of the current frame or null if it is the top-most frame. A handler object: [ <type>, <fun> ] type: type of exception handled by this handler; fun: handler function. A handler function is called with two arguments: an exception and a next-handler function. It has three possibilities: (1) return a value -- this will be the result of the `signal' that invoked the handler; (2) take a non-local exit, aborting execution of the signaler; (3) decline handling the exception by calling the next-handler function (without arguments), which will continue the search for an applicable handler stack-upwards. */ var lisp_handler_frame = null; // bottom-most frame or null function lisp_bif_bind_handlers(_key_, handlers, fun) { try { var orig_frame = lisp_handler_frame; lisp_handler_frame = { handlers: handlers, parent_frame: orig_frame }; return fun(null); } finally { lisp_handler_frame = orig_frame; } } function lisp_bif_signal(_key_, exception) { function handler_type(handler) { return handler[0]; } function handler_fun(handler) { return handler[1]; } function find_handler(exception, handler_frame) { if (!handler_frame) return null; var handlers = handler_frame.handlers; var type = lisp_type_of(exception); for (var i = 0, len = handlers.length; i < len; i++) { var handler = handlers[i]; if (lisp_subtypep(type, handler_type(handler))) { return [handler, handler_frame]; } } return find_handler(exception, handler_frame.parent_frame); } function do_signal(exception, handler_frame) { var handler_and_frame = find_handler(exception, handler_frame); if (handler_and_frame) { var handler = handler_and_frame[0]; var frame = handler_and_frame[1]; function next_handler(_key_) { return do_signal(exception, frame.parent_frame); } return (handler_fun(handler))(null, exception, next_handler); } else { lisp_error("No applicable handler", exception); } } return do_signal(exception, lisp_handler_frame); } function lisp_bif_call_with_escape_function(_key_, fun) { var token = {}; var escape_function = function(_key_, result) { token.result = result; throw token; }; try { return fun(null, escape_function); } catch(obj) { if (obj === token) { return token.result; } else { throw obj; } } } function lisp_bif_call_unwind_protected(_key_, protected_fun, cleanup_fun) { try { return protected_fun(null); } finally { cleanup_fun(null); } } function lisp_bif_call_while(_key_, test_fun, body_fun) { while(test_fun(null)) { body_fun(null); } return null; } /*** Multiple Dispatch ***/ function Lisp_generic() { this.method_entries = []; } function Lisp_method_entry(method, specializers) { this.method = method; this.specializers = specializers; } function lisp_bif_make_generic(_key_) { return new Lisp_generic(); } function lisp_make_method_entry(method, specializers) { return new Lisp_method_entry(method, specializers); } function lisp_bif_put_method(_key_, generic, specializers, method) { for (var i = 0, len = generic.method_entries; i < len; i++) { var me = generic.method_entries[i]; if (lisp_lists_equal(me.specializers, specializers)) { me.method = method; return; } } generic.method_entries.push(lisp_make_method_entry(method, specializers)); } function lisp_bif_params_specializers(_key_, params) { var specializers = []; var sig = lisp_compile_sig(params.elts); for (var i = 0, len = sig.req_params.length; i < len; i++) { var param = sig.req_params[i]; var specializer = param.specializer ? param.specializer : "object"; var specs = [ new Lisp_symbol_form("%%identifier"), new Lisp_symbol_form(specializer), new Lisp_symbol_form("class") ]; specializers.push(new Lisp_compound_form(specs)); } return new Lisp_compound_form(specializers); } function lisp_bif_find_method(_key_, generic, arguments) { var applicable_mes = lisp_find_applicable_method_entries(generic, arguments); if (applicable_mes.length == 0) return lisp_no_applicable_method(generic, arguments); var me = lisp_most_specific_method_entry(generic, applicable_mes); if (me) return me.method; else return lisp_no_most_specific_method(generic, arguments, applicable_mes); } function lisp_find_applicable_method_entries(generic, arguments) { var actual_specializers = []; // start at 1 to skip over calling convention argument for (var i = 1, len = arguments.length; i < len; i++) actual_specializers.push(lisp_type_of(arguments[i])); var applicable_mes = []; var mes = generic.method_entries; for (var i = 0, len = mes.length; i < len; i++) { if (lisp_specializers_lists_agree(actual_specializers, mes[i].specializers)) { applicable_mes.push(mes[i]); } } return applicable_mes; } function lisp_specializers_lists_agree(actuals, formals) { if (actuals.length != formals.length) return false; for (var i = 0, len = actuals.length; i < len; i++) if (!lisp_specializers_agree(actuals[i], formals[i])) return false; return true; } function lisp_specializers_agree(actual, formal) { return lisp_subtypep(actual, formal); } function lisp_most_specific_method_entry(generic, applicable_mes) { if (applicable_mes.length == 1) return applicable_mes[0]; for (var i = 0, len = applicable_mes.length; i < len; i++) if (lisp_least_method_entry(applicable_mes[i], applicable_mes)) return applicable_mes[i]; return null; } function lisp_least_method_entry(me, mes) { for (var i = 0, len = mes.length; i < len; i++) { if (me === mes[i]) continue; if (!lisp_smaller_method_entry(me, mes[i])) return false; } return true; } function lisp_smaller_method_entry(me1, me2) { if (me1.specializers.length != me2.specializers.length) return false; for (var i = 0, len = me1.specializers.length; i < len; i++) if ((!lisp_classes_comparable(me1.specializers[i], me2.specializers[i])) || (!lisp_subtypep(me1.specializers[i], me2.specializers[i]))) return false; return true; } function lisp_classes_comparable(class1, class2) { return ((lisp_subtypep(class1, class2)) || (lisp_subtypep(class2, class1))) } function lisp_no_applicable_method(generic, arguments) { lisp_error("No applicable method", generic); } function lisp_no_most_specific_method(generic, arguments, applicable_mes) { lisp_error("No most specific method", generic); } /*** Classes ***/ function lisp_type_of(obj) { if (obj === null) return lisp_nil_class; else return obj.__proto__; } function lisp_bif_type_of(_key_, obj) { return lisp_type_of(obj); } /* Returns true iff type1 is a general subtype of type2, meaning either equal to type2, or a subtype of type2. */ function lisp_subtypep(type1, type2) { if (type1 == type2) return true; var supertype = type1.lisp_superclass; if (supertype) return lisp_subtypep(supertype, type2); return false; } function lisp_bif_subtypep(_key_, type1, type2) { return lisp_subtypep(type1, type2); } function lisp_bif_make_class(_key_) { return {}; } function lisp_bif_set_superclass(_key_, clsA, clsB) { clsA.lisp_superclass = clsB; } function lisp_bif_make_instance(_key_, cls) { var obj = {}; obj.__proto__ = cls; return obj; } function lisp_bif_is_typename(_key_, string) { return lisp_is_type_name(string); } /*** Slots ***/ function lisp_bif_slot(_key_, obj, name) { lisp_assert_string(name); return obj[lisp_mangle_slot(name)]; } function lisp_bif_set_slot(_key_, obj, name, value) { lisp_assert_string(name); return obj[lisp_mangle_slot(name)] = value; } function lisp_bif_has_slot(_key_, obj, name) { lisp_assert_string(name); return obj.hasOwnProperty(lisp_mangle_slot(name)); } /*** Utilities ***/ function lisp_bif_macroexpand_1(_key_, form) { var macro = lisp_macro_function(form.elts[0].name); return macro(null, form); } function lisp_bif_print(_key_, object) { lisp_print(object); // defined in REPL } function lisp_bif_eq(_key_, a, b) { return a === b; } function lisp_bif_symbol_name(_key_, symbol) { lisp_assert_symbol_form(symbol); return symbol.name; } function lisp_bif_symbolp(_key_, form) { return form.formt == "symbol"; } function lisp_bif_compoundp(_key_, form) { return form.formt == "compound"; } function lisp_bif_list(_key_) { var elts = []; for (var i = 1; i < arguments.length; i++) { elts.push(arguments[i]); } return elts; } function lisp_bif_list_elt(_key_, list, i) { return list[i]; } function lisp_bif_list_len(_key_, list, i) { return list.length; } function lisp_bif_list_add(_key_, list, elt) { list.push(elt); return list; } function lisp_bif_string_concat(_key_, s1, s2) { return s1.concat(s2); } function lisp_bif_string_to_form(_key_, string) { return new Lisp_string_form(string); } function lisp_bif_string_to_symbol(_key_, string) { return new Lisp_symbol_form(string); } function lisp_bif_apply(_key_, fun, args, keys) { return fun.apply(null, [ keys ].concat(args)); } function lisp_is_true(obj) // T { return (obj !== false) && (obj !== null); } /*** Export to Lisp ***/ lisp_set("#t", "true"); lisp_set("#f", "false"); lisp_set_class("object", "Object.prototype"); lisp_set_class("<boolean>", "Boolean.prototype"); lisp_set_class("<function>", "Function.prototype"); lisp_set_class("<compound-form>", "Lisp_compound_form.prototype"); lisp_set_class("<list>", "Array.prototype"); lisp_set_class("<number-form>", "Lisp_number_form.prototype"); lisp_set_class("<string-dict>", "Lisp_string_dict.prototype"); lisp_set_class("<string-form>", "Lisp_string_form.prototype"); lisp_set_class("<string>", "String.prototype"); lisp_set_class("<symbol-form>", "Lisp_symbol_form.prototype"); var lisp_nil_class = lisp_bif_make_class(null); lisp_set_class("nil", "lisp_nil_class"); lisp_set("nil", "null"); // Numbers lisp_set_class("small-integer", "Number.prototype"); lisp_set_class("big-integer", "jsnums.BigInteger.prototype") lisp_set_class("real", "jsnums.FloatPoint.prototype"); lisp_set_class("rational", "jsnums.Rational.prototype"); lisp_set_function("append-compounds", "lisp_bif_append_compounds"); lisp_set_function("apply", "lisp_bif_apply"); lisp_set_function("bind-handlers", "lisp_bif_bind_handlers"); lisp_set_function("call-unwind-protected", "lisp_bif_call_unwind_protected"); lisp_set_function("call-while", "lisp_bif_call_while"); lisp_set_function("call-with-escape-function", "lisp_bif_call_with_escape_function"); lisp_set_function("compound-apply", "lisp_bif_compound_apply"); lisp_set_function("compound-elt", "lisp_bif_compound_elt"); lisp_set_function("compound-elts", "lisp_bif_compound_elts"); lisp_set_function("compound-empty?", "lisp_bif_compound_emptyp"); lisp_set_function("compound-len", "lisp_bif_compound_len"); lisp_set_function("compound-map", "lisp_bif_compound_map"); lisp_set_function("compound-slice", "lisp_bif_compound_slice"); lisp_set_function("compound?", "lisp_bif_compoundp"); lisp_set_function("eq", "lisp_bif_eq"); lisp_set_function("fast-apply", "lisp_bif_fast_apply"); lisp_set_function("find-method", "lisp_bif_find_method"); lisp_set_function("has-slot", "lisp_bif_has_slot"); lisp_set_function("list", "lisp_bif_list"); lisp_set_function("list-add", "lisp_bif_list_add"); lisp_set_function("list-elt", "lisp_bif_list_elt"); lisp_set_function("list-len", "lisp_bif_list_len"); lisp_set_function("macroexpand-1", "lisp_bif_macroexpand_1"); lisp_set_function("make-class", "lisp_bif_make_class"); lisp_set_function("make-compound", "lisp_bif_make_compound"); lisp_set_function("make-generic", "lisp_bif_make_generic"); lisp_set_function("make-instance", "lisp_bif_make_instance"); lisp_set_function("params-specializers", "lisp_bif_params_specializers"); lisp_set_function("print", "lisp_bif_print"); lisp_set_function("put-method", "lisp_bif_put_method"); lisp_set_function("set-slot", "lisp_bif_set_slot"); lisp_set_function("set-superclass", "lisp_bif_set_superclass"); lisp_set_function("signal", "lisp_bif_signal"); lisp_set_function("slot", "lisp_bif_slot"); lisp_set_function("string-concat", "lisp_bif_string_concat"); lisp_set_function("string-dict-get", "lisp_bif_string_dict_get"); lisp_set_function("string-dict-has-key", "lisp_bif_string_dict_has_key"); lisp_set_function("string-dict-put", "lisp_bif_string_dict_put"); lisp_set_function("string-to-form", "lisp_bif_string_to_form"); lisp_set_function("string-to-symbol", "lisp_bif_string_to_symbol"); lisp_set_function("subtype?", "lisp_bif_subtypep"); lisp_set_function("symbol-name", "lisp_bif_symbol_name"); lisp_set_function("symbol?", "lisp_bif_symbolp"); lisp_set_function("type-of", "lisp_bif_type_of"); /*** Utilities ***/ function lisp_set(lisp_name, js_object) { eval(lisp_mangle_var(lisp_name) + " = " + js_object); } function lisp_set_function(lisp_name, js_function) { eval(lisp_mangle_function(lisp_name) + " = " + js_function); } function lisp_set_class(lisp_name, js_class) { eval(lisp_mangle_class(lisp_name) + " = " + js_class); }
simplified lisp_specializers_lists_agree
runtime.js
simplified lisp_specializers_lists_agree
<ide><path>untime.js <ide> { <ide> if (actuals.length != formals.length) return false; <ide> for (var i = 0, len = actuals.length; i < len; i++) <del> if (!lisp_specializers_agree(actuals[i], formals[i])) <add> if (!lisp_subtypep(actuals[i], formals[i])) <ide> return false; <ide> return true; <del>} <del> <del>function lisp_specializers_agree(actual, formal) <del>{ <del> return lisp_subtypep(actual, formal); <ide> } <ide> <ide> function lisp_most_specific_method_entry(generic, applicable_mes)
Java
agpl-3.0
b6b61180d09bd8a6447aebcef8266826c1b52135
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
e437a966-2e5f-11e5-9284-b827eb9e62be
hello.java
e432435e-2e5f-11e5-9284-b827eb9e62be
e437a966-2e5f-11e5-9284-b827eb9e62be
hello.java
e437a966-2e5f-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>e432435e-2e5f-11e5-9284-b827eb9e62be <add>e437a966-2e5f-11e5-9284-b827eb9e62be
Java
apache-2.0
0f30328d7c3fee1bf101ab1094169c753cb0295a
0
apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj
/* * 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.uima.caseditor.editor.util; import org.apache.uima.cas.CAS; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeatureStructure; /** * This enumeration contains all primitives and some util methods. * TODO: remove all array and list * types, thats are FeatureStructures !!! */ public enum Primitives { /** * The uima {@link Boolean} type. */ BOOLEAN(CAS.TYPE_NAME_BOOLEAN, Boolean.class), /** * The uima {@link Byte} type. */ BYTE(CAS.TYPE_NAME_BYTE, Byte.class), /** * The uima {@link Short} type. */ SHORT(CAS.TYPE_NAME_SHORT, Short.class), /** * The uima {@link Integer} type. */ INTEGER(CAS.TYPE_NAME_INTEGER, Integer.class), /** * The uima {@link Long} type. */ LONG(CAS.TYPE_NAME_LONG, Long.class), /** * The uima {@link Float} type. */ FLOAT(CAS.TYPE_NAME_FLOAT, Float.class), /** * The uima {@link Double} type. */ DOUBLE(CAS.TYPE_NAME_DOUBLE, Double.class), /** * The uima {@link String} type. */ STRING(CAS.TYPE_NAME_STRING, String.class); private final String mTypeName; private final Class mType; private Primitives(String typeName, Class type) { mTypeName = typeName; mType = type; } /** * Retrieves the uima name of the type. * * @return the uima name. */ public String getTypeName() { return mTypeName; } /** * Retrieves the type. * * @return the type */ public Class getType() { return mType; } /** * Checks if the given feature has the same type. * * @param feature * @return true if type is the same otherwise false */ public boolean isCompatible(Feature feature) { return feature.getRange().getName().equals(getTypeName()); } /** * Checks if a given <code>Feature</code> has a primitive type. * * @param f * @return true if primitive otherwise false */ @Deprecated public static boolean isPrimitive(Feature f) { if (f == null) { throw new IllegalArgumentException(); } return isPrimitive(f.getRange().getName()); } /** * Checks if the given typeName is a primitive. * * @param typeName * @return true if primitive otherwise false. */ @Deprecated public static boolean isPrimitive(String typeName) { if (typeName == null) { throw new IllegalArgumentException(); } return getPrimitive(typeName) != null ? true : false; } /** * Retrieves the {@link Class} for the current primitive. * * @param f * @return the class */ public static Class getPrimitiveClass(Feature f) { assert Primitives.isPrimitive(f); return getPrimitive(f.getRange().getName()).getType(); } /** * Retrieves a primitive by name. * * @param typeName * @return the primitive or null if none */ public static Primitives getPrimitive(String typeName) { for (Primitives primitive : values()) { if (primitive.getTypeName().equals(typeName)) { return primitive; } } return null; } /** * Retrieves the primitive value. * * @param structure * @param feature * @return the primitive value as object */ public static Object getPrimitiv(FeatureStructure structure, Feature feature) { Object result; if (Primitives.BOOLEAN.isCompatible(feature)) { result = structure.getBooleanValue(feature); } else if (Primitives.BYTE.isCompatible(feature)) { result = structure.getByteValue(feature); } else if (Primitives.SHORT.isCompatible(feature)) { result = structure.getShortValue(feature); } else if (Primitives.INTEGER.isCompatible(feature)) { result = structure.getIntValue(feature); } else if (Primitives.LONG.isCompatible(feature)) { result = structure.getLongValue(feature); } else if (Primitives.FLOAT.isCompatible(feature)) { result = structure.getFloatValue(feature); } else if (Primitives.DOUBLE.isCompatible(feature)) { result = structure.getDoubleValue(feature); } else if (Primitives.STRING.isCompatible(feature)) { result = structure.getStringValue(feature); } else { assert false; result = "unexpected type"; } return result; } }
uimaj-ep-cas-editor/src/main/java/org/apache/uima/caseditor/editor/util/Primitives.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.uima.caseditor.editor.util; import org.apache.uima.cas.CAS; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeatureStructure; /** * This enumeration contains all primitives and some util methods. * TODO: remove all array and list * types, thats are FeatureStructures !!! */ public enum Primitives { /** * The uima {@link Boolean} type. */ BOOLEAN(CAS.TYPE_NAME_BOOLEAN, Boolean.class), /** * The uima {@link Byte} type. */ BYTE(CAS.TYPE_NAME_BYTE, Byte.class), /** * The uima {@link Short} type. */ SHORT(CAS.TYPE_NAME_SHORT, Short.class), /** * The uima {@link Integer} type. */ INTEGER(CAS.TYPE_NAME_INTEGER, Integer.class), /** * The uima {@link Long} type. */ LONG(CAS.TYPE_NAME_LONG, Long.class), /** * The uima {@link Float} type. */ FLOAT(CAS.TYPE_NAME_FLOAT, Float.class), /** * The uima {@link Double} type. */ DOUBLE(CAS.TYPE_NAME_DOUBLE, Double.class), /** * The uima {@link String} type. */ STRING(CAS.TYPE_NAME_STRING, String.class); private final String mTypeName; @SuppressWarnings("unchecked") private final Class mType; @SuppressWarnings("unchecked") private Primitives(String typeName, Class type) { mTypeName = typeName; mType = type; } /** * Retrieves the uima name of the type. * * @return the uima name. */ public String getTypeName() { return mTypeName; } /** * Retrieves the type. * * @return the type */ @SuppressWarnings("unchecked") public Class getType() { return mType; } /** * Checks if the given feature has the same type. * * @param feature * @return true if type is the same otherwise false */ public boolean isCompatible(Feature feature) { return feature.getRange().getName().equals(getTypeName()); } /** * Checks if a given <code>Feature</code> has a primitive type. * * @param f * @return true if primitive otherwise false */ @Deprecated public static boolean isPrimitive(Feature f) { if (f == null) { throw new IllegalArgumentException(); } return isPrimitive(f.getRange().getName()); } /** * Checks if the given typeName is a primitive. * * @param typeName * @return true if primitive otherwise false. */ @Deprecated public static boolean isPrimitive(String typeName) { if (typeName == null) { throw new IllegalArgumentException(); } return getPrimitive(typeName) != null ? true : false; } /** * Retrieves the {@link Class} for the current primitive. * * @param f * @return the class */ @SuppressWarnings("unchecked") public static Class getPrimitiveClass(Feature f) { assert Primitives.isPrimitive(f); return getPrimitive(f.getRange().getName()).getType(); } /** * Retrieves a primitive by name. * * @param typeName * @return the primitive or null if none */ public static Primitives getPrimitive(String typeName) { for (Primitives primitive : values()) { if (primitive.getTypeName().equals(typeName)) { return primitive; } } return null; } /** * Retrieves the primitive value. * * @param structure * @param feature * @return the primitive value as object */ public static Object getPrimitiv(FeatureStructure structure, Feature feature) { Object result; if (Primitives.BOOLEAN.isCompatible(feature)) { result = structure.getBooleanValue(feature); } else if (Primitives.BYTE.isCompatible(feature)) { result = structure.getByteValue(feature); } else if (Primitives.SHORT.isCompatible(feature)) { result = structure.getShortValue(feature); } else if (Primitives.INTEGER.isCompatible(feature)) { result = structure.getIntValue(feature); } else if (Primitives.LONG.isCompatible(feature)) { result = structure.getLongValue(feature); } else if (Primitives.FLOAT.isCompatible(feature)) { result = structure.getFloatValue(feature); } else if (Primitives.DOUBLE.isCompatible(feature)) { result = structure.getDoubleValue(feature); } else if (Primitives.STRING.isCompatible(feature)) { result = structure.getStringValue(feature); } else { assert false; result = "unexpected type"; } return result; } }
No jira, removed unused SuppressWarnings annotation. git-svn-id: a5af42c550a078756190f4e79161aff2e348b436@1004559 13f79535-47bb-0310-9956-ffa450edef68
uimaj-ep-cas-editor/src/main/java/org/apache/uima/caseditor/editor/util/Primitives.java
No jira, removed unused SuppressWarnings annotation.
<ide><path>imaj-ep-cas-editor/src/main/java/org/apache/uima/caseditor/editor/util/Primitives.java <ide> <ide> private final String mTypeName; <ide> <del> @SuppressWarnings("unchecked") <ide> private final Class mType; <ide> <del> @SuppressWarnings("unchecked") <ide> private Primitives(String typeName, Class type) { <ide> mTypeName = typeName; <ide> mType = type; <ide> * <ide> * @return the type <ide> */ <del> @SuppressWarnings("unchecked") <ide> public Class getType() { <ide> return mType; <ide> } <ide> * @param f <ide> * @return the class <ide> */ <del> @SuppressWarnings("unchecked") <ide> public static Class getPrimitiveClass(Feature f) { <ide> assert Primitives.isPrimitive(f); <ide>
Java
mit
0e548afb4703aeda5ee247ab2de3244fdc8353f5
0
touist/touist,olzd/touist,FredMaris/touist,olzd/touist,touist/touist,touist/touist,touist/touist,olzd/touist,FredMaris/touist,FredMaris/touist
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package solution; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Map; /** * This class * - launches the solver program with the DIMACS input * - if this DIMACS is satisfiable, gives an iterable Models * - gives a way to get the next Model and do the translation * with the literalsMap (DIMACS integers to literal names) * * the next model. * @author Abdel */ public class Solver { private Process p; private PrintWriter out; private String dimacsFilePath; private Map<Integer,String> literalsMap; public Solver(String dimacsFilePath) { this.dimacsFilePath = dimacsFilePath; this.literalsMap = null; } public Solver(String dimacsFilePath, Map<Integer,String> literalsMap) { this.dimacsFilePath = dimacsFilePath; this.literalsMap = literalsMap; } public Models launch() { return null; } /** * ONLY used by ModelsIterator * @return null if no more model (or if not satisfiable) * @throws IOException */ protected Model nextModel() throws IOException { out=new PrintWriter (new BufferedWriter (new OutputStreamWriter(p.getOutputStream()))); out.println("1"); out.flush(); out.close(); StringBuffer br=new StringBuffer(); BufferedReader reader =new BufferedReader(new InputStreamReader(p.getInputStream())); String line=""; while((line=reader.readLine())!=null){ br.append(line+"\n"); } return parseModel(br.toString().split(" ")); } /** * * @param rawModelOutput The output * @return a model with, if a literalMap was given, the translated * literal. If no literalMap is given, the Model stores the literal * as given by the solver (an integer). */ private Model parseModel(String[] rawModelOutput){ Model model=new Model(); for (String rawLiteral : rawModelOutput){ if(literalsMap != null){ model.addLiteral(literalsMap.get(Integer.parseInt(rawLiteral))); } else { model.addLiteral(rawLiteral); } } return model; } public Process start(String dimacsFilesPath) throws IOException { this.p=Runtime.getRuntime().exec("java -cp .:sat4j-sat.jar Minisat "+dimacsFilesPath); return p; } /** * Kills the solver program process */ public void close() { out=new PrintWriter (new BufferedWriter (new OutputStreamWriter(p.getOutputStream()))); out.println("\n0"); out.close(); this.p.destroy(); } }
ui/solution/Solver.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package solution; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import translation.ResultatOcaml; /** * This class * - launches the solver program with the DIMACS input * - if this DIMACS is satisfiable, gives an iterable * object that will, itself, call SolverSAT to get * the next model. * @author Abdel */ public class Solver implements Iterable<Model> { private Process p; private boolean IsFirtCompute=true; private PrintWriter out; public Solver(String dimacsFilePath) { } public Solver(String dimacsFilePath, LiteralsMap map) { } public Models launch() { return null; } public void stop() { } public Model computeModel(ResultatOcaml ocaml,Models all_models) throws IOException { if(this.IsFirtCompute) {this.p=start(ocaml.getDimacsFilePath()); this.IsFirtCompute=false; } //wizz out=new PrintWriter (new BufferedWriter (new OutputStreamWriter(p.getOutputStream()))); out.println("1"); out.flush(); out.close(); //wizz StringBuffer br=new StringBuffer(); BufferedReader reader =new BufferedReader(new InputStreamReader(p.getInputStream())); String line=""; while((line=reader.readLine())!=null){ br.append(line+"\n"); } Model model=new Model(); Parse_Model(model,ocaml,br.toString().split(" ")); all_models.addModel(model); return model; } //Get Correspondance and Valuate Literal item. private void Parse_Model(Model model,ResultatOcaml ocaml,String[] output_Value){ for (String Literal : output_Value){ model.addLiteral(ocaml.getLiteraux().get(Integer.parseInt(Literal))); } } public Process start(String dimacsFilesPath) throws IOException { this.p=Runtime.getRuntime().exec("java -cp .:sat4j-sat.jar Minisat "+dimacsFilesPath); return p; } public void stop() { out=new PrintWriter (new BufferedWriter (new OutputStreamWriter(p.getOutputStream()))); out.println("\n0"); out.close(); this.IsFirtCompute=true; this.p.destroy(); } }
Deleted and modified to match the ModelsIterator class and the deleted the "OcamlResult" class
ui/solution/Solver.java
Deleted and modified to match the ModelsIterator class and the deleted the "OcamlResult" class
<ide><path>i/solution/Solver.java <ide> import java.io.InputStreamReader; <ide> import java.io.OutputStreamWriter; <ide> import java.io.PrintWriter; <del> <del>import translation.ResultatOcaml; <add>import java.util.Map; <ide> <ide> /** <ide> * This class <ide> * - launches the solver program with the DIMACS input <del> * - if this DIMACS is satisfiable, gives an iterable <del> * object that will, itself, call SolverSAT to get <add> * - if this DIMACS is satisfiable, gives an iterable Models <add> * - gives a way to get the next Model and do the translation <add> * with the literalsMap (DIMACS integers to literal names) <add> * <ide> * the next model. <ide> * @author Abdel <ide> */ <del>public class Solver implements Iterable<Model> { <add>public class Solver { <ide> private Process p; <del> private boolean IsFirtCompute=true; <ide> private PrintWriter out; <add> private String dimacsFilePath; <add> private Map<Integer,String> literalsMap; <ide> <ide> public Solver(String dimacsFilePath) { <del> <add> this.dimacsFilePath = dimacsFilePath; <add> this.literalsMap = null; <ide> } <ide> <del> public Solver(String dimacsFilePath, LiteralsMap map) { <del> <add> public Solver(String dimacsFilePath, Map<Integer,String> literalsMap) { <add> this.dimacsFilePath = dimacsFilePath; <add> this.literalsMap = literalsMap; <ide> } <ide> <ide> public Models launch() { <ide> return null; <del> <del> } <del> public void stop() { <del> <ide> } <ide> <del> public Model computeModel(ResultatOcaml ocaml,Models all_models) throws IOException { <del> if(this.IsFirtCompute) <del> {this.p=start(ocaml.getDimacsFilePath()); <del> this.IsFirtCompute=false; <del> } <del> //wizz <add> /** <add> * ONLY used by ModelsIterator <add> * @return null if no more model (or if not satisfiable) <add> * @throws IOException <add> */ <add> protected Model nextModel() throws IOException { <ide> out=new PrintWriter (new BufferedWriter (new OutputStreamWriter(p.getOutputStream()))); <ide> out.println("1"); <ide> out.flush(); <ide> out.close(); <del> //wizz <ide> StringBuffer br=new StringBuffer(); <ide> BufferedReader reader =new BufferedReader(new InputStreamReader(p.getInputStream())); <ide> String line=""; <ide> while((line=reader.readLine())!=null){ <ide> br.append(line+"\n"); <ide> } <add> return parseModel(br.toString().split(" ")); <add> } <add> <add> /** <add> * <add> * @param rawModelOutput The output <add> * @return a model with, if a literalMap was given, the translated <add> * literal. If no literalMap is given, the Model stores the literal <add> * as given by the solver (an integer). <add> */ <add> private Model parseModel(String[] rawModelOutput){ <ide> Model model=new Model(); <del> Parse_Model(model,ocaml,br.toString().split(" ")); <del> all_models.addModel(model); <add> for (String rawLiteral : rawModelOutput){ <add> if(literalsMap != null){ <add> model.addLiteral(literalsMap.get(Integer.parseInt(rawLiteral))); <add> } else { <add> model.addLiteral(rawLiteral); <add> } <add> } <ide> return model; <del> } <del> //Get Correspondance and Valuate Literal item. <del> private void Parse_Model(Model model,ResultatOcaml ocaml,String[] output_Value){ <del> for (String Literal : output_Value){ <del> model.addLiteral(ocaml.getLiteraux().get(Integer.parseInt(Literal))); <del> } <ide> } <ide> public Process start(String dimacsFilesPath) throws IOException { <ide> this.p=Runtime.getRuntime().exec("java -cp .:sat4j-sat.jar Minisat "+dimacsFilesPath); <ide> return p; <ide> } <ide> <del> public void stop() { <add> /** <add> * Kills the solver program process <add> */ <add> public void close() { <ide> out=new PrintWriter (new BufferedWriter (new OutputStreamWriter(p.getOutputStream()))); <ide> out.println("\n0"); <ide> out.close(); <del> this.IsFirtCompute=true; <ide> this.p.destroy(); <ide> } <del> <ide> }
JavaScript
mit
e55fa9a3e502414528d5bec9bde23871ef929271
0
cesarmarinhorj/strata,bigeasy/strata,cesarmarinhorj/strata,bigeasy/strata
#!/usr/bin/env node require('./proof')(1, function (step, Strata, tmp, load, serialize, vivify, assert) { var strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 }) step(function () { serialize(__dirname + '/fixtures/empties-non-pivot.before.json', tmp, step()) }, function () { strata.open(step()) }, function () { strata.mutator('cr', step()) }, function (cursor) { step(function () { cursor.remove(cursor.index, step()) }, function () { cursor.unlock() }) }, function () { strata.balance(step()) }, function () { vivify(tmp, step()) load(__dirname + '/fixtures/empties-non-pivot.after.json', step()) }, function (actual, expected) { assert(actual, expected, 'after') strata.close(step()) }) })
t/merge/empties-non-pivot.t.js
#!/usr/bin/env node require('./proof')(1, function (step, Strata, tmp, serialize, load, vivify, assert) { var strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 }) step(function () { serialize(__dirname + '/fixtures/empties-non-pivot.before.json', tmp, step()) }, function () { strata.open(step()) }, function () { strata.mutator('cr', step()) }, function (cursor) { step(function () { cursor.remove(cursor.index, step()) }, function () { cursor.unlock() }) }, function () { strata.balance(step()) }, function () { vivify(tmp, step()) load(__dirname + '/fixtures/empties-non-pivot.after.json', step()) }, function (actual, expected) { assert(actual, expected, 'after') strata.close(step()) }) })
More tidy `empties-non-pivot.t.js`. See #351.
t/merge/empties-non-pivot.t.js
More tidy `empties-non-pivot.t.js`.
<ide><path>/merge/empties-non-pivot.t.js <ide> #!/usr/bin/env node <ide> <del>require('./proof')(1, function (step, Strata, tmp, serialize, load, vivify, assert) { <add>require('./proof')(1, function (step, Strata, tmp, load, serialize, vivify, assert) { <ide> var strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 }) <ide> step(function () { <ide> serialize(__dirname + '/fixtures/empties-non-pivot.before.json', tmp, step())
Java
apache-2.0
329732fc96e1d818c49e7be5cc3375fac1e78cc8
0
getlantern/lantern-java,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,getlantern/lantern-java,lqch14102/lantern
package org.lantern; import java.io.File; import org.apache.commons.lang3.SystemUtils; import org.lantern.exceptional4j.ExceptionalUtils; /** * Client-side constants. */ public class LanternClientConstants { public static final String FALLBACK_SERVER_HOST; public static final String FALLBACK_SERVER_PORT; static { final String host = "fallback_server_host_tok"; final String port = "fallback_server_port_tok"; FALLBACK_SERVER_HOST = host.endsWith("_tok") ? "75.101.134.244" : host; FALLBACK_SERVER_PORT = port.endsWith("_tok") ? "7777" : port; } public static final String FALLBACK_SERVER_USER = "fallback_server_user_tok"; public static final String FALLBACK_SERVER_PASS = "fallback_server_pass_tok"; /** * This is the version of Lantern we're running. This is automatically * replaced when we push new releases. */ public static final String VERSION = "0.21.0-dev"; public static File DATA_DIR; public static File LOG_DIR; public static final File CONFIG_DIR = new File(System.getProperty("user.home"), ".lantern"); public static final File DEFAULT_MODEL_FILE = new File(CONFIG_DIR, "model"); public static final File DEFAULT_TRANSFERS_FILE = new File(CONFIG_DIR, "transfers"); public static final File TEST_PROPS = new File(CONFIG_DIR, "test.properties"); public static final File TEST_PROPS2 = new File(SystemUtils.USER_DIR, "src/test/resources/test.properties"); public static final long START_TIME = System.currentTimeMillis(); public static final int SYNC_INTERVAL_SECONDS = 2; /** * Plist file for launchd on OSX. */ public static final File LAUNCHD_PLIST = new File(System.getProperty("user.home"), "Library/LaunchAgents/org.lantern.plist"); /** * Configuration file for starting at login on Gnome. */ public static final File GNOME_AUTOSTART = new File(System.getProperty("user.home"), ".config/autostart/lantern-autostart.desktop"); public static final String GET_EXCEPTIONAL_API_KEY = ExceptionalUtils.NO_OP_KEY; static { // Only load these if we're not on app engine. if (SystemUtils.IS_OS_WINDOWS) { //logDirParent = CommonUtils.getDataDir(); DATA_DIR = new File(System.getenv("APPDATA"), "Lantern"); LOG_DIR = new File(DATA_DIR, "logs"); } else if (SystemUtils.IS_OS_MAC_OSX) { final File homeLibrary = new File(System.getProperty("user.home"), "Library"); DATA_DIR = CONFIG_DIR;//new File(homeLibrary, "Logs"); final File allLogsDir = new File(homeLibrary, "Logs"); LOG_DIR = new File(allLogsDir, "Lantern"); } else { DATA_DIR = new File(System.getProperty("user.home"), ".lantern"); LOG_DIR = new File(DATA_DIR, "logs"); } if (!DATA_DIR.isDirectory()) { if (!DATA_DIR.mkdirs()) { System.err.println("Could not create parent at: " + DATA_DIR); } } if (!LOG_DIR.isDirectory()) { if (!LOG_DIR.mkdirs()) { System.err.println("Could not create dir at: " + LOG_DIR); } } if (!CONFIG_DIR.isDirectory()) { if (!CONFIG_DIR.mkdirs()) { System.err.println("Could not make config directory at: "+ CONFIG_DIR); } } } public static final File GEOIP = new File(DATA_DIR, "GeoIP.dat"); public static final String LANTERN_VERSION_HTTP_HEADER_VALUE = VERSION; public static final String LOCALHOST = "127.0.0.1"; // Not final because it may be set from the command line for debugging. public static String LANTERN_JID; // Not final because it may be set from the command line for debugging. public static String STATS_URL; public static void setControllerId(final String id) { LANTERN_JID = id + "@appspot.com"; STATS_URL = "https://" + id + ".appspot.com/stats"; } static { setControllerId("lanternctrl"); } }
src/main/java/org/lantern/LanternClientConstants.java
package org.lantern; import java.io.File; import org.apache.commons.lang3.SystemUtils; import org.lantern.exceptional4j.ExceptionalUtils; /** * Client-side constants. */ public class LanternClientConstants { public static final String FALLBACK_SERVER_HOST; public static final String FALLBACK_SERVER_PORT; static { final String host = "fallback_server_host_tok"; final String port = "fallback_server_port_tok"; FALLBACK_SERVER_HOST = host.endsWith("_tok") ? "75.101.134.244" : host; FALLBACK_SERVER_PORT = port.endsWith("_tok") ? "7777" : port; } public static final String FALLBACK_SERVER_USER = "fallback_server_user_tok"; public static final String FALLBACK_SERVER_PASS = "fallback_server_pass_tok"; /** * This is the version of Lantern we're running. This is automatically * replaced when we push new releases. */ public static final String VERSION = "0.21.0-dev"; public static File DATA_DIR; public static File LOG_DIR; public static final File CONFIG_DIR = new File(System.getProperty("user.home"), ".lantern"); public static final File DEFAULT_MODEL_FILE = new File(CONFIG_DIR, "model"); public static final File DEFAULT_TRANSFERS_FILE = new File(CONFIG_DIR, "transfers"); public static final File TEST_PROPS = new File(CONFIG_DIR, "test.properties"); public static final File TEST_PROPS2 = new File(SystemUtils.USER_DIR, "src/test/resources/test.properties"); public static final long START_TIME = System.currentTimeMillis(); public static final int SYNC_INTERVAL_SECONDS = 2; /** * Plist file for launchd on OSX. */ public static final File LAUNCHD_PLIST = new File(System.getProperty("user.home"), "Library/LaunchAgents/org.lantern.plist"); /** * Configuration file for starting at login on Gnome. */ public static final File GNOME_AUTOSTART = new File(System.getProperty("user.home"), ".config/autostart/lantern-autostart.desktop"); public static final String GET_EXCEPTIONAL_API_KEY = ExceptionalUtils.NO_OP_KEY; static { // Only load these if we're not on app engine. if (SystemUtils.IS_OS_WINDOWS) { //logDirParent = CommonUtils.getDataDir(); DATA_DIR = new File(System.getenv("APPDATA"), "Lantern"); LOG_DIR = new File(DATA_DIR, "logs"); } else if (SystemUtils.IS_OS_MAC_OSX) { final File homeLibrary = new File(System.getProperty("user.home"), "Library"); DATA_DIR = CONFIG_DIR;//new File(homeLibrary, "Logs"); final File allLogsDir = new File(homeLibrary, "Logs"); LOG_DIR = new File(allLogsDir, "Lantern"); } else { DATA_DIR = new File(System.getProperty("user.home"), ".lantern"); LOG_DIR = new File(DATA_DIR, "logs"); } if (!DATA_DIR.isDirectory()) { if (!DATA_DIR.mkdirs()) { System.err.println("Could not create parent at: " + DATA_DIR); } } if (!LOG_DIR.isDirectory()) { if (!LOG_DIR.mkdirs()) { System.err.println("Could not create dir at: " + LOG_DIR); } } if (!CONFIG_DIR.isDirectory()) { if (!CONFIG_DIR.mkdirs()) { System.err.println("Could not make config directory at: "+ CONFIG_DIR); } } } public static final File GEOIP = new File(DATA_DIR, "GeoIP.dat"); public static final String LANTERN_VERSION_HTTP_HEADER_VALUE = VERSION; public static final String LOCALHOST = "127.0.0.1"; // Not final because it may be set from the command line for debugging. public static String LANTERN_JID; // Not final because it may be set from the command line for debugging. public static String STATS_URL; public static void setControllerId(final String id) { LANTERN_JID = id + "@appspot.com"; STATS_URL = "http://" + id + ".appspot.com/stats"; } static { setControllerId("lanternctrl"); } }
Changed to use https for stats
src/main/java/org/lantern/LanternClientConstants.java
Changed to use https for stats
<ide><path>rc/main/java/org/lantern/LanternClientConstants.java <ide> <ide> public static void setControllerId(final String id) { <ide> LANTERN_JID = id + "@appspot.com"; <del> STATS_URL = "http://" + id + ".appspot.com/stats"; <add> STATS_URL = "https://" + id + ".appspot.com/stats"; <ide> } <ide> <ide> static {
Java
apache-2.0
5ddf1fee43b623b6f4b22e208cb7bef4c6cfcb5b
0
Diusrex/CMPUT301-Assignment1
package com.example.assignment1; import java.util.Calendar; import java.util.Currency; import java.util.GregorianCalendar; public class TravelExpense { private Calendar date; private String description; private Category category; private float amount; private Currency currency; enum Category { AIR_FAIR, GROUND_TRANSPORT, VEHICLE_RENTAL, FUEL, PARKING, REGISTARTION, ACCOMMODATION, MEAL, OTHER }; TravelExpense() { date = new GregorianCalendar(); description = ""; category = Category.OTHER; amount = 0; currency = CurrencyHandler.getLocalDefaultCurrency(); } public Calendar getDate() { return date; } public String getDescription() { return description; } public Category getCategory() { return category; } public float getAmount() { return amount; } public Currency getCurrency() { return currency; } }
src/com/example/assignment1/TravelExpense.java
package com.example.assignment1; public class TravelExpense { }
Set up the expense class with all its needed members
src/com/example/assignment1/TravelExpense.java
Set up the expense class with all its needed members
<ide><path>rc/com/example/assignment1/TravelExpense.java <ide> package com.example.assignment1; <ide> <add>import java.util.Calendar; <add>import java.util.Currency; <add>import java.util.GregorianCalendar; <add> <ide> public class TravelExpense { <add> private Calendar date; <add> private String description; <add> private Category category; <add> private float amount; <add> private Currency currency; <add> <add> enum Category { <add> AIR_FAIR, GROUND_TRANSPORT, VEHICLE_RENTAL, FUEL, PARKING, REGISTARTION, ACCOMMODATION, MEAL, OTHER <add> }; <add> <add> TravelExpense() { <add> date = new GregorianCalendar(); <add> description = ""; <add> category = Category.OTHER; <add> amount = 0; <add> currency = CurrencyHandler.getLocalDefaultCurrency(); <add> } <add> <add> public Calendar getDate() { <add> return date; <add> } <add> <add> public String getDescription() { <add> return description; <add> } <add> <add> public Category getCategory() { <add> return category; <add> } <add> <add> public float getAmount() { <add> return amount; <add> } <add> <add> public Currency getCurrency() { <add> return currency; <add> } <ide> <ide> }
JavaScript
mit
82e5d198ff7fcc39293e8dea1e02bea034545a0c
0
SpectrumBroad/xible,SpectrumBroad/xible
View.routes['/settings/general'] = function(EL) { EL.innerHTML = ` <section> <h1>General</h1> <section id="webserver"> <h2>Webserver</h2> <dl> <dt> <label for="settingsGeneralWebserverPort"> Port <div>The plain-HTTP (non-SSL) port this web interface and the API routes are hosted on. If SSL is enabled, requests from this port are redirected to a secure connection on this port number incremented by 1.<br/>For example, if port 9600 is configured here and SSL is enabled, port 9601 will host the secure connection.</div> </label> </dt> <dd><input id="settingsGeneralWebserverPort" type="number" data-configpath="webServer.port" /></dd> <dt> <label for="settingsGeneralWebserverKeyPath"> SSL key path <div>Path to a SSL key file. If configured together with the &quot;SSL certificate path&quot;, SSL will be enabled and plain HTTP requests redirect to the HTTPS connection.</div> </label> </dt> <dd><input id="settingsGeneralWebserverKeyPath" type="text" data-configpath="webServer.keyPath" /></dd> <dt> <label for="settingsGeneralWebserverCertPath"> SSL certificate path <div>Path to a SSL certificate file. If configured together with the &quot;SSL key path&quot;, SSL will be enabled and plain HTTP requests redirect to the HTTPS connection.</div> </label> </dt> <dd><input id="settingsGeneralWebserverCertPath" type="text" data-configpath="webServer.certPath" /></dd> </dl> </section> </section> `; };
editor/views/settings/general.js
View.routes['/settings/general'] = function(EL) { EL.innerHTML = ` <section> <h1>General</h1> <section id="webserver"> <h2>Webserver</h2> <dl> <dt> <label for="settingsGeneralWebserverPort"> Port <div>The plain-HTTP (non-SSL) port this web interface and the API routes are hosted on. If SSL is enabled, requests from this port are redirected to a secure connection on this port number incremented by 1.<br/>For example, if port 9600 is configured here and SSL is enabled, port 9601 will host the secure connection.</div> </label> </dt> <dd><input id="settingsGeneralWebserverPort" type="number" value="9600" /></dd> <dt> <label for="settingsGeneralWebserverKeyPath"> SSL key path <div>Path to a SSL key file. If configured together with the &quot;SSL certificate path&quot;, SSL will be enabled and plain HTTP requests redirect to the HTTPS connection.</div> </label> </dt> <dd><input id="settingsGeneralWebserverKeyPath" type="text" /></dd> <dt> <label for="settingsGeneralWebserverCertPath"> SSL certificate path <div>Path to a SSL certificate file. If configured together with the &quot;SSL key path&quot;, SSL will be enabled and plain HTTP requests redirect to the HTTPS connection.</div> </label> </dt> <dd><input id="settingsGeneralWebserverCertPath" type="text" /></dd> </dl> </section> </section> `; };
added configpaths for working ui
editor/views/settings/general.js
added configpaths for working ui
<ide><path>ditor/views/settings/general.js <ide> <div>The plain-HTTP (non-SSL) port this web interface and the API routes are hosted on. If SSL is enabled, requests from this port are redirected to a secure connection on this port number incremented by 1.<br/>For example, if port 9600 is configured here and SSL is enabled, port 9601 will host the secure connection.</div> <ide> </label> <ide> </dt> <del> <dd><input id="settingsGeneralWebserverPort" type="number" value="9600" /></dd> <add> <dd><input id="settingsGeneralWebserverPort" type="number" data-configpath="webServer.port" /></dd> <ide> <ide> <dt> <ide> <label for="settingsGeneralWebserverKeyPath"> <ide> <div>Path to a SSL key file. If configured together with the &quot;SSL certificate path&quot;, SSL will be enabled and plain HTTP requests redirect to the HTTPS connection.</div> <ide> </label> <ide> </dt> <del> <dd><input id="settingsGeneralWebserverKeyPath" type="text" /></dd> <add> <dd><input id="settingsGeneralWebserverKeyPath" type="text" data-configpath="webServer.keyPath" /></dd> <ide> <ide> <dt> <ide> <label for="settingsGeneralWebserverCertPath"> <ide> <div>Path to a SSL certificate file. If configured together with the &quot;SSL key path&quot;, SSL will be enabled and plain HTTP requests redirect to the HTTPS connection.</div> <ide> </label> <ide> </dt> <del> <dd><input id="settingsGeneralWebserverCertPath" type="text" /></dd> <add> <dd><input id="settingsGeneralWebserverCertPath" type="text" data-configpath="webServer.certPath" /></dd> <ide> <ide> </dl> <ide> </section>
Java
agpl-3.0
939f5cdd6b23b11546990f6e62031687ec64fd78
0
AlienQueen/HatchetHarry,AlienQueen/HatchetHarry,AlienQueen/HatchetHarry
package org.alienlabs.hatchetharry.service; import java.io.Serializable; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import org.alienlabs.hatchetharry.model.CardZone; import org.alienlabs.hatchetharry.model.CollectibleCard; import org.alienlabs.hatchetharry.model.Counter; import org.alienlabs.hatchetharry.model.Deck; import org.alienlabs.hatchetharry.model.DeckArchive; import org.alienlabs.hatchetharry.model.Game; import org.alienlabs.hatchetharry.model.MagicCard; import org.alienlabs.hatchetharry.model.Player; import org.alienlabs.hatchetharry.model.Side; import org.alienlabs.hatchetharry.model.Token; import org.alienlabs.hatchetharry.persistence.dao.CollectibleCardDao; import org.alienlabs.hatchetharry.persistence.dao.CounterDao; import org.alienlabs.hatchetharry.persistence.dao.DeckArchiveDao; import org.alienlabs.hatchetharry.persistence.dao.DeckDao; import org.alienlabs.hatchetharry.persistence.dao.GameDao; import org.alienlabs.hatchetharry.persistence.dao.MagicCardDao; import org.alienlabs.hatchetharry.persistence.dao.PlayerDao; import org.alienlabs.hatchetharry.persistence.dao.SideDao; import org.alienlabs.hatchetharry.persistence.dao.TokenDao; import org.apache.wicket.spring.injection.annot.SpringBean; import org.hibernate.ObjectNotFoundException; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; public class PersistenceService implements Serializable { private static final long serialVersionUID = 1L; static final Logger LOGGER = LoggerFactory.getLogger(PersistenceService.class); @SpringBean private PlayerDao playerDao; @SpringBean private DeckDao deckDao; @SpringBean private DeckArchiveDao deckArchiveDao; @SpringBean private CollectibleCardDao collectibleCardDao; @SpringBean private MagicCardDao magicCardDao; @SpringBean private GameDao gameDao; @SpringBean private SideDao sideDao; @SpringBean private CounterDao counterDao; @SpringBean private TokenDao tokenDao; public PersistenceService() { } @Transactional(readOnly = true) public MagicCard getNthCardOfGame(final Long index) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("from MagicCard magiccard0_ where magiccard0_.id=?"); query.setLong(0, index); final MagicCard c = (MagicCard)query.uniqueResult(); return c; } @Transactional(isolation = Isolation.SERIALIZABLE) public MagicCard saveCardByGeneratingItsUuid(final MagicCard _c, final long gameId) { final MagicCard c = _c; c.setUuid(UUID.randomUUID().toString()); c.setGameId(gameId); final Session session = this.magicCardDao.getSession(); final Long id = (Long)session.save(c); c.setId(id); return c; } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveCard(final MagicCard c) { this.magicCardDao.getSession().save(c); } @Transactional(isolation = Isolation.SERIALIZABLE) public MagicCard saveOrUpdateCardAndDeck(final MagicCard c) { this.deckDao.getSession().merge(c.getDeck()); this.magicCardDao.getSession().merge(c); return c; } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveToken(final Token t) { this.tokenDao.getSession().save(t); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateAllMagicCards(final List<MagicCard> allMagicCards) { for (final MagicCard card : allMagicCards) { this.magicCardDao.getSession().saveOrUpdate(card); } } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateCard(final MagicCard c) { this.magicCardDao.getSession().update(c); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateToken(final Token t) { this.tokenDao.getSession().update(t); } @Transactional(isolation = Isolation.SERIALIZABLE) public void deleteCardAndToken(final MagicCard c) { final Token token = c.getToken(); final Player p = token.getPlayer(); token.setPlayer(null); final Set<Counter> counters = c.getCounters(); final List<MagicCard> magicCardCards = c.getDeck().getCards(); magicCardCards.remove(c); c.getDeck().setCards(magicCardCards); final Deck d = c.getDeck(); p.setDeck(d); token.setPlayer(p); final Long magicCardId = c.getId(); this.deckDao.getSession().merge(d); Session session = this.magicCardDao.getSession(); Query query = session.createSQLQuery("delete from MagicCard where magicCardId = ? "); query.setLong(0, magicCardId); query.executeUpdate(); session = this.tokenDao.getSession(); query = session .createSQLQuery("delete t.* from Card_Counter cc, Token t, MagicCard mc where t.tokenId = mc.token_tokenId and cc.counterId = t.tokenId and mc.magicCardId = ?"); query.setLong(0, magicCardId); query.executeUpdate(); session = this.magicCardDao.getSession(); query = session .createSQLQuery("delete cc.* from Card_Counter cc, Counter c, MagicCard mc where c.card = mc.magicCardId and cc.counterId = c.counterId and mc.magicCardId = ?"); query.setLong(0, magicCardId); query.executeUpdate(); for (final Counter counter : counters) { session = this.counterDao.getSession(); query = session.createSQLQuery("delete from Counter where counterId = ? "); query.setLong(0, counter.getId()); query.executeUpdate(); } } @Transactional(readOnly = true) public MagicCard getCardFromUuid(final UUID uuid) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("from MagicCard magiccard0_ where magiccard0_.uuid= ? "); query.setString(0, uuid.toString()); query.setCacheable(true); PersistenceService.LOGGER.debug("card UUID: " + uuid.toString()); if (query.list().size() > 1) { return (MagicCard)query.list().get(0); } final MagicCard c = (MagicCard)query.uniqueResult(); return c; } @Transactional(readOnly = true) public Token getTokenFromUuid(final String uuid) { final Session session = this.tokenDao.getSession(); final Query query = session.createQuery("from Token t0_ where t0_.uuid= ? "); query.setString(0, uuid); query.setCacheable(true); PersistenceService.LOGGER.debug("token UUID: "); if (query.list().size() > 1) { return (Token)query.list().get(0); } final Token t = (Token)query.uniqueResult(); return t; } @Transactional(readOnly = true) public Token getTokenFromUuid(final UUID uuid) { final Session session = this.tokenDao.getSession(); final Query query = session.createQuery("from Token token0 where token0.uuid= ? "); query.setString(0, uuid.toString()); PersistenceService.LOGGER.debug("token UUID: " + uuid.toString()); if (query.list().size() > 1) { return (Token)query.list().get(0); } final Token t = (Token)query.uniqueResult(); return t; } @Transactional(readOnly = true) public List<MagicCard> getFirstHand(final long gameId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("from MagicCard magiccard0_ where magiccard0_.gameId=?"); query.setLong(0, gameId); query.setFirstResult(0); query.setMaxResults(7); final List<MagicCard> cards = query.list(); return cards; } @Transactional(readOnly = true) public Player getFirstPlayer() { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from Player player0_"); query.setFirstResult(0); query.setMaxResults(1); final Object mc = query.uniqueResult(); return (mc == null ? null : (Player)mc); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updatePlayer(final Player p) { final Session session = this.playerDao.getSession(); session.merge(p); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateSide(final Side s) { final Session session = this.sideDao.getSession(); session.merge(s); } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveCounter(final Counter c) { final Session session = this.counterDao.getSession(); session.save(c); } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveGame(final Game g) { final Session session = this.gameDao.getSession(); session.save(g); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateGame(final Game g) { this.gameDao.getSession().update(g); } @Transactional(readOnly = true) public int countPlayers(final long l) { final Session session = this.playerDao.getSession(); final Query query = session.createQuery("from Player player0_ where player0_.gameId=?"); query.setLong(0, l); return query.list().size(); } @Transactional(readOnly = true) public int countDeckArchives() { final Session session = this.deckArchiveDao.getSession(); final Query query = session.createQuery("from DeckArchive"); return query.list().size(); } @Transactional(readOnly = true) public int countCollectibleCards() { final Session session = this.collectibleCardDao.getSession(); final Query query = session.createQuery("from CollectibleCard"); return query.list().size(); } @Transactional(readOnly = true) public int countCollectibleCardsInDeckArchive(final DeckArchive deckArchive) { final Session session = this.collectibleCardDao.getSession(); final Query query = session .createQuery("from CollectibleCard cc where cc.deckArchiveId = ?"); query.setLong(0, deckArchive.getDeckArchiveId()); return query.list().size(); } @Transactional(readOnly = true) public List<CollectibleCard> giveAllCollectibleCardsInDeckArchive(final DeckArchive deckArchive) { final Session session = this.collectibleCardDao.getSession(); final Query query = session .createQuery("from CollectibleCard cc where cc.deckArchiveId = ?"); query.setLong(0, deckArchive.getDeckArchiveId()); return query.list(); } @Transactional(readOnly = true) public int countMagicCards() { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from MagicCard"); return query.list().size(); } @Transactional(readOnly = true) public int countDecks() { final Session session = this.deckDao.getSession(); final Query query = session.createQuery("from Deck"); return query.list().size(); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateDeck(final Deck d) { final Session session = this.deckDao.getSession(); session.update(d); } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveOrUpdateDeck(final Deck d) { final Session session = this.deckDao.getSession(); session.merge(d); } @Transactional(isolation = Isolation.SERIALIZABLE) public Deck saveDeck(final Deck d) { this.deckDao.getSession().save(d); return d; } @Transactional(isolation = Isolation.SERIALIZABLE) public Deck saveDeckOrUpdate(final Deck d) { this.deckDao.getSession().saveOrUpdate(d); return d; } @Transactional(isolation = Isolation.SERIALIZABLE) public Side saveSide(final Side s) { this.sideDao.getSession().save(s); return s; } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveSides(final Set<Side> sides) { for (final Side s : sides) { this.sideDao.getSession().save(s); } } @Transactional(readOnly = true) public Player getPlayer(final Long l) { return this.playerDao.load(l); } @Transactional(readOnly = true) public boolean getPlayerByGame(final long l) { final Session session = this.playerDao.getSession(); final Query query = session.createQuery("from Player player0_ where player0_.gameId=?"); query.setLong(0, l); return query.list().size() > 0; } @Transactional(readOnly = true) public List<Player> getAllPlayersOfGame(final long l) { final Session session = this.playerDao.getSession(); final SQLQuery query = session .createSQLQuery("select player0_.* from Player player0_ where player0_.game_gameId=?"); query.addEntity(Player.class); query.setLong(0, l); return query.list(); } // Isolation level chosen to be consistent with // RuntimeDataGenerator#generateData() @Transactional(isolation = Isolation.REPEATABLE_READ) public DeckArchive getDeckArchiveByName(final String name) { final Session session = this.deckDao.getSession(); final SQLQuery query = session .createSQLQuery("select da.* from Deck d, DeckArchive da where da.deckName=? and da.deckArchiveId = d.Deck_DeckArchive"); query.addEntity(DeckArchive.class); query.setString(0, name); @SuppressWarnings("rawtypes") final List results = query.list(); return (results.size() > 0 ? (DeckArchive)query.list().get(0) : null); } @Transactional(readOnly = true) public boolean getPlayerByJsessionId(final String jsessionid) { final Session session = this.playerDao.getSession(); final Query query = session.createQuery("from Player player0_ where player0_.jsessionid=?"); query.setString(0, jsessionid); return query.list().size() > 0; } @Transactional(readOnly = true) public boolean doesCollectibleCardAlreadyExistsInDb(final String title) { final Session session = this.collectibleCardDao.getSession(); final Query query = session.createQuery("from CollectibleCard cc0_ where cc0_.title=?"); query.setString(0, title); final List<?> list = query.list(); return ((list != null) && (list.size() > 0)); } @Transactional(readOnly = true) public Deck getDeck(final long deckId) { final Session session = this.deckDao.getSession(); final Query query = session.createQuery("from Deck deck0_ where deck0_.deckId=?"); query.setLong(0, deckId); query.setMaxResults(1); return (Deck)query.uniqueResult(); } @Transactional(readOnly = true) public Deck getDeckByDeckArchiveIdAndPlayerId(final long deckArchiveId, final long playerId) { final Session session = this.deckDao.getSession(); final Query query = session .createQuery("from Deck d where d.deckArchive=? and d.playerId=?"); query.setLong(0, deckArchiveId); query.setLong(1, playerId); query.setMaxResults(1); return (Deck)query.uniqueResult(); } @Transactional(readOnly = true) public List<MagicCard> getAllCardsFromDeck(final long l) { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from MagicCard card0_ where card0_.deck=?"); query.setLong(0, l); List<MagicCard> list = new ArrayList<MagicCard>(); try { list = query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("error!", e); } return list; } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInLibraryForDeckAndPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ? order by mc.zoneOrder"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.LIBRARY.toString()); query.setLong(2, playerId); query.setLong(3, deckId); List<MagicCard> list = new ArrayList<MagicCard>(); try { list = query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("error!", e); } return list; } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveCollectibleCard(final CollectibleCard cc) { this.collectibleCardDao.getSession().save(cc); } @Transactional(isolation = Isolation.SERIALIZABLE) public DeckArchive saveDeckArchive(final DeckArchive da) { final Session session = this.deckArchiveDao.getSession(); final SQLQuery query = session .createSQLQuery("select da.* from Deck d, DeckArchive da where da.deckName=? and da.deckArchiveId = d.Deck_DeckArchive"); query.addEntity(DeckArchive.class); query.setString(0, da.getDeckName()); if (query.list().size() > 0) { return ((DeckArchive)query.list().get(0)); } session.save(da); return da; } @Transactional(isolation = Isolation.SERIALIZABLE) public DeckArchive updateDeckArchive(final DeckArchive da) { final Session session = this.deckArchiveDao.getSession(); session.update(da); return da; } @Required public void setPlayerDao(final PlayerDao _playerDao) { this.playerDao = _playerDao; } @Required public void setDeckDao(final DeckDao _deckDao) { this.deckDao = _deckDao; } @Required public void setDeckArchiveDao(final DeckArchiveDao _deckArchiveDao) { this.deckArchiveDao = _deckArchiveDao; } @Required public void setSideDao(final SideDao _sideDao) { this.sideDao = _sideDao; } @Required public void setCollectibleCardDao(final CollectibleCardDao _collectibleCardDao) { this.collectibleCardDao = _collectibleCardDao; } @Required public void setMagicCardDao(final MagicCardDao _magicCardDao) { this.magicCardDao = _magicCardDao; } @Required public void setGameDao(final GameDao _gameDao) { this.gameDao = _gameDao; } @Required public void setCounterDao(final CounterDao _counterDao) { this.counterDao = _counterDao; } @Required public void setTokenDao(final TokenDao _tokenDao) { this.tokenDao = _tokenDao; } @Transactional(readOnly = true) public List<?> getCardsByDeckId(final long gameId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("select card0_ from MagicCard card0_ , Deck deck0_ where card0_.deck = deck0_.deckId and deck0_.deckId = ?"); query.setLong(0, gameId); return query.list(); } @Transactional(readOnly = true) public List<Deck> getAllDecks() { final Session session = this.deckDao.getSession(); final Query query = session.createQuery("from Deck deck0_ where deck0_.playerId != -1"); return query.list(); } @Transactional(readOnly = true) public List<DeckArchive> getAllDeckArchives() { final Session session = this.deckDao.getSession(); final Query query = session.createQuery("from DeckArchive d where d.deckName != null"); return query.list(); } @Transactional(readOnly = true) public List<Deck> getAllDecksFromDeckArchives() { final Session session = this.deckDao.getSession(); final SQLQuery query = session .createSQLQuery("select dd.* from Deck dd where dd.Deck_DeckArchive in (select distinct da.deckArchiveId from Deck de, DeckArchive da where de.Deck_DeckArchive = da.deckArchiveId and da.deckName is not null) group by dd.Deck_DeckArchive"); query.addEntity(Deck.class); return query.list(); } @Transactional(isolation = Isolation.SERIALIZABLE) public Game createGameAndPlayer(final Game game, final Player player) { final Set<Player> set = game.getPlayers(); set.add(player); game.setPlayers(set); player.setGame(game); this.playerDao.getSession().save(player); this.gameDao.getSession().save(game); return game; } @Transactional(readOnly = true) public MagicCard findCardByName(final String _name) { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from MagicCard m where m.title = ?"); query.setString(0, _name); query.setMaxResults(1); try { return (MagicCard)query.list().get(0); } catch (final IndexOutOfBoundsException e) { PersistenceService.LOGGER.error("error!", e); return null; } } @Transactional(readOnly = true) public CollectibleCard findCollectibleCardByName(final String title) { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from CollectibleCard cc where cc.title = ?"); query.setString(0, title); query.setMaxResults(1); try { return (CollectibleCard)query.uniqueResult(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("error!", e); return null; } } @Transactional(readOnly = true) public Game getGame(final Long _id) { return this.gameDao.load(_id); } @Transactional public void deleteMagicCard(final MagicCard mc) { this.magicCardDao.delete(mc.getId()); } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInHandForAGameAndAPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ? order by mc.zoneOrder"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.HAND.toString()); query.setLong(2, playerId); query.setLong(3, deckId); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in hand for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInBattleFieldForAGame(final Long gameId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("select m from MagicCard m where m.gameId = :gameId and m.zone = :zone"); query.setLong("gameId", gameId); query.setParameter("zone", CardZone.BATTLEFIELD); query.setCacheable(true); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in battlefield for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInBattlefieldForAGameAndAPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ? order by mc.zoneOrder"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.BATTLEFIELD.toString()); query.setLong(2, playerId); query.setLong(3, deckId); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in graveyard for game: " + gameId + " => no result found", e); return null; } } // TODO remove this @Transactional(readOnly = true) public List<MagicCard> getAllCardsInGraveyardForAGame(final Long gameId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("select m from MagicCard m where m.gameId = :gameId and m.zone = :zone"); query.setLong("gameId", gameId); query.setParameter("zone", CardZone.GRAVEYARD); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in graveyard for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInGraveyardForAGameAndAPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ?"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.GRAVEYARD.toString()); query.setLong(2, playerId); query.setLong(3, deckId); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in graveyard for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInExileForAGameAndAPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ?"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.EXILE.toString()); query.setLong(2, playerId); query.setLong(3, deckId); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in graveyard for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<Side> getSidesFromGame(final Game game) { final Session session = this.sideDao.getSession(); final Query query = session.createQuery("from Side s where s.game=?"); query.setEntity(0, game); final List<Side> s = query.list(); return s; } @Transactional(readOnly = true) public List<BigInteger> giveAllPlayersFromGameExceptMe(final Long gameId, final Long me) { final Session session = this.gameDao.getSession(); final Query query = session .createSQLQuery("select playerId from Player_Game pg where pg.gameId = ? and pg.playerId <> ?"); query.setLong(0, gameId); query.setLong(1, me); final List<BigInteger> l = query.list(); return l; } @Transactional(readOnly = true) public List<BigInteger> giveAllPlayersFromGame(final Long gameId) { final Session session = this.gameDao.getSession(); final Query query = session .createSQLQuery("select playerId from Player_Game pg where pg.gameId = ?"); query.setLong(0, gameId); final List<BigInteger> l = query.list(); return l; } @Transactional public void deleteGame(final Game oldGame) { this.gameDao.delete(oldGame.getId()); } @Transactional public void clearAllMagicCardsForGameAndDeck(final Long gameId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createSQLQuery("delete from MagicCard where gameId = ? and card_deck = ?"); query.setLong(0, gameId); query.setLong(1, deckId); query.executeUpdate(); } @Transactional public void resetDb() { final Session session = this.gameDao.getSession(); session.createSQLQuery("delete from Player_Game").executeUpdate(); session.createSQLQuery("delete from MagicCard").executeUpdate(); session.createSQLQuery("delete from Counter").executeUpdate(); session.createSQLQuery("delete from Token").executeUpdate(); session.createSQLQuery("delete from Card_Counter").executeUpdate(); session.createSQLQuery("delete from Player").executeUpdate(); session.createSQLQuery("delete from Game_Side").executeUpdate(); session.createSQLQuery("delete from Game").executeUpdate(); session.createSQLQuery("delete from Side").executeUpdate(); session.createSQLQuery("delete from Counter").executeUpdate(); session.createSQLQuery("delete from Deck").executeUpdate(); session.createSQLQuery("delete from DeckArchive").executeUpdate(); session.createSQLQuery("delete from CollectibleCard").executeUpdate(); } @Transactional(readOnly = true) public int getNumberOfCardsInACertainZoneForAGameAndADeck(final CardZone zone, final Long gameId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("from MagicCard where zone = ? and gameId = ? and card_deck = ?"); query.setString(0, zone.toString()); query.setLong(1, gameId); query.setLong(2, deckId); final List<MagicCard> cards = query.list(); return (cards == null) ? 0 : cards.size(); } @Transactional public void deleteCounter(final Counter counter, final MagicCard card, final Token token) { if ((card != null) && (card.getCounters() != null) && (!card.getCounters().isEmpty())) { card.getCounters().remove(counter); } else { token.getCounters().remove(counter); } counter.setCard(null); Query query = this.magicCardDao.getSession().createSQLQuery( "delete from Card_Counter where counterId = ?"); query.setLong(0, counter.getId()); query.executeUpdate(); query = this.counterDao.getSession().createSQLQuery( "delete from Counter where counterId = ?"); query.setLong(0, counter.getId()); query.executeUpdate(); } @Transactional public void updateCounter(final Counter counter) { final Query query = this.counterDao.getSession().createSQLQuery( "update Counter set numberOfCounters = ? where counterId = ?"); query.setLong(0, counter.getNumberOfCounters()); query.setLong(1, counter.getId()); query.executeUpdate(); } }
src/main/java/org/alienlabs/hatchetharry/service/PersistenceService.java
package org.alienlabs.hatchetharry.service; import java.io.Serializable; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import org.alienlabs.hatchetharry.model.CardZone; import org.alienlabs.hatchetharry.model.CollectibleCard; import org.alienlabs.hatchetharry.model.Counter; import org.alienlabs.hatchetharry.model.Deck; import org.alienlabs.hatchetharry.model.DeckArchive; import org.alienlabs.hatchetharry.model.Game; import org.alienlabs.hatchetharry.model.MagicCard; import org.alienlabs.hatchetharry.model.Player; import org.alienlabs.hatchetharry.model.Side; import org.alienlabs.hatchetharry.model.Token; import org.alienlabs.hatchetharry.persistence.dao.CollectibleCardDao; import org.alienlabs.hatchetharry.persistence.dao.CounterDao; import org.alienlabs.hatchetharry.persistence.dao.DeckArchiveDao; import org.alienlabs.hatchetharry.persistence.dao.DeckDao; import org.alienlabs.hatchetharry.persistence.dao.GameDao; import org.alienlabs.hatchetharry.persistence.dao.MagicCardDao; import org.alienlabs.hatchetharry.persistence.dao.PlayerDao; import org.alienlabs.hatchetharry.persistence.dao.SideDao; import org.alienlabs.hatchetharry.persistence.dao.TokenDao; import org.apache.wicket.spring.injection.annot.SpringBean; import org.hibernate.ObjectNotFoundException; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; public class PersistenceService implements Serializable { private static final long serialVersionUID = 1L; static final Logger LOGGER = LoggerFactory.getLogger(PersistenceService.class); @SpringBean private PlayerDao playerDao; @SpringBean private DeckDao deckDao; @SpringBean private DeckArchiveDao deckArchiveDao; @SpringBean private CollectibleCardDao collectibleCardDao; @SpringBean private MagicCardDao magicCardDao; @SpringBean private GameDao gameDao; @SpringBean private SideDao sideDao; @SpringBean private CounterDao counterDao; @SpringBean private TokenDao tokenDao; public PersistenceService() { } @Transactional(readOnly = true) public MagicCard getNthCardOfGame(final Long index) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("from MagicCard magiccard0_ where magiccard0_.id=?"); query.setLong(0, index); final MagicCard c = (MagicCard)query.uniqueResult(); return c; } @Transactional(isolation = Isolation.SERIALIZABLE) public MagicCard saveCardByGeneratingItsUuid(final MagicCard _c, final long gameId) { final MagicCard c = _c; c.setUuid(UUID.randomUUID().toString()); c.setGameId(gameId); final Session session = this.magicCardDao.getSession(); final Long id = (Long)session.save(c); c.setId(id); return c; } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveCard(final MagicCard c) { this.magicCardDao.getSession().save(c); } @Transactional(isolation = Isolation.SERIALIZABLE) public MagicCard saveOrUpdateCardAndDeck(final MagicCard c) { this.deckDao.getSession().merge(c.getDeck()); this.magicCardDao.getSession().merge(c); return c; } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveToken(final Token t) { this.tokenDao.getSession().save(t); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateAllMagicCards(final List<MagicCard> allMagicCards) { for (final MagicCard card : allMagicCards) { this.magicCardDao.getSession().saveOrUpdate(card); } } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateCard(final MagicCard c) { this.magicCardDao.getSession().update(c); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateToken(final Token t) { this.tokenDao.getSession().update(t); } @Transactional(isolation = Isolation.SERIALIZABLE) public void deleteCardAndToken(final MagicCard c) { final Token token = c.getToken(); final Player p = token.getPlayer(); token.setPlayer(null); final Set<Counter> counters = c.getCounters(); final List<MagicCard> magicCardCards = c.getDeck().getCards(); magicCardCards.remove(c); c.getDeck().setCards(magicCardCards); final Deck d = c.getDeck(); p.setDeck(d); token.setPlayer(p); this.deckDao.getSession().merge(d); Session session = this.magicCardDao.getSession(); Query query = session.createSQLQuery("delete from MagicCard where magicCardId = ? "); query.setLong(0, c.getId()); query.executeUpdate(); session = this.tokenDao.getSession(); query = session.createSQLQuery("delete from Token where tokenId = ? "); query.setLong(0, token.getId()); query.executeUpdate(); for (final Counter counter : counters) { session = this.counterDao.getSession(); query = session.createSQLQuery("delete from Counter where counterId = ? "); query.setLong(0, counter.getId()); query.executeUpdate(); } } @Transactional(readOnly = true) public MagicCard getCardFromUuid(final UUID uuid) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("from MagicCard magiccard0_ where magiccard0_.uuid= ? "); query.setString(0, uuid.toString()); query.setCacheable(true); PersistenceService.LOGGER.debug("card UUID: " + uuid.toString()); if (query.list().size() > 1) { return (MagicCard)query.list().get(0); } final MagicCard c = (MagicCard)query.uniqueResult(); return c; } @Transactional(readOnly = true) public Token getTokenFromUuid(final String uuid) { final Session session = this.tokenDao.getSession(); final Query query = session.createQuery("from Token t0_ where t0_.uuid= ? "); query.setString(0, uuid); query.setCacheable(true); PersistenceService.LOGGER.debug("token UUID: "); if (query.list().size() > 1) { return (Token)query.list().get(0); } final Token t = (Token)query.uniqueResult(); return t; } @Transactional(readOnly = true) public Token getTokenFromUuid(final UUID uuid) { final Session session = this.tokenDao.getSession(); final Query query = session.createQuery("from Token token0 where token0.uuid= ? "); query.setString(0, uuid.toString()); PersistenceService.LOGGER.debug("token UUID: " + uuid.toString()); if (query.list().size() > 1) { return (Token)query.list().get(0); } final Token t = (Token)query.uniqueResult(); return t; } @Transactional(readOnly = true) public List<MagicCard> getFirstHand(final long gameId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("from MagicCard magiccard0_ where magiccard0_.gameId=?"); query.setLong(0, gameId); query.setFirstResult(0); query.setMaxResults(7); final List<MagicCard> cards = query.list(); return cards; } @Transactional(readOnly = true) public Player getFirstPlayer() { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from Player player0_"); query.setFirstResult(0); query.setMaxResults(1); final Object mc = query.uniqueResult(); return (mc == null ? null : (Player)mc); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updatePlayer(final Player p) { final Session session = this.playerDao.getSession(); session.merge(p); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateSide(final Side s) { final Session session = this.sideDao.getSession(); session.merge(s); } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveCounter(final Counter c) { final Session session = this.counterDao.getSession(); session.save(c); } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveGame(final Game g) { final Session session = this.gameDao.getSession(); session.save(g); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateGame(final Game g) { this.gameDao.getSession().update(g); } @Transactional(readOnly = true) public int countPlayers(final long l) { final Session session = this.playerDao.getSession(); final Query query = session.createQuery("from Player player0_ where player0_.gameId=?"); query.setLong(0, l); return query.list().size(); } @Transactional(readOnly = true) public int countDeckArchives() { final Session session = this.deckArchiveDao.getSession(); final Query query = session.createQuery("from DeckArchive"); return query.list().size(); } @Transactional(readOnly = true) public int countCollectibleCards() { final Session session = this.collectibleCardDao.getSession(); final Query query = session.createQuery("from CollectibleCard"); return query.list().size(); } @Transactional(readOnly = true) public int countCollectibleCardsInDeckArchive(final DeckArchive deckArchive) { final Session session = this.collectibleCardDao.getSession(); final Query query = session .createQuery("from CollectibleCard cc where cc.deckArchiveId = ?"); query.setLong(0, deckArchive.getDeckArchiveId()); return query.list().size(); } @Transactional(readOnly = true) public List<CollectibleCard> giveAllCollectibleCardsInDeckArchive(final DeckArchive deckArchive) { final Session session = this.collectibleCardDao.getSession(); final Query query = session .createQuery("from CollectibleCard cc where cc.deckArchiveId = ?"); query.setLong(0, deckArchive.getDeckArchiveId()); return query.list(); } @Transactional(readOnly = true) public int countMagicCards() { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from MagicCard"); return query.list().size(); } @Transactional(readOnly = true) public int countDecks() { final Session session = this.deckDao.getSession(); final Query query = session.createQuery("from Deck"); return query.list().size(); } @Transactional(isolation = Isolation.SERIALIZABLE) public void updateDeck(final Deck d) { final Session session = this.deckDao.getSession(); session.update(d); } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveOrUpdateDeck(final Deck d) { final Session session = this.deckDao.getSession(); session.merge(d); } @Transactional(isolation = Isolation.SERIALIZABLE) public Deck saveDeck(final Deck d) { this.deckDao.getSession().save(d); return d; } @Transactional(isolation = Isolation.SERIALIZABLE) public Deck saveDeckOrUpdate(final Deck d) { this.deckDao.getSession().saveOrUpdate(d); return d; } @Transactional(isolation = Isolation.SERIALIZABLE) public Side saveSide(final Side s) { this.sideDao.getSession().save(s); return s; } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveSides(final Set<Side> sides) { for (final Side s : sides) { this.sideDao.getSession().save(s); } } @Transactional(readOnly = true) public Player getPlayer(final Long l) { return this.playerDao.load(l); } @Transactional(readOnly = true) public boolean getPlayerByGame(final long l) { final Session session = this.playerDao.getSession(); final Query query = session.createQuery("from Player player0_ where player0_.gameId=?"); query.setLong(0, l); return query.list().size() > 0; } @Transactional(readOnly = true) public List<Player> getAllPlayersOfGame(final long l) { final Session session = this.playerDao.getSession(); final SQLQuery query = session .createSQLQuery("select player0_.* from Player player0_ where player0_.game_gameId=?"); query.addEntity(Player.class); query.setLong(0, l); return query.list(); } // Isolation level chosen to be consistent with // RuntimeDataGenerator#generateData() @Transactional(isolation = Isolation.REPEATABLE_READ) public DeckArchive getDeckArchiveByName(final String name) { final Session session = this.deckDao.getSession(); final SQLQuery query = session .createSQLQuery("select da.* from Deck d, DeckArchive da where da.deckName=? and da.deckArchiveId = d.Deck_DeckArchive"); query.addEntity(DeckArchive.class); query.setString(0, name); @SuppressWarnings("rawtypes") final List results = query.list(); return (results.size() > 0 ? (DeckArchive)query.list().get(0) : null); } @Transactional(readOnly = true) public boolean getPlayerByJsessionId(final String jsessionid) { final Session session = this.playerDao.getSession(); final Query query = session.createQuery("from Player player0_ where player0_.jsessionid=?"); query.setString(0, jsessionid); return query.list().size() > 0; } @Transactional(readOnly = true) public boolean doesCollectibleCardAlreadyExistsInDb(final String title) { final Session session = this.collectibleCardDao.getSession(); final Query query = session.createQuery("from CollectibleCard cc0_ where cc0_.title=?"); query.setString(0, title); final List<?> list = query.list(); return ((list != null) && (list.size() > 0)); } @Transactional(readOnly = true) public Deck getDeck(final long deckId) { final Session session = this.deckDao.getSession(); final Query query = session.createQuery("from Deck deck0_ where deck0_.deckId=?"); query.setLong(0, deckId); query.setMaxResults(1); return (Deck)query.uniqueResult(); } @Transactional(readOnly = true) public Deck getDeckByDeckArchiveIdAndPlayerId(final long deckArchiveId, final long playerId) { final Session session = this.deckDao.getSession(); final Query query = session .createQuery("from Deck d where d.deckArchive=? and d.playerId=?"); query.setLong(0, deckArchiveId); query.setLong(1, playerId); query.setMaxResults(1); return (Deck)query.uniqueResult(); } @Transactional(readOnly = true) public List<MagicCard> getAllCardsFromDeck(final long l) { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from MagicCard card0_ where card0_.deck=?"); query.setLong(0, l); List<MagicCard> list = new ArrayList<MagicCard>(); try { list = query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("error!", e); } return list; } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInLibraryForDeckAndPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ? order by mc.zoneOrder"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.LIBRARY.toString()); query.setLong(2, playerId); query.setLong(3, deckId); List<MagicCard> list = new ArrayList<MagicCard>(); try { list = query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("error!", e); } return list; } @Transactional(isolation = Isolation.SERIALIZABLE) public void saveCollectibleCard(final CollectibleCard cc) { this.collectibleCardDao.getSession().save(cc); } @Transactional(isolation = Isolation.SERIALIZABLE) public DeckArchive saveDeckArchive(final DeckArchive da) { final Session session = this.deckArchiveDao.getSession(); final SQLQuery query = session .createSQLQuery("select da.* from Deck d, DeckArchive da where da.deckName=? and da.deckArchiveId = d.Deck_DeckArchive"); query.addEntity(DeckArchive.class); query.setString(0, da.getDeckName()); if (query.list().size() > 0) { return ((DeckArchive)query.list().get(0)); } session.save(da); return da; } @Transactional(isolation = Isolation.SERIALIZABLE) public DeckArchive updateDeckArchive(final DeckArchive da) { final Session session = this.deckArchiveDao.getSession(); session.update(da); return da; } @Required public void setPlayerDao(final PlayerDao _playerDao) { this.playerDao = _playerDao; } @Required public void setDeckDao(final DeckDao _deckDao) { this.deckDao = _deckDao; } @Required public void setDeckArchiveDao(final DeckArchiveDao _deckArchiveDao) { this.deckArchiveDao = _deckArchiveDao; } @Required public void setSideDao(final SideDao _sideDao) { this.sideDao = _sideDao; } @Required public void setCollectibleCardDao(final CollectibleCardDao _collectibleCardDao) { this.collectibleCardDao = _collectibleCardDao; } @Required public void setMagicCardDao(final MagicCardDao _magicCardDao) { this.magicCardDao = _magicCardDao; } @Required public void setGameDao(final GameDao _gameDao) { this.gameDao = _gameDao; } @Required public void setCounterDao(final CounterDao _counterDao) { this.counterDao = _counterDao; } @Required public void setTokenDao(final TokenDao _tokenDao) { this.tokenDao = _tokenDao; } @Transactional(readOnly = true) public List<?> getCardsByDeckId(final long gameId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("select card0_ from MagicCard card0_ , Deck deck0_ where card0_.deck = deck0_.deckId and deck0_.deckId = ?"); query.setLong(0, gameId); return query.list(); } @Transactional(readOnly = true) public List<Deck> getAllDecks() { final Session session = this.deckDao.getSession(); final Query query = session.createQuery("from Deck deck0_ where deck0_.playerId != -1"); return query.list(); } @Transactional(readOnly = true) public List<DeckArchive> getAllDeckArchives() { final Session session = this.deckDao.getSession(); final Query query = session.createQuery("from DeckArchive d where d.deckName != null"); return query.list(); } @Transactional(readOnly = true) public List<Deck> getAllDecksFromDeckArchives() { final Session session = this.deckDao.getSession(); final SQLQuery query = session .createSQLQuery("select dd.* from Deck dd where dd.Deck_DeckArchive in (select distinct da.deckArchiveId from Deck de, DeckArchive da where de.Deck_DeckArchive = da.deckArchiveId and da.deckName is not null) group by dd.Deck_DeckArchive"); query.addEntity(Deck.class); return query.list(); } @Transactional(isolation = Isolation.SERIALIZABLE) public Game createGameAndPlayer(final Game game, final Player player) { final Set<Player> set = game.getPlayers(); set.add(player); game.setPlayers(set); player.setGame(game); this.playerDao.getSession().save(player); this.gameDao.getSession().save(game); return game; } @Transactional(readOnly = true) public MagicCard findCardByName(final String _name) { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from MagicCard m where m.title = ?"); query.setString(0, _name); query.setMaxResults(1); try { return (MagicCard)query.list().get(0); } catch (final IndexOutOfBoundsException e) { PersistenceService.LOGGER.error("error!", e); return null; } } @Transactional(readOnly = true) public CollectibleCard findCollectibleCardByName(final String title) { final Session session = this.magicCardDao.getSession(); final Query query = session.createQuery("from CollectibleCard cc where cc.title = ?"); query.setString(0, title); query.setMaxResults(1); try { return (CollectibleCard)query.uniqueResult(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("error!", e); return null; } } @Transactional(readOnly = true) public Game getGame(final Long _id) { return this.gameDao.load(_id); } @Transactional public void deleteMagicCard(final MagicCard mc) { this.magicCardDao.delete(mc.getId()); } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInHandForAGameAndAPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ? order by mc.zoneOrder"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.HAND.toString()); query.setLong(2, playerId); query.setLong(3, deckId); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in hand for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInBattleFieldForAGame(final Long gameId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("select m from MagicCard m where m.gameId = :gameId and m.zone = :zone"); query.setLong("gameId", gameId); query.setParameter("zone", CardZone.BATTLEFIELD); query.setCacheable(true); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in battlefield for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInBattlefieldForAGameAndAPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ? order by mc.zoneOrder"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.BATTLEFIELD.toString()); query.setLong(2, playerId); query.setLong(3, deckId); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in graveyard for game: " + gameId + " => no result found", e); return null; } } // TODO remove this @Transactional(readOnly = true) public List<MagicCard> getAllCardsInGraveyardForAGame(final Long gameId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("select m from MagicCard m where m.gameId = :gameId and m.zone = :zone"); query.setLong("gameId", gameId); query.setParameter("zone", CardZone.GRAVEYARD); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in graveyard for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInGraveyardForAGameAndAPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ?"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.GRAVEYARD.toString()); query.setLong(2, playerId); query.setLong(3, deckId); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in graveyard for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<MagicCard> getAllCardsInExileForAGameAndAPlayer(final Long gameId, final Long playerId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final SQLQuery query = session .createSQLQuery("select mc.* from MagicCard mc, Deck d where mc.gameId = ? and mc.zone = ? and d.playerId = ? and mc.card_deck = d.deckId and d.deckId = ?"); query.addEntity(MagicCard.class); query.setLong(0, gameId); query.setString(1, CardZone.EXILE.toString()); query.setLong(2, playerId); query.setLong(3, deckId); try { return query.list(); } catch (final ObjectNotFoundException e) { PersistenceService.LOGGER.error("Error retrieving cards in graveyard for game: " + gameId + " => no result found", e); return null; } } @Transactional(readOnly = true) public List<Side> getSidesFromGame(final Game game) { final Session session = this.sideDao.getSession(); final Query query = session.createQuery("from Side s where s.game=?"); query.setEntity(0, game); final List<Side> s = query.list(); return s; } @Transactional(readOnly = true) public List<BigInteger> giveAllPlayersFromGameExceptMe(final Long gameId, final Long me) { final Session session = this.gameDao.getSession(); final Query query = session .createSQLQuery("select playerId from Player_Game pg where pg.gameId = ? and pg.playerId <> ?"); query.setLong(0, gameId); query.setLong(1, me); final List<BigInteger> l = query.list(); return l; } @Transactional(readOnly = true) public List<BigInteger> giveAllPlayersFromGame(final Long gameId) { final Session session = this.gameDao.getSession(); final Query query = session .createSQLQuery("select playerId from Player_Game pg where pg.gameId = ?"); query.setLong(0, gameId); final List<BigInteger> l = query.list(); return l; } @Transactional public void deleteGame(final Game oldGame) { this.gameDao.delete(oldGame.getId()); } @Transactional public void clearAllMagicCardsForGameAndDeck(final Long gameId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createSQLQuery("delete from MagicCard where gameId = ? and card_deck = ?"); query.setLong(0, gameId); query.setLong(1, deckId); query.executeUpdate(); } @Transactional public void resetDb() { final Session session = this.gameDao.getSession(); session.createSQLQuery("delete from Player_Game").executeUpdate(); session.createSQLQuery("delete from MagicCard").executeUpdate(); session.createSQLQuery("delete from Counter").executeUpdate(); session.createSQLQuery("delete from Token").executeUpdate(); session.createSQLQuery("delete from Card_Counter").executeUpdate(); session.createSQLQuery("delete from Player").executeUpdate(); session.createSQLQuery("delete from Game_Side").executeUpdate(); session.createSQLQuery("delete from Game").executeUpdate(); session.createSQLQuery("delete from Side").executeUpdate(); session.createSQLQuery("delete from Counter").executeUpdate(); session.createSQLQuery("delete from Deck").executeUpdate(); session.createSQLQuery("delete from DeckArchive").executeUpdate(); session.createSQLQuery("delete from CollectibleCard").executeUpdate(); } @Transactional(readOnly = true) public int getNumberOfCardsInACertainZoneForAGameAndADeck(final CardZone zone, final Long gameId, final Long deckId) { final Session session = this.magicCardDao.getSession(); final Query query = session .createQuery("from MagicCard where zone = ? and gameId = ? and card_deck = ?"); query.setString(0, zone.toString()); query.setLong(1, gameId); query.setLong(2, deckId); final List<MagicCard> cards = query.list(); return (cards == null) ? 0 : cards.size(); } @Transactional public void deleteCounter(final Counter counter, final MagicCard card, final Token token) { if ((card != null) && (card.getCounters() != null) && (!card.getCounters().isEmpty())) { card.getCounters().remove(counter); } else { token.getCounters().remove(counter); } counter.setCard(null); Query query = this.magicCardDao.getSession().createSQLQuery( "delete from Card_Counter where counterId = ?"); query.setLong(0, counter.getId()); query.executeUpdate(); query = this.counterDao.getSession().createSQLQuery( "delete from Counter where counterId = ?"); query.setLong(0, counter.getId()); query.executeUpdate(); } @Transactional public void updateCounter(final Counter counter) { final Query query = this.counterDao.getSession().createSQLQuery( "update Counter set numberOfCounters = ? where counterId = ?"); query.setLong(0, counter.getNumberOfCounters()); query.setLong(1, counter.getId()); query.executeUpdate(); } }
FIXED bug
src/main/java/org/alienlabs/hatchetharry/service/PersistenceService.java
FIXED bug
<ide><path>rc/main/java/org/alienlabs/hatchetharry/service/PersistenceService.java <ide> p.setDeck(d); <ide> token.setPlayer(p); <ide> <add> final Long magicCardId = c.getId(); <add> <ide> this.deckDao.getSession().merge(d); <ide> <ide> Session session = this.magicCardDao.getSession(); <ide> Query query = session.createSQLQuery("delete from MagicCard where magicCardId = ? "); <del> query.setLong(0, c.getId()); <add> query.setLong(0, magicCardId); <ide> query.executeUpdate(); <ide> <ide> session = this.tokenDao.getSession(); <del> query = session.createSQLQuery("delete from Token where tokenId = ? "); <del> query.setLong(0, token.getId()); <add> query = session <add> .createSQLQuery("delete t.* from Card_Counter cc, Token t, MagicCard mc where t.tokenId = mc.token_tokenId and cc.counterId = t.tokenId and mc.magicCardId = ?"); <add> query.setLong(0, magicCardId); <add> query.executeUpdate(); <add> <add> session = this.magicCardDao.getSession(); <add> query = session <add> .createSQLQuery("delete cc.* from Card_Counter cc, Counter c, MagicCard mc where c.card = mc.magicCardId and cc.counterId = c.counterId and mc.magicCardId = ?"); <add> query.setLong(0, magicCardId); <ide> query.executeUpdate(); <ide> <ide> for (final Counter counter : counters)
Java
unlicense
7979486f16d44fa6b3561b01b21250fe9281997d
0
Samourai-Wallet/samourai-wallet-android
package com.samourai.wallet; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.text.Html; import android.text.InputType; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AnticipateInterpolator; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.util.Log; import org.apache.commons.lang3.tuple.Pair; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.DumpedPrivateKey; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.TransactionWitness; import org.bitcoinj.crypto.BIP38PrivateKey; import org.bitcoinj.crypto.MnemonicException; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.wallet.JSONRPC.JSONRPC; import com.samourai.wallet.JSONRPC.PoW; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.api.Tx; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.rpc.*; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_Address; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.send.BlockedUTXO; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionInput; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFSpend; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.SweepUtil; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.PushTx; import com.samourai.wallet.service.WebSocketService; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.BlockExplorerUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.DateUtil; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.PrivKeyReader; import com.samourai.wallet.util.TimeOutUtil; import com.samourai.wallet.util.TorUtil; import com.samourai.wallet.util.TypefaceUtil; import org.bitcoinj.core.Coin; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.core.Transaction; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.encoders.DecoderException; import net.i2p.android.ext.floatingactionbutton.FloatingActionButton; import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu; import net.sourceforge.zbar.Symbol; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import info.guardianproject.netcipher.proxy.OrbotHelper; public class BalanceActivity extends Activity { private final static int SCAN_COLD_STORAGE = 2011; private final static int SCAN_QR = 2012; private LinearLayout layoutAlert = null; private LinearLayout tvBalanceBar = null; private TextView tvBalanceAmount = null; private TextView tvBalanceUnits = null; private ListView txList = null; private List<Tx> txs = null; private HashMap<String, Boolean> txStates = null; private TransactionAdapter txAdapter = null; private SwipeRefreshLayout swipeRefreshLayout = null; private FloatingActionsMenu ibQuickSend = null; private FloatingActionButton actionReceive = null; private FloatingActionButton actionSend = null; private FloatingActionButton actionBIP47 = null; private boolean isBTC = true; private RefreshTask refreshTask = null; private PoWTask powTask = null; private RBFTask rbfTask = null; private CPFPTask cpfpTask = null; public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH"; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { final boolean notifTx = intent.getBooleanExtra("notifTx", false); final boolean fetch = intent.getBooleanExtra("fetch", false); final String rbfHash; final String blkHash; if(intent.hasExtra("rbf")) { rbfHash = intent.getStringExtra("rbf"); } else { rbfHash = null; } if(intent.hasExtra("hash")) { blkHash = intent.getStringExtra("hash"); } else { blkHash = null; } BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); refreshTx(notifTx, fetch, false, false); if(BalanceActivity.this != null) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } if(rbfHash != null) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming)) .setCancelable(true) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doExplorerView(rbfHash); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } } } }); if(BalanceActivity.this != null && blkHash != null && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true && TrustedNodeUtil.getInstance().isSet()) { BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { if(powTask == null || powTask.getStatus().equals(AsyncTask.Status.FINISHED)) { powTask = new PoWTask(); powTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, blkHash); } } }); } } } }; protected BroadcastReceiver torStatusReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("BalanceActivity", "torStatusReceiver onReceive()"); if (OrbotHelper.ACTION_STATUS.equals(intent.getAction())) { boolean enabled = (intent.getStringExtra(OrbotHelper.EXTRA_STATUS).equals(OrbotHelper.STATUS_ON)); Log.i("BalanceActivity", "status:" + enabled); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(enabled); } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_balance); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if(SamouraiWallet.getInstance().isTestNet()) { setTitle(getText(R.string.app_name) + ":" + "TestNet"); } LayoutInflater inflator = BalanceActivity.this.getLayoutInflater(); tvBalanceBar = (LinearLayout)inflator.inflate(R.layout.balance_layout, null); tvBalanceBar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(isBTC) { isBTC = false; } else { isBTC = true; } displayBalance(); txAdapter.notifyDataSetChanged(); return false; } }); tvBalanceAmount = (TextView)tvBalanceBar.findViewById(R.id.BalanceAmount); tvBalanceUnits = (TextView)tvBalanceBar.findViewById(R.id.BalanceUnits); ibQuickSend = (FloatingActionsMenu)findViewById(R.id.wallet_menu); actionSend = (FloatingActionButton)findViewById(R.id.send); actionSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("via_menu", true); startActivity(intent); } }); actionReceive = (FloatingActionButton)findViewById(R.id.receive); actionReceive.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { try { HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get(); if(hdw != null) { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } }); actionBIP47 = (FloatingActionButton)findViewById(R.id.bip47); actionBIP47.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, com.samourai.wallet.bip47.BIP47Activity.class); startActivity(intent); } }); txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); txList = (ListView)findViewById(R.id.txList); txAdapter = new TransactionAdapter(); txList.setAdapter(txAdapter); txList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { if(position == 0) { return; } long viewId = view.getId(); View v = (View)view.getParent(); final Tx tx = txs.get(position - 1); ImageView ivTxStatus = (ImageView)v.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)v.findViewById(R.id.ConfirmationCount); if(viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) { if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } } else { String message = getString(R.string.options_unconfirmed_tx); // RBF if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0 && RBFUtil.getInstance().contains(tx.getHash())) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(rbfTask == null || rbfTask.getStatus().equals(AsyncTask.Status.FINISHED)) { rbfTask = new RBFTask(); rbfTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP receive else if(tx.getConfirmations() < 1 && tx.getAmount() >= 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP spend else if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } else { doExplorerView(tx.getHash()); return; } } } }); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().post(new Runnable() { @Override public void run() { refreshTx(false, true, true, false); } }); } }); swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); // TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); registerReceiver(torStatusReceiver, new IntentFilter(OrbotHelper.ACTION_STATUS)); boolean notifTx = false; boolean fetch = false; Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey("notifTx")) { notifTx = extras.getBoolean("notifTx"); } if(extras != null && extras.containsKey("uri")) { fetch = extras.getBoolean("fetch"); } refreshTx(notifTx, fetch, false, true); // // user checks mnemonic & passphrase // if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CREDS_CHECK, 0L) == 0L) { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.recovery_checkup) .setMessage(BalanceActivity.this.getText(R.string.recovery_checkup_message)) .setCancelable(false) .setPositiveButton(R.string.next, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); try { final String seed = HD_WalletFactory.getInstance(BalanceActivity.this).get().getMnemonic(); final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String message = BalanceActivity.this.getText(R.string.mnemonic) + ":<br><br><b>" + seed + "</b><br><br>" + BalanceActivity.this.getText(R.string.passphrase) + ":<br><br><b>" + passphrase + "</b>"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.recovery_checkup) .setMessage(Html.fromHtml(message)) .setCancelable(false) .setPositiveButton(R.string.recovery_checkup_finish, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.CREDS_CHECK, System.currentTimeMillis() / 1000L); dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } catch(IOException | MnemonicException.MnemonicLengthException e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } }); if(!isFinishing()) { dlg.show(); } } if(!AppUtil.getInstance(BalanceActivity.this).isClipboardSeen()) { doClipboardCheck(); } } @Override public void onResume() { super.onResume(); // IntentFilter filter = new IntentFilter(ACTION_INTENT); // LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); } AppUtil.getInstance(BalanceActivity.this).checkTimeOut(); if(!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } } @Override public void onPause() { super.onPause(); // LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); ibQuickSend.collapse(); } @Override public void onDestroy() { LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); unregisterReceiver(torStatusReceiver); if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { menu.findItem(R.id.action_tor).setVisible(false); } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_on); } else { menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_off); } menu.findItem(R.id.action_refresh).setVisible(false); menu.findItem(R.id.action_share_receive).setVisible(false); menu.findItem(R.id.action_ricochet).setVisible(false); menu.findItem(R.id.action_empty_ricochet).setVisible(false); menu.findItem(R.id.action_sign).setVisible(false); menu.findItem(R.id.action_fees).setVisible(false); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // noinspection SimplifiableIfStatement if (id == R.id.action_settings) { doSettings(); } else if (id == R.id.action_sweep) { doSweep(); } else if (id == R.id.action_utxo) { doUTXO(); } else if (id == R.id.action_tor) { if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { ; } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { item.setIcon(R.drawable.tor_off); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); } else { OrbotHelper.requestStartTor(BalanceActivity.this); item.setIcon(R.drawable.tor_on); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(true); } return true; } else if (id == R.id.action_backup) { if(SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { try { if(HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { doBackup(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); }}); if(!isFinishing()) { alert.show(); } } } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(IOException ioe) { ; } } else { Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show(); } } else if (id == R.id.action_scan_qr) { doScan(); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); doPrivKey(strResult); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) { ; } else if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(strResult)); try { if(privKeyReader.getFormat() != null) { doPrivKey(strResult); } else { Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("uri", strResult); startActivity(intent); } } catch(Exception e) { ; } } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_SINGLE_TOP); BalanceActivity.this.startActivity(intent); }}); alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); if(!isFinishing()) { alert.show(); } return true; } else { ; } return false; } private void doSettings() { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class); startActivity(intent); } private void doUTXO() { Intent intent = new Intent(BalanceActivity.this, UTXOActivity.class); startActivity(intent); } private void doScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_QR); } private void doSweepViaScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_COLD_STORAGE); } private void doSweep() { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.action_sweep) .setCancelable(true) .setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final EditText privkey = new EditText(BalanceActivity.this); privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.enter_privkey) .setView(privkey) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String strPrivKey = privkey.getText().toString(); if(strPrivKey != null && strPrivKey.length() > 0) { doPrivKey(strPrivKey); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } }).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doSweepViaScan(); } }); if(!isFinishing()) { dlg.show(); } } private void doPrivKey(final String data) { PrivKeyReader privKeyReader = null; String format = null; try { privKeyReader = new PrivKeyReader(new CharSequenceX(data), null); format = privKeyReader.getFormat(); } catch(Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } if(format != null) { if(format.equals(PrivKeyReader.BIP38)) { final PrivKeyReader pvr = privKeyReader; final EditText password38 = new EditText(BalanceActivity.this); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.bip38_pw) .setView(password38) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String password = password38.getText().toString(); ProgressDialog progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.decrypting_bip38)); progress.show(); boolean keyDecoded = false; try { BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data); final ECKey ecKey = bip38.decrypt(password); if(ecKey != null && ecKey.hasPrivKey()) { if(progress != null && progress.isShowing()) { progress.cancel(); } pvr.setPassword(new CharSequenceX(password)); keyDecoded = true; Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show(); } } catch(Exception e) { e.printStackTrace(); Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.cancel(); } if(keyDecoded) { SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, false); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } }); if(!isFinishing()) { dlg.show(); } } else if(privKeyReader != null) { SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, false); } else { ; } } else { Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show(); } } private void doBackup() { try { final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String[] export_methods = new String[2]; export_methods[0] = getString(R.string.export_to_clipboard); export_methods[1] = getString(R.string.export_to_email); new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.options_export) .setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch (IOException ioe) { ; } catch (JSONException je) { ; } catch (DecryptionException de) { ; } catch (MnemonicException.MnemonicLengthException mle) { ; } String encrypted = null; try { encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations); } catch (Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { if (encrypted == null) { Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show(); return; } } JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true); if (which == 0) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Wallet backup", obj.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } else { Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup"); email.putExtra(Intent.EXTRA_TEXT, obj.toString()); email.setType("message/rfc822"); startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client))); } dialog.dismiss(); } } ).show(); } catch(IOException ioe) { ioe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } } private void doClipboardCheck() { final android.content.ClipboardManager clipboard = (android.content.ClipboardManager)BalanceActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE); if(clipboard.hasPrimaryClip()) { final ClipData clip = clipboard.getPrimaryClip(); ClipData.Item item = clip.getItemAt(0); if(item.getText() != null) { String text = item.getText().toString(); String[] s = text.split("\\s+"); try { for(int i = 0; i < s.length; i++) { PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(s[i])); if(privKeyReader.getFormat() != null && (privKeyReader.getFormat().equals(PrivKeyReader.WIF_COMPRESSED) || privKeyReader.getFormat().equals(PrivKeyReader.WIF_UNCOMPRESSED) || privKeyReader.getFormat().equals(PrivKeyReader.BIP38) ) ) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.privkey_clipboard) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { clipboard.setPrimaryClip(ClipData.newPlainText("", "")); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } } } catch(Exception e) { ; } } } } private class TransactionAdapter extends BaseAdapter { private LayoutInflater inflater = null; private static final int TYPE_ITEM = 0; private static final int TYPE_BALANCE = 1; TransactionAdapter() { inflater = (LayoutInflater)BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } return txs.size() + 1; } @Override public String getItem(int position) { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } if(position == 0) { return ""; } return txs.get(position - 1).toString(); } @Override public long getItemId(int position) { return position - 1; } @Override public int getItemViewType(int position) { return position == 0 ? TYPE_BALANCE : TYPE_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { View view = null; int type = getItemViewType(position); if(convertView == null) { if(type == TYPE_BALANCE) { view = tvBalanceBar; } else { view = inflater.inflate(R.layout.tx_layout_simple, parent, false); } } else { view = convertView; } if(type == TYPE_BALANCE) { ; } else { view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); Tx tx = txs.get(position - 1); TextView tvTodayLabel = (TextView)view.findViewById(R.id.TodayLabel); String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS()); if(position == 1) { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } else { Tx prevTx = txs.get(position - 2); String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS()); if(strPrevDateGroup.equals(strDateGroup)) { tvTodayLabel.setVisibility(View.GONE); } else { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } } String strDetails = null; String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS()); long _amount = 0L; if(tx.getAmount() < 0.0) { _amount = Math.abs((long)tx.getAmount()); strDetails = BalanceActivity.this.getString(R.string.you_sent); } else { _amount = (long)tx.getAmount(); strDetails = BalanceActivity.this.getString(R.string.you_received); } String strAmount = null; String strUnits = null; if(isBTC) { strAmount = getBTCDisplayAmount(_amount); strUnits = getBTCDisplayUnits(); } else { strAmount = getFiatDisplayAmount(_amount); strUnits = getFiatDisplayUnits(); } TextView tvDirection = (TextView)view.findViewById(R.id.TransactionDirection); TextView tvDirection2 = (TextView)view.findViewById(R.id.TransactionDirection2); TextView tvDetails = (TextView)view.findViewById(R.id.TransactionDetails); ImageView ivTxStatus = (ImageView)view.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)view.findViewById(R.id.ConfirmationCount); tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface()); if(tx.getAmount() < 0.0) { tvDirection.setTextColor(Color.RED); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up)); } else { tvDirection.setTextColor(Color.GREEN); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down)); } if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits); if(tx.getPaymentCode() != null) { String strTaggedTS = strTS + " "; String strSubText = " " + BIP47Meta.getInstance().getDisplayLabel(tx.getPaymentCode()) + " "; strTaggedTS += strSubText; tvDetails.setText(strTaggedTS); } else { tvDetails.setText(strTS); } } return view; } } private void refreshTx(final boolean notifTx, final boolean fetch, final boolean dragged, final boolean launch) { if(refreshTask == null || refreshTask.getStatus().equals(AsyncTask.Status.FINISHED)) { refreshTask = new RefreshTask(dragged, launch); refreshTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, notifTx ? "1" : "0", fetch ? "1" : "0"); } } private void displayBalance() { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); long balance = 0L; if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance(); } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount()).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } double btc_balance = (((double)balance) / 1e8); double fiat_balance = btc_fx * btc_balance; if(isBTC) { tvBalanceAmount.setText(getBTCDisplayAmount(balance)); tvBalanceUnits.setText(getBTCDisplayUnits()); } else { tvBalanceAmount.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(fiat_balance)); tvBalanceUnits.setText(strFiat); } } private String getBTCDisplayAmount(long value) { String strAmount = null; DecimalFormat df = new DecimalFormat("#"); df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); strAmount = Coin.valueOf(value).toPlainString(); return strAmount; } private String getBTCDisplayUnits() { return MonetaryUtil.getInstance().getBTCUnits(); } private String getFiatDisplayAmount(long value) { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); String strAmount = MonetaryUtil.getInstance().getFiatFormat(strFiat).format(btc_fx * (((double)value) / 1e8)); return strAmount; } private String getFiatDisplayUnits() { return PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); } private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) { if(heads) { if(confirmations == 0) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_query_builder_white); tvConfirmationCount.setVisibility(View.GONE); } else if(confirmations > 3) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_done_white); tvConfirmationCount.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } } else { if(confirmations < 100) { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText("\u221e"); ivTxStatus.setVisibility(View.GONE); } } } private void rotateTxStatus(View view, boolean clockwise) { float degrees = 360f; if(!clockwise) { degrees = -360f; } ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees); animation.setDuration(1000); animation.setRepeatCount(0); animation.setInterpolator(new AnticipateInterpolator()); animation.start(); } private void doExplorerView(String strHash) { if(strHash != null) { int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0); if(sel >= BlockExplorerUtil.getInstance().getBlockExplorerTxUrls().length) { sel = 0; } CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerTxUrls()[sel]; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + strHash)); startActivity(browserIntent); } } private class RefreshTask extends AsyncTask<String, Void, String> { private String strProgressTitle = null; private String strProgressMessage = null; private ProgressDialog progress = null; private Handler handler = null; private boolean dragged = false; private boolean launch = false; public RefreshTask(boolean dragged, boolean launch) { super(); Log.d("BalanceActivity", "RefreshTask, dragged==" + dragged); handler = new Handler(); this.dragged = dragged; this.launch = launch; } @Override protected void onPreExecute() { Log.d("BalanceActivity", "RefreshTask.preExecute()"); if(progress != null && progress.isShowing()) { progress.dismiss(); } if(!dragged) { strProgressTitle = BalanceActivity.this.getText(R.string.app_name).toString(); strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx_pre).toString(); progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(true); progress.setTitle(strProgressTitle); progress.setMessage(strProgressMessage); progress.show(); } } @Override protected String doInBackground(String... params) { Log.d("BalanceActivity", "doInBackground()"); final boolean notifTx = params[0].equals("1") ? true : false; final boolean fetch = params[1].equals("1") ? true : false; // // TBD: check on lookahead/lookbehind for all incoming payment codes // if(fetch || txs.size() == 0) { APIFactory.getInstance(BalanceActivity.this).initWallet(); } try { int acc = 0; txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs(); if(txs != null) { Collections.sort(txs, new APIFactory.TxMostRecentDateComparator()); } if(AddressFactory.getInstance().getHighestTxReceiveIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestTxReceiveIdx(acc)); } if(AddressFactory.getInstance().getHighestTxChangeIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().setAddrIdx(AddressFactory.getInstance().getHighestTxChangeIdx(acc)); } if(AddressFactory.getInstance().getHighestBIP49ReceiveIdx() > BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx()) { BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestBIP49ReceiveIdx()); } if(AddressFactory.getInstance().getHighestBIP49ChangeIdx() > BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()) { BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(AddressFactory.getInstance().getHighestBIP49ChangeIdx()); } } catch(IOException ioe) { ioe.printStackTrace(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); } finally { ; } if(!dragged) { strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx).toString(); publishProgress(); } handler.post(new Runnable() { public void run() { if(dragged) { swipeRefreshLayout.setRefreshing(false); } tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); displayBalance(); txAdapter.notifyDataSetChanged(); } }); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.FIRST_RUN, false); if(notifTx) { // // check for incoming payment code notification tx // try { PaymentCode pcode = BIP47Util.getInstance(BalanceActivity.this).getPaymentCode(); // Log.i("BalanceFragment", "payment code:" + pcode.toString()); // Log.i("BalanceFragment", "notification address:" + pcode.notificationAddress().getAddressString()); APIFactory.getInstance(BalanceActivity.this).getNotifAddress(pcode.notificationAddress().getAddressString()); } catch (AddressFormatException afe) { afe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } strProgressMessage = BalanceActivity.this.getText(R.string.refresh_incoming_notif_tx).toString(); publishProgress(); // // check on outgoing payment code notification tx // List<Pair<String,String>> outgoingUnconfirmed = BIP47Meta.getInstance().getOutgoingUnconfirmed(); // Log.i("BalanceFragment", "outgoingUnconfirmed:" + outgoingUnconfirmed.size()); for(Pair<String,String> pair : outgoingUnconfirmed) { // Log.i("BalanceFragment", "outgoing payment code:" + pair.getLeft()); // Log.i("BalanceFragment", "outgoing payment code tx:" + pair.getRight()); int confirmations = APIFactory.getInstance(BalanceActivity.this).getNotifTxConfirmations(pair.getRight()); if(confirmations > 0) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_SENT_CFM); } if(confirmations == -1) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_NOT_SENT); } } if(!dragged) { strProgressMessage = BalanceActivity.this.getText(R.string.refresh_outgoing_notif_tx).toString(); publishProgress(); } Intent intent = new Intent("com.samourai.wallet.BalanceActivity.RESTART_SERVICE"); LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent); } if(!dragged) { if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.GUID_V, 0) < 4) { Log.i("BalanceActivity", "guid_v < 4"); try { String _guid = AccessFactory.getInstance(BalanceActivity.this).createGUID(); String _hash = AccessFactory.getInstance(BalanceActivity.this).getHash(_guid, new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getPIN()), AESUtil.DefaultPBKDF2Iterations); PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(_guid + AccessFactory.getInstance().getPIN())); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.ACCESS_HASH, _hash); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.ACCESS_HASH2, _hash); Log.i("BalanceActivity", "guid_v == 4"); } catch(MnemonicException.MnemonicLengthException | IOException | JSONException | DecryptionException e) { ; } } else if(!launch) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(Exception e) { } } else { ; } } /* if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.XPUB44LOCK, false) == false) { try { String[] s = HD_WalletFactory.getInstance(BalanceActivity.this).get().getXPUBs(); for(int i = 0; i < s.length; i++) { APIFactory.getInstance(BalanceActivity.this).lockXPUB(s[0], false); } } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.XPUB49LOCK, false) == false) { ; } */ return "OK"; } @Override protected void onPostExecute(String result) { if(!dragged) { if(progress != null && progress.isShowing()) { progress.dismiss(); } } List<UTXO> utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(false); for(UTXO utxo : utxos) { List<MyTransactionOutPoint> outpoints = utxo.getOutpoints(); for(MyTransactionOutPoint out : outpoints) { byte[] scriptBytes = out.getScriptBytes(); String address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(address); if(path != null && path.startsWith("M/1/")) { continue; } final String hash = out.getHash().toString(); final int idx = out.getTxOutputN(); final long amount = out.getValue().longValue(); if(amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD && !BlockedUTXO.getInstance().contains(hash, idx) && !BlockedUTXO.getInstance().containsNotDusted(hash, idx)) { String message = BalanceActivity.this.getString(R.string.dusting_attempt); message += "\n\n"; message += BalanceActivity.this.getString(R.string.dusting_attempt_amount); message += " "; message += Coin.valueOf(amount).toPlainString(); message += " BTC\n"; message += BalanceActivity.this.getString(R.string.dusting_attempt_id); message += " "; message += hash + "-" + idx; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.dusting_tx) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { BlockedUTXO.getInstance().add(hash, idx, amount); } }).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { BlockedUTXO.getInstance().addNotDusted(hash, idx); } }); if(!isFinishing()) { dlg.show(); } } } } } @Override protected void onProgressUpdate(Void... values) { if(!dragged) { progress.setTitle(strProgressTitle); progress.setMessage(strProgressMessage); } } } private class PoWTask extends AsyncTask<String, Void, String> { private boolean isOK = true; private String strBlockHash = null; @Override protected String doInBackground(String... params) { strBlockHash = params[0]; JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort()); JSONObject nodeObj = jsonrpc.getBlockHeader(strBlockHash); if(nodeObj != null && nodeObj.has("hash")) { PoW pow = new PoW(strBlockHash); String hash = pow.calcHash(nodeObj); if(hash != null && hash.toLowerCase().equals(strBlockHash.toLowerCase())) { JSONObject headerObj = APIFactory.getInstance(BalanceActivity.this).getBlockHeader(strBlockHash); if(headerObj != null && headerObj.has("")) { if(!pow.check(headerObj, nodeObj, hash)) { isOK = false; } } } else { isOK = false; } } return "OK"; } @Override protected void onPostExecute(String result) { if(!isOK) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(getString(R.string.trusted_node_pow_failed) + "\n" + "Block hash:" + strBlockHash) .setCancelable(false) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } } @Override protected void onPreExecute() { ; } } private class CPFPTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(true); } @Override protected String doInBackground(String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(txObj.has("inputs") && txObj.has("outputs")) { final SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); int p2pkh = 0; int p2wpkh = 0; for(int i = 0; i < inputs.length(); i++) { if(inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) { String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey"); Script script = new Script(Hex.decode(scriptpubkey)); Address address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(address.isP2SHAddress()) { p2wpkh++; } else { p2pkh++; } } } FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, outputs.length()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; UTXO utxo = null; for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String addr = obj.getString("address"); Log.d("BalanceActivity", "checking address:" + addr); if(utxo == null) { utxo = getUTXO(addr); } else { break; } } } boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); if(utxo != null) { Log.d("BalanceActivity", "utxo found"); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); selectedUTXO.add(utxo); int selected = utxo.getOutpoints().size(); long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "remaining fee:" + remainingFee); int receiveIdx = AddressFactory.getInstance(BalanceActivity.this).getHighestTxReceiveIdx(0); Log.d("BalanceActivity", "receive index:" + receiveIdx); final String addr = outputs.getJSONObject(0).getString("address"); final String ownReceiveAddr; if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString(); } else { ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); } Log.d("BalanceActivity", "receive address:" + ownReceiveAddr); long totalAmount = utxo.getValue(); Log.d("BalanceActivity", "amount before fee:" + totalAmount); Pair<Integer,Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(utxo.getOutpoints()); BigInteger cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getRight(), 1); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); p2pkh = outpointTypes.getLeft(); p2wpkh = outpointTypes.getRight(); if(totalAmount < (cpfpFee.longValue() + remainingFee)) { Log.d("BalanceActivity", "selecting additional utxo"); Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { totalAmount += _utxo.getValue(); selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); outpointTypes = FeeUtil.getInstance().getOutpointCount(utxo.getOutpoints()); p2pkh += outpointTypes.getLeft(); p2wpkh += outpointTypes.getRight(); cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, 1); if(totalAmount > (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { break; } } if(totalAmount < (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); FeeUtil.getInstance().setSuggestedFee(suggestedFee); return "KO"; } } cpfpFee = cpfpFee.add(BigInteger.valueOf(remainingFee)); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for(UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } long _totalAmount = 0L; for(MyTransactionOutPoint outpoint : outPoints) { _totalAmount += outpoint.getValue().longValue(); } Log.d("BalanceActivity", "checked total amount:" + _totalAmount); assert(_totalAmount == totalAmount); long amount = totalAmount - cpfpFee.longValue(); Log.d("BalanceActivity", "amount after fee:" + amount); if(amount < SamouraiWallet.bDust.longValue()) { Log.d("BalanceActivity", "dust output"); Toast.makeText(BalanceActivity.this, R.string.cannot_output_dust, Toast.LENGTH_SHORT).show(); } final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(ownReceiveAddr, BigInteger.valueOf(amount)); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); Transaction tx = SendFactory.getInstance(BalanceActivity.this).makeTransaction(0, outPoints, receivers); if(tx != null) { tx = SendFactory.getInstance(BalanceActivity.this).signTransaction(tx); final String hexTx = new String(Hex.encode(tx.bitcoinSerialize())); Log.d("BalanceActivity", hexTx); final String strTxHash = tx.getHashAsString(); Log.d("BalanceActivity", strTxHash); boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_spent, Toast.LENGTH_SHORT).show(); FeeUtil.getInstance().setSuggestedFee(suggestedFee); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); // reset receive index upon tx fail if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else { int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } } } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else { int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { dialog.dismiss(); } } }); if(!isFinishing()) { dlg.show(); } } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_cpfp, Toast.LENGTH_SHORT).show(); } }); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "cpfp:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } }); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private UTXO getUTXO(String address) { UTXO ret = null; int idx = -1; for(int i = 0; i < utxos.size(); i++) { UTXO utxo = utxos.get(i); Log.d("BalanceActivity", "utxo address:" + utxo.getOutpoints().get(0).getAddress()); if(utxo.getOutpoints().get(0).getAddress().equals(address)) { ret = utxo; idx = i; break; } } if(ret != null) { utxos.remove(idx); return ret; } return null; } } private class RBFTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; private RBFSpend rbf = null; private HashMap<String,Long> input_values = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(true); input_values = new HashMap<String,Long>(); } @Override protected String doInBackground(final String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); rbf = RBFUtil.getInstance().get(params[0]); Log.d("BalanceActivity", "rbf:" + ((rbf == null) ? "null" : "not null")); final Transaction tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams(), Hex.decode(rbf.getSerializedTx())); Log.d("BalanceActivity", "tx serialized:" + rbf.getSerializedTx()); Log.d("BalanceActivity", "tx inputs:" + tx.getInputs().size()); Log.d("BalanceActivity", "tx outputs:" + tx.getOutputs().size()); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(tx != null && txObj.has("inputs") && txObj.has("outputs")) { try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); int p2pkh = 0; int p2wpkh = 0; for(int i = 0; i < inputs.length(); i++) { if(inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) { String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey"); Script script = new Script(Hex.decode(scriptpubkey)); Address address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(address.isP2SHAddress()) { p2wpkh++; } else { p2pkh++; } } } SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, outputs.length()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; long total_change = 0L; List<String> selfAddresses = new ArrayList<String>(); for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); String key = objPrev.getString("txid") + ":" + objPrev.getLong("vout"); input_values.put(key, objPrev.getLong("value")); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String _addr = null; if(obj.has("address")) { _addr = obj.getString("address"); } // if !obj.has("address"), not a change address -- probably bech32 selfAddresses.add(_addr); if(_addr != null && rbf.getChangeAddrs().contains(_addr.toString())) { total_change += obj.getLong("value"); } } } boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "total change:" + total_change); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); Log.d("BalanceActivity", "remaining fee:" + remainingFee); List<TransactionOutput> txOutputs = new ArrayList<TransactionOutput>(); txOutputs.addAll(tx.getOutputs()); long remainder = remainingFee; if(total_change > remainder) { for(TransactionOutput output : txOutputs) { Address _p2sh = output.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()); Address _p2pkh = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); if((_p2sh != null && rbf.getChangeAddrs().contains(_p2sh.toString())) || (_p2pkh != null && rbf.getChangeAddrs().contains(_p2pkh.toString()))) { if(output.getValue().longValue() >= (remainder + SamouraiWallet.bDust.longValue())) { output.setValue(Coin.valueOf(output.getValue().longValue() - remainder)); remainder = 0L; break; } else { remainder -= output.getValue().longValue(); output.setValue(Coin.valueOf(0L)); // output will be discarded later } } } } // // original inputs are not modified // List<MyTransactionInput> _inputs = new ArrayList<MyTransactionInput>(); List<TransactionInput> txInputs = tx.getInputs(); for(TransactionInput input : txInputs) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], input.getOutpoint(), input.getOutpoint().getHash().toString(), (int)input.getOutpoint().getIndex()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add outpoint:" + _input.getOutpoint().toString()); } Pair<Integer,Integer> outpointTypes = null; if(remainder > 0L) { List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long selectedAmount = 0L; int selected = 0; long _remainingFee = remainder; Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { Log.d("BalanceActivity", "utxo value:" + _utxo.getValue()); // // do not select utxo that are change outputs in current rbf tx // boolean isChange = false; boolean isSelf = false; for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { if(rbf.containsChangeAddr(outpoint.getAddress())) { Log.d("BalanceActivity", "is change:" + outpoint.getAddress()); Log.d("BalanceActivity", "is change:" + outpoint.getValue().longValue()); isChange = true; break; } if(selfAddresses.contains(outpoint.getAddress())) { Log.d("BalanceActivity", "is self:" + outpoint.getAddress()); Log.d("BalanceActivity", "is self:" + outpoint.getValue().longValue()); isSelf = true; break; } } if(isChange || isSelf) { continue; } selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); Log.d("BalanceActivity", "selected utxo:" + selected); selectedAmount += _utxo.getValue(); Log.d("BalanceActivity", "selected utxo value:" + _utxo.getValue()); outpointTypes = FeeUtil.getInstance().getOutpointCount(_utxo.getOutpoints()); p2pkh += outpointTypes.getLeft(); p2wpkh += outpointTypes.getRight(); _remainingFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, outputs.length() == 1 ? 2 : outputs.length()).longValue(); Log.d("BalanceActivity", "_remaining fee:" + _remainingFee); if(selectedAmount >= (_remainingFee + SamouraiWallet.bDust.longValue())) { break; } } long extraChange = 0L; if(selectedAmount < (_remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); return "KO"; } else { extraChange = selectedAmount - _remainingFee; Log.d("BalanceActivity", "extra change:" + extraChange); } boolean addedChangeOutput = false; // parent tx didn't have change output if(outputs.length() == 1 && extraChange > 0L) { try { boolean isSegwitChange = (FormatsUtil.getInstance().isValidBech32(outputs.getJSONObject(0).getString("address")) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outputs.getJSONObject(0).getString("address")).isP2SHAddress()) || PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false; String change_address = null; if(isSegwitChange) { int changeIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); change_address = BIP49Util.getInstance(BalanceActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, changeIdx).getAddressAsString(); } else { int changeIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddrIdx(); change_address = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddressAt(changeIdx).getAddressString(); } Script toOutputScript = ScriptBuilder.createOutputScript(org.bitcoinj.core.Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), change_address)); TransactionOutput output = new TransactionOutput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, Coin.valueOf(extraChange), toOutputScript.getProgram()); txOutputs.add(output); addedChangeOutput = true; } catch(MnemonicException.MnemonicLengthException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } } // parent tx had change output else { for(TransactionOutput output : txOutputs) { Address _address = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(_address == null) { _address = output.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()); } Log.d("BalanceActivity", "checking for change:" + _address.toString()); if(rbf.containsChangeAddr(_address.toString())) { Log.d("BalanceActivity", "before extra:" + output.getValue().longValue()); output.setValue(Coin.valueOf(extraChange + output.getValue().longValue())); Log.d("BalanceActivity", "after extra:" + output.getValue().longValue()); addedChangeOutput = true; break; } } } // sanity check if(extraChange > 0L && !addedChangeOutput) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } // // update keyBag w/ any new paths // final HashMap<String,String> keyBag = rbf.getKeyBag(); for(UTXO _utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], outpoint, outpoint.getTxHash().toString(), outpoint.getTxOutputN()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add selected outpoint:" + _input.getOutpoint().toString()); String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(outpoint.getAddress()); if(path != null) { Address address = Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outpoint.getAddress()); if(address != null && address.isP2SHAddress()) { rbf.addKey(outpoint.toString(), path + "/49"); } else { rbf.addKey(outpoint.toString(), path); } } else { String pcode = BIP47Meta.getInstance().getPCode4Addr(outpoint.getAddress()); int idx = BIP47Meta.getInstance().getIdx4Addr(outpoint.getAddress()); rbf.addKey(outpoint.toString(), pcode + "/" + idx); } } } rbf.setKeyBag(keyBag); } // // BIP69 sort of outputs/inputs // final Transaction _tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams()); List<TransactionOutput> _txOutputs = new ArrayList<TransactionOutput>(); _txOutputs.addAll(txOutputs); Collections.sort(_txOutputs, new SendFactory.BIP69OutputComparator()); for(TransactionOutput to : _txOutputs) { // zero value outputs discarded here if(to.getValue().longValue() > 0L) { _tx.addOutput(to); } } List<MyTransactionInput> __inputs = new ArrayList<MyTransactionInput>(); __inputs.addAll(_inputs); Collections.sort(__inputs, new SendFactory.BIP69InputComparator()); for(TransactionInput input : __inputs) { _tx.addInput(input); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Transaction __tx = signTx(_tx); final String hexTx = new String(Hex.encode(__tx.bitcoinSerialize())); Log.d("BalanceActivity", "hex tx:" + hexTx); final String strTxHash = __tx.getHashAsString(); Log.d("BalanceActivity", "tx hash" + strTxHash); if(__tx != null) { boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.rbf_spent, Toast.LENGTH_SHORT).show(); RBFSpend _rbf = rbf; // includes updated 'keyBag' _rbf.setSerializedTx(hexTx); _rbf.setHash(strTxHash); _rbf.setPrevHash(params[0]); RBFUtil.getInstance().add(_rbf); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); } } catch(final DecoderException de) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "rbf:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } else { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private Transaction signTx(Transaction tx) { HashMap<String,ECKey> keyBag = new HashMap<String,ECKey>(); HashMap<String,ECKey> keyBag49 = new HashMap<String,ECKey>(); HashMap<String,String> keys = rbf.getKeyBag(); for(String outpoint : keys.keySet()) { ECKey ecKey = null; String[] s = keys.get(outpoint).split("/"); Log.i("BalanceActivity", "path length:" + s.length); if(s.length == 4) { HD_Address addr = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChain(Integer.parseInt(s[1])).getAddressAt(Integer.parseInt(s[2])); ecKey = addr.getECKey(); } else if(s.length == 3) { HD_Address hd_address = AddressFactory.getInstance(BalanceActivity.this).get(0, Integer.parseInt(s[1]), Integer.parseInt(s[2])); String strPrivKey = hd_address.getPrivateKeyString(); DumpedPrivateKey pk = new DumpedPrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), strPrivKey); ecKey = pk.getKey(); } else if(s.length == 2) { try { PaymentAddress address = BIP47Util.getInstance(BalanceActivity.this).getReceiveAddress(new PaymentCode(s[0]), Integer.parseInt(s[1])); ecKey = address.getReceiveECKey(); } catch(Exception e) { ; } } else { ; } Log.i("BalanceActivity", "outpoint:" + outpoint); Log.i("BalanceActivity", "path:" + keys.get(outpoint)); // Log.i("BalanceActivity", "ECKey address from ECKey:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); if(ecKey != null) { if(s.length == 4) { keyBag49.put(outpoint, ecKey); } else { keyBag.put(outpoint, ecKey); } } else { throw new RuntimeException("ECKey error: cannot process private key"); // Log.i("ECKey error", "cannot process private key"); } } List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { ECKey ecKey = null; if(inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString())) { ecKey = keyBag49.get(inputs.get(i).getOutpoint().toString()); } else { ecKey = keyBag.get(inputs.get(i).getOutpoint().toString()); } if(inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString())) { final SegwitAddress p2shp2wpkh = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); System.out.println("pubKey:" + Hex.toHexString(ecKey.getPubKey())); Script scriptPubKey = p2shp2wpkh.segWitOutputScript(); System.out.println("to address from script:" + scriptPubKey.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); final Script redeemScript = p2shp2wpkh.segWitRedeemScript(); System.out.println("redeem script:" + Hex.toHexString(redeemScript.getProgram())); final Script scriptCode = redeemScript.scriptCode(); System.out.println("script code:" + Hex.toHexString(scriptCode.getProgram())); TransactionSignature sig = tx.calculateWitnessSignature(i, ecKey, scriptCode, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Transaction.SigHash.ALL, false); final TransactionWitness witness = new TransactionWitness(2); witness.setPush(0, sig.encodeToBitcoin()); witness.setPush(1, ecKey.getPubKey()); tx.setWitness(i, witness); final ScriptBuilder sigScript = new ScriptBuilder(); sigScript.data(redeemScript.getProgram()); tx.getInput(i).setScriptSig(sigScript.build()); tx.getInput(i).getScriptSig().correctlySpends(tx, i, scriptPubKey, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Script.ALL_VERIFY_FLAGS); } else { Log.i("BalanceActivity", "sign outpoint:" + inputs.get(i).getOutpoint().toString()); Log.i("BalanceActivity", "ECKey address from keyBag:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); Log.i("BalanceActivity", "script:" + ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()))); Log.i("BalanceActivity", "script:" + Hex.toHexString(ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram())); TransactionSignature sig = tx.calculateSignature(i, ecKey, ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram(), Transaction.SigHash.ALL, false); tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(sig, ecKey)); } } return tx; } } }
app/src/main/java/com/samourai/wallet/BalanceActivity.java
package com.samourai.wallet; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.ClipData; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.text.Html; import android.text.InputType; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AnticipateInterpolator; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.util.Log; import org.apache.commons.lang3.tuple.Pair; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.DumpedPrivateKey; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.TransactionWitness; import org.bitcoinj.crypto.BIP38PrivateKey; import org.bitcoinj.crypto.MnemonicException; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.wallet.JSONRPC.JSONRPC; import com.samourai.wallet.JSONRPC.PoW; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.api.Tx; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.rpc.*; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_Address; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.send.BlockedUTXO; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionInput; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFSpend; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.SweepUtil; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.PushTx; import com.samourai.wallet.service.WebSocketService; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.BlockExplorerUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.DateUtil; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.PrivKeyReader; import com.samourai.wallet.util.TimeOutUtil; import com.samourai.wallet.util.TorUtil; import com.samourai.wallet.util.TypefaceUtil; import org.bitcoinj.core.Coin; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.core.Transaction; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.encoders.DecoderException; import net.i2p.android.ext.floatingactionbutton.FloatingActionButton; import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu; import net.sourceforge.zbar.Symbol; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import info.guardianproject.netcipher.proxy.OrbotHelper; public class BalanceActivity extends Activity { private final static int SCAN_COLD_STORAGE = 2011; private final static int SCAN_QR = 2012; private LinearLayout layoutAlert = null; private LinearLayout tvBalanceBar = null; private TextView tvBalanceAmount = null; private TextView tvBalanceUnits = null; private ListView txList = null; private List<Tx> txs = null; private HashMap<String, Boolean> txStates = null; private TransactionAdapter txAdapter = null; private SwipeRefreshLayout swipeRefreshLayout = null; private FloatingActionsMenu ibQuickSend = null; private FloatingActionButton actionReceive = null; private FloatingActionButton actionSend = null; private FloatingActionButton actionBIP47 = null; private boolean isBTC = true; private RefreshTask refreshTask = null; private PoWTask powTask = null; private RBFTask rbfTask = null; private CPFPTask cpfpTask = null; public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH"; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { final boolean notifTx = intent.getBooleanExtra("notifTx", false); final boolean fetch = intent.getBooleanExtra("fetch", false); final String rbfHash; final String blkHash; if(intent.hasExtra("rbf")) { rbfHash = intent.getStringExtra("rbf"); } else { rbfHash = null; } if(intent.hasExtra("hash")) { blkHash = intent.getStringExtra("hash"); } else { blkHash = null; } BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); refreshTx(notifTx, fetch, false, false); if(BalanceActivity.this != null) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } if(rbfHash != null) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming)) .setCancelable(true) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doExplorerView(rbfHash); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } } } }); if(BalanceActivity.this != null && blkHash != null && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true && TrustedNodeUtil.getInstance().isSet()) { BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { if(powTask == null || powTask.getStatus().equals(AsyncTask.Status.FINISHED)) { powTask = new PoWTask(); powTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, blkHash); } } }); } } } }; protected BroadcastReceiver torStatusReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("BalanceActivity", "torStatusReceiver onReceive()"); if (OrbotHelper.ACTION_STATUS.equals(intent.getAction())) { boolean enabled = (intent.getStringExtra(OrbotHelper.EXTRA_STATUS).equals(OrbotHelper.STATUS_ON)); Log.i("BalanceActivity", "status:" + enabled); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(enabled); } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_balance); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if(SamouraiWallet.getInstance().isTestNet()) { setTitle(getText(R.string.app_name) + ":" + "TestNet"); } LayoutInflater inflator = BalanceActivity.this.getLayoutInflater(); tvBalanceBar = (LinearLayout)inflator.inflate(R.layout.balance_layout, null); tvBalanceBar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(isBTC) { isBTC = false; } else { isBTC = true; } displayBalance(); txAdapter.notifyDataSetChanged(); return false; } }); tvBalanceAmount = (TextView)tvBalanceBar.findViewById(R.id.BalanceAmount); tvBalanceUnits = (TextView)tvBalanceBar.findViewById(R.id.BalanceUnits); ibQuickSend = (FloatingActionsMenu)findViewById(R.id.wallet_menu); actionSend = (FloatingActionButton)findViewById(R.id.send); actionSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("via_menu", true); startActivity(intent); } }); actionReceive = (FloatingActionButton)findViewById(R.id.receive); actionReceive.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { try { HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get(); if(hdw != null) { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } }); actionBIP47 = (FloatingActionButton)findViewById(R.id.bip47); actionBIP47.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, com.samourai.wallet.bip47.BIP47Activity.class); startActivity(intent); } }); txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); txList = (ListView)findViewById(R.id.txList); txAdapter = new TransactionAdapter(); txList.setAdapter(txAdapter); txList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { if(position == 0) { return; } long viewId = view.getId(); View v = (View)view.getParent(); final Tx tx = txs.get(position - 1); ImageView ivTxStatus = (ImageView)v.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)v.findViewById(R.id.ConfirmationCount); if(viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) { if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } } else { String message = getString(R.string.options_unconfirmed_tx); // RBF if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0 && RBFUtil.getInstance().contains(tx.getHash())) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(rbfTask == null || rbfTask.getStatus().equals(AsyncTask.Status.FINISHED)) { rbfTask = new RBFTask(); rbfTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP receive else if(tx.getConfirmations() < 1 && tx.getAmount() >= 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP spend else if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } else { doExplorerView(tx.getHash()); return; } } } }); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().post(new Runnable() { @Override public void run() { refreshTx(false, true, true, false); } }); } }); swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); // TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); registerReceiver(torStatusReceiver, new IntentFilter(OrbotHelper.ACTION_STATUS)); boolean notifTx = false; boolean fetch = false; Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey("notifTx")) { notifTx = extras.getBoolean("notifTx"); } if(extras != null && extras.containsKey("uri")) { fetch = extras.getBoolean("fetch"); } refreshTx(notifTx, fetch, false, true); // // user checks mnemonic & passphrase // if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CREDS_CHECK, 0L) == 0L) { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.recovery_checkup) .setMessage(BalanceActivity.this.getText(R.string.recovery_checkup_message)) .setCancelable(false) .setPositiveButton(R.string.next, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); try { final String seed = HD_WalletFactory.getInstance(BalanceActivity.this).get().getMnemonic(); final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String message = BalanceActivity.this.getText(R.string.mnemonic) + ":<br><br><b>" + seed + "</b><br><br>" + BalanceActivity.this.getText(R.string.passphrase) + ":<br><br><b>" + passphrase + "</b>"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.recovery_checkup) .setMessage(Html.fromHtml(message)) .setCancelable(false) .setPositiveButton(R.string.recovery_checkup_finish, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.CREDS_CHECK, System.currentTimeMillis() / 1000L); dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } catch(IOException | MnemonicException.MnemonicLengthException e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } }); if(!isFinishing()) { dlg.show(); } } if(!AppUtil.getInstance(BalanceActivity.this).isClipboardSeen()) { doClipboardCheck(); } } @Override public void onResume() { super.onResume(); // IntentFilter filter = new IntentFilter(ACTION_INTENT); // LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); } AppUtil.getInstance(BalanceActivity.this).checkTimeOut(); if(!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } } @Override public void onPause() { super.onPause(); // LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); ibQuickSend.collapse(); } @Override public void onDestroy() { LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); unregisterReceiver(torStatusReceiver); if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { menu.findItem(R.id.action_tor).setVisible(false); } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_on); } else { menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_off); } menu.findItem(R.id.action_refresh).setVisible(false); menu.findItem(R.id.action_share_receive).setVisible(false); menu.findItem(R.id.action_ricochet).setVisible(false); menu.findItem(R.id.action_empty_ricochet).setVisible(false); menu.findItem(R.id.action_sign).setVisible(false); menu.findItem(R.id.action_fees).setVisible(false); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // noinspection SimplifiableIfStatement if (id == R.id.action_settings) { doSettings(); } else if (id == R.id.action_sweep) { doSweep(); } else if (id == R.id.action_utxo) { doUTXO(); } else if (id == R.id.action_tor) { if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { ; } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { item.setIcon(R.drawable.tor_off); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); } else { OrbotHelper.requestStartTor(BalanceActivity.this); item.setIcon(R.drawable.tor_on); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(true); } return true; } else if (id == R.id.action_backup) { if(SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { try { if(HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { doBackup(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); }}); if(!isFinishing()) { alert.show(); } } } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(IOException ioe) { ; } } else { Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show(); } } else if (id == R.id.action_scan_qr) { doScan(); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); doPrivKey(strResult); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) { ; } else if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(strResult)); try { if(privKeyReader.getFormat() != null) { doPrivKey(strResult); } else { Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("uri", strResult); startActivity(intent); } } catch(Exception e) { ; } } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_SINGLE_TOP); BalanceActivity.this.startActivity(intent); }}); alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); if(!isFinishing()) { alert.show(); } return true; } else { ; } return false; } private void doSettings() { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class); startActivity(intent); } private void doUTXO() { Intent intent = new Intent(BalanceActivity.this, UTXOActivity.class); startActivity(intent); } private void doScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_QR); } private void doSweepViaScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_COLD_STORAGE); } private void doSweep() { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.action_sweep) .setCancelable(true) .setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final EditText privkey = new EditText(BalanceActivity.this); privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.enter_privkey) .setView(privkey) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String strPrivKey = privkey.getText().toString(); if(strPrivKey != null && strPrivKey.length() > 0) { doPrivKey(strPrivKey); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } }).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doSweepViaScan(); } }); if(!isFinishing()) { dlg.show(); } } private void doPrivKey(final String data) { PrivKeyReader privKeyReader = null; String format = null; try { privKeyReader = new PrivKeyReader(new CharSequenceX(data), null); format = privKeyReader.getFormat(); } catch(Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } if(format != null) { if(format.equals(PrivKeyReader.BIP38)) { final PrivKeyReader pvr = privKeyReader; final EditText password38 = new EditText(BalanceActivity.this); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.bip38_pw) .setView(password38) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String password = password38.getText().toString(); ProgressDialog progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.decrypting_bip38)); progress.show(); boolean keyDecoded = false; try { BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data); final ECKey ecKey = bip38.decrypt(password); if(ecKey != null && ecKey.hasPrivKey()) { if(progress != null && progress.isShowing()) { progress.cancel(); } pvr.setPassword(new CharSequenceX(password)); keyDecoded = true; Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show(); } } catch(Exception e) { e.printStackTrace(); Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.cancel(); } if(keyDecoded) { SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, false); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } }); if(!isFinishing()) { dlg.show(); } } else if(privKeyReader != null) { SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, false); } else { ; } } else { Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show(); } } private void doBackup() { try { final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String[] export_methods = new String[2]; export_methods[0] = getString(R.string.export_to_clipboard); export_methods[1] = getString(R.string.export_to_email); new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.options_export) .setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch (IOException ioe) { ; } catch (JSONException je) { ; } catch (DecryptionException de) { ; } catch (MnemonicException.MnemonicLengthException mle) { ; } String encrypted = null; try { encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations); } catch (Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { if (encrypted == null) { Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show(); return; } } JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true); if (which == 0) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Wallet backup", obj.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } else { Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup"); email.putExtra(Intent.EXTRA_TEXT, obj.toString()); email.setType("message/rfc822"); startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client))); } dialog.dismiss(); } } ).show(); } catch(IOException ioe) { ioe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } } private void doClipboardCheck() { final android.content.ClipboardManager clipboard = (android.content.ClipboardManager)BalanceActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE); if(clipboard.hasPrimaryClip()) { final ClipData clip = clipboard.getPrimaryClip(); ClipData.Item item = clip.getItemAt(0); if(item.getText() != null) { String text = item.getText().toString(); String[] s = text.split("\\s+"); try { for(int i = 0; i < s.length; i++) { PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(s[i])); if(privKeyReader.getFormat() != null && (privKeyReader.getFormat().equals(PrivKeyReader.WIF_COMPRESSED) || privKeyReader.getFormat().equals(PrivKeyReader.WIF_UNCOMPRESSED) || privKeyReader.getFormat().equals(PrivKeyReader.BIP38) ) ) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.privkey_clipboard) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { clipboard.setPrimaryClip(ClipData.newPlainText("", "")); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } } } catch(Exception e) { ; } } } } private class TransactionAdapter extends BaseAdapter { private LayoutInflater inflater = null; private static final int TYPE_ITEM = 0; private static final int TYPE_BALANCE = 1; TransactionAdapter() { inflater = (LayoutInflater)BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } return txs.size() + 1; } @Override public String getItem(int position) { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } if(position == 0) { return ""; } return txs.get(position - 1).toString(); } @Override public long getItemId(int position) { return position - 1; } @Override public int getItemViewType(int position) { return position == 0 ? TYPE_BALANCE : TYPE_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { View view = null; int type = getItemViewType(position); if(convertView == null) { if(type == TYPE_BALANCE) { view = tvBalanceBar; } else { view = inflater.inflate(R.layout.tx_layout_simple, parent, false); } } else { view = convertView; } if(type == TYPE_BALANCE) { ; } else { view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); Tx tx = txs.get(position - 1); TextView tvTodayLabel = (TextView)view.findViewById(R.id.TodayLabel); String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS()); if(position == 1) { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } else { Tx prevTx = txs.get(position - 2); String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS()); if(strPrevDateGroup.equals(strDateGroup)) { tvTodayLabel.setVisibility(View.GONE); } else { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } } String strDetails = null; String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS()); long _amount = 0L; if(tx.getAmount() < 0.0) { _amount = Math.abs((long)tx.getAmount()); strDetails = BalanceActivity.this.getString(R.string.you_sent); } else { _amount = (long)tx.getAmount(); strDetails = BalanceActivity.this.getString(R.string.you_received); } String strAmount = null; String strUnits = null; if(isBTC) { strAmount = getBTCDisplayAmount(_amount); strUnits = getBTCDisplayUnits(); } else { strAmount = getFiatDisplayAmount(_amount); strUnits = getFiatDisplayUnits(); } TextView tvDirection = (TextView)view.findViewById(R.id.TransactionDirection); TextView tvDirection2 = (TextView)view.findViewById(R.id.TransactionDirection2); TextView tvDetails = (TextView)view.findViewById(R.id.TransactionDetails); ImageView ivTxStatus = (ImageView)view.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)view.findViewById(R.id.ConfirmationCount); tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface()); if(tx.getAmount() < 0.0) { tvDirection.setTextColor(Color.RED); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up)); } else { tvDirection.setTextColor(Color.GREEN); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down)); } if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits); if(tx.getPaymentCode() != null) { String strTaggedTS = strTS + " "; String strSubText = " " + BIP47Meta.getInstance().getDisplayLabel(tx.getPaymentCode()) + " "; strTaggedTS += strSubText; tvDetails.setText(strTaggedTS); } else { tvDetails.setText(strTS); } } return view; } } private void refreshTx(final boolean notifTx, final boolean fetch, final boolean dragged, final boolean launch) { if(refreshTask == null || refreshTask.getStatus().equals(AsyncTask.Status.FINISHED)) { refreshTask = new RefreshTask(dragged, launch); refreshTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, notifTx ? "1" : "0", fetch ? "1" : "0"); } } private void displayBalance() { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); long balance = 0L; if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance(); } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount()).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } double btc_balance = (((double)balance) / 1e8); double fiat_balance = btc_fx * btc_balance; if(isBTC) { tvBalanceAmount.setText(getBTCDisplayAmount(balance)); tvBalanceUnits.setText(getBTCDisplayUnits()); } else { tvBalanceAmount.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(fiat_balance)); tvBalanceUnits.setText(strFiat); } } private String getBTCDisplayAmount(long value) { String strAmount = null; DecimalFormat df = new DecimalFormat("#"); df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); strAmount = Coin.valueOf(value).toPlainString(); return strAmount; } private String getBTCDisplayUnits() { return MonetaryUtil.getInstance().getBTCUnits(); } private String getFiatDisplayAmount(long value) { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); String strAmount = MonetaryUtil.getInstance().getFiatFormat(strFiat).format(btc_fx * (((double)value) / 1e8)); return strAmount; } private String getFiatDisplayUnits() { return PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); } private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) { if(heads) { if(confirmations == 0) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_query_builder_white); tvConfirmationCount.setVisibility(View.GONE); } else if(confirmations > 3) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_done_white); tvConfirmationCount.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } } else { if(confirmations < 100) { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText("\u221e"); ivTxStatus.setVisibility(View.GONE); } } } private void rotateTxStatus(View view, boolean clockwise) { float degrees = 360f; if(!clockwise) { degrees = -360f; } ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees); animation.setDuration(1000); animation.setRepeatCount(0); animation.setInterpolator(new AnticipateInterpolator()); animation.start(); } private void doExplorerView(String strHash) { if(strHash != null) { int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0); if(sel >= BlockExplorerUtil.getInstance().getBlockExplorerTxUrls().length) { sel = 0; } CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerTxUrls()[sel]; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + strHash)); startActivity(browserIntent); } } private class RefreshTask extends AsyncTask<String, Void, String> { private String strProgressTitle = null; private String strProgressMessage = null; private ProgressDialog progress = null; private Handler handler = null; private boolean dragged = false; private boolean launch = false; public RefreshTask(boolean dragged, boolean launch) { super(); Log.d("BalanceActivity", "RefreshTask, dragged==" + dragged); handler = new Handler(); this.dragged = dragged; this.launch = launch; } @Override protected void onPreExecute() { Log.d("BalanceActivity", "RefreshTask.preExecute()"); if(progress != null && progress.isShowing()) { progress.dismiss(); } if(!dragged) { strProgressTitle = BalanceActivity.this.getText(R.string.app_name).toString(); strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx_pre).toString(); progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(true); progress.setTitle(strProgressTitle); progress.setMessage(strProgressMessage); progress.show(); } } @Override protected String doInBackground(String... params) { Log.d("BalanceActivity", "doInBackground()"); final boolean notifTx = params[0].equals("1") ? true : false; final boolean fetch = params[1].equals("1") ? true : false; // // TBD: check on lookahead/lookbehind for all incoming payment codes // if(fetch || txs.size() == 0) { APIFactory.getInstance(BalanceActivity.this).initWallet(); } try { int acc = 0; txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs(); if(txs != null) { Collections.sort(txs, new APIFactory.TxMostRecentDateComparator()); } if(AddressFactory.getInstance().getHighestTxReceiveIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestTxReceiveIdx(acc)); } if(AddressFactory.getInstance().getHighestTxChangeIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().setAddrIdx(AddressFactory.getInstance().getHighestTxChangeIdx(acc)); } if(AddressFactory.getInstance().getHighestBIP49ReceiveIdx() > BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx()) { BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestBIP49ReceiveIdx()); } if(AddressFactory.getInstance().getHighestBIP49ChangeIdx() > BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()) { BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(AddressFactory.getInstance().getHighestBIP49ChangeIdx()); } } catch(IOException ioe) { ioe.printStackTrace(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); } finally { ; } if(!dragged) { strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx).toString(); publishProgress(); } handler.post(new Runnable() { public void run() { if(dragged) { swipeRefreshLayout.setRefreshing(false); } tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); displayBalance(); txAdapter.notifyDataSetChanged(); } }); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.FIRST_RUN, false); if(notifTx) { // // check for incoming payment code notification tx // try { PaymentCode pcode = BIP47Util.getInstance(BalanceActivity.this).getPaymentCode(); // Log.i("BalanceFragment", "payment code:" + pcode.toString()); // Log.i("BalanceFragment", "notification address:" + pcode.notificationAddress().getAddressString()); APIFactory.getInstance(BalanceActivity.this).getNotifAddress(pcode.notificationAddress().getAddressString()); } catch (AddressFormatException afe) { afe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } strProgressMessage = BalanceActivity.this.getText(R.string.refresh_incoming_notif_tx).toString(); publishProgress(); // // check on outgoing payment code notification tx // List<Pair<String,String>> outgoingUnconfirmed = BIP47Meta.getInstance().getOutgoingUnconfirmed(); // Log.i("BalanceFragment", "outgoingUnconfirmed:" + outgoingUnconfirmed.size()); for(Pair<String,String> pair : outgoingUnconfirmed) { // Log.i("BalanceFragment", "outgoing payment code:" + pair.getLeft()); // Log.i("BalanceFragment", "outgoing payment code tx:" + pair.getRight()); int confirmations = APIFactory.getInstance(BalanceActivity.this).getNotifTxConfirmations(pair.getRight()); if(confirmations > 0) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_SENT_CFM); } if(confirmations == -1) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_NOT_SENT); } } if(!dragged) { strProgressMessage = BalanceActivity.this.getText(R.string.refresh_outgoing_notif_tx).toString(); publishProgress(); } Intent intent = new Intent("com.samourai.wallet.BalanceActivity.RESTART_SERVICE"); LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent); } if(!dragged) { if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.GUID_V, 0) < 4) { Log.i("BalanceActivity", "guid_v < 4"); try { String _guid = AccessFactory.getInstance(BalanceActivity.this).createGUID(); String _hash = AccessFactory.getInstance(BalanceActivity.this).getHash(_guid, new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getPIN()), AESUtil.DefaultPBKDF2Iterations); PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(_guid + AccessFactory.getInstance().getPIN())); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.ACCESS_HASH, _hash); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.ACCESS_HASH2, _hash); Log.i("BalanceActivity", "guid_v == 4"); } catch(MnemonicException.MnemonicLengthException | IOException | JSONException | DecryptionException e) { ; } } else if(!launch) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(Exception e) { } } else { ; } } /* if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.XPUB44LOCK, false) == false) { try { String[] s = HD_WalletFactory.getInstance(BalanceActivity.this).get().getXPUBs(); for(int i = 0; i < s.length; i++) { APIFactory.getInstance(BalanceActivity.this).lockXPUB(s[0], false); } } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.XPUB49LOCK, false) == false) { ; } */ return "OK"; } @Override protected void onPostExecute(String result) { if(!dragged) { if(progress != null && progress.isShowing()) { progress.dismiss(); } } List<UTXO> utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(false); for(UTXO utxo : utxos) { List<MyTransactionOutPoint> outpoints = utxo.getOutpoints(); for(MyTransactionOutPoint out : outpoints) { byte[] scriptBytes = out.getScriptBytes(); String address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(address); if(path != null && path.startsWith("M/1/")) { continue; } final String hash = out.getHash().toString(); final int idx = out.getTxOutputN(); final long amount = out.getValue().longValue(); if(amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD && !BlockedUTXO.getInstance().contains(hash, idx) && !BlockedUTXO.getInstance().containsNotDusted(hash, idx)) { String message = BalanceActivity.this.getString(R.string.dusting_attempt); message += "\n\n"; message += BalanceActivity.this.getString(R.string.dusting_attempt_amount); message += " "; message += Coin.valueOf(amount).toPlainString(); message += " BTC\n"; message += BalanceActivity.this.getString(R.string.dusting_attempt_id); message += " "; message += hash + "-" + idx; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.dusting_tx) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { BlockedUTXO.getInstance().add(hash, idx, amount); } }).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { BlockedUTXO.getInstance().addNotDusted(hash, idx); } }); if(!isFinishing()) { dlg.show(); } } } } } @Override protected void onProgressUpdate(Void... values) { if(!dragged) { progress.setTitle(strProgressTitle); progress.setMessage(strProgressMessage); } } } private class PoWTask extends AsyncTask<String, Void, String> { private boolean isOK = true; private String strBlockHash = null; @Override protected String doInBackground(String... params) { strBlockHash = params[0]; JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort()); JSONObject nodeObj = jsonrpc.getBlockHeader(strBlockHash); if(nodeObj != null && nodeObj.has("hash")) { PoW pow = new PoW(strBlockHash); String hash = pow.calcHash(nodeObj); if(hash != null && hash.toLowerCase().equals(strBlockHash.toLowerCase())) { JSONObject headerObj = APIFactory.getInstance(BalanceActivity.this).getBlockHeader(strBlockHash); if(headerObj != null && headerObj.has("")) { if(!pow.check(headerObj, nodeObj, hash)) { isOK = false; } } } else { isOK = false; } } return "OK"; } @Override protected void onPostExecute(String result) { if(!isOK) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(getString(R.string.trusted_node_pow_failed) + "\n" + "Block hash:" + strBlockHash) .setCancelable(false) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } } @Override protected void onPreExecute() { ; } } private class CPFPTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(true); } @Override protected String doInBackground(String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(txObj.has("inputs") && txObj.has("outputs")) { final SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); int p2pkh = 0; int p2wpkh = 0; for(int i = 0; i < inputs.length(); i++) { if(inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) { String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey"); Script script = new Script(Hex.decode(scriptpubkey)); Address address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(address.isP2SHAddress()) { p2wpkh++; } else { p2pkh++; } } } FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, outputs.length()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; UTXO utxo = null; for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String addr = obj.getString("address"); Log.d("BalanceActivity", "checking address:" + addr); if(utxo == null) { utxo = getUTXO(addr); } else { break; } } } boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); if(utxo != null) { Log.d("BalanceActivity", "utxo found"); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); selectedUTXO.add(utxo); int selected = utxo.getOutpoints().size(); long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "remaining fee:" + remainingFee); int receiveIdx = AddressFactory.getInstance(BalanceActivity.this).getHighestTxReceiveIdx(0); Log.d("BalanceActivity", "receive index:" + receiveIdx); final String addr = outputs.getJSONObject(0).getString("address"); final String ownReceiveAddr; if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString(); } else { ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); } Log.d("BalanceActivity", "receive address:" + ownReceiveAddr); long totalAmount = utxo.getValue(); Log.d("BalanceActivity", "amount before fee:" + totalAmount); Pair<Integer,Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(utxo.getOutpoints()); BigInteger cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getRight(), 1); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); p2pkh = outpointTypes.getLeft(); p2wpkh = outpointTypes.getRight(); if(totalAmount < (cpfpFee.longValue() + remainingFee)) { Log.d("BalanceActivity", "selecting additional utxo"); Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { totalAmount += _utxo.getValue(); selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); outpointTypes = FeeUtil.getInstance().getOutpointCount(utxo.getOutpoints()); p2pkh += outpointTypes.getLeft(); p2wpkh += outpointTypes.getRight(); cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, 1); if(totalAmount > (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { break; } } if(totalAmount < (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); FeeUtil.getInstance().setSuggestedFee(suggestedFee); return "KO"; } } cpfpFee = cpfpFee.add(BigInteger.valueOf(remainingFee)); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for(UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } long _totalAmount = 0L; for(MyTransactionOutPoint outpoint : outPoints) { _totalAmount += outpoint.getValue().longValue(); } Log.d("BalanceActivity", "checked total amount:" + _totalAmount); assert(_totalAmount == totalAmount); long amount = totalAmount - cpfpFee.longValue(); Log.d("BalanceActivity", "amount after fee:" + amount); if(amount < SamouraiWallet.bDust.longValue()) { Log.d("BalanceActivity", "dust output"); Toast.makeText(BalanceActivity.this, R.string.cannot_output_dust, Toast.LENGTH_SHORT).show(); } final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(ownReceiveAddr, BigInteger.valueOf(amount)); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); Transaction tx = SendFactory.getInstance(BalanceActivity.this).makeTransaction(0, outPoints, receivers); if(tx != null) { tx = SendFactory.getInstance(BalanceActivity.this).signTransaction(tx); final String hexTx = new String(Hex.encode(tx.bitcoinSerialize())); Log.d("BalanceActivity", hexTx); final String strTxHash = tx.getHashAsString(); Log.d("BalanceActivity", strTxHash); boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_spent, Toast.LENGTH_SHORT).show(); FeeUtil.getInstance().setSuggestedFee(suggestedFee); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); // reset receive index upon tx fail if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else { int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } } } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else { int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { dialog.dismiss(); } } }); if(!isFinishing()) { dlg.show(); } } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_cpfp, Toast.LENGTH_SHORT).show(); } }); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "cpfp:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } }); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private UTXO getUTXO(String address) { UTXO ret = null; int idx = -1; for(int i = 0; i < utxos.size(); i++) { UTXO utxo = utxos.get(i); Log.d("BalanceActivity", "utxo address:" + utxo.getOutpoints().get(0).getAddress()); if(utxo.getOutpoints().get(0).getAddress().equals(address)) { ret = utxo; idx = i; break; } } if(ret != null) { utxos.remove(idx); return ret; } return null; } } private class RBFTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; private RBFSpend rbf = null; private HashMap<String,Long> input_values = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(true); input_values = new HashMap<String,Long>(); } @Override protected String doInBackground(final String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); rbf = RBFUtil.getInstance().get(params[0]); Log.d("BalanceActivity", "rbf:" + ((rbf == null) ? "null" : "not null")); final Transaction tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams(), Hex.decode(rbf.getSerializedTx())); Log.d("BalanceActivity", "tx serialized:" + rbf.getSerializedTx()); Log.d("BalanceActivity", "tx inputs:" + tx.getInputs().size()); Log.d("BalanceActivity", "tx outputs:" + tx.getOutputs().size()); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(tx != null && txObj.has("inputs") && txObj.has("outputs")) { try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); int p2pkh = 0; int p2wpkh = 0; for(int i = 0; i < inputs.length(); i++) { if(inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) { String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey"); Script script = new Script(Hex.decode(scriptpubkey)); Address address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(address.isP2SHAddress()) { p2wpkh++; } else { p2pkh++; } } } SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, outputs.length()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; long total_change = 0L; List<String> selfAddresses = new ArrayList<String>(); for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); String key = objPrev.getString("txid") + ":" + objPrev.getLong("vout"); input_values.put(key, objPrev.getLong("value")); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String _addr = obj.getString("address"); selfAddresses.add(_addr); if(_addr != null && rbf.getChangeAddrs().contains(_addr.toString())) { total_change += obj.getLong("value"); } } } boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "total change:" + total_change); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); Log.d("BalanceActivity", "remaining fee:" + remainingFee); List<TransactionOutput> txOutputs = new ArrayList<TransactionOutput>(); txOutputs.addAll(tx.getOutputs()); long remainder = remainingFee; if(total_change > remainder) { for(TransactionOutput output : txOutputs) { Address _p2sh = output.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()); Address _p2pkh = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); if((_p2sh != null && rbf.getChangeAddrs().contains(_p2sh.toString())) || (_p2pkh != null && rbf.getChangeAddrs().contains(_p2pkh.toString()))) { if(output.getValue().longValue() >= (remainder + SamouraiWallet.bDust.longValue())) { output.setValue(Coin.valueOf(output.getValue().longValue() - remainder)); remainder = 0L; break; } else { remainder -= output.getValue().longValue(); output.setValue(Coin.valueOf(0L)); // output will be discarded later } } } } // // original inputs are not modified // List<MyTransactionInput> _inputs = new ArrayList<MyTransactionInput>(); List<TransactionInput> txInputs = tx.getInputs(); for(TransactionInput input : txInputs) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], input.getOutpoint(), input.getOutpoint().getHash().toString(), (int)input.getOutpoint().getIndex()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add outpoint:" + _input.getOutpoint().toString()); } Pair<Integer,Integer> outpointTypes = null; if(remainder > 0L) { List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long selectedAmount = 0L; int selected = 0; long _remainingFee = remainder; Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { Log.d("BalanceActivity", "utxo value:" + _utxo.getValue()); // // do not select utxo that are change outputs in current rbf tx // boolean isChange = false; boolean isSelf = false; for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { if(rbf.containsChangeAddr(outpoint.getAddress())) { Log.d("BalanceActivity", "is change:" + outpoint.getAddress()); Log.d("BalanceActivity", "is change:" + outpoint.getValue().longValue()); isChange = true; break; } if(selfAddresses.contains(outpoint.getAddress())) { Log.d("BalanceActivity", "is self:" + outpoint.getAddress()); Log.d("BalanceActivity", "is self:" + outpoint.getValue().longValue()); isSelf = true; break; } } if(isChange || isSelf) { continue; } selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); Log.d("BalanceActivity", "selected utxo:" + selected); selectedAmount += _utxo.getValue(); Log.d("BalanceActivity", "selected utxo value:" + _utxo.getValue()); outpointTypes = FeeUtil.getInstance().getOutpointCount(_utxo.getOutpoints()); p2pkh += outpointTypes.getLeft(); p2wpkh += outpointTypes.getRight(); _remainingFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, outputs.length() == 1 ? 2 : outputs.length()).longValue(); Log.d("BalanceActivity", "_remaining fee:" + _remainingFee); if(selectedAmount >= (_remainingFee + SamouraiWallet.bDust.longValue())) { break; } } long extraChange = 0L; if(selectedAmount < (_remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); return "KO"; } else { extraChange = selectedAmount - _remainingFee; Log.d("BalanceActivity", "extra change:" + extraChange); } boolean addedChangeOutput = false; // parent tx didn't have change output if(outputs.length() == 1 && extraChange > 0L) { try { boolean isSegwitChange = (FormatsUtil.getInstance().isValidBech32(outputs.getJSONObject(0).getString("address")) || Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outputs.getJSONObject(0).getString("address")).isP2SHAddress()) || PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_LIKE_TYPED_CHANGE, true) == false; String change_address = null; if(isSegwitChange) { int changeIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().getAddrIdx(); change_address = BIP49Util.getInstance(BalanceActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, changeIdx).getAddressAsString(); } else { int changeIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddrIdx(); change_address = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddressAt(changeIdx).getAddressString(); } Script toOutputScript = ScriptBuilder.createOutputScript(org.bitcoinj.core.Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), change_address)); TransactionOutput output = new TransactionOutput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, Coin.valueOf(extraChange), toOutputScript.getProgram()); txOutputs.add(output); addedChangeOutput = true; } catch(MnemonicException.MnemonicLengthException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } } // parent tx had change output else { for(TransactionOutput output : txOutputs) { Address _address = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(_address == null) { _address = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); } Log.d("BalanceActivity", "checking for change:" + _address.toString()); if(rbf.containsChangeAddr(_address.toString())) { Log.d("BalanceActivity", "before extra:" + output.getValue().longValue()); output.setValue(Coin.valueOf(extraChange + output.getValue().longValue())); Log.d("BalanceActivity", "after extra:" + output.getValue().longValue()); addedChangeOutput = true; break; } } } // sanity check if(extraChange > 0L && !addedChangeOutput) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } // // update keyBag w/ any new paths // final HashMap<String,String> keyBag = rbf.getKeyBag(); for(UTXO _utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], outpoint, outpoint.getTxHash().toString(), outpoint.getTxOutputN()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add selected outpoint:" + _input.getOutpoint().toString()); String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(outpoint.getAddress()); if(path != null) { Address address = Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outpoint.getAddress()); if(address != null && address.isP2SHAddress()) { rbf.addKey(outpoint.toString(), path + "/49"); } else { rbf.addKey(outpoint.toString(), path); } } else { String pcode = BIP47Meta.getInstance().getPCode4Addr(outpoint.getAddress()); int idx = BIP47Meta.getInstance().getIdx4Addr(outpoint.getAddress()); rbf.addKey(outpoint.toString(), pcode + "/" + idx); } } } rbf.setKeyBag(keyBag); } // // BIP69 sort of outputs/inputs // final Transaction _tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams()); List<TransactionOutput> _txOutputs = new ArrayList<TransactionOutput>(); _txOutputs.addAll(txOutputs); Collections.sort(_txOutputs, new SendFactory.BIP69OutputComparator()); for(TransactionOutput to : _txOutputs) { // zero value outputs discarded here if(to.getValue().longValue() > 0L) { _tx.addOutput(to); } } List<MyTransactionInput> __inputs = new ArrayList<MyTransactionInput>(); __inputs.addAll(_inputs); Collections.sort(__inputs, new SendFactory.BIP69InputComparator()); for(TransactionInput input : __inputs) { _tx.addInput(input); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Transaction __tx = signTx(_tx); final String hexTx = new String(Hex.encode(__tx.bitcoinSerialize())); Log.d("BalanceActivity", "hex tx:" + hexTx); final String strTxHash = __tx.getHashAsString(); Log.d("BalanceActivity", "tx hash" + strTxHash); if(__tx != null) { boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.rbf_spent, Toast.LENGTH_SHORT).show(); RBFSpend _rbf = rbf; // includes updated 'keyBag' _rbf.setSerializedTx(hexTx); _rbf.setHash(strTxHash); _rbf.setPrevHash(params[0]); RBFUtil.getInstance().add(_rbf); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); } } catch(final DecoderException de) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "rbf:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } else { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private Transaction signTx(Transaction tx) { HashMap<String,ECKey> keyBag = new HashMap<String,ECKey>(); HashMap<String,ECKey> keyBag49 = new HashMap<String,ECKey>(); HashMap<String,String> keys = rbf.getKeyBag(); for(String outpoint : keys.keySet()) { ECKey ecKey = null; String[] s = keys.get(outpoint).split("/"); Log.i("BalanceActivity", "path length:" + s.length); if(s.length == 4) { HD_Address addr = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChain(Integer.parseInt(s[1])).getAddressAt(Integer.parseInt(s[2])); ecKey = addr.getECKey(); } else if(s.length == 3) { HD_Address hd_address = AddressFactory.getInstance(BalanceActivity.this).get(0, Integer.parseInt(s[1]), Integer.parseInt(s[2])); String strPrivKey = hd_address.getPrivateKeyString(); DumpedPrivateKey pk = new DumpedPrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), strPrivKey); ecKey = pk.getKey(); } else if(s.length == 2) { try { PaymentAddress address = BIP47Util.getInstance(BalanceActivity.this).getReceiveAddress(new PaymentCode(s[0]), Integer.parseInt(s[1])); ecKey = address.getReceiveECKey(); } catch(Exception e) { ; } } else { ; } Log.i("BalanceActivity", "outpoint:" + outpoint); Log.i("BalanceActivity", "path:" + keys.get(outpoint)); // Log.i("BalanceActivity", "ECKey address from ECKey:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); if(ecKey != null) { if(s.length == 4) { keyBag49.put(outpoint, ecKey); } else { keyBag.put(outpoint, ecKey); } } else { throw new RuntimeException("ECKey error: cannot process private key"); // Log.i("ECKey error", "cannot process private key"); } } List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { ECKey ecKey = null; if(inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString())) { ecKey = keyBag49.get(inputs.get(i).getOutpoint().toString()); } else { ecKey = keyBag.get(inputs.get(i).getOutpoint().toString()); } if(inputs.get(i).getValue() != null || keyBag49.containsKey(inputs.get(i).getOutpoint().toString())) { final SegwitAddress p2shp2wpkh = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); System.out.println("pubKey:" + Hex.toHexString(ecKey.getPubKey())); Script scriptPubKey = p2shp2wpkh.segWitOutputScript(); System.out.println("to address from script:" + scriptPubKey.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); final Script redeemScript = p2shp2wpkh.segWitRedeemScript(); System.out.println("redeem script:" + Hex.toHexString(redeemScript.getProgram())); final Script scriptCode = redeemScript.scriptCode(); System.out.println("script code:" + Hex.toHexString(scriptCode.getProgram())); TransactionSignature sig = tx.calculateWitnessSignature(i, ecKey, scriptCode, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Transaction.SigHash.ALL, false); final TransactionWitness witness = new TransactionWitness(2); witness.setPush(0, sig.encodeToBitcoin()); witness.setPush(1, ecKey.getPubKey()); tx.setWitness(i, witness); final ScriptBuilder sigScript = new ScriptBuilder(); sigScript.data(redeemScript.getProgram()); tx.getInput(i).setScriptSig(sigScript.build()); tx.getInput(i).getScriptSig().correctlySpends(tx, i, scriptPubKey, Coin.valueOf(input_values.get(inputs.get(i).getOutpoint().toString())), Script.ALL_VERIFY_FLAGS); } else { Log.i("BalanceActivity", "sign outpoint:" + inputs.get(i).getOutpoint().toString()); Log.i("BalanceActivity", "ECKey address from keyBag:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); Log.i("BalanceActivity", "script:" + ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()))); Log.i("BalanceActivity", "script:" + Hex.toHexString(ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram())); TransactionSignature sig = tx.calculateSignature(i, ecKey, ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram(), Transaction.SigHash.ALL, false); tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(sig, ecKey)); } } return tx; } } }
Check for bech32 spend for boosted RBF
app/src/main/java/com/samourai/wallet/BalanceActivity.java
Check for bech32 spend for boosted RBF
<ide><path>pp/src/main/java/com/samourai/wallet/BalanceActivity.java <ide> if(obj.has("value")) { <ide> total_outputs += obj.getLong("value"); <ide> <del> String _addr = obj.getString("address"); <add> String _addr = null; <add> if(obj.has("address")) { <add> _addr = obj.getString("address"); <add> } <add> // if !obj.has("address"), not a change address -- probably bech32 <add> <ide> selfAddresses.add(_addr); <ide> if(_addr != null && rbf.getChangeAddrs().contains(_addr.toString())) { <ide> total_change += obj.getLong("value"); <ide> for(TransactionOutput output : txOutputs) { <ide> Address _address = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); <ide> if(_address == null) { <del> _address = output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()); <add> _address = output.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()); <ide> } <ide> Log.d("BalanceActivity", "checking for change:" + _address.toString()); <ide> if(rbf.containsChangeAddr(_address.toString())) {
Java
apache-2.0
e5fca0d18fd9910c780b6dab2f3c2cc5c8a645e8
0
UKGovLD/registry-core,UKGovLD/registry-core,UKGovLD/registry-core,UKGovLD/registry-core
/****************************************************************** * File: TestAPI.java * Created by: Dave Reynolds * Created on: 1 Feb 2013 * * (c) Copyright 2013, Epimorphics 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.epimorphics.registry.webapi; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import org.apache.jena.riot.RDFDataMgr; import org.junit.Test; import com.epimorphics.rdfutil.RDFUtil; import com.epimorphics.registry.csv.CSVPayloadRead; import com.epimorphics.registry.util.JSONLDSupport; import com.epimorphics.registry.util.Prefixes; import com.epimorphics.registry.vocab.Ldbp; import com.epimorphics.registry.vocab.Prov; import com.epimorphics.registry.vocab.RegistryVocab; import com.epimorphics.registry.vocab.Version; import com.epimorphics.util.TestUtil; import com.epimorphics.vocabs.API; import com.epimorphics.vocabs.SKOS; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFList; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.util.FileManager; import com.hp.hpl.jena.vocabulary.DCTerms; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.sun.jersey.api.client.ClientResponse; /** * Test harness for testing access to the API - launches a registry using an * embedded tomcat and a memory-backed store then talks to the API using http. * * @author <a href="mailto:[email protected]">Dave Reynolds</a> */ public class TestAPI extends TomcatTestBase { static final String EXT_BLACK = "http://example.com/colours/black"; static final String REG1 = BASE_URL + "reg1"; static final String REG1_URI = ROOT_REGISTER + "reg1"; static final String REG1_ITEM = ROOT_REGISTER + "_reg1"; static final String REGL_URL = BASE_URL + "regL"; protected File exportFile; String getWebappRoot() { return "src/test/webapp"; } @Test public void testBasics() throws IOException { // Create reg1 doRegisterRegistrationTests(); // Puts red in reg1/red doItemRegistrationTests(); // Adds external resource reg1/black doExternalRegistrationTests(); // Updates red to be called red1 String versionSuffix = doUpdateTest(); // Patches red to be called red1b Calendar checkpoint = Calendar.getInstance(); doPatchTest(); // Check we can still get back the old version of reg from before the last patch checkModelResponse(REG1 + "/_red" + versionSuffix, ROOT_REGISTER + "reg1/red", "test/expected/red1.ttl"); // Adds reg1/blue and tests views with different status setting and metadata doRegisterListingTest(); // Update tests on register itself, ISSUE-27, changes register name so so after listing test doRegUpdateTest(); // Check for case of invalid patch requests doInvalidUpdateTest(); // Create a large register regL and checks paged views and retrieving early version of register doPagingTest(); doRegisterVersionRetrievalTest(); // Register timestamp view - predates changing red1 to red1b and adding blue checkRegisterList( getModelResponse(REG1 + "?status=any&_versionAt=" + checkpoint.getTimeInMillis()), REG1_URI, "red1", "black"); // List versions doListVersionsTest(); // Check some status transitions doStatusTransitionsTest(); // Checking of legal relative URIs in registration payload assertEquals(400, postFileStatus("test/bad-green.ttl", REG1)); // Bulk registration - creates a collection and a scheme register from skos collection and concept scheme doBulkRegistrationTest(); // Check patching of register metadata - tests on /collection created in prior step doRegisterMetadataPatchTest(); // Test deletions using the /collection register doDeletionTest(); // Test validation operation doValidationTest(); // List a register - was a bug here Model m = getModelResponse(BASE_URL + "?status=any"); checkRegisterList(m, RDFS.member, ROOT_REGISTER, "system register", "register 1", "A test collection", "Long register", "A nice test collection", "A test concept scheme") ; // Delegation tests doForwardingTest(); doDelegationTest(); // Check prefix system register doPrefixTests(); // Check we can register and patch using jsonld syntax payloads doJsonldTests(); // Check registration of entity and item information together doRegisterWithMetadataTest(); // Check patching metadata annotations doMetadataPatchTest(); // Check upload of multiple items in a single payload doMultiPostTest(); // Test reservation of entries using bNode entity addresses doReservationTest(); // Check that an explicit reg:register in payload doesn't get through doBlockInternalPropertiesTest(); // Check validation of entries in a register with validation constraints doValidationChecks(); // Check use of numeric literals as notation values doCheckNumericNotations(); // Check tagging doTaggingTest(); // Export doTestCSVOut(); // Graph entities and annotations doGraphEntityTest(); doGraphAnnotationTest(); // Typed template lookup and change notification doTypedTemplateTest(); // Bug tests doBNodeDuplicationBugTest(); doSkosLabelTest(); // CSV parsing, needs runtime registry to access prefixes register doTestPayloadRead("test/csv/reg3-red.csv", "test/csv/reg3-red.ttl"); doTestPayloadRead("test/csv/reg3-red-no-metadata.csv", "test/csv/reg3-red-no-metadata.ttl"); doTestPayloadRead("test/edit/edit3.csv", "test/csv/edit3.ttl"); // Edit doEditTest(); exportFile = File.createTempFile("export", "nq"); doExport(); // Deletion doTestRealDelete(); // Reimport from before delete doImportTest(); // System.out.println("Store dump"); // ServiceConfig.get().getServiceAs("basestore", Store.class).asDataset().getDefaultModel().write(System.out, "Turtle"); } private void doSkosLabelTest() { assertEquals(201, postFileStatus("test/bugs/brown-preflabel.ttl", REG1)); checkModelResponse(REG1 + "/brown", ROOT_REGISTER + "reg1/brown", "test/expected/brown.ttl"); checkModelResponse(REG1 + "/brown?_view=with_metadata", ROOT_REGISTER + "reg1/brown", "test/expected/brown_metadata.ttl"); } private void doInvalidUpdateTest() { assertEquals(400, invoke("PATCH", "test/blue-patch.ttl", BASE_URL).getStatus()); assertEquals(400, invoke("PATCH", "test/blue-patch.ttl", REG1).getStatus()); // Can't drop label assertEquals(400, invoke("PUT", "test/red-bad-update-label.ttl", REG1 + "/red").getStatus()); // Can't remove type assertEquals(400, invoke("PUT", "test/red-bad-update-type.ttl", REG1 + "/red").getStatus()); } private void doRegisterRegistrationTests() { // Leaves register reg1 set up ClientResponse response = postFile("test/reg1.ttl", BASE_URL, "text/turtle"); assertEquals("Register a register", 201, response.getStatus()); assertEquals(REG1_ITEM, response.getLocation().toString()); assertEquals("Register in non-existant location", 404, postFileStatus("test/reg1.ttl", BASE_URL+"foo")); assertEquals("Register the same again", 403, postFileStatus("test/reg1.ttl", BASE_URL)); } // Assumes reg1 has been created // Adds an item (reg1/red) and checks it all looks OK // Leaves reg1/red in plce private void doItemRegistrationTests() { assertEquals(201, postFileStatus("test/red.ttl", REG1)); checkModelResponse(REG1 + "/red", ROOT_REGISTER + "reg1/red", "test/expected/red.ttl"); Model m = getModelResponse(REG1 + "/red?_view=with_metadata"); checkModelResponse(m, ROOT_REGISTER + "reg1/_red", "test/expected/red_item.ttl"); checkModelResponse(m, ROOT_REGISTER + "reg1/red", "test/expected/red.ttl"); checkEntity(m, ROOT_REGISTER + "reg1/_red", ROOT_REGISTER + "reg1/red"); assertEquals(404, getResponse(REG1 + "/notred").getStatus()); assertEquals(404, getResponse(REG1 + "/notred/").getStatus()); m = getModelResponse(REG1 + "/_red"); checkModelResponse(m, ROOT_REGISTER + "reg1/_red", "test/expected/red_item.ttl"); checkModelResponse(m, ROOT_REGISTER + "reg1/red", "test/expected/red.ttl"); checkEntity(m, ROOT_REGISTER + "reg1/_red", ROOT_REGISTER + "reg1/red"); } // Assumes reg1 has been created // Adds an external entity and check it can be retrieved private void doExternalRegistrationTests() { // External (not managed) entities assertEquals(201, postFileStatus("test/absolute-black.ttl", REG1)); Model m = checkModelResponse(REG1 + "/_black", EXT_BLACK, "test/expected/absolute-black.ttl"); checkEntity(m, ROOT_REGISTER + "reg1/_black", EXT_BLACK); // Entity retrieval checkModelResponse(REG1 + "?entity=" + EXT_BLACK, EXT_BLACK, "test/expected/absolute-black.ttl"); checkModelResponse(BASE_URL + "?entity=" + EXT_BLACK, EXT_BLACK, "test/expected/absolute-black.ttl"); m = getModelResponse(BASE_URL, "entity", EXT_BLACK, "_view", "with_metadata"); checkModelResponse(m, EXT_BLACK, "test/expected/absolute-black.ttl"); checkModelResponse(m, ROOT_REGISTER + "reg1/_black", "test/expected/absolute-black.ttl"); } // Assumes reg1 and reg1/red exists // Updates name of red to red1 // Returns the version number of the new version private String doUpdateTest() { // Updates, change properties on red ClientResponse response = invoke("PUT", "test/red1.ttl", REG1 + "/red"); assertEquals(204, response.getStatus()); String red1Version = response.getLocation().toString(); assertTrue(red1Version.startsWith(ROOT_REGISTER + "reg1/_red:")); String versionSuffix = red1Version.substring( red1Version.length()-2 ); checkModelResponse(REG1 + "/red", ROOT_REGISTER + "reg1/red", "test/expected/red1.ttl"); return versionSuffix; } private void doRegUpdateTest() { String reg1meta = REG1 + "?non-member-properties"; Model m = getModelResponse(reg1meta); Resource reg1 = m.getResource(REG1_URI); long version = RDFUtil.getLongValue(reg1, OWL.versionInfo); ClientResponse response = invoke("PUT", "test/reg1-put.ttl", reg1meta); assertEquals(204, response.getStatus()); m = getModelResponse(reg1meta); reg1 = m.getResource(REG1_URI); long newversion = RDFUtil.getLongValue(reg1, OWL.versionInfo); assertEquals(version + 1, newversion); assertEquals("Example register 1 - put update", RDFUtil.getStringValue(reg1, DCTerms.description)); response = invoke("PATCH", "test/reg1-patch.ttl", reg1meta); assertEquals(204, response.getStatus()); m = getModelResponse(reg1meta); reg1 = m.getResource(REG1_URI); newversion = RDFUtil.getLongValue(reg1, OWL.versionInfo); assertEquals(version + 2, newversion); assertEquals("Example register 1 - patch update", RDFUtil.getStringValue(reg1, DCTerms.description)); // Verify access to earlier version of the RegisterItem containing the register - ISSUE-26 Resource current = getModelResponse(BASE_URL + "_reg1").getResource(REG1_URI); assertEquals(version + 2, RDFUtil.getLongValue(current, OWL.versionInfo).longValue()); assertEquals("Example register 1 - patch update", RDFUtil.getStringValue(current, DCTerms.description)); Resource orig = getModelResponse(BASE_URL + "_reg1:1").getResource(REG1_URI); assertEquals(1, RDFUtil.getLongValue(orig, OWL.versionInfo).longValue()); assertEquals("Example register 1", RDFUtil.getStringValue(orig, DCTerms.description)); // Safe against versioninfo being in payload response = invoke("PUT", "test/reg1-put2.ttl", reg1meta); m = getModelResponse(reg1meta); reg1 = m.getResource(REG1_URI); newversion = RDFUtil.getLongValue(reg1, OWL.versionInfo); assertEquals(version + 3, newversion); assertEquals("Example register 1 - put update2", RDFUtil.getStringValue(reg1, DCTerms.description)); // Try to change RDF type // assertEquals(400, invoke("PUT", "test/reg1-bad-put1.ttl", reg1meta).getStatus()); // Multiple roots in change file assertEquals(400, invoke("PUT", "test/reg1-bad-put2.ttl", reg1meta).getStatus()); } // Assumes reg1/red exists // Patch its name to red1b private void doPatchTest() { ClientResponse response = invoke("PATCH", "test/red1b.ttl", REG1 + "/red"); assertEquals(204, response.getStatus()); checkModelResponse(REG1 + "/red", ROOT_REGISTER + "reg1/red", "test/expected/red1b.ttl"); } // Assumes reg1 exists and already has red (now called red1b) and black in it // Tests listing different status filters and basic metadata access // Leaves register with blue as well, red as "stable" and black as "experimental" private void doRegisterListingTest() { // Register read checkModelResponse(REG1, ROOT_REGISTER + "reg1", "test/expected/reg1-empty.ttl"); assertEquals(204, post(REG1 + "/_red?update&status=stable").getStatus()); assertEquals(204, post(REG1 + "/_black?update&status=experimental").getStatus()); checkModelResponse(REG1, ROOT_REGISTER + "reg1", "test/expected/reg1_red_black.ttl"); // Register listing assertEquals(201, postFileStatus("test/blue.ttl", REG1)); Model m = getModelResponse(REG1 + "?non-member-properties"); checkModelResponse(m, REG1_URI, "test/expected/reg1-empty.ttl"); checkRegisterList( getModelResponse(REG1 + "?status=stable"), REG1_URI, "red1b"); checkRegisterList( getModelResponse(REG1 + "?status=experimental"), REG1_URI, "black"); checkRegisterList( getModelResponse(REG1 + "?status=valid"), REG1_URI, "red1b", "black"); checkRegisterList( getModelResponse(REG1 + "?status=accepted"), REG1_URI, "red1b", "black"); checkRegisterList( getModelResponse(REG1 + "?status=notaccepted"), REG1_URI, "blue"); checkRegisterList( getModelResponse(REG1 + "?status=any"), REG1_URI, "red1b", "black", "blue"); // Register metadata view m = getModelResponse(REG1 + "?non-member-properties&_view=with_metadata"); checkModelResponse(m, REG1_URI, "test/expected/reg1_nmp_metadata.ttl"); checkModelResponse(m, REG1_ITEM, "test/expected/reg1_nmp_metadata.ttl"); m = getModelResponse(REG1 + "?_view=with_metadata"); checkModelResponse(m, REG1_URI, "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, REG1_URI+"/red", "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, REG1_URI+"/_red", "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, EXT_BLACK, "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, REG1_URI+"/_black", "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, REG1_ITEM, "test/expected/reg1_nmp_metadata.ttl"); } private void doPagingTest() { // Register paging makeRegister(60); checkPageResponse(getModelResponse(REGL_URL + "?firstPage&status=notaccepted"), "1", 50); checkPageResponse(getModelResponse(REGL_URL + "?_page=1&status=notaccepted"), null, 10); } private void doRegisterVersionRetrievalTest() { // Register version view Model m = getModelResponse(REGL_URL + ":3?status=notaccepted"); checkModelResponse(m, ROOT_REGISTER + "regL", "test/expected/regL-two-entries.ttl"); checkModelResponse(m, ROOT_REGISTER + "regL/item0", "test/expected/regL-two-entries.ttl"); checkModelResponse(m, ROOT_REGISTER + "regL/item1", "test/expected/regL-two-entries.ttl"); } // Leaves new registers /collection and /scheme private void doBulkRegistrationTest() { assertEquals("Not a bulk type", 400, postFileStatus("test/blue.ttl", BASE_URL + "?batch-managed")); // assertEquals(201, postFileStatus("test/bulk-skos-collection.ttl", BASE_URL + "?batch-managed")); ClientResponse response = postFile("test/bulk-skos-collection.ttl", BASE_URL + "?batch-managed"); TestAPIDebug.debugStatus(response); Model m = getModelResponse(BASE_URL + "collection?status=any"); checkRegisterList( m, ROOT_REGISTER + "collection", "item 1", "item 2", "item 3"); assertEquals(201, postFileStatus("test/bulk-skos-scheme.ttl", BASE_URL + "?batch-managed")); m = getModelResponse(BASE_URL + "scheme?status=any"); TestUtil.testArray( m.listSubjectsWithProperty(SKOS.inScheme, m.getResource(ROOT_REGISTER + "scheme")).toList(), new Resource[]{ m.createResource(ROOT_REGISTER + "scheme/item1"), m.createResource(ROOT_REGISTER + "scheme/item2"), m.createResource(ROOT_REGISTER + "scheme/item3") } ); assertEquals(201, postFileStatus("test/bulk-skos-collection.ttl", BASE_URL + "collection?batch-managed&status=stable")); m = getModelResponse(BASE_URL + "collection/collection?status=stable"); checkRegisterList( m, ROOT_REGISTER + "collection/collection", "item 1", "item 2", "item 3"); assertEquals(201, postFileStatus("test/bulk-skos-collection-of-scheme.ttl", BASE_URL + "?batch-referenced")); m = getModelResponse(BASE_URL + "scheme-collection?status=any"); checkRegisterList( m, ROOT_REGISTER + "scheme-collection", "item 1", "item 2"); assertEquals(400, postFileStatus("test/bulk-skos-collection-spurious.ttl", BASE_URL + "?batch-managed") ); } // Assumes /collection exists from bulk registration test private void doRegisterMetadataPatchTest() { // Updating register metadata assertEquals(400, invoke("PATCH", "test/register-update.ttl", BASE_URL + "collection").getStatus()); assertEquals(204, invoke("PATCH", "test/register-update.ttl", BASE_URL + "collection?non-member-properties").getStatus()); Model m = getModelResponse(BASE_URL + "collection?non-member-properties"); checkModelResponse(m, ROOT_REGISTER + "collection", "test/expected/updated-collection-register.ttl"); } // Assumes /colleciton exists from bulk registration tests // Test deletion of items from register private void doDeletionTest() { long timestamp = System.currentTimeMillis(); assertEquals(204, invoke("DELETE", null, BASE_URL + "collection/collection/item1").getStatus()); checkRegisterList( getModelResponse(BASE_URL + "collection/collection?status=stable"), ROOT_REGISTER + "collection/collection", "item 2", "item 3"); assertEquals(204, invoke("DELETE", null, BASE_URL + "collection/collection/_item2").getStatus()); checkRegisterList( getModelResponse(BASE_URL + "collection/collection?status=stable"), ROOT_REGISTER + "collection/collection", "item 3"); // Reconstruct register pre-delete checkRegisterList( getModelResponse(BASE_URL + "collection/collection?status=stable&_versionAt=" + timestamp), ROOT_REGISTER + "collection/collection", "item 1", "item 2", "item 3"); Resource collection = ResourceFactory.createResource("http://location.data.gov.uk/collection"); Resource collectionCollection = ResourceFactory.createResource("http://location.data.gov.uk/collection/collection"); assertTrue( getModelResponse(BASE_URL + "collection?status=stable").contains(collection, SKOS.member, collectionCollection)); assertEquals(204, invoke("DELETE", null, BASE_URL + "collection/collection").getStatus()); assertFalse( getModelResponse(BASE_URL + "collection?status=stable").contains(collection, SKOS.member, collectionCollection)); checkRegisterList( getModelResponse(BASE_URL + "collection/collection?status=stable"), ROOT_REGISTER + "collection/collection"); } private void doValidationTest() { assertEquals(400, postFileStatus("test/validation-request1.txt", BASE_URL + "?validate" )); assertEquals(204, post(BASE_URL + "collection?update&status=stable&force").getStatus()); assertEquals(200, postFileStatus("test/validation-request1.txt", BASE_URL + "?validate" )); assertEquals(400, postFileStatus("test/validation-request2.txt", BASE_URL + "?validate" )); assertEquals(200, post(BASE_URL + "?validate=http://location.data.gov.uk/collection/item1").getStatus()); assertEquals(404, post(BASE_URL + "foo?validate=http://location.data.gov.uk/collection/item1").getStatus()); assertEquals(400, post(BASE_URL + "?validate=http://location.data.gov.uk/collection/item1&validate=http://location.data.gov.uk/collection/item8").getStatus()); ClientResponse response = post(BASE_URL + "?validate=http://location.data.gov.uk/collection/item1"); assertEquals(200, response.getStatus()); assertEquals("http://location.data.gov.uk/collection/item1 is http://location.data.gov.uk/collection/_item1", response.getEntity(String.class).trim()); } // Assumes reg1/red exists and has go through update (to red1) and patch (to red1b) and status change private void doListVersionsTest() { Model m = getModelResponse(BASE_URL + "reg1/_red?_view=version_list"); assertTrue( m.listSubjectsWithProperty(DCTerms.isVersionOf, m.getResource(ROOT_REGISTER + "reg1/_red")).toList().size() >= 4); assertTrue( m.contains(m.getResource(ROOT_REGISTER + "reg1/_red:3"), DCTerms.replaces, m.getResource(ROOT_REGISTER + "reg1/_red:2")) ); assertTrue( m.contains(m.getResource(ROOT_REGISTER + "reg1/_red"), Version.currentVersion, m.getResource(ROOT_REGISTER + "reg1/_red:4")) ); } // Assumes reg1/blue exists, leaves it in "invalid" status private void doStatusTransitionsTest() { assertEquals(403, post(REG1 + "/_blue?update&status=retired").getStatus()); assertEquals(403, post(REG1 + "/_blue?update&status=superseded").getStatus()); assertEquals(204, post(REG1 + "/_blue?update&status=experimental").getStatus()); assertEquals(204, post(REG1 + "/_blue?update&status=stable").getStatus()); assertEquals(403, post(REG1 + "/_blue?update&status=experimental").getStatus()); assertEquals(403, post(REG1 + "/_blue?update&status=submitted").getStatus()); assertEquals(204, post(REG1 + "/_blue?update&status=superseded").getStatus()); assertEquals(204, post(REG1 + "/_blue?update&status=invalid").getStatus()); } // Set up a namespace forward to EA data and checks can access it // Relies on the EA service being up :) private void doForwardingTest() { assertEquals(201, postFileStatus("test/bw-forward.ttl", REG1)); assertEquals(404, getResponse(REG1 + "/eabw/ukc2102-03600").getStatus()); assertEquals(204, post(REG1 + "/_eabw?update&status=stable").getStatus()); assertEquals(200, getResponse(REG1 + "/eabw/ukc2102-03600").getStatus()); Model m = getModelResponse(REG1 + "/eabw/ukc2102-03600"); Resource bw = m.getResource("http://environment.data.gov.uk/id/bathing-water/ukc2102-03600"); assertEquals("Spittal", RDFUtil.getStringValue(bw, SKOS.prefLabel)); // convert forwarding to proxying, will only actually function if nginx is up and test doesn't require that assertEquals(204, invoke("PATCH", "test/bw-proxy-patch.ttl", REG1 + "/eabw").getStatus()); String proxyConfig = FileManager.get().readWholeFileAsUTF8("/var/opt/ldregistry/proxy-registry.conf"); assertTrue(proxyConfig.contains("location /reg1/eabw")); assertTrue(proxyConfig.contains("proxy_pass http://environment.data.gov.uk/doc/bathing-water/")); // Switch batch to forwarding mode to check switching off proxy works assertEquals(204, invoke("PATCH", "test/bw-forward-patch.ttl", REG1 + "/eabw").getStatus()); proxyConfig = FileManager.get().readWholeFileAsUTF8("/var/opt/ldregistry/proxy-registry.conf"); assertFalse(proxyConfig.contains("location /reg1/eabw")); assertEquals(200, getResponse(REG1 + "/eabw/ukc2102-03600").getStatus()); } // Set up a delegated register for the EA bathingwaters URI set and checks register listing // Relies on the EA service being up :) private void doDelegationTest() { // Check read on delegated register assertEquals(201, postFileStatus("test/bw-delegated.ttl", REG1)); assertEquals(204, post(REG1 + "/_bathingWaters?update&status=stable").getStatus()); Model m = getModelResponse(REG1 + "/bathingWaters?firstPage"); Resource register = m.getResource(REG1_URI + "/bathingWaters"); List<Resource> members = RDFUtil.allResourceValues(register, RDFS.member); assertTrue(members.size() > 20); for (Resource member : members) { assertTrue(member.hasProperty(RDFS.label)); assertTrue(member.hasProperty(RDF.type)); } m = getModelResponse(REG1 + "?entity=http://environment.data.gov.uk/id/bathing-water/ukc2102-03600"); Resource bw = m.getResource("http://environment.data.gov.uk/id/bathing-water/ukc2102-03600"); assertEquals("Spittal", RDFUtil.getStringValue(bw, SKOS.prefLabel)); } private void doPrefixTests() { Map<String, String> pm = Prefixes.get().getNsPrefixMap(); assertTrue(pm.containsKey("rdf")); assertEquals(RDF.getURI(), pm.get("rdf")); assertTrue(pm.containsKey("reg")); assertEquals(RegistryVocab.getURI(), pm.get("reg")); assertEquals(200, getResponse(BASE_URL + "system").getStatus()); assertEquals(200, getResponse(BASE_URL + "system/prefixes").getStatus()); assertEquals(200, getResponse(BASE_URL + "system/prefixes").getStatus()); // Prefix update assertEquals(201, postFileStatus("test/prefix-test-xyz.ttl", BASE_URL + "system/prefixes")); // Update of prefixes depends on the background message thread, this is fragile to test for int trycount = 0; boolean passed = false; while (trycount < 10 && !passed) { trycount++; pm = Prefixes.get().getNsPrefixMap(); if (pm.containsKey("xyz")) { assertTrue(pm.containsKey("xyz")); assertEquals("http://example.com/xyz", pm.get("xyz")); passed = true; } else { try { Thread.sleep(50); } catch (InterruptedException e) {}; } } } // Assumes /reg1 exists all earlier tests run (so has at least blue in it) // Leaves it with /reg1/purple and with reg1 dct:description changed private void doJsonldTests() throws IOException { // Assumes reg1 set up assertEquals(201, postFileStatus("test/purple-testcase.jsonld", REG1, JSONLDSupport.MIME_JSONLD)); Model m = getModelResponse(BASE_URL + "reg1/purple"); Resource r = m.getResource(ROOT_REGISTER + "reg1/purple"); assertEquals("purple", RDFUtil.getStringValue(r, RDFS.label)); assertEquals("I am purple but described using JSON-LD, good luck with that", RDFUtil.getStringValue(r, DCTerms.description)); ClientResponse response = getResponse(BASE_URL + "reg1/blue", JSONLDSupport.MIME_JSONLD); assertEquals(200, response.getStatus()); InputStream is = response.getEntityInputStream(); m = JSONLDSupport.readModel(RequestProcessor.DUMMY_BASE_URI, is); is.close(); r = m.getResource(ROOT_REGISTER + "reg1/blue"); assertEquals("blue", RDFUtil.getStringValue(r, RDFS.label)); // JSON-LD patch assertEquals(204, invoke("PATCH", "test/reg1-patch.jsonld", REG1 + "?non-member-properties", "application/ld+json").getStatus()); m = getModelResponse(REG1 + "?non-member-properties"); assertEquals("Updated register 1", RDFUtil.getStringValue(m.getResource(REG1_URI), DCTerms.description)); } // Register two entries for "eight", both with explicit RegsiterItems as well as the associated entity // First version has no URI and gives notation, second uses relative URI to infer notation // ISSUE-38 private void doRegisterWithMetadataTest() { // Testing update of item + entity - ISSUE-38 ClientResponse response = postFile("test/jmt/number-eight-post-notation.ttl", REG1); assertEquals(201, response.getStatus()); String itemURI = ROOT_REGISTER + "reg1/_eight"; assertEquals(itemURI, response.getLocation().toASCIIString()); checkRegisteredMetadata( getModelResponse(REG1+"/eight?_view=with_metadata"), "eight" ); response = postFile("test/jmt/number-eightb-post-relative.ttl", REG1); assertEquals(201, response.getStatus()); itemURI = ROOT_REGISTER + "reg1/_eightb"; assertEquals(itemURI, response.getLocation().toASCIIString()); checkRegisteredMetadata( getModelResponse(REG1+"/_eightb"), "eightb" ); } private void checkRegisteredMetadata(Model m, String notation) { String itemURI = ROOT_REGISTER + "reg1/_" + notation; Resource item = m.getResource(itemURI); assertEquals(notation, RDFUtil.getStringValue(item, RegistryVocab.notation)); assertEquals("http://ukgovld-registry.dnsalias.net/def/numbers/eight", item.getPropertyResourceValue(RegistryVocab.definition) .getPropertyResourceValue(RegistryVocab.entity) .getURI()); assertEquals(RegistryVocab.statusStable, item.getPropertyResourceValue(RegistryVocab.status)); Property attributedTo = m.getProperty("http://www.w3.org/ns/prov#wasAttributedTo"); assertEquals("http://jeremytandy.me.uk/self#id", item.getPropertyResourceValue(attributedTo).getURI()); } // Test patching a RegisterItem with external metadata // ISSUE-39 private void doMetadataPatchTest() { assertEquals(201, postFileStatus("test/jmt/number-nine-post.ttl", REG1)); Property attributedTo = ResourceFactory.createProperty("http://www.w3.org/ns/prov#wasAttributedTo"); Resource item = getModelResponse(REG1 + "/nine?_view=with_metadata").getResource(REG1_URI + "/_nine"); assertFalse(item.hasProperty(attributedTo)); assertEquals(204, invoke("PATCH", "test/jmt/number-nine-patch.ttl", REG1 + "/_nine").getStatus() ); item = getModelResponse(REG1 + "/nine?_view=with_metadata").getResource(REG1_URI + "/_nine"); assertEquals("http://jeremytandy.me.uk/self#id", item.getPropertyResourceValue(attributedTo).getURI()); } // Test upload of multiple register items at the same time private void doMultiPostTest() { List<String> before = getRegisterList(getModelResponse(REG1 + "?status=stable"), SKOS.member, REG1_URI); assertEquals(201, postFileStatus("test/jmt/number-eleven-twelve-post-rel.ttl", REG1)); List<String> after = getRegisterList(getModelResponse(REG1 + "?status=stable"), SKOS.member, REG1_URI); checkAdded(before, after, "eleven", "twelve"); assertEquals(201, postFileStatus("test/jmt/number-eleven-twelve-post-bnode.ttl", REG1)); List<String> after2 = getRegisterList(getModelResponse(REG1 + "?status=stable"), SKOS.member, REG1_URI); checkAdded(after, after2, "elevenb", "twelveb"); } private void checkAdded(List<String> before, List<String> after, String...additions) { assertTrue( after.containsAll(before) ); List<String> residual = new ArrayList<String>(after); residual.removeAll(before); TestUtil.testArray(residual, additions); } // Test reservation of entries using bNode entity addresses private void doReservationTest() { List<String> before = getRegisterList(getModelResponse(REG1), SKOS.member, REG1_URI); assertEquals(201, postFileStatus("test/jmt/number-six-reserved-post.ttl", REG1)); Model m = getModelResponse(REG1+"?status=any&_view=with_metadata"); validateReservedEntry(m, null, "reserved"); getModelResponse(REG1+"?status=any&firstPage"); // Fails if bNodes not skolemized getModelResponse(REG1+"?status=any"); // Fails if bNodes not skolemized assertEquals(204, invoke("PUT", "test/jmt/number-six-update.ttl", REG1+"/_six").getStatus()); m = getModelResponse(REG1+"?status=any&_view=with_metadata"); validateReservedEntry(m, "http://example.com/six", "six"); // Check that reserved item does not appear in normal listing List<String> after = getRegisterList(getModelResponse(REG1), SKOS.member, REG1_URI); assertTrue(after.containsAll(before) && before.containsAll(after)); // Check can't transition straight from reserved to stable assertEquals(403, post(REG1 + "/_six?update&status=stable").getStatus()); // Check that once accepted can no longer change the entity URI assertEquals(204, post(REG1 + "/_six?update&status=submitted").getStatus()); assertEquals(204, post(REG1 + "/_six?update&status=stable").getStatus()); assertEquals(400, invoke("PUT", "test/jmt/number-six-update2.ttl", REG1+"/_six").getStatus()); } private void validateReservedEntry(Model m, String entityURI, String label) { Resource reg1 = m.getResource(REG1_URI); Resource _six = m.getResource(REG1_URI + "/_six"); assertTrue(m.contains(_six, RegistryVocab.register, reg1)); Resource entity = _six.getPropertyResourceValue(RegistryVocab.definition).getPropertyResourceValue(RegistryVocab.entity); if (entityURI != null) { assertEquals(entityURI, entity.getURI()); } assertEquals(label, RDFUtil.getStringValue(entity, RDFS.label)); } // Check that an explicit reg:register in payload doesn't get through private void doBlockInternalPropertiesTest() { assertEquals(201, postFileStatus("test/jmt/number-fifteen-reserved-post.ttl", REG1)); Model m = getModelResponse(REG1 + "/_fifteen"); Resource r = m.getResource(REG1_URI + "/_fifteen"); TestUtil.testArray(RDFUtil.allResourceValues(r, RegistryVocab.register), new Resource[]{ m.getResource(REG1_URI)}); } // Check validation of entries in a register with validation constraints private void doValidationChecks() { assertEquals(201, postFileStatus("test/reg2.ttl", BASE_URL)); assertEquals(201, postFileStatus("test/reg2-entry-good.ttl", BASE_URL+"reg2")); checkRegisterList(getModelResponse(BASE_URL+"reg2?status=any"), ROOT_REGISTER + "reg2", "entry concept"); assertEquals(400, postFileStatus("test/reg2-entry-bad1.ttl", BASE_URL+"reg2")); assertEquals(400, postFileStatus("test/reg2-entry-bad2.ttl", BASE_URL+"reg2")); assertEquals(400, postFileStatus("test/reg2-entry-bad3.ttl", BASE_URL+"reg2")); assertEquals(400, postFileStatus("test/reg2-entry-bad4.ttl", BASE_URL+"reg2")); // Check that a multi-item upload is reject in its entirety assertEquals(400, postFileStatus("test/test-multi-item-validate.ttl", BASE_URL+"reg2")); Model m = getModelResponse(BASE_URL + "reg2?status=any"); List<String> members = getRegisterList(m, SKOS.member, ROOT_REGISTER + "reg2"); assertFalse(members.contains("concept1")); assertFalse(members.contains("concept2")); assertFalse(members.contains("concept3")); } /** * Check use of numeric literals as notation values, both that * they survive processing and that register page listing orders * numerically instead of lexically in that case. */ private void doCheckNumericNotations() { assertEquals(201, postFileStatus("test/codes.ttl", BASE_URL)); assertEquals(201, postFileStatus("test/jmt/runway-numeric.ttl", BASE_URL + "codes")); Model m = getModelResponse(BASE_URL + "codes?_view=with_metadata&firstPage"); Resource page = m.getResource(ROOT_REGISTER + "codes?_view=with_metadata&firstPage="); Resource items = page.getPropertyResourceValue(API.items); assertNotNull(items); List<RDFNode> itemList = items.as(RDFList.class).asJavaList(); int[] expected = new int[]{7, 8, 9, 15}; for (int i = 0; i < expected.length; i++) { int e = expected[i]; Resource item = itemList.get(i).asResource(); assertTrue(item.getURI().endsWith("/" + e)); Resource meta = m.getResource(ROOT_REGISTER + "codes/_" + e); Object value = meta.getProperty(RegistryVocab.notation).getObject().asLiteral().getValue(); assert(value instanceof Number); assertEquals(e, ((Number)value).intValue()); } } /** * Check that tagging a register works and the results can be retrieved */ private void doTaggingTest() { // Create a clean register state assertEquals(201, postFileStatus("test/reg3.ttl", BASE_URL)); assertEquals(201, postFileStatus("test/red.ttl", BASE_URL + "reg3")); assertEquals(201, postFileStatus("test/blue.ttl", BASE_URL + "reg3")); assertEquals(204, post(BASE_URL + "reg3/_red?update&status=stable").getStatus()); assertEquals(204, post(BASE_URL + "reg3/_blue?update&status=stable").getStatus()); // Tag it ClientResponse response = post(BASE_URL+"reg3?tag=tag1"); assertEquals(201, response.getStatus()); String uri = ROOT_REGISTER+"reg3?tag=tag1"; assertEquals(uri, response.getLocation().toString()); // Modify some entries response = invoke("PATCH", "test/red1b.ttl", BASE_URL + "reg3/red"); assertEquals(204, response.getStatus()); assertEquals(201, postFileStatus("test/green.ttl", BASE_URL + "reg3")); Model model = getModelResponse(BASE_URL + "reg3?tag=tag1"); Resource collection = model.getResource(uri); assertTrue(collection.hasProperty(RDF.type, Prov.Collection)); assertTrue(collection.hasProperty(Prov.generatedAtTime)); assertTrue(collection.hasProperty(RegistryVocab.tag, "tag1")); assertTrue(collection.hasProperty(Prov.wasDerivedFrom)); List<RDFNode> members = model.listObjectsOfProperty(collection, Prov.hadMember).toList(); assertTrue( members.contains( model.getResource(ROOT_REGISTER + "reg3/_red:2") ) ); assertTrue( members.contains( model.getResource(ROOT_REGISTER + "reg3/_blue:2") ) ); assertEquals(2, members.size()); } /** * Test export to CSV, assumes a particular state for reg3 so has * be run after tagging test */ private void doTestCSVOut() { ClientResponse response = getResponse(BASE_URL + "reg3?_view=with_metadata", "text/csv"); assertEquals(200, response.getStatus()); assertEquals( FileManager.get().readWholeFileAsUTF8("test/csv/reg3.csv"), response.getEntity(String.class).replace("\r", "")); response = getResponse(BASE_URL + "reg3/red?_view=with_metadata", "text/csv"); assertEquals(200, response.getStatus()); assertEquals( FileManager.get().readWholeFileAsUTF8("test/csv/reg3-red.csv"), response.getEntity(String.class).replace("\r", "")); response = getResponse(BASE_URL + "reg3/red", "text/csv"); assertEquals(200, response.getStatus()); assertEquals( FileManager.get().readWholeFileAsUTF8("test/csv/reg3-red-no-metadata.csv"), response.getEntity(String.class).replace("\r", "")); } /** * Check support for graph entities */ private void doGraphEntityTest() { ClientResponse response; Model m; response = invoke("PUT", "test/ont1.ttl", BASE_URL + "reg1/ont?graph"); assertEquals(201, response.getStatus()); m = getModelResponse(BASE_URL + "reg1/ont"); assertTrue( hasTerm(m, "A") ); assertTrue( hasTerm(m, "a") ); assertTrue( hasTerm(m, "p") ); assertEquals(204, invoke("PUT", "test/ont1-modified.ttl", BASE_URL + "reg1/ont?graph").getStatus()); m = getModelResponse(BASE_URL + "reg1/ont"); assertFalse( hasTerm(m, "A") ); assertFalse( hasTerm(m, "a") ); assertTrue( hasTerm(m, "D") ); assertTrue( hasTerm(m, "d") ); } /** * Check support for attaching graphs to items */ private void doGraphAnnotationTest() { String annotationGraph = BASE_URL + "reg1/_red?annotation=test"; assertEquals(404, getResponse(annotationGraph).getStatus()); ClientResponse response = invoke("PUT", "test/ont1.ttl", annotationGraph); assertEquals(201, response.getStatus()); Model m = getModelResponse(annotationGraph); assertNotNull(m); assertTrue( hasTerm(m, "A") ); assertTrue( hasTerm(m, "a") ); assertTrue( hasTerm(m, "p") ); m = getModelResponse(BASE_URL + "reg1/_red"); Resource item = m.getResource(ROOT_REGISTER + "reg1/_red"); assertTrue( item.hasProperty(RegistryVocab.annotation) ); assertTrue( item.hasProperty(RegistryVocab.annotation, m.getResource(ROOT_REGISTER + "reg1/_red?annotation=test")) ); } private boolean hasTerm(Model m, String term) { Resource r = m.getResource(ROOT_REGISTER + "reg1/ont#" + term); return r.hasProperty(RDF.type); } /** * Typed template lookup and change notification */ private void doTypedTemplateTest() { String stt_reg = BASE_URL + "system/typed-templates"; assertEquals(201, postFileStatus("test/typed-templates-reg.ttl", BASE_URL + "system")); assertEquals(201, postFileStatus("test/concept-scheme-typed-template.ttl", stt_reg)); assertEquals(204, post(stt_reg + "/_concept-scheme?update&status=stable").getStatus()); LibReg reg = new LibReg(); Resource test = ModelFactory.createDefaultModel().createResource("http://example.com/test") .addProperty(RDF.type, SKOS.ConceptScheme) .addProperty(RDF.type, SKOS.Collection); assertEquals("concept-scheme-render.vm", reg.templateFor(test) ); assertEquals(201, postFileStatus("test/collection-typed-template.ttl", stt_reg)); assertEquals(204, post(stt_reg + "/_collection?update&status=stable").getStatus()); assertEquals("collection-render.vm", reg.templateFor(test) ); } /** * Test case for bnode duplication on registry reconstruction */ private void doBNodeDuplicationBugTest() { assertEquals(201, postFileStatus("test/rbd.ttl", BASE_URL + "?batch-managed&status=stable")); Model m = getModelResponse(BASE_URL + "RiverBasinDistrict"); Resource reg = m.getResource("http://location.data.gov.uk/RiverBasinDistrict"); int count = reg.listProperties(DCTerms.rights).toList().size(); assertEquals(1, count); int version = RDFUtil.getIntValue(reg, OWL.versionInfo, -1); // Add to the register assertEquals(201, postFileStatus("test/red.ttl", BASE_URL + "RiverBasinDistrict")); m = getModelResponse(BASE_URL + "RiverBasinDistrict"); reg = m.getResource("http://location.data.gov.uk/RiverBasinDistrict"); assertEquals(version + 1, RDFUtil.getIntValue(reg, OWL.versionInfo, -1)); } /** * Test case for real delete, assumes reg1 and reg1/red exist before hand */ private void doTestRealDelete() { assertEquals(200, getResponse(REG1).getStatus()); assertEquals(200, getResponse(REG1 + "/red").getStatus()); assertEquals(204, post(REG1 + "?real_delete").getStatus()); assertEquals(404, getResponse(REG1).getStatus()); assertEquals(404, getResponse(REG1 + "/red").getStatus()); } /** * Export Reg1 for later import test */ private void doExport() { ClientResponse response = getResponse(REG1, "application/n-quads"); assertEquals(200, response.getStatus()); // TODO working here // InputStream response.getEntity(InputStream.class); } /** * Reimport the earlier export and test REG1 is back */ private void doImportTest() { // TODO working here } /** * Basic edit test cases */ private void doEditTest() { final String REGE = BASE_URL + "rege"; assertEquals(201, postFileStatus("test/edit/rege.ttl", BASE_URL)); assertEquals(204, postFileStatus("test/edit/edit1.ttl", REGE + "?edit")); checkModelResponse(REGE + "?_view=with_metadata&status=any", ROOT_REGISTER + "rege", "test/edit/expected1.ttl", DCTerms.dateSubmitted, DCTerms.modified); assertEquals(204, postFileStatus("test/edit/edit2.ttl", REGE + "?edit")); checkModelResponse(REGE + "?_view=with_metadata&status=any", ROOT_REGISTER + "rege", "test/edit/expected2.ttl", DCTerms.dateSubmitted, DCTerms.modified); assertEquals(204, postFileStatus("test/edit/edit3.csv", REGE + "?edit", "text/csv")); checkModelResponse(REGE + "?_view=with_metadata&status=any", ROOT_REGISTER + "rege", "test/edit/expected3.ttl", DCTerms.dateSubmitted, DCTerms.modified); } private void checkPageResponse(Model m, String nextpage, int length) { ResIterator ri = m.listSubjectsWithProperty(RDF.type, Ldbp.Page); assertTrue(ri.hasNext()); Resource page = ri.next(); assertFalse(ri.hasNext()); if (nextpage != null) { Resource next = page.getPropertyResourceValue(Ldbp.nextPage); assertNotNull(next); assertTrue(next.getURI().contains("_page=" + nextpage)); } else { assertFalse(page.hasProperty(Ldbp.nextPage)); } Resource reg = page.getPropertyResourceValue(Ldbp.pageOf); int count = 0; for (StmtIterator si = reg.listProperties(RDFS.member); si.hasNext();) { si.next(); count++; } assertEquals(length, count); List<RDFNode> items = page.getPropertyResourceValue(API.items).as(RDFList.class).asJavaList(); assertEquals(length, items.size()); } private void makeRegister(int length) { Model m = ModelFactory.createDefaultModel(); m.createResource("regL") .addProperty(RDF.type, RegistryVocab.Register) .addProperty(RDFS.label, "Long register"); assertEquals(201, postModel(m, BASE_URL).getStatus()); for (int i = 0; i < length; i++) { m = ModelFactory.createDefaultModel(); m.createResource("item" +i) .addProperty(RDFS.label, "item" + i) .addProperty(RDF.type, SKOS.Concept); assertEquals(201, postModel(m, REGL_URL).getStatus()); } } private void doTestPayloadRead(String csv, String expected) throws IOException { InputStream ins = new FileInputStream(csv); String baseURI = "http://location.data.gov.uk/reg3/"; Model payload = CSVPayloadRead.readCSVStream(ins, baseURI); assertTrue( payload.isIsomorphicWith( RDFDataMgr.loadModel(expected) ) ); } }
src/test/java/com/epimorphics/registry/webapi/TestAPI.java
/****************************************************************** * File: TestAPI.java * Created by: Dave Reynolds * Created on: 1 Feb 2013 * * (c) Copyright 2013, Epimorphics 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.epimorphics.registry.webapi; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import org.apache.jena.riot.RDFDataMgr; import org.junit.Test; import com.epimorphics.rdfutil.RDFUtil; import com.epimorphics.registry.csv.CSVPayloadRead; import com.epimorphics.registry.util.JSONLDSupport; import com.epimorphics.registry.util.Prefixes; import com.epimorphics.registry.vocab.Ldbp; import com.epimorphics.registry.vocab.Prov; import com.epimorphics.registry.vocab.RegistryVocab; import com.epimorphics.registry.vocab.Version; import com.epimorphics.util.TestUtil; import com.epimorphics.vocabs.API; import com.epimorphics.vocabs.SKOS; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFList; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.util.FileManager; import com.hp.hpl.jena.vocabulary.DCTerms; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.sun.jersey.api.client.ClientResponse; /** * Test harness for testing access to the API - launches a registry using an * embedded tomcat and a memory-backed store then talks to the API using http. * * @author <a href="mailto:[email protected]">Dave Reynolds</a> */ public class TestAPI extends TomcatTestBase { static final String EXT_BLACK = "http://example.com/colours/black"; static final String REG1 = BASE_URL + "reg1"; static final String REG1_URI = ROOT_REGISTER + "reg1"; static final String REG1_ITEM = ROOT_REGISTER + "_reg1"; static final String REGL_URL = BASE_URL + "regL"; String getWebappRoot() { return "src/test/webapp"; } @Test public void testBasics() throws IOException { // Create reg1 doRegisterRegistrationTests(); // Puts red in reg1/red doItemRegistrationTests(); // Adds external resource reg1/black doExternalRegistrationTests(); // Updates red to be called red1 String versionSuffix = doUpdateTest(); // Patches red to be called red1b Calendar checkpoint = Calendar.getInstance(); doPatchTest(); // Check we can still get back the old version of reg from before the last patch checkModelResponse(REG1 + "/_red" + versionSuffix, ROOT_REGISTER + "reg1/red", "test/expected/red1.ttl"); // Adds reg1/blue and tests views with different status setting and metadata doRegisterListingTest(); // Update tests on register itself, ISSUE-27, changes register name so so after listing test doRegUpdateTest(); // Check for case of invalid patch requests doInvalidUpdateTest(); // Create a large register regL and checks paged views and retrieving early version of register doPagingTest(); doRegisterVersionRetrievalTest(); // Register timestamp view - predates changing red1 to red1b and adding blue checkRegisterList( getModelResponse(REG1 + "?status=any&_versionAt=" + checkpoint.getTimeInMillis()), REG1_URI, "red1", "black"); // List versions doListVersionsTest(); // Check some status transitions doStatusTransitionsTest(); // Checking of legal relative URIs in registration payload assertEquals(400, postFileStatus("test/bad-green.ttl", REG1)); // Bulk registration - creates a collection and a scheme register from skos collection and concept scheme doBulkRegistrationTest(); // Check patching of register metadata - tests on /collection created in prior step doRegisterMetadataPatchTest(); // Test deletions using the /collection register doDeletionTest(); // Test validation operation doValidationTest(); // List a register - was a bug here Model m = getModelResponse(BASE_URL + "?status=any"); checkRegisterList(m, RDFS.member, ROOT_REGISTER, "system register", "register 1", "A test collection", "Long register", "A nice test collection", "A test concept scheme") ; // Delegation tests doForwardingTest(); doDelegationTest(); // Check prefix system register doPrefixTests(); // Check we can register and patch using jsonld syntax payloads doJsonldTests(); // Check registration of entity and item information together doRegisterWithMetadataTest(); // Check patching metadata annotations doMetadataPatchTest(); // Check upload of multiple items in a single payload doMultiPostTest(); // Test reservation of entries using bNode entity addresses doReservationTest(); // Check that an explicit reg:register in payload doesn't get through doBlockInternalPropertiesTest(); // Check validation of entries in a register with validation constraints doValidationChecks(); // Check use of numeric literals as notation values doCheckNumericNotations(); // Check tagging doTaggingTest(); // Export doTestExport(); // Graph entities and annotations doGraphEntityTest(); doGraphAnnotationTest(); // Typed template lookup and change notification doTypedTemplateTest(); // Bug tests doBNodeDuplicationBugTest(); doSkosLabelTest(); // CSV parsing, needs runtime registry to access prefixes register doTestPayloadRead("test/csv/reg3-red.csv", "test/csv/reg3-red.ttl"); doTestPayloadRead("test/csv/reg3-red-no-metadata.csv", "test/csv/reg3-red-no-metadata.ttl"); doTestPayloadRead("test/edit/edit3.csv", "test/csv/edit3.ttl"); // Edit doEditTest(); // Deletion doTestRealDelete(); // System.out.println("Store dump"); // ServiceConfig.get().getServiceAs("basestore", Store.class).asDataset().getDefaultModel().write(System.out, "Turtle"); } private void doSkosLabelTest() { assertEquals(201, postFileStatus("test/bugs/brown-preflabel.ttl", REG1)); checkModelResponse(REG1 + "/brown", ROOT_REGISTER + "reg1/brown", "test/expected/brown.ttl"); checkModelResponse(REG1 + "/brown?_view=with_metadata", ROOT_REGISTER + "reg1/brown", "test/expected/brown_metadata.ttl"); } private void doInvalidUpdateTest() { assertEquals(400, invoke("PATCH", "test/blue-patch.ttl", BASE_URL).getStatus()); assertEquals(400, invoke("PATCH", "test/blue-patch.ttl", REG1).getStatus()); // Can't drop label assertEquals(400, invoke("PUT", "test/red-bad-update-label.ttl", REG1 + "/red").getStatus()); // Can't remove type assertEquals(400, invoke("PUT", "test/red-bad-update-type.ttl", REG1 + "/red").getStatus()); } private void doRegisterRegistrationTests() { // Leaves register reg1 set up ClientResponse response = postFile("test/reg1.ttl", BASE_URL, "text/turtle"); assertEquals("Register a register", 201, response.getStatus()); assertEquals(REG1_ITEM, response.getLocation().toString()); assertEquals("Register in non-existant location", 404, postFileStatus("test/reg1.ttl", BASE_URL+"foo")); assertEquals("Register the same again", 403, postFileStatus("test/reg1.ttl", BASE_URL)); } // Assumes reg1 has been created // Adds an item (reg1/red) and checks it all looks OK // Leaves reg1/red in plce private void doItemRegistrationTests() { assertEquals(201, postFileStatus("test/red.ttl", REG1)); checkModelResponse(REG1 + "/red", ROOT_REGISTER + "reg1/red", "test/expected/red.ttl"); Model m = getModelResponse(REG1 + "/red?_view=with_metadata"); checkModelResponse(m, ROOT_REGISTER + "reg1/_red", "test/expected/red_item.ttl"); checkModelResponse(m, ROOT_REGISTER + "reg1/red", "test/expected/red.ttl"); checkEntity(m, ROOT_REGISTER + "reg1/_red", ROOT_REGISTER + "reg1/red"); assertEquals(404, getResponse(REG1 + "/notred").getStatus()); assertEquals(404, getResponse(REG1 + "/notred/").getStatus()); m = getModelResponse(REG1 + "/_red"); checkModelResponse(m, ROOT_REGISTER + "reg1/_red", "test/expected/red_item.ttl"); checkModelResponse(m, ROOT_REGISTER + "reg1/red", "test/expected/red.ttl"); checkEntity(m, ROOT_REGISTER + "reg1/_red", ROOT_REGISTER + "reg1/red"); } // Assumes reg1 has been created // Adds an external entity and check it can be retrieved private void doExternalRegistrationTests() { // External (not managed) entities assertEquals(201, postFileStatus("test/absolute-black.ttl", REG1)); Model m = checkModelResponse(REG1 + "/_black", EXT_BLACK, "test/expected/absolute-black.ttl"); checkEntity(m, ROOT_REGISTER + "reg1/_black", EXT_BLACK); // Entity retrieval checkModelResponse(REG1 + "?entity=" + EXT_BLACK, EXT_BLACK, "test/expected/absolute-black.ttl"); checkModelResponse(BASE_URL + "?entity=" + EXT_BLACK, EXT_BLACK, "test/expected/absolute-black.ttl"); m = getModelResponse(BASE_URL, "entity", EXT_BLACK, "_view", "with_metadata"); checkModelResponse(m, EXT_BLACK, "test/expected/absolute-black.ttl"); checkModelResponse(m, ROOT_REGISTER + "reg1/_black", "test/expected/absolute-black.ttl"); } // Assumes reg1 and reg1/red exists // Updates name of red to red1 // Returns the version number of the new version private String doUpdateTest() { // Updates, change properties on red ClientResponse response = invoke("PUT", "test/red1.ttl", REG1 + "/red"); assertEquals(204, response.getStatus()); String red1Version = response.getLocation().toString(); assertTrue(red1Version.startsWith(ROOT_REGISTER + "reg1/_red:")); String versionSuffix = red1Version.substring( red1Version.length()-2 ); checkModelResponse(REG1 + "/red", ROOT_REGISTER + "reg1/red", "test/expected/red1.ttl"); return versionSuffix; } private void doRegUpdateTest() { String reg1meta = REG1 + "?non-member-properties"; Model m = getModelResponse(reg1meta); Resource reg1 = m.getResource(REG1_URI); long version = RDFUtil.getLongValue(reg1, OWL.versionInfo); ClientResponse response = invoke("PUT", "test/reg1-put.ttl", reg1meta); assertEquals(204, response.getStatus()); m = getModelResponse(reg1meta); reg1 = m.getResource(REG1_URI); long newversion = RDFUtil.getLongValue(reg1, OWL.versionInfo); assertEquals(version + 1, newversion); assertEquals("Example register 1 - put update", RDFUtil.getStringValue(reg1, DCTerms.description)); response = invoke("PATCH", "test/reg1-patch.ttl", reg1meta); assertEquals(204, response.getStatus()); m = getModelResponse(reg1meta); reg1 = m.getResource(REG1_URI); newversion = RDFUtil.getLongValue(reg1, OWL.versionInfo); assertEquals(version + 2, newversion); assertEquals("Example register 1 - patch update", RDFUtil.getStringValue(reg1, DCTerms.description)); // Verify access to earlier version of the RegisterItem containing the register - ISSUE-26 Resource current = getModelResponse(BASE_URL + "_reg1").getResource(REG1_URI); assertEquals(version + 2, RDFUtil.getLongValue(current, OWL.versionInfo).longValue()); assertEquals("Example register 1 - patch update", RDFUtil.getStringValue(current, DCTerms.description)); Resource orig = getModelResponse(BASE_URL + "_reg1:1").getResource(REG1_URI); assertEquals(1, RDFUtil.getLongValue(orig, OWL.versionInfo).longValue()); assertEquals("Example register 1", RDFUtil.getStringValue(orig, DCTerms.description)); // Safe against versioninfo being in payload response = invoke("PUT", "test/reg1-put2.ttl", reg1meta); m = getModelResponse(reg1meta); reg1 = m.getResource(REG1_URI); newversion = RDFUtil.getLongValue(reg1, OWL.versionInfo); assertEquals(version + 3, newversion); assertEquals("Example register 1 - put update2", RDFUtil.getStringValue(reg1, DCTerms.description)); // Try to change RDF type // assertEquals(400, invoke("PUT", "test/reg1-bad-put1.ttl", reg1meta).getStatus()); // Multiple roots in change file assertEquals(400, invoke("PUT", "test/reg1-bad-put2.ttl", reg1meta).getStatus()); } // Assumes reg1/red exists // Patch its name to red1b private void doPatchTest() { ClientResponse response = invoke("PATCH", "test/red1b.ttl", REG1 + "/red"); assertEquals(204, response.getStatus()); checkModelResponse(REG1 + "/red", ROOT_REGISTER + "reg1/red", "test/expected/red1b.ttl"); } // Assumes reg1 exists and already has red (now called red1b) and black in it // Tests listing different status filters and basic metadata access // Leaves register with blue as well, red as "stable" and black as "experimental" private void doRegisterListingTest() { // Register read checkModelResponse(REG1, ROOT_REGISTER + "reg1", "test/expected/reg1-empty.ttl"); assertEquals(204, post(REG1 + "/_red?update&status=stable").getStatus()); assertEquals(204, post(REG1 + "/_black?update&status=experimental").getStatus()); checkModelResponse(REG1, ROOT_REGISTER + "reg1", "test/expected/reg1_red_black.ttl"); // Register listing assertEquals(201, postFileStatus("test/blue.ttl", REG1)); Model m = getModelResponse(REG1 + "?non-member-properties"); checkModelResponse(m, REG1_URI, "test/expected/reg1-empty.ttl"); checkRegisterList( getModelResponse(REG1 + "?status=stable"), REG1_URI, "red1b"); checkRegisterList( getModelResponse(REG1 + "?status=experimental"), REG1_URI, "black"); checkRegisterList( getModelResponse(REG1 + "?status=valid"), REG1_URI, "red1b", "black"); checkRegisterList( getModelResponse(REG1 + "?status=accepted"), REG1_URI, "red1b", "black"); checkRegisterList( getModelResponse(REG1 + "?status=notaccepted"), REG1_URI, "blue"); checkRegisterList( getModelResponse(REG1 + "?status=any"), REG1_URI, "red1b", "black", "blue"); // Register metadata view m = getModelResponse(REG1 + "?non-member-properties&_view=with_metadata"); checkModelResponse(m, REG1_URI, "test/expected/reg1_nmp_metadata.ttl"); checkModelResponse(m, REG1_ITEM, "test/expected/reg1_nmp_metadata.ttl"); m = getModelResponse(REG1 + "?_view=with_metadata"); checkModelResponse(m, REG1_URI, "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, REG1_URI+"/red", "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, REG1_URI+"/_red", "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, EXT_BLACK, "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, REG1_URI+"/_black", "test/expected/reg1_red_black_metadata.ttl"); checkModelResponse(m, REG1_ITEM, "test/expected/reg1_nmp_metadata.ttl"); } private void doPagingTest() { // Register paging makeRegister(60); checkPageResponse(getModelResponse(REGL_URL + "?firstPage&status=notaccepted"), "1", 50); checkPageResponse(getModelResponse(REGL_URL + "?_page=1&status=notaccepted"), null, 10); } private void doRegisterVersionRetrievalTest() { // Register version view Model m = getModelResponse(REGL_URL + ":3?status=notaccepted"); checkModelResponse(m, ROOT_REGISTER + "regL", "test/expected/regL-two-entries.ttl"); checkModelResponse(m, ROOT_REGISTER + "regL/item0", "test/expected/regL-two-entries.ttl"); checkModelResponse(m, ROOT_REGISTER + "regL/item1", "test/expected/regL-two-entries.ttl"); } // Leaves new registers /collection and /scheme private void doBulkRegistrationTest() { assertEquals("Not a bulk type", 400, postFileStatus("test/blue.ttl", BASE_URL + "?batch-managed")); // assertEquals(201, postFileStatus("test/bulk-skos-collection.ttl", BASE_URL + "?batch-managed")); ClientResponse response = postFile("test/bulk-skos-collection.ttl", BASE_URL + "?batch-managed"); TestAPIDebug.debugStatus(response); Model m = getModelResponse(BASE_URL + "collection?status=any"); checkRegisterList( m, ROOT_REGISTER + "collection", "item 1", "item 2", "item 3"); assertEquals(201, postFileStatus("test/bulk-skos-scheme.ttl", BASE_URL + "?batch-managed")); m = getModelResponse(BASE_URL + "scheme?status=any"); TestUtil.testArray( m.listSubjectsWithProperty(SKOS.inScheme, m.getResource(ROOT_REGISTER + "scheme")).toList(), new Resource[]{ m.createResource(ROOT_REGISTER + "scheme/item1"), m.createResource(ROOT_REGISTER + "scheme/item2"), m.createResource(ROOT_REGISTER + "scheme/item3") } ); assertEquals(201, postFileStatus("test/bulk-skos-collection.ttl", BASE_URL + "collection?batch-managed&status=stable")); m = getModelResponse(BASE_URL + "collection/collection?status=stable"); checkRegisterList( m, ROOT_REGISTER + "collection/collection", "item 1", "item 2", "item 3"); assertEquals(201, postFileStatus("test/bulk-skos-collection-of-scheme.ttl", BASE_URL + "?batch-referenced")); m = getModelResponse(BASE_URL + "scheme-collection?status=any"); checkRegisterList( m, ROOT_REGISTER + "scheme-collection", "item 1", "item 2"); assertEquals(400, postFileStatus("test/bulk-skos-collection-spurious.ttl", BASE_URL + "?batch-managed") ); } // Assumes /collection exists from bulk registration test private void doRegisterMetadataPatchTest() { // Updating register metadata assertEquals(400, invoke("PATCH", "test/register-update.ttl", BASE_URL + "collection").getStatus()); assertEquals(204, invoke("PATCH", "test/register-update.ttl", BASE_URL + "collection?non-member-properties").getStatus()); Model m = getModelResponse(BASE_URL + "collection?non-member-properties"); checkModelResponse(m, ROOT_REGISTER + "collection", "test/expected/updated-collection-register.ttl"); } // Assumes /colleciton exists from bulk registration tests // Test deletion of items from register private void doDeletionTest() { long timestamp = System.currentTimeMillis(); assertEquals(204, invoke("DELETE", null, BASE_URL + "collection/collection/item1").getStatus()); checkRegisterList( getModelResponse(BASE_URL + "collection/collection?status=stable"), ROOT_REGISTER + "collection/collection", "item 2", "item 3"); assertEquals(204, invoke("DELETE", null, BASE_URL + "collection/collection/_item2").getStatus()); checkRegisterList( getModelResponse(BASE_URL + "collection/collection?status=stable"), ROOT_REGISTER + "collection/collection", "item 3"); // Reconstruct register pre-delete checkRegisterList( getModelResponse(BASE_URL + "collection/collection?status=stable&_versionAt=" + timestamp), ROOT_REGISTER + "collection/collection", "item 1", "item 2", "item 3"); Resource collection = ResourceFactory.createResource("http://location.data.gov.uk/collection"); Resource collectionCollection = ResourceFactory.createResource("http://location.data.gov.uk/collection/collection"); assertTrue( getModelResponse(BASE_URL + "collection?status=stable").contains(collection, SKOS.member, collectionCollection)); assertEquals(204, invoke("DELETE", null, BASE_URL + "collection/collection").getStatus()); assertFalse( getModelResponse(BASE_URL + "collection?status=stable").contains(collection, SKOS.member, collectionCollection)); checkRegisterList( getModelResponse(BASE_URL + "collection/collection?status=stable"), ROOT_REGISTER + "collection/collection"); } private void doValidationTest() { assertEquals(400, postFileStatus("test/validation-request1.txt", BASE_URL + "?validate" )); assertEquals(204, post(BASE_URL + "collection?update&status=stable&force").getStatus()); assertEquals(200, postFileStatus("test/validation-request1.txt", BASE_URL + "?validate" )); assertEquals(400, postFileStatus("test/validation-request2.txt", BASE_URL + "?validate" )); assertEquals(200, post(BASE_URL + "?validate=http://location.data.gov.uk/collection/item1").getStatus()); assertEquals(404, post(BASE_URL + "foo?validate=http://location.data.gov.uk/collection/item1").getStatus()); assertEquals(400, post(BASE_URL + "?validate=http://location.data.gov.uk/collection/item1&validate=http://location.data.gov.uk/collection/item8").getStatus()); ClientResponse response = post(BASE_URL + "?validate=http://location.data.gov.uk/collection/item1"); assertEquals(200, response.getStatus()); assertEquals("http://location.data.gov.uk/collection/item1 is http://location.data.gov.uk/collection/_item1", response.getEntity(String.class).trim()); } // Assumes reg1/red exists and has go through update (to red1) and patch (to red1b) and status change private void doListVersionsTest() { Model m = getModelResponse(BASE_URL + "reg1/_red?_view=version_list"); assertTrue( m.listSubjectsWithProperty(DCTerms.isVersionOf, m.getResource(ROOT_REGISTER + "reg1/_red")).toList().size() >= 4); assertTrue( m.contains(m.getResource(ROOT_REGISTER + "reg1/_red:3"), DCTerms.replaces, m.getResource(ROOT_REGISTER + "reg1/_red:2")) ); assertTrue( m.contains(m.getResource(ROOT_REGISTER + "reg1/_red"), Version.currentVersion, m.getResource(ROOT_REGISTER + "reg1/_red:4")) ); } // Assumes reg1/blue exists, leaves it in "invalid" status private void doStatusTransitionsTest() { assertEquals(403, post(REG1 + "/_blue?update&status=retired").getStatus()); assertEquals(403, post(REG1 + "/_blue?update&status=superseded").getStatus()); assertEquals(204, post(REG1 + "/_blue?update&status=experimental").getStatus()); assertEquals(204, post(REG1 + "/_blue?update&status=stable").getStatus()); assertEquals(403, post(REG1 + "/_blue?update&status=experimental").getStatus()); assertEquals(403, post(REG1 + "/_blue?update&status=submitted").getStatus()); assertEquals(204, post(REG1 + "/_blue?update&status=superseded").getStatus()); assertEquals(204, post(REG1 + "/_blue?update&status=invalid").getStatus()); } // Set up a namespace forward to EA data and checks can access it // Relies on the EA service being up :) private void doForwardingTest() { assertEquals(201, postFileStatus("test/bw-forward.ttl", REG1)); assertEquals(404, getResponse(REG1 + "/eabw/ukc2102-03600").getStatus()); assertEquals(204, post(REG1 + "/_eabw?update&status=stable").getStatus()); assertEquals(200, getResponse(REG1 + "/eabw/ukc2102-03600").getStatus()); Model m = getModelResponse(REG1 + "/eabw/ukc2102-03600"); Resource bw = m.getResource("http://environment.data.gov.uk/id/bathing-water/ukc2102-03600"); assertEquals("Spittal", RDFUtil.getStringValue(bw, SKOS.prefLabel)); // convert forwarding to proxying, will only actually function if nginx is up and test doesn't require that assertEquals(204, invoke("PATCH", "test/bw-proxy-patch.ttl", REG1 + "/eabw").getStatus()); String proxyConfig = FileManager.get().readWholeFileAsUTF8("/var/opt/ldregistry/proxy-registry.conf"); assertTrue(proxyConfig.contains("location /reg1/eabw")); assertTrue(proxyConfig.contains("proxy_pass http://environment.data.gov.uk/doc/bathing-water/")); // Switch batch to forwarding mode to check switching off proxy works assertEquals(204, invoke("PATCH", "test/bw-forward-patch.ttl", REG1 + "/eabw").getStatus()); proxyConfig = FileManager.get().readWholeFileAsUTF8("/var/opt/ldregistry/proxy-registry.conf"); assertFalse(proxyConfig.contains("location /reg1/eabw")); assertEquals(200, getResponse(REG1 + "/eabw/ukc2102-03600").getStatus()); } // Set up a delegated register for the EA bathingwaters URI set and checks register listing // Relies on the EA service being up :) private void doDelegationTest() { // Check read on delegated register assertEquals(201, postFileStatus("test/bw-delegated.ttl", REG1)); assertEquals(204, post(REG1 + "/_bathingWaters?update&status=stable").getStatus()); Model m = getModelResponse(REG1 + "/bathingWaters?firstPage"); Resource register = m.getResource(REG1_URI + "/bathingWaters"); List<Resource> members = RDFUtil.allResourceValues(register, RDFS.member); assertTrue(members.size() > 20); for (Resource member : members) { assertTrue(member.hasProperty(RDFS.label)); assertTrue(member.hasProperty(RDF.type)); } m = getModelResponse(REG1 + "?entity=http://environment.data.gov.uk/id/bathing-water/ukc2102-03600"); Resource bw = m.getResource("http://environment.data.gov.uk/id/bathing-water/ukc2102-03600"); assertEquals("Spittal", RDFUtil.getStringValue(bw, SKOS.prefLabel)); } private void doPrefixTests() { Map<String, String> pm = Prefixes.get().getNsPrefixMap(); assertTrue(pm.containsKey("rdf")); assertEquals(RDF.getURI(), pm.get("rdf")); assertTrue(pm.containsKey("reg")); assertEquals(RegistryVocab.getURI(), pm.get("reg")); assertEquals(200, getResponse(BASE_URL + "system").getStatus()); assertEquals(200, getResponse(BASE_URL + "system/prefixes").getStatus()); assertEquals(200, getResponse(BASE_URL + "system/prefixes").getStatus()); // Prefix update assertEquals(201, postFileStatus("test/prefix-test-xyz.ttl", BASE_URL + "system/prefixes")); // Update of prefixes depends on the background message thread, this is fragile to test for int trycount = 0; boolean passed = false; while (trycount < 10 && !passed) { trycount++; pm = Prefixes.get().getNsPrefixMap(); if (pm.containsKey("xyz")) { assertTrue(pm.containsKey("xyz")); assertEquals("http://example.com/xyz", pm.get("xyz")); passed = true; } else { try { Thread.sleep(50); } catch (InterruptedException e) {}; } } } // Assumes /reg1 exists all earlier tests run (so has at least blue in it) // Leaves it with /reg1/purple and with reg1 dct:description changed private void doJsonldTests() throws IOException { // Assumes reg1 set up assertEquals(201, postFileStatus("test/purple-testcase.jsonld", REG1, JSONLDSupport.MIME_JSONLD)); Model m = getModelResponse(BASE_URL + "reg1/purple"); Resource r = m.getResource(ROOT_REGISTER + "reg1/purple"); assertEquals("purple", RDFUtil.getStringValue(r, RDFS.label)); assertEquals("I am purple but described using JSON-LD, good luck with that", RDFUtil.getStringValue(r, DCTerms.description)); ClientResponse response = getResponse(BASE_URL + "reg1/blue", JSONLDSupport.MIME_JSONLD); assertEquals(200, response.getStatus()); InputStream is = response.getEntityInputStream(); m = JSONLDSupport.readModel(RequestProcessor.DUMMY_BASE_URI, is); is.close(); r = m.getResource(ROOT_REGISTER + "reg1/blue"); assertEquals("blue", RDFUtil.getStringValue(r, RDFS.label)); // JSON-LD patch assertEquals(204, invoke("PATCH", "test/reg1-patch.jsonld", REG1 + "?non-member-properties", "application/ld+json").getStatus()); m = getModelResponse(REG1 + "?non-member-properties"); assertEquals("Updated register 1", RDFUtil.getStringValue(m.getResource(REG1_URI), DCTerms.description)); } // Register two entries for "eight", both with explicit RegsiterItems as well as the associated entity // First version has no URI and gives notation, second uses relative URI to infer notation // ISSUE-38 private void doRegisterWithMetadataTest() { // Testing update of item + entity - ISSUE-38 ClientResponse response = postFile("test/jmt/number-eight-post-notation.ttl", REG1); assertEquals(201, response.getStatus()); String itemURI = ROOT_REGISTER + "reg1/_eight"; assertEquals(itemURI, response.getLocation().toASCIIString()); checkRegisteredMetadata( getModelResponse(REG1+"/eight?_view=with_metadata"), "eight" ); response = postFile("test/jmt/number-eightb-post-relative.ttl", REG1); assertEquals(201, response.getStatus()); itemURI = ROOT_REGISTER + "reg1/_eightb"; assertEquals(itemURI, response.getLocation().toASCIIString()); checkRegisteredMetadata( getModelResponse(REG1+"/_eightb"), "eightb" ); } private void checkRegisteredMetadata(Model m, String notation) { String itemURI = ROOT_REGISTER + "reg1/_" + notation; Resource item = m.getResource(itemURI); assertEquals(notation, RDFUtil.getStringValue(item, RegistryVocab.notation)); assertEquals("http://ukgovld-registry.dnsalias.net/def/numbers/eight", item.getPropertyResourceValue(RegistryVocab.definition) .getPropertyResourceValue(RegistryVocab.entity) .getURI()); assertEquals(RegistryVocab.statusStable, item.getPropertyResourceValue(RegistryVocab.status)); Property attributedTo = m.getProperty("http://www.w3.org/ns/prov#wasAttributedTo"); assertEquals("http://jeremytandy.me.uk/self#id", item.getPropertyResourceValue(attributedTo).getURI()); } // Test patching a RegisterItem with external metadata // ISSUE-39 private void doMetadataPatchTest() { assertEquals(201, postFileStatus("test/jmt/number-nine-post.ttl", REG1)); Property attributedTo = ResourceFactory.createProperty("http://www.w3.org/ns/prov#wasAttributedTo"); Resource item = getModelResponse(REG1 + "/nine?_view=with_metadata").getResource(REG1_URI + "/_nine"); assertFalse(item.hasProperty(attributedTo)); assertEquals(204, invoke("PATCH", "test/jmt/number-nine-patch.ttl", REG1 + "/_nine").getStatus() ); item = getModelResponse(REG1 + "/nine?_view=with_metadata").getResource(REG1_URI + "/_nine"); assertEquals("http://jeremytandy.me.uk/self#id", item.getPropertyResourceValue(attributedTo).getURI()); } // Test upload of multiple register items at the same time private void doMultiPostTest() { List<String> before = getRegisterList(getModelResponse(REG1 + "?status=stable"), SKOS.member, REG1_URI); assertEquals(201, postFileStatus("test/jmt/number-eleven-twelve-post-rel.ttl", REG1)); List<String> after = getRegisterList(getModelResponse(REG1 + "?status=stable"), SKOS.member, REG1_URI); checkAdded(before, after, "eleven", "twelve"); assertEquals(201, postFileStatus("test/jmt/number-eleven-twelve-post-bnode.ttl", REG1)); List<String> after2 = getRegisterList(getModelResponse(REG1 + "?status=stable"), SKOS.member, REG1_URI); checkAdded(after, after2, "elevenb", "twelveb"); } private void checkAdded(List<String> before, List<String> after, String...additions) { assertTrue( after.containsAll(before) ); List<String> residual = new ArrayList<String>(after); residual.removeAll(before); TestUtil.testArray(residual, additions); } // Test reservation of entries using bNode entity addresses private void doReservationTest() { List<String> before = getRegisterList(getModelResponse(REG1), SKOS.member, REG1_URI); assertEquals(201, postFileStatus("test/jmt/number-six-reserved-post.ttl", REG1)); Model m = getModelResponse(REG1+"?status=any&_view=with_metadata"); validateReservedEntry(m, null, "reserved"); getModelResponse(REG1+"?status=any&firstPage"); // Fails if bNodes not skolemized getModelResponse(REG1+"?status=any"); // Fails if bNodes not skolemized assertEquals(204, invoke("PUT", "test/jmt/number-six-update.ttl", REG1+"/_six").getStatus()); m = getModelResponse(REG1+"?status=any&_view=with_metadata"); validateReservedEntry(m, "http://example.com/six", "six"); // Check that reserved item does not appear in normal listing List<String> after = getRegisterList(getModelResponse(REG1), SKOS.member, REG1_URI); assertTrue(after.containsAll(before) && before.containsAll(after)); // Check can't transition straight from reserved to stable assertEquals(403, post(REG1 + "/_six?update&status=stable").getStatus()); // Check that once accepted can no longer change the entity URI assertEquals(204, post(REG1 + "/_six?update&status=submitted").getStatus()); assertEquals(204, post(REG1 + "/_six?update&status=stable").getStatus()); assertEquals(400, invoke("PUT", "test/jmt/number-six-update2.ttl", REG1+"/_six").getStatus()); } private void validateReservedEntry(Model m, String entityURI, String label) { Resource reg1 = m.getResource(REG1_URI); Resource _six = m.getResource(REG1_URI + "/_six"); assertTrue(m.contains(_six, RegistryVocab.register, reg1)); Resource entity = _six.getPropertyResourceValue(RegistryVocab.definition).getPropertyResourceValue(RegistryVocab.entity); if (entityURI != null) { assertEquals(entityURI, entity.getURI()); } assertEquals(label, RDFUtil.getStringValue(entity, RDFS.label)); } // Check that an explicit reg:register in payload doesn't get through private void doBlockInternalPropertiesTest() { assertEquals(201, postFileStatus("test/jmt/number-fifteen-reserved-post.ttl", REG1)); Model m = getModelResponse(REG1 + "/_fifteen"); Resource r = m.getResource(REG1_URI + "/_fifteen"); TestUtil.testArray(RDFUtil.allResourceValues(r, RegistryVocab.register), new Resource[]{ m.getResource(REG1_URI)}); } // Check validation of entries in a register with validation constraints private void doValidationChecks() { assertEquals(201, postFileStatus("test/reg2.ttl", BASE_URL)); assertEquals(201, postFileStatus("test/reg2-entry-good.ttl", BASE_URL+"reg2")); checkRegisterList(getModelResponse(BASE_URL+"reg2?status=any"), ROOT_REGISTER + "reg2", "entry concept"); assertEquals(400, postFileStatus("test/reg2-entry-bad1.ttl", BASE_URL+"reg2")); assertEquals(400, postFileStatus("test/reg2-entry-bad2.ttl", BASE_URL+"reg2")); assertEquals(400, postFileStatus("test/reg2-entry-bad3.ttl", BASE_URL+"reg2")); assertEquals(400, postFileStatus("test/reg2-entry-bad4.ttl", BASE_URL+"reg2")); // Check that a multi-item upload is reject in its entirety assertEquals(400, postFileStatus("test/test-multi-item-validate.ttl", BASE_URL+"reg2")); Model m = getModelResponse(BASE_URL + "reg2?status=any"); List<String> members = getRegisterList(m, SKOS.member, ROOT_REGISTER + "reg2"); assertFalse(members.contains("concept1")); assertFalse(members.contains("concept2")); assertFalse(members.contains("concept3")); } /** * Check use of numeric literals as notation values, both that * they survive processing and that register page listing orders * numerically instead of lexically in that case. */ private void doCheckNumericNotations() { assertEquals(201, postFileStatus("test/codes.ttl", BASE_URL)); assertEquals(201, postFileStatus("test/jmt/runway-numeric.ttl", BASE_URL + "codes")); Model m = getModelResponse(BASE_URL + "codes?_view=with_metadata&firstPage"); Resource page = m.getResource(ROOT_REGISTER + "codes?_view=with_metadata&firstPage="); Resource items = page.getPropertyResourceValue(API.items); assertNotNull(items); List<RDFNode> itemList = items.as(RDFList.class).asJavaList(); int[] expected = new int[]{7, 8, 9, 15}; for (int i = 0; i < expected.length; i++) { int e = expected[i]; Resource item = itemList.get(i).asResource(); assertTrue(item.getURI().endsWith("/" + e)); Resource meta = m.getResource(ROOT_REGISTER + "codes/_" + e); Object value = meta.getProperty(RegistryVocab.notation).getObject().asLiteral().getValue(); assert(value instanceof Number); assertEquals(e, ((Number)value).intValue()); } } /** * Check that tagging a register works and the results can be retrieved */ private void doTaggingTest() { // Create a clean register state assertEquals(201, postFileStatus("test/reg3.ttl", BASE_URL)); assertEquals(201, postFileStatus("test/red.ttl", BASE_URL + "reg3")); assertEquals(201, postFileStatus("test/blue.ttl", BASE_URL + "reg3")); assertEquals(204, post(BASE_URL + "reg3/_red?update&status=stable").getStatus()); assertEquals(204, post(BASE_URL + "reg3/_blue?update&status=stable").getStatus()); // Tag it ClientResponse response = post(BASE_URL+"reg3?tag=tag1"); assertEquals(201, response.getStatus()); String uri = ROOT_REGISTER+"reg3?tag=tag1"; assertEquals(uri, response.getLocation().toString()); // Modify some entries response = invoke("PATCH", "test/red1b.ttl", BASE_URL + "reg3/red"); assertEquals(204, response.getStatus()); assertEquals(201, postFileStatus("test/green.ttl", BASE_URL + "reg3")); Model model = getModelResponse(BASE_URL + "reg3?tag=tag1"); Resource collection = model.getResource(uri); assertTrue(collection.hasProperty(RDF.type, Prov.Collection)); assertTrue(collection.hasProperty(Prov.generatedAtTime)); assertTrue(collection.hasProperty(RegistryVocab.tag, "tag1")); assertTrue(collection.hasProperty(Prov.wasDerivedFrom)); List<RDFNode> members = model.listObjectsOfProperty(collection, Prov.hadMember).toList(); assertTrue( members.contains( model.getResource(ROOT_REGISTER + "reg3/_red:2") ) ); assertTrue( members.contains( model.getResource(ROOT_REGISTER + "reg3/_blue:2") ) ); assertEquals(2, members.size()); } /** * Test export to CSV, assumes a particular state for reg3 so has * be run after tagging test */ private void doTestExport() { ClientResponse response = getResponse(BASE_URL + "reg3?_view=with_metadata", "text/csv"); assertEquals(200, response.getStatus()); assertEquals( FileManager.get().readWholeFileAsUTF8("test/csv/reg3.csv"), response.getEntity(String.class).replace("\r", "")); response = getResponse(BASE_URL + "reg3/red?_view=with_metadata", "text/csv"); assertEquals(200, response.getStatus()); assertEquals( FileManager.get().readWholeFileAsUTF8("test/csv/reg3-red.csv"), response.getEntity(String.class).replace("\r", "")); response = getResponse(BASE_URL + "reg3/red", "text/csv"); assertEquals(200, response.getStatus()); assertEquals( FileManager.get().readWholeFileAsUTF8("test/csv/reg3-red-no-metadata.csv"), response.getEntity(String.class).replace("\r", "")); } /** * Check support for graph entities */ private void doGraphEntityTest() { ClientResponse response; Model m; response = invoke("PUT", "test/ont1.ttl", BASE_URL + "reg1/ont?graph"); assertEquals(201, response.getStatus()); m = getModelResponse(BASE_URL + "reg1/ont"); assertTrue( hasTerm(m, "A") ); assertTrue( hasTerm(m, "a") ); assertTrue( hasTerm(m, "p") ); assertEquals(204, invoke("PUT", "test/ont1-modified.ttl", BASE_URL + "reg1/ont?graph").getStatus()); m = getModelResponse(BASE_URL + "reg1/ont"); assertFalse( hasTerm(m, "A") ); assertFalse( hasTerm(m, "a") ); assertTrue( hasTerm(m, "D") ); assertTrue( hasTerm(m, "d") ); } /** * Check support for attaching graphs to items */ private void doGraphAnnotationTest() { String annotationGraph = BASE_URL + "reg1/_red?annotation=test"; assertEquals(404, getResponse(annotationGraph).getStatus()); ClientResponse response = invoke("PUT", "test/ont1.ttl", annotationGraph); assertEquals(201, response.getStatus()); Model m = getModelResponse(annotationGraph); assertNotNull(m); assertTrue( hasTerm(m, "A") ); assertTrue( hasTerm(m, "a") ); assertTrue( hasTerm(m, "p") ); m = getModelResponse(BASE_URL + "reg1/_red"); Resource item = m.getResource(ROOT_REGISTER + "reg1/_red"); assertTrue( item.hasProperty(RegistryVocab.annotation) ); assertTrue( item.hasProperty(RegistryVocab.annotation, m.getResource(ROOT_REGISTER + "reg1/_red?annotation=test")) ); } private boolean hasTerm(Model m, String term) { Resource r = m.getResource(ROOT_REGISTER + "reg1/ont#" + term); return r.hasProperty(RDF.type); } /** * Typed template lookup and change notification */ private void doTypedTemplateTest() { String stt_reg = BASE_URL + "system/typed-templates"; assertEquals(201, postFileStatus("test/typed-templates-reg.ttl", BASE_URL + "system")); assertEquals(201, postFileStatus("test/concept-scheme-typed-template.ttl", stt_reg)); assertEquals(204, post(stt_reg + "/_concept-scheme?update&status=stable").getStatus()); LibReg reg = new LibReg(); Resource test = ModelFactory.createDefaultModel().createResource("http://example.com/test") .addProperty(RDF.type, SKOS.ConceptScheme) .addProperty(RDF.type, SKOS.Collection); assertEquals("concept-scheme-render.vm", reg.templateFor(test) ); assertEquals(201, postFileStatus("test/collection-typed-template.ttl", stt_reg)); assertEquals(204, post(stt_reg + "/_collection?update&status=stable").getStatus()); assertEquals("collection-render.vm", reg.templateFor(test) ); } /** * Test case for bnode duplication on registry reconstruction */ private void doBNodeDuplicationBugTest() { assertEquals(201, postFileStatus("test/rbd.ttl", BASE_URL + "?batch-managed&status=stable")); Model m = getModelResponse(BASE_URL + "RiverBasinDistrict"); Resource reg = m.getResource("http://location.data.gov.uk/RiverBasinDistrict"); int count = reg.listProperties(DCTerms.rights).toList().size(); assertEquals(1, count); int version = RDFUtil.getIntValue(reg, OWL.versionInfo, -1); // Add to the register assertEquals(201, postFileStatus("test/red.ttl", BASE_URL + "RiverBasinDistrict")); m = getModelResponse(BASE_URL + "RiverBasinDistrict"); reg = m.getResource("http://location.data.gov.uk/RiverBasinDistrict"); assertEquals(version + 1, RDFUtil.getIntValue(reg, OWL.versionInfo, -1)); } /** * Test case for real delete, assumes reg1 and reg1/red exist before hand */ private void doTestRealDelete() { assertEquals(200, getResponse(REG1).getStatus()); assertEquals(200, getResponse(REG1 + "/red").getStatus()); assertEquals(204, post(REG1 + "?real_delete").getStatus()); assertEquals(404, getResponse(REG1).getStatus()); assertEquals(404, getResponse(REG1 + "/red").getStatus()); } /** * Basic edit test cases */ private void doEditTest() { final String REGE = BASE_URL + "rege"; assertEquals(201, postFileStatus("test/edit/rege.ttl", BASE_URL)); assertEquals(204, postFileStatus("test/edit/edit1.ttl", REGE + "?edit")); checkModelResponse(REGE + "?_view=with_metadata&status=any", ROOT_REGISTER + "rege", "test/edit/expected1.ttl", DCTerms.dateSubmitted, DCTerms.modified); assertEquals(204, postFileStatus("test/edit/edit2.ttl", REGE + "?edit")); checkModelResponse(REGE + "?_view=with_metadata&status=any", ROOT_REGISTER + "rege", "test/edit/expected2.ttl", DCTerms.dateSubmitted, DCTerms.modified); assertEquals(204, postFileStatus("test/edit/edit3.csv", REGE + "?edit", "text/csv")); checkModelResponse(REGE + "?_view=with_metadata&status=any", ROOT_REGISTER + "rege", "test/edit/expected3.ttl", DCTerms.dateSubmitted, DCTerms.modified); } private void checkPageResponse(Model m, String nextpage, int length) { ResIterator ri = m.listSubjectsWithProperty(RDF.type, Ldbp.Page); assertTrue(ri.hasNext()); Resource page = ri.next(); assertFalse(ri.hasNext()); if (nextpage != null) { Resource next = page.getPropertyResourceValue(Ldbp.nextPage); assertNotNull(next); assertTrue(next.getURI().contains("_page=" + nextpage)); } else { assertFalse(page.hasProperty(Ldbp.nextPage)); } Resource reg = page.getPropertyResourceValue(Ldbp.pageOf); int count = 0; for (StmtIterator si = reg.listProperties(RDFS.member); si.hasNext();) { si.next(); count++; } assertEquals(length, count); List<RDFNode> items = page.getPropertyResourceValue(API.items).as(RDFList.class).asJavaList(); assertEquals(length, items.size()); } private void makeRegister(int length) { Model m = ModelFactory.createDefaultModel(); m.createResource("regL") .addProperty(RDF.type, RegistryVocab.Register) .addProperty(RDFS.label, "Long register"); assertEquals(201, postModel(m, BASE_URL).getStatus()); for (int i = 0; i < length; i++) { m = ModelFactory.createDefaultModel(); m.createResource("item" +i) .addProperty(RDFS.label, "item" + i) .addProperty(RDF.type, SKOS.Concept); assertEquals(201, postModel(m, REGL_URL).getStatus()); } } private void doTestPayloadRead(String csv, String expected) throws IOException { InputStream ins = new FileInputStream(csv); String baseURI = "http://location.data.gov.uk/reg3/"; Model payload = CSVPayloadRead.readCSVStream(ins, baseURI); assertTrue( payload.isIsomorphicWith( RDFDataMgr.loadModel(expected) ) ); } }
Starting on further tests for import/export
src/test/java/com/epimorphics/registry/webapi/TestAPI.java
Starting on further tests for import/export
<ide><path>rc/test/java/com/epimorphics/registry/webapi/TestAPI.java <ide> import static org.junit.Assert.assertNotNull; <ide> import static org.junit.Assert.assertTrue; <ide> <add>import java.io.File; <ide> import java.io.FileInputStream; <ide> import java.io.IOException; <ide> import java.io.InputStream; <ide> static final String REG1_URI = ROOT_REGISTER + "reg1"; <ide> static final String REG1_ITEM = ROOT_REGISTER + "_reg1"; <ide> static final String REGL_URL = BASE_URL + "regL"; <add> <add> protected File exportFile; <ide> <ide> String getWebappRoot() { <ide> return "src/test/webapp"; <ide> doTaggingTest(); <ide> <ide> // Export <del> doTestExport(); <add> doTestCSVOut(); <ide> <ide> // Graph entities and annotations <ide> doGraphEntityTest(); <ide> // Edit <ide> doEditTest(); <ide> <add> exportFile = File.createTempFile("export", "nq"); <add> doExport(); <add> <ide> // Deletion <ide> doTestRealDelete(); <ide> <add> // Reimport from before delete <add> doImportTest(); <add> <ide> // System.out.println("Store dump"); <ide> // ServiceConfig.get().getServiceAs("basestore", Store.class).asDataset().getDefaultModel().write(System.out, "Turtle"); <ide> } <add> <ide> <ide> private void doSkosLabelTest() { <ide> assertEquals(201, postFileStatus("test/bugs/brown-preflabel.ttl", REG1)); <ide> * Test export to CSV, assumes a particular state for reg3 so has <ide> * be run after tagging test <ide> */ <del> private void doTestExport() { <add> private void doTestCSVOut() { <ide> ClientResponse response = getResponse(BASE_URL + "reg3?_view=with_metadata", "text/csv"); <ide> assertEquals(200, response.getStatus()); <ide> assertEquals( FileManager.get().readWholeFileAsUTF8("test/csv/reg3.csv"), response.getEntity(String.class).replace("\r", "")); <ide> <ide> assertEquals(404, getResponse(REG1).getStatus()); <ide> assertEquals(404, getResponse(REG1 + "/red").getStatus()); <add> } <add> <add> /** <add> * Export Reg1 for later import test <add> */ <add> private void doExport() { <add> ClientResponse response = getResponse(REG1, "application/n-quads"); <add> assertEquals(200, response.getStatus()); <add> // TODO working here <add>// InputStream response.getEntity(InputStream.class); <add> } <add> <add> /** <add> * Reimport the earlier export and test REG1 is back <add> */ <add> private void doImportTest() { <add> // TODO working here <ide> } <ide> <ide> /**
Java
mit
c3f8bfa9a102899804a48e8d59047210928384db
0
sharpstewie/ICS4UFinal
/* GUESS THAT CHAMPION * * ---------------------------------------------------------------------------- * "Guess That Champion!" isn't endorsed by Riot Games and doesn't reflect * the views or opinions of Riot Games or anyone * officially involved in producing or managing League of Legends. * League of Legends and Riot Games are trademarks or * registered trademarks of Riot Games, Inc. League of Legends © Riot Games, Inc. * * ---------------------------------------------------------------------------- * * FEATURES * - Fully functional gameplay w/images of champion ability/passive as hint * - Select which categories to be tested on in menu screen * - Displays score in GUI * - Plays sound to let user know if their guess was correct * - Scoring becoomes disabled when timer reaches zero * - Player has a limited number of incorrect answers (lives) before their scoring doesn't work * - After playing on round, game loops to the category select screen * - Pressing the exit button closes the program (everywhere except during disclaimer) * * NEW FEATURES * - Time limit can now be changed to 30, 60, 90, 120, or 150 seconds * * PLANNED FEATURES * - Select which *champion* categories you'll be tested on (only Marksmen, only Fighters, etc.) * - System to keep track of high scores * * CODE ADJUSTMENTS * - Some commenting * * KNOWN BUGS * - Takes extremely long time to contact RiotAPI for full champion list (on slow connection) * */ import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.Timer; import javax.swing.border.BevelBorder; import javax.swing.border.SoftBevelBorder; import com.robrua.orianna.type.core.staticdata.Champion; public class guiGuess_v1_3 { // Instance variables // JFrame variables static JLayeredPane layeredPane; static JPanel mainPane; static JPanel timerBG; static JFrame frame; static GridBagLayout gridbag; static GridBagConstraints c; static JLabel lblBG; // Champion variables static ArrayList<Integer> used = new ArrayList<Integer>(); static ArrayList<Integer> usedFills = new ArrayList<Integer>(); static List<Champion> champions; static Champion champ; static Font text; static BufferedImage champAbi; static BufferedImage champPics[] = new BufferedImage[4]; static JButton champButts[] = new JButton[4]; // Hint variables static JLabel champAbility; static boolean passive; static boolean regular; static boolean ultimate; // Counters/temporary variables static String pass; static int answer; static int i; // Keep track of score static JLabel scoreLabel; static JLabel pointsLabel; static int score = 0; static int total = 0; static int points = 0; // Keep track of lives static JLabel lblLife1; static JLabel lblLife2; static JLabel lblLife3; static int lives = 3; // Keep track of time static StopWatch watch = new StopWatch(); static Timer timer; static JLabel timeLabel = new JLabel(); static long gameStart; static long roundStart; static long roundEnd; static long roundTime; static int cap; static long time = cap; /* Default: Passives [X] * Regular abilities [X] * Ultimate ability [X] */ public guiGuess_v1_3(List<Champion> champs, int limit) throws IOException{ passive = true; regular = true; ultimate = true; champions = champs; cap = limit; play(); } /* * Use parameters to select which types of icons to display */ public guiGuess_v1_3(List<Champion> champs, int limit, boolean doPassives, boolean doRegulars, boolean doUltimates) throws IOException{ passive = doPassives; regular = doRegulars; ultimate = doUltimates; champions = champs; cap = limit; play(); } /* * Display first set of icons */ protected static void play() throws IOException{ // Create JFrame frame = new JFrame("Guess That Champion!"); frame.setResizable(false); frame.setBounds(100, 100, 800, 600); frame.getContentPane().setLayout(null); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Initialize layered frame system; crucial to getting background image to work layeredPane = new JLayeredPane(); layeredPane.setBounds(0, 0, 800, 578); frame.getContentPane().add(layeredPane); // Background image setup/assignment BufferedImage BG = ImageIO.read(new File("lib//akaliBG.jpg")); lblBG = new JLabel(new ImageIcon(BG)); layeredPane.setLayer(lblBG, 0); lblBG.setBounds(0, 0, 800, 578); layeredPane.add(lblBG); // Add pane for buttons/content mainPane = new JPanel(); mainPane.setForeground(new Color(255, 255, 255)); layeredPane.setLayer(mainPane, 2); mainPane.setBounds(0, 0, 800, 578); layeredPane.add(mainPane); mainPane.setBackground(null); mainPane.setOpaque(false); mainPane.setLayout(null); // Choose title of application scoreLabel = new JLabel("Score: " + score + " / " + total); pointsLabel = new JLabel("Points: " + points); // Select champion, choose hint to be displayed champ = newChamp(); getAbilityType(); // Load and display image to be displayed as hint try{ champAbi = ImageIO.read(new File("lib/images/abilities/" + champ.getName() + "_" + pass + ".png")); }catch(IOException e){ System.out.println("lib/images/abilities/" + champ.getName() + "_" + pass + ".png"); } champAbility = new JLabel(new ImageIcon(champAbi)); // Load and display correct champion image, and 3 other champions answer = (int) (4 * Math.random()); for(int i = 0; i < champPics.length; i++){ if(i==answer) champPics[i] = ImageIO.read(new File("lib/images/champs/" + champ.getName() + ".png")); else champPics[i] = ImageIO.read(new File(newChampFill())); champButts[i] = new JButton(new ImageIcon(champPics[i])); } // Initialize buttons, score label and timers. champAbility.setBounds(368, 102, 64, 64); champButts[0].setBounds(270, 190, 120, 120); champButts[1].setBounds(408, 190, 120, 120); champButts[2].setBounds(270, 320, 120, 120); champButts[3].setBounds(408, 320, 120, 120); // Initialize score label pointsLabel.setFont(new Font("Bangla MN", Font.BOLD, 13)); pointsLabel.setForeground(new Color(255, 255, 255)); pointsLabel.setBounds(351, 470, 113, 25); // Initialize timers timeLabel.setText(Long.toString(time)); timeLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 21)); timeLabel.setForeground(new Color(255, 255, 255)); timeLabel.setBounds(384, 512, 50, 37); // Initialize life bars BufferedImage life = ImageIO.read(new File("lib//images//lives.png")); lblLife1 = new JLabel(new ImageIcon(life)); lblLife1.setBounds(650, 200, 64, 64); lblLife2 = new JLabel(new ImageIcon(life)); lblLife2.setBounds(650, 274, 64, 64); lblLife3 = new JLabel(new ImageIcon(life)); lblLife3.setBounds(650, 348, 64, 64); // Add elements to pane mainPane.add(champAbility); mainPane.add(champButts[0]); mainPane.add(champButts[1]); mainPane.add(champButts[2]); mainPane.add(champButts[3]); mainPane.add(pointsLabel); mainPane.add(timeLabel); mainPane.add(lblLife1); mainPane.add(lblLife2); mainPane.add(lblLife3); // Background for timer/score tracker timerBG = new JPanel(); timerBG.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null)); timerBG.setBackground(new Color(0, 0, 0)); layeredPane.setLayer(timerBG, 1); timerBG.setBounds(300, 460, 200, 100); layeredPane.add(timerBG); // Add listeners to buttons champButts[0].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { handleScore(0); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[1].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { handleScore(1); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[2].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { handleScore(2); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[3].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { handleScore(3); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); // Create game timer int delay = 1000; //milliseconds ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { gameStart = watch.getElapsedTimeSecs(); if(gameStart < cap) timeLabel.setText(Long.toString(cap-gameStart)); else timeLabel.setText("0"); timeLabel.setVisible(true); } }; // Start timers new Timer(delay, taskPerformer).start(); watch.start(); gameStart = watch.getElapsedTimeSecs(); roundStart = watch.getElapsedTimeSecs(); // Refresh frame with new elements frame.setVisible(true); } /* * Display next set of icons */ public static void nextRound() throws IOException{ // Remove elements from pane mainPane.remove(champAbility); mainPane.remove(champButts[0]); mainPane.remove(champButts[1]); mainPane.remove(champButts[2]); mainPane.remove(champButts[3]); mainPane.remove(pointsLabel); mainPane.remove(timeLabel); mainPane.remove(lblLife1); mainPane.remove(lblLife2); mainPane.remove(lblLife3); layeredPane.remove(timerBG); // Select new champion, choose hint to be displayed champ = newChamp(); answer = (int) (4 * Math.random()); getAbilityType(); // Load and display hint image try{ champAbi = ImageIO.read(new File("lib/images/abilities/" + champ.getName() + "_" + pass + ".png")); }catch (IOException e){System.out.println("Can't read: lib/images/abilities/" + champ.getName() + "_" + pass + ".png");} frame.getContentPane().remove(champAbility); champAbility = new JLabel(new ImageIcon(champAbi)); // Load and display correct champion image, and 3 other champion images for(int i = 0; i < champPics.length; i++){ if(i==answer){ try{ champPics[i] = ImageIO.read(new File("lib/images/champs/" + champ.getName() + ".png")); }catch(IOException e) {System.out.println("lib/images/champs/" + champ.getName() + ".png");} }else{ try{ champPics[i] = ImageIO.read(new File(newChampFill())); }catch(IOException e){ System.out.println();} } } for(int i = 0; i < champButts.length; i++){ frame.getContentPane().remove(champButts[i]); champButts[i] = new JButton(new ImageIcon(champPics[i])); champButts[i].setVisible(true); } // Display score and time scoreLabel = new JLabel("Score: " + score + " / " + total); pointsLabel = new JLabel("Points: " + points); scoreLabel.setVisible(true); timeLabel.setVisible(true); pointsLabel.setVisible(true); // Initialize buttons, score label and timers. champAbility.setBounds(368, 102, 64, 64); champButts[0].setBounds(270, 190, 120, 120); champButts[1].setBounds(408, 190, 120, 120); champButts[2].setBounds(270, 320, 120, 120); champButts[3].setBounds(408, 320, 120, 120); // Initialize score label pointsLabel.setFont(new Font("Bangla MN", Font.BOLD, 13)); pointsLabel.setForeground(new Color(255, 255, 255)); pointsLabel.setBounds(351, 470, 113, 25); // Initialize timers timeLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 21)); timeLabel.setForeground(new Color(255, 255, 255)); timeLabel.setBounds(384, 512, 50, 37); // Add elements to pane mainPane.add(champAbility); mainPane.add(champButts[0]); mainPane.add(champButts[1]); mainPane.add(champButts[2]); mainPane.add(champButts[3]); mainPane.add(pointsLabel); mainPane.add(timeLabel); layeredPane.add(timerBG); // Manage lives count if(lives>2) mainPane.add(lblLife1); if(lives>1) mainPane.add(lblLife2); if(lives>0) mainPane.add(lblLife3); // Add listeners to buttons champButts[0].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)){ handleScore(0); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } }else{ frame.setVisible(false); newGame(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[1].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)){ handleScore(0); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } }else{ frame.setVisible(false); newGame(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[2].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)){ handleScore(2); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } }else{ frame.setVisible(false); newGame(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[3].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)){ handleScore(3); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } }else{ frame.setVisible(false); newGame(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); // Refresh frame mainPane.setVisible(false); layeredPane.setVisible(false); mainPane.setVisible(true); layeredPane.setVisible(true); } /* * Starts a fresh new game */ public static void newGame(){ frame.setVisible(false); EventQueue.invokeLater(new Runnable() { public void run() { try { // Reset stats lives = 3; mainFrame_v4 window = new mainFrame_v4(points); points = 0; window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /* * Find new champ, mark as used */ public static Champion newChamp(){ // Pull random champion from list int index = (int)(champions.size() * Math.random()); // Make sure champion hasn't already been used as an answer while(used.contains(index)) index = (int)(champions.size() * Math.random()); // Save that champion Champion c = champions.get(index); // Add champion to used array used.add(index); return c; } /* * Find new champ to fill in empty slot, don't mark as used yet */ public static String newChampFill(){ // Pull random champion from list int index = (int)(champions.size() * Math.random()); // Make sure champion hasn't already been used as an answer while(used.contains(index)||usedFills.contains(index)) index = (int)(champions.size() * Math.random()); // Save that champion Champion c = champions.get(index); usedFills.add(index); //Return the appropriate file name return "lib/images/champs/" + c.getName() + ".png"; } /* * Generate string for an ability type to display */ public static void getAbilityType(){ String returnThis = ""; if(passive){ if(regular){ if(ultimate){ // All enabled int rn = (int) (5 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "W"; else if(rn==2) returnThis = "E"; else if(rn==3) returnThis = "R"; else returnThis = "Passive"; }else{ // No ultimates int rn = (int) (4 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "W"; else if(rn==2) returnThis = "E"; else returnThis = "Passive"; } }else{ if(ultimate){ // No regular abilities int rn = (int) (3 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "R"; else returnThis = "Passive"; }else{ // Only passives returnThis = "Passive"; } } }else{ if(regular){ if(ultimate){ // No passive int rn = (int) (4 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "W"; else if(rn==2) returnThis = "E"; else returnThis = "R"; } else{ // Only regular abilities int rn = (int) (3 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "W"; else returnThis = "E"; } }else{ if(ultimate){ // Only ultimates returnThis = "R"; } } } pass = returnThis; } /* * Play a sound */ public static void playSound(String soundFile){ try { // Create AudioStream from sound file AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundFile).getAbsoluteFile()); // Create clip from AudioStream and play clip Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); } catch(Exception ex) { System.out.println("Sound error on playing file: " + soundFile); ex.printStackTrace(); } } /* * Increment score when needed, and total guesses always */ public static void handleScore(int spot) throws IOException{ if((total < champions.size() - 3) && (gameStart < cap)){ int inc = (int) (400 / Math.pow(2, roundTime)); int dec = (int) (300 / Math.pow(1.5, roundTime)); // Play appropriate sound, change score if(answer==spot){ playSound("lib/sounds/correct.wav"); score++; points += inc; }else{ playSound("lib/sounds/incorrect.wav"); lives--; points -= dec; } total++; // System.out.println("Lives: " + lives); } // Refresh score / points scoreLabel.setVisible(true); pointsLabel.setVisible(true); } }
src/guiGuess_v1_3.java
/* GUESS THAT CHAMPION * * ---------------------------------------------------------------------------- * "Guess That Champion!" isn't endorsed by Riot Games and doesn't reflect * the views or opinions of Riot Games or anyone * officially involved in producing or managing League of Legends. * League of Legends and Riot Games are trademarks or * registered trademarks of Riot Games, Inc. League of Legends © Riot Games, Inc. * * ---------------------------------------------------------------------------- * * FEATURES * - Fully functional gameplay w/images of champion ability/passive as hint * - Select which categories to be tested on in menu screen * - Displays score in GUI * - Plays sound to let user know if their guess was correct * - Scoring becoomes disabled when timer reaches zero * - Player has a limited number of incorrect answers (lives) before their scoring doesn't work * - After playing on round, game loops to the category select screen * - Pressing the exit button closes the program (everywhere except during disclaimer) * * NEW FEATURES * - Time limit can now be changed to 30, 60, 90, 120, or 150 seconds * * PLANNED FEATURES * - Select which *champion* categories you'll be tested on (only Marksmen, only Fighters, etc.) * - System to keep track of high scores * * CODE ADJUSTMENTS * - Some commenting * * KNOWN BUGS * - Takes extremely long time to contact RiotAPI for full champion list (on slow connection) * */ import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.Timer; import javax.swing.border.BevelBorder; import javax.swing.border.SoftBevelBorder; import com.robrua.orianna.type.core.staticdata.Champion; public class guiGuess_v1_3 { // Instance variables // JFrame variables static JLayeredPane layeredPane; static JPanel mainPane; static JPanel timerBG; static JFrame frame; static GridBagLayout gridbag; static GridBagConstraints c; static JLabel lblBG; // Champion variables static ArrayList<Integer> used = new ArrayList<Integer>(); static ArrayList<Integer> usedFills = new ArrayList<Integer>(); static List<Champion> champions; static Champion champ; static Font text; static BufferedImage champAbi; static BufferedImage champPics[] = new BufferedImage[4]; static JButton champButts[] = new JButton[4]; // Hint variables static JLabel champAbility; static boolean passive; static boolean regular; static boolean ultimate; // Counters/temporary variables static String pass; static int answer; static int i; // Keep track of score static JLabel scoreLabel; static JLabel pointsLabel; static int score = 0; static int total = 0; static int points = 0; // Keep track of lives static JLabel lblLife1; static JLabel lblLife2; static JLabel lblLife3; static int lives = 3; // Keep track of time static StopWatch watch = new StopWatch(); static Timer timer; static JLabel timeLabel = new JLabel(); static long gameStart; static long roundStart; static long roundEnd; static long roundTime; static int cap; static long time = cap; /* Default: Passives [X] * Regular abilities [X] * Ultimate ability [X] */ public guiGuess_v1_3(List<Champion> champs, int limit) throws IOException{ passive = true; regular = true; ultimate = true; champions = champs; cap = limit; play(); } /* * Use parameters to select which types of icons to display */ public guiGuess_v1_3(List<Champion> champs, int limit, boolean doPassives, boolean doRegulars, boolean doUltimates) throws IOException{ passive = doPassives; regular = doRegulars; ultimate = doUltimates; champions = champs; cap = limit; play(); } /* * Display first set of icons */ protected static void play() throws IOException{ // Create JFrame frame = new JFrame("Guess That Champion!"); frame.setResizable(false); frame.setBounds(100, 100, 800, 600); frame.getContentPane().setLayout(null); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Initialize layered frame system; crucial to getting background image to work layeredPane = new JLayeredPane(); layeredPane.setBounds(0, 0, 800, 578); frame.getContentPane().add(layeredPane); // Background image setup/assignment BufferedImage BG = ImageIO.read(new File("lib//akaliBG.jpg")); lblBG = new JLabel(new ImageIcon(BG)); layeredPane.setLayer(lblBG, 0); lblBG.setBounds(0, 0, 800, 578); layeredPane.add(lblBG); // Add pane for buttons/content mainPane = new JPanel(); mainPane.setForeground(new Color(255, 255, 255)); layeredPane.setLayer(mainPane, 2); mainPane.setBounds(0, 0, 800, 578); layeredPane.add(mainPane); mainPane.setBackground(null); mainPane.setOpaque(false); mainPane.setLayout(null); // Choose title of application scoreLabel = new JLabel("Score: " + score + " / " + total); pointsLabel = new JLabel("Points: " + points); // Select champion, choose hint to be displayed champ = newChamp(); getAbilityType(); // Load and display image to be displayed as hint try{ champAbi = ImageIO.read(new File("lib/images/abilities/" + champ.getName() + "_" + pass + ".png")); }catch(IOException e){ System.out.println("lib/images/abilities/" + champ.getName() + "_" + pass + ".png"); } champAbility = new JLabel(new ImageIcon(champAbi)); // Load and display correct champion image, and 3 other champions answer = (int) (4 * Math.random()); for(int i = 0; i < champPics.length; i++){ if(i==answer) champPics[i] = ImageIO.read(new File("lib/images/champs/" + champ.getName() + ".png")); else champPics[i] = ImageIO.read(new File(newChampFill())); champButts[i] = new JButton(new ImageIcon(champPics[i])); } // Initialize buttons, score label and timers. champAbility.setBounds(368, 102, 64, 64); champButts[0].setBounds(270, 190, 120, 120); champButts[1].setBounds(408, 190, 120, 120); champButts[2].setBounds(270, 320, 120, 120); champButts[3].setBounds(408, 320, 120, 120); // Initialize score label pointsLabel.setFont(new Font("Bangla MN", Font.BOLD, 13)); pointsLabel.setForeground(new Color(255, 255, 255)); pointsLabel.setBounds(351, 470, 113, 25); // Initialize timers timeLabel.setText(Long.toString(time)); timeLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 21)); timeLabel.setForeground(new Color(255, 255, 255)); timeLabel.setBounds(384, 512, 50, 37); // Initialize life bars BufferedImage life = ImageIO.read(new File("lib//images//lives.png")); lblLife1 = new JLabel(new ImageIcon(life)); lblLife1.setBounds(650, 200, 64, 64); lblLife2 = new JLabel(new ImageIcon(life)); lblLife2.setBounds(650, 274, 64, 64); lblLife3 = new JLabel(new ImageIcon(life)); lblLife3.setBounds(650, 348, 64, 64); // Add elements to pane mainPane.add(champAbility); mainPane.add(champButts[0]); mainPane.add(champButts[1]); mainPane.add(champButts[2]); mainPane.add(champButts[3]); mainPane.add(pointsLabel); mainPane.add(timeLabel); mainPane.add(lblLife1); mainPane.add(lblLife2); mainPane.add(lblLife3); // Background for timer/score tracker timerBG = new JPanel(); timerBG.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null)); timerBG.setBackground(new Color(0, 0, 0)); layeredPane.setLayer(timerBG, 1); timerBG.setBounds(300, 460, 200, 100); layeredPane.add(timerBG); // Add listeners to buttons champButts[0].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { handleScore(0); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[1].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { handleScore(1); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[2].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { handleScore(2); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[3].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { handleScore(3); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); // Create game timer int delay = 1000; //milliseconds ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { gameStart = watch.getElapsedTimeSecs(); if(gameStart < cap) timeLabel.setText(Long.toString(cap-gameStart)); else timeLabel.setText("0"); timeLabel.setVisible(true); } }; // Start timers new Timer(delay, taskPerformer).start(); watch.start(); gameStart = watch.getElapsedTimeSecs(); roundStart = watch.getElapsedTimeSecs(); // Refresh frame with new elements frame.setVisible(true); } /* * Display next set of icons */ public static void nextRound() throws IOException{ // Remove elements from pane mainPane.remove(champAbility); mainPane.remove(champButts[0]); mainPane.remove(champButts[1]); mainPane.remove(champButts[2]); mainPane.remove(champButts[3]); mainPane.remove(pointsLabel); mainPane.remove(timeLabel); mainPane.remove(lblLife1); mainPane.remove(lblLife2); mainPane.remove(lblLife3); layeredPane.remove(timerBG); // Select new champion, choose hint to be displayed champ = newChamp(); answer = (int) (4 * Math.random()); getAbilityType(); // Load and display hint image try{ champAbi = ImageIO.read(new File("lib/images/abilities/" + champ.getName() + "_" + pass + ".png")); }catch (IOException e){System.out.println("Can't read: lib/images/abilities/" + champ.getName() + "_" + pass + ".png");} frame.getContentPane().remove(champAbility); champAbility = new JLabel(new ImageIcon(champAbi)); // Load and display correct champion image, and 3 other champion images for(int i = 0; i < champPics.length; i++){ if(i==answer){ try{ champPics[i] = ImageIO.read(new File("lib/images/champs/" + champ.getName() + ".png")); }catch(IOException e) {System.out.println("lib/images/champs/" + champ.getName() + ".png");} }else{ try{ champPics[i] = ImageIO.read(new File(newChampFill())); }catch(IOException e){ System.out.println();} } } for(int i = 0; i < champButts.length; i++){ frame.getContentPane().remove(champButts[i]); champButts[i] = new JButton(new ImageIcon(champPics[i])); champButts[i].setVisible(true); } // Display score and time scoreLabel = new JLabel("Score: " + score + " / " + total); pointsLabel = new JLabel("Points: " + points); scoreLabel.setVisible(true); timeLabel.setVisible(true); pointsLabel.setVisible(true); // Initialize buttons, score label and timers. champAbility.setBounds(368, 102, 64, 64); champButts[0].setBounds(270, 190, 120, 120); champButts[1].setBounds(408, 190, 120, 120); champButts[2].setBounds(270, 320, 120, 120); champButts[3].setBounds(408, 320, 120, 120); // Initialize score label pointsLabel.setFont(new Font("Bangla MN", Font.BOLD, 13)); pointsLabel.setForeground(new Color(255, 255, 255)); pointsLabel.setBounds(351, 470, 113, 25); // Initialize timers timeLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 21)); timeLabel.setForeground(new Color(255, 255, 255)); timeLabel.setBounds(384, 512, 50, 37); // Add elements to pane mainPane.add(champAbility); mainPane.add(champButts[0]); mainPane.add(champButts[1]); mainPane.add(champButts[2]); mainPane.add(champButts[3]); mainPane.add(pointsLabel); mainPane.add(timeLabel); layeredPane.add(timerBG); // Manage lives count if(lives>2) mainPane.add(lblLife1); if(lives>1) mainPane.add(lblLife2); if(lives>0) mainPane.add(lblLife3); // Add listeners to buttons champButts[0].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)){ handleScore(0); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; if((total < champions.size() - 3) && (gameStart < cap)) nextRound(); else{ frame.dispose(); new mainFrame_v4(0); } }else{ frame.setVisible(false); newGame(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[1].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)){ handleScore(0); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; nextRound(); }else{ frame.setVisible(false); newGame(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[2].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)){ handleScore(2); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; nextRound(); }else{ frame.setVisible(false); newGame(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); champButts[3].addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { try { if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)){ handleScore(3); // Scoring // End round timer roundEnd = watch.getElapsedTimeSecs(); roundTime = roundEnd-roundStart; // Start new round roundStart = roundEnd; nextRound(); }else{ frame.setVisible(false); newGame(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); // Refresh frame mainPane.setVisible(false); layeredPane.setVisible(false); mainPane.setVisible(true); layeredPane.setVisible(true); } /* * Starts a fresh new game */ public static void newGame(){ frame.setVisible(false); EventQueue.invokeLater(new Runnable() { public void run() { try { // Reset stats lives = 3; mainFrame_v4 window = new mainFrame_v4(points); points = 0; window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /* * Find new champ, mark as used */ public static Champion newChamp(){ // Pull random champion from list int index = (int)(champions.size() * Math.random()); // Make sure champion hasn't already been used as an answer while(used.contains(index)) index = (int)(champions.size() * Math.random()); // Save that champion Champion c = champions.get(index); // Add champion to used array used.add(index); return c; } /* * Find new champ to fill in empty slot, don't mark as used yet */ public static String newChampFill(){ // Pull random champion from list int index = (int)(champions.size() * Math.random()); // Make sure champion hasn't already been used as an answer while(used.contains(index)||usedFills.contains(index)) index = (int)(champions.size() * Math.random()); // Save that champion Champion c = champions.get(index); usedFills.add(index); //Return the appropriate file name return "lib/images/champs/" + c.getName() + ".png"; } /* * Generate string for an ability type to display */ public static void getAbilityType(){ String returnThis = ""; if(passive){ if(regular){ if(ultimate){ // All enabled int rn = (int) (5 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "W"; else if(rn==2) returnThis = "E"; else if(rn==3) returnThis = "R"; else returnThis = "Passive"; }else{ // No ultimates int rn = (int) (4 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "W"; else if(rn==2) returnThis = "E"; else returnThis = "Passive"; } }else{ if(ultimate){ // No regular abilities int rn = (int) (3 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "R"; else returnThis = "Passive"; }else{ // Only passives returnThis = "Passive"; } } }else{ if(regular){ if(ultimate){ // No passive int rn = (int) (4 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "W"; else if(rn==2) returnThis = "E"; else returnThis = "R"; } else{ // Only regular abilities int rn = (int) (3 * Math.random()); if(rn==0) returnThis = "Q"; else if(rn==1) returnThis = "W"; else returnThis = "E"; } }else{ if(ultimate){ // Only ultimates returnThis = "R"; } } } pass = returnThis; } /* * Play a sound */ public static void playSound(String soundFile){ try { // Create AudioStream from sound file AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundFile).getAbsoluteFile()); // Create clip from AudioStream and play clip Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); } catch(Exception ex) { System.out.println("Sound error on playing file: " + soundFile); ex.printStackTrace(); } } /* * Increment score when needed, and total guesses always */ public static void handleScore(int spot) throws IOException{ if((total < champions.size() - 3) && (gameStart < cap)){ int inc = (int) (400 / Math.pow(2, roundTime)); int dec = (int) (300 / Math.pow(1.5, roundTime)); // Play appropriate sound, change score if(answer==spot){ playSound("lib/sounds/correct.wav"); score++; points += inc; }else{ playSound("lib/sounds/incorrect.wav"); lives--; points -= dec; } total++; // System.out.println("P: " + points); } // Refresh score / points scoreLabel.setVisible(true); pointsLabel.setVisible(true); } }
Round ends immediately after running out of lives
src/guiGuess_v1_3.java
Round ends immediately after running out of lives
<ide><path>rc/guiGuess_v1_3.java <ide> <ide> // Start new round <ide> roundStart = roundEnd; <del> if((total < champions.size() - 3) && (gameStart < cap)) <add> if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) <ide> nextRound(); <ide> else{ <ide> frame.dispose(); <ide> <ide> // Start new round <ide> roundStart = roundEnd; <del> if((total < champions.size() - 3) && (gameStart < cap)) <add> if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) <ide> nextRound(); <ide> else{ <ide> frame.dispose(); <ide> <ide> // Start new round <ide> roundStart = roundEnd; <del> if((total < champions.size() - 3) && (gameStart < cap)) <add> if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) <ide> nextRound(); <ide> else{ <ide> frame.dispose(); <ide> <ide> // Start new round <ide> roundStart = roundEnd; <del> if((total < champions.size() - 3) && (gameStart < cap)) <add> if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) <ide> nextRound(); <ide> else{ <ide> frame.dispose(); <ide> <ide> // Start new round <ide> roundStart = roundEnd; <del> if((total < champions.size() - 3) && (gameStart < cap)) <add> if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) <ide> nextRound(); <ide> else{ <ide> frame.dispose(); <ide> <ide> // Start new round <ide> roundStart = roundEnd; <del> nextRound(); <add> if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) <add> nextRound(); <add> else{ <add> frame.dispose(); <add> new mainFrame_v4(0); <add> } <ide> }else{ <ide> frame.setVisible(false); <ide> newGame(); <ide> <ide> // Start new round <ide> roundStart = roundEnd; <del> nextRound(); <add> if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) <add> nextRound(); <add> else{ <add> frame.dispose(); <add> new mainFrame_v4(0); <add> } <ide> }else{ <ide> frame.setVisible(false); <ide> newGame(); <ide> <ide> // Start new round <ide> roundStart = roundEnd; <del> nextRound(); <add> if((total < champions.size() - 3) && (gameStart < cap) && (lives > 0)) <add> nextRound(); <add> else{ <add> frame.dispose(); <add> new mainFrame_v4(0); <add> } <ide> }else{ <ide> frame.setVisible(false); <ide> newGame(); <ide> } <ide> <ide> total++; <del>// System.out.println("P: " + points); <add>// System.out.println("Lives: " + lives); <ide> } <ide> <ide> // Refresh score / points
JavaScript
mit
d28166805f72de1f76dcbc322e5c79ec50791882
0
GrayYoung/jQuery.UI.Extension,GrayYoung/jQuery.UI.Extension
/* * jQuery UI Droppable @VERSION * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Droppables * * Depends: * ui.core.js * ui.draggable.js */ (function($) { $.widget("ui.droppable", { _init: function() { var o = this.options, accept = o.accept; this.isover = 0; this.isout = 1; this.accept = $.isFunction(accept) ? accept : function(d) { return d.is(accept); }; //Store the droppable's proportions this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; // Add the reference and positions to the manager $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || []; $.ui.ddmanager.droppables[o.scope].push(this); (o.addClasses && this.element.addClass("ui-droppable")); }, destroy: function() { var drop = $.ui.ddmanager.droppables[this.options.scope]; for ( var i = 0; i < drop.length; i++ ) if ( drop[i] == this ) drop.splice(i, 1); this.element .removeClass("ui-droppable ui-droppable-disabled") .removeData("droppable") .unbind(".droppable"); return this; }, _setData: function(key, value) { if(key == 'accept') { this.accept = $.isFunction(value) ? value : function(d) { return d.is(value); }; } $.widget.prototype._setData.apply(this, arguments); }, _activate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) this.element.addClass(this.options.activeClass); (draggable && this._trigger('activate', event, this.ui(draggable))); }, _deactivate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) this.element.removeClass(this.options.activeClass); (draggable && this._trigger('deactivate', event, this.ui(draggable))); }, _over: function(event) { var draggable = $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) this.element.addClass(this.options.hoverClass); this._trigger('over', event, this.ui(draggable)); } }, _out: function(event) { var draggable = $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); this._trigger('out', event, this.ui(draggable)); } }, _drop: function(event,custom) { var draggable = custom || $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element var childrenIntersection = false; this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() { var inst = $.data(this, 'droppable'); if( inst.options.greedy && !inst.options.disabled && inst.options.scope == draggable.options.scope && inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance) ) { childrenIntersection = true; return false; } }); if(childrenIntersection) return false; if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.activeClass) this.element.removeClass(this.options.activeClass); if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); this._trigger('drop', event, this.ui(draggable)); return this.element; } return false; }, ui: function(c) { return { draggable: (c.currentItem || c.element), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.extend($.ui.droppable, { version: "@VERSION", eventPrefix: 'drop', defaults: { accept: '*', activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: 'default', tolerance: 'intersect' } }); $.ui.intersect = function(draggable, droppable, toleranceMode) { if (!droppable.offset) return false; var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height; var l = droppable.offset.left, r = l + droppable.proportions.width, t = droppable.offset.top, b = t + droppable.proportions.height; switch (toleranceMode) { case 'fit': return (l < x1 && x2 < r && t < y1 && y2 < b); break; case 'intersect': return (l < x1 + (draggable.helperProportions.width / 2) // Right Half && x2 - (draggable.helperProportions.width / 2) < r // Left Half && t < y1 + (draggable.helperProportions.height / 2) // Bottom Half && y2 - (draggable.helperProportions.height / 2) < b ); // Top Half break; case 'pointer': var draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left), draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top), isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width); return isOver; break; case 'touch': return ( (y1 >= t && y1 <= b) || // Top edge touching (y2 >= t && y2 <= b) || // Bottom edge touching (y1 < t && y2 > b) // Surrounded vertically ) && ( (x1 >= l && x1 <= r) || // Left edge touching (x2 >= l && x2 <= r) || // Right edge touching (x1 < l && x2 > r) // Surrounded horizontally ); break; default: return false; break; } }; /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { 'default': [] }, prepareOffsets: function(t, event) { var m = $.ui.ddmanager.droppables[t.options.scope] || []; var type = event ? event.type : null; // workaround for #2317 var list = (t.currentItem || t.element).find(":data(droppable)").andSelf(); droppablesLoop: for (var i = 0; i < m.length; i++) { if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) continue; //No disabled and non-accepted for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; //If the element is not visible, continue m[i].offset = m[i].element.offset(); m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight }; if(type == "mousedown") m[i]._activate.call(m[i], event); //Activate the droppable if used directly from draggables } }, drop: function(draggable, event) { var dropped = false; $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { if(!this.options) return; if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) dropped = this._drop.call(this, event); if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { this.isout = 1; this.isover = 0; this._deactivate.call(this, event); } }); return dropped; }, drag: function(draggable, event) { //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event); //Run through all droppables and check their positions based on specific tolerance options $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { if(this.options.disabled || this.greedyChild || !this.visible) return; var intersects = $.ui.intersect(draggable, this, this.options.tolerance); var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null); if(!c) return; var parentInstance; if (this.options.greedy) { var parent = this.element.parents(':data(droppable):eq(0)'); if (parent.length) { parentInstance = $.data(parent[0], 'droppable'); parentInstance.greedyChild = (c == 'isover' ? 1 : 0); } } // we just moved into a greedy child if (parentInstance && c == 'isover') { parentInstance['isover'] = 0; parentInstance['isout'] = 1; parentInstance._out.call(parentInstance, event); } this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0; this[c == "isover" ? "_over" : "_out"].call(this, event); // we just moved out of a greedy child if (parentInstance && c == 'isout') { parentInstance['isout'] = 0; parentInstance['isover'] = 1; parentInstance._over.call(parentInstance, event); } }); } }; })(jQuery);
ui/ui.droppable.js
/* * jQuery UI Droppable @VERSION * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Droppables * * Depends: * ui.core.js * ui.draggable.js */ (function($) { $.widget("ui.droppable", { _init: function() { var o = this.options, accept = o.accept; this.isover = 0; this.isout = 1; this.accept = $.isFunction(accept) ? accept : function(d) { return d.is(accept); }; //Store the droppable's proportions this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; // Add the reference and positions to the manager $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || []; $.ui.ddmanager.droppables[o.scope].push(this); (o.addClasses && this.element.addClass("ui-droppable")); }, destroy: function() { var drop = $.ui.ddmanager.droppables[this.options.scope]; for ( var i = 0; i < drop.length; i++ ) if ( drop[i] == this ) drop.splice(i, 1); this.element .removeClass("ui-droppable ui-droppable-disabled") .removeData("droppable") .unbind(".droppable"); return this; }, _setData: function(key, value) { if(key == 'accept') { this.accept = $.isFunction(value) ? value : function(d) { return d.is(value); }; } $.widget.prototype._setData.apply(this, arguments); }, _activate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) this.element.addClass(this.options.activeClass); (draggable && this._trigger('activate', event, this.ui(draggable))); }, _deactivate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) this.element.removeClass(this.options.activeClass); (draggable && this._trigger('deactivate', event, this.ui(draggable))); }, _over: function(event) { var draggable = $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) this.element.addClass(this.options.hoverClass); this._trigger('over', event, this.ui(draggable)); } }, _out: function(event) { var draggable = $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); this._trigger('out', event, this.ui(draggable)); } }, _drop: function(event,custom) { var draggable = custom || $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element var childrenIntersection = false; this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() { var inst = $.data(this, 'droppable'); if(inst.options.greedy && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)) { childrenIntersection = true; return false; } }); if(childrenIntersection) return false; if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.activeClass) this.element.removeClass(this.options.activeClass); if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); this._trigger('drop', event, this.ui(draggable)); return this.element; } return false; }, ui: function(c) { return { draggable: (c.currentItem || c.element), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.extend($.ui.droppable, { version: "@VERSION", eventPrefix: 'drop', defaults: { accept: '*', activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: 'default', tolerance: 'intersect' } }); $.ui.intersect = function(draggable, droppable, toleranceMode) { if (!droppable.offset) return false; var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height; var l = droppable.offset.left, r = l + droppable.proportions.width, t = droppable.offset.top, b = t + droppable.proportions.height; switch (toleranceMode) { case 'fit': return (l < x1 && x2 < r && t < y1 && y2 < b); break; case 'intersect': return (l < x1 + (draggable.helperProportions.width / 2) // Right Half && x2 - (draggable.helperProportions.width / 2) < r // Left Half && t < y1 + (draggable.helperProportions.height / 2) // Bottom Half && y2 - (draggable.helperProportions.height / 2) < b ); // Top Half break; case 'pointer': var draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left), draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top), isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width); return isOver; break; case 'touch': return ( (y1 >= t && y1 <= b) || // Top edge touching (y2 >= t && y2 <= b) || // Bottom edge touching (y1 < t && y2 > b) // Surrounded vertically ) && ( (x1 >= l && x1 <= r) || // Left edge touching (x2 >= l && x2 <= r) || // Right edge touching (x1 < l && x2 > r) // Surrounded horizontally ); break; default: return false; break; } }; /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { 'default': [] }, prepareOffsets: function(t, event) { var m = $.ui.ddmanager.droppables[t.options.scope] || []; var type = event ? event.type : null; // workaround for #2317 var list = (t.currentItem || t.element).find(":data(droppable)").andSelf(); droppablesLoop: for (var i = 0; i < m.length; i++) { if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) continue; //No disabled and non-accepted for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; //If the element is not visible, continue m[i].offset = m[i].element.offset(); m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight }; if(type == "mousedown") m[i]._activate.call(m[i], event); //Activate the droppable if used directly from draggables } }, drop: function(draggable, event) { var dropped = false; $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { if(!this.options) return; if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) dropped = this._drop.call(this, event); if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { this.isout = 1; this.isover = 0; this._deactivate.call(this, event); } }); return dropped; }, drag: function(draggable, event) { //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event); //Run through all droppables and check their positions based on specific tolerance options $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { if(this.options.disabled || this.greedyChild || !this.visible) return; var intersects = $.ui.intersect(draggable, this, this.options.tolerance); var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null); if(!c) return; var parentInstance; if (this.options.greedy) { var parent = this.element.parents(':data(droppable):eq(0)'); if (parent.length) { parentInstance = $.data(parent[0], 'droppable'); parentInstance.greedyChild = (c == 'isover' ? 1 : 0); } } // we just moved into a greedy child if (parentInstance && c == 'isover') { parentInstance['isover'] = 0; parentInstance['isout'] = 1; parentInstance._out.call(parentInstance, event); } this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0; this[c == "isover" ? "_over" : "_out"].call(this, event); // we just moved out of a greedy child if (parentInstance && c == 'isout') { parentInstance['isout'] = 0; parentInstance['isover'] = 1; parentInstance._over.call(parentInstance, event); } }); } }; })(jQuery);
droppable: greedy childs that dont accept the draggable dont block propagation anymore, fixes #4570
ui/ui.droppable.js
droppable: greedy childs that dont accept the draggable dont block propagation anymore, fixes #4570
<ide><path>i/ui.droppable.js <ide> var childrenIntersection = false; <ide> this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() { <ide> var inst = $.data(this, 'droppable'); <del> if(inst.options.greedy && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)) { <del> childrenIntersection = true; return false; <del> } <add> if( <add> inst.options.greedy <add> && !inst.options.disabled <add> && inst.options.scope == draggable.options.scope <add> && inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) <add> && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance) <add> ) { childrenIntersection = true; return false; } <ide> }); <ide> if(childrenIntersection) return false; <ide> <ide> if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event); <ide> <ide> //Run through all droppables and check their positions based on specific tolerance options <del> <ide> $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { <ide> <ide> if(this.options.disabled || this.greedyChild || !this.visible) return;
Java
mit
647038bd9eaffff9c3a845d1c88d5bea2fbffe69
0
ximsfei/Android-skin-support,ximsfei/Android-skin-support
package skin.support.widget; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.DrawableRes; import android.support.v7.widget.AppCompatCheckedTextView; import android.util.AttributeSet; import skin.support.R; import skin.support.content.res.SkinCompatResources; import static skin.support.widget.SkinCompatHelper.INVALID_ID; /** * Created by ximsfei on 17-1-14. */ public class SkinCompatCheckedTextView extends AppCompatCheckedTextView implements SkinCompatSupportable { private static final int[] TINT_ATTRS = { android.R.attr.checkMark }; private int mCheckMarkResId = INVALID_ID; private SkinCompatTextHelper mTextHelper; private SkinCompatBackgroundHelper mBackgroundTintHelper; public SkinCompatCheckedTextView(Context context) { this(context, null); } public SkinCompatCheckedTextView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.checkedTextViewStyle); } public SkinCompatCheckedTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mBackgroundTintHelper = new SkinCompatBackgroundHelper(this); mBackgroundTintHelper.loadFromAttributes(attrs, defStyleAttr); mTextHelper = SkinCompatTextHelper.create(this); mTextHelper.loadFromAttributes(attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, TINT_ATTRS, defStyleAttr, 0); mCheckMarkResId = a.getResourceId(0, INVALID_ID); a.recycle(); applyCheckMark(); } @Override public void setCheckMarkDrawable(@DrawableRes int resId) { mCheckMarkResId = resId; applyCheckMark(); } @Override public void setBackgroundResource(@DrawableRes int resId) { super.setBackgroundResource(resId); if (mBackgroundTintHelper != null) { mBackgroundTintHelper.onSetBackgroundResource(resId); } } @Override public void setTextAppearance(int resId) { setTextAppearance(getContext(), resId); } @Override public void setTextAppearance(Context context, int resId) { super.setTextAppearance(context, resId); if (mTextHelper != null) { mTextHelper.onSetTextAppearance(context, resId); } } @Override public void setCompoundDrawablesRelativeWithIntrinsicBounds( @DrawableRes int start, @DrawableRes int top, @DrawableRes int end, @DrawableRes int bottom) { super.setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); if (mTextHelper != null) { mTextHelper.onSetCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); } } @Override public void setCompoundDrawablesWithIntrinsicBounds( @DrawableRes int left, @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) { super.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); if (mTextHelper != null) { mTextHelper.onSetCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } } @Override public void applySkin() { if (mBackgroundTintHelper != null) { mBackgroundTintHelper.applySkin(); } if (mTextHelper != null) { mTextHelper.applySkin(); } applyCheckMark(); } private void applyCheckMark() { mCheckMarkResId = SkinCompatHelper.checkResourceId(mCheckMarkResId); if (mCheckMarkResId != INVALID_ID) { setCheckMarkDrawable(SkinCompatResources.getInstance().getDrawable(mCheckMarkResId)); } } }
android-support/skin-support/src/main/java/skin/support/widget/SkinCompatCheckedTextView.java
package skin.support.widget; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.DrawableRes; import android.support.v7.widget.AppCompatCheckedTextView; import android.util.AttributeSet; import skin.support.content.res.SkinCompatResources; import static skin.support.widget.SkinCompatHelper.INVALID_ID; /** * Created by ximsfei on 17-1-14. */ public class SkinCompatCheckedTextView extends AppCompatCheckedTextView implements SkinCompatSupportable { private static final int[] TINT_ATTRS = { android.R.attr.checkMark }; private int mCheckMarkResId = INVALID_ID; private SkinCompatTextHelper mTextHelper; private SkinCompatBackgroundHelper mBackgroundTintHelper; public SkinCompatCheckedTextView(Context context) { this(context, null); } public SkinCompatCheckedTextView(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.checkedTextViewStyle); } public SkinCompatCheckedTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mBackgroundTintHelper = new SkinCompatBackgroundHelper(this); mBackgroundTintHelper.loadFromAttributes(attrs, defStyleAttr); mTextHelper = SkinCompatTextHelper.create(this); mTextHelper.loadFromAttributes(attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, TINT_ATTRS, defStyleAttr, 0); mCheckMarkResId = a.getResourceId(0, INVALID_ID); a.recycle(); applyCheckMark(); } @Override public void setCheckMarkDrawable(@DrawableRes int resId) { mCheckMarkResId = resId; applyCheckMark(); } @Override public void setBackgroundResource(@DrawableRes int resId) { super.setBackgroundResource(resId); if (mBackgroundTintHelper != null) { mBackgroundTintHelper.onSetBackgroundResource(resId); } } @Override public void setTextAppearance(int resId) { setTextAppearance(getContext(), resId); } @Override public void setTextAppearance(Context context, int resId) { super.setTextAppearance(context, resId); if (mTextHelper != null) { mTextHelper.onSetTextAppearance(context, resId); } } @Override public void setCompoundDrawablesRelativeWithIntrinsicBounds( @DrawableRes int start, @DrawableRes int top, @DrawableRes int end, @DrawableRes int bottom) { super.setCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); if (mTextHelper != null) { mTextHelper.onSetCompoundDrawablesRelativeWithIntrinsicBounds(start, top, end, bottom); } } @Override public void setCompoundDrawablesWithIntrinsicBounds( @DrawableRes int left, @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) { super.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); if (mTextHelper != null) { mTextHelper.onSetCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } } @Override public void applySkin() { if (mBackgroundTintHelper != null) { mBackgroundTintHelper.applySkin(); } if (mTextHelper != null) { mTextHelper.applySkin(); } applyCheckMark(); } private void applyCheckMark() { mCheckMarkResId = SkinCompatHelper.checkResourceId(mCheckMarkResId); if (mCheckMarkResId != INVALID_ID) { setCheckMarkDrawable(SkinCompatResources.getInstance().getDrawable(mCheckMarkResId)); } } }
CheckedTextView 低版本手机崩溃问题
android-support/skin-support/src/main/java/skin/support/widget/SkinCompatCheckedTextView.java
CheckedTextView 低版本手机崩溃问题
<ide><path>ndroid-support/skin-support/src/main/java/skin/support/widget/SkinCompatCheckedTextView.java <ide> import android.support.v7.widget.AppCompatCheckedTextView; <ide> import android.util.AttributeSet; <ide> <add>import skin.support.R; <ide> import skin.support.content.res.SkinCompatResources; <ide> <ide> import static skin.support.widget.SkinCompatHelper.INVALID_ID; <ide> } <ide> <ide> public SkinCompatCheckedTextView(Context context, AttributeSet attrs) { <del> this(context, attrs, android.R.attr.checkedTextViewStyle); <add> this(context, attrs, R.attr.checkedTextViewStyle); <ide> } <ide> <ide> public SkinCompatCheckedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
Java
agpl-3.0
b488c7d2a38166c93809fbe3848a90ca53623d0d
0
jrnold/rstudio,tbarrongh/rstudio,suribes/rstudio,pssguy/rstudio,jzhu8803/rstudio,sfloresm/rstudio,thklaus/rstudio,more1/rstudio,githubfun/rstudio,jar1karp/rstudio,more1/rstudio,JanMarvin/rstudio,jrnold/rstudio,pssguy/rstudio,JanMarvin/rstudio,jzhu8803/rstudio,edrogers/rstudio,maligulzar/Rstudio-instrumented,maligulzar/Rstudio-instrumented,edrogers/rstudio,nvoron23/rstudio,suribes/rstudio,maligulzar/Rstudio-instrumented,suribes/rstudio,nvoron23/rstudio,edrogers/rstudio,jar1karp/rstudio,jar1karp/rstudio,john-r-mcpherson/rstudio,pssguy/rstudio,maligulzar/Rstudio-instrumented,jzhu8803/rstudio,jzhu8803/rstudio,suribes/rstudio,jar1karp/rstudio,edrogers/rstudio,more1/rstudio,maligulzar/Rstudio-instrumented,JanMarvin/rstudio,jrnold/rstudio,pssguy/rstudio,nvoron23/rstudio,piersharding/rstudio,JanMarvin/rstudio,githubfun/rstudio,vbelakov/rstudio,thklaus/rstudio,brsimioni/rstudio,john-r-mcpherson/rstudio,more1/rstudio,nvoron23/rstudio,jar1karp/rstudio,tbarrongh/rstudio,maligulzar/Rstudio-instrumented,jzhu8803/rstudio,githubfun/rstudio,thklaus/rstudio,jar1karp/rstudio,vbelakov/rstudio,pssguy/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,tbarrongh/rstudio,piersharding/rstudio,nvoron23/rstudio,sfloresm/rstudio,thklaus/rstudio,more1/rstudio,edrogers/rstudio,vbelakov/rstudio,pssguy/rstudio,piersharding/rstudio,john-r-mcpherson/rstudio,jzhu8803/rstudio,brsimioni/rstudio,jrnold/rstudio,john-r-mcpherson/rstudio,piersharding/rstudio,vbelakov/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,JanMarvin/rstudio,brsimioni/rstudio,vbelakov/rstudio,tbarrongh/rstudio,jrnold/rstudio,suribes/rstudio,sfloresm/rstudio,brsimioni/rstudio,githubfun/rstudio,sfloresm/rstudio,sfloresm/rstudio,jrnold/rstudio,githubfun/rstudio,john-r-mcpherson/rstudio,githubfun/rstudio,jrnold/rstudio,brsimioni/rstudio,JanMarvin/rstudio,sfloresm/rstudio,thklaus/rstudio,jzhu8803/rstudio,edrogers/rstudio,githubfun/rstudio,brsimioni/rstudio,nvoron23/rstudio,piersharding/rstudio,vbelakov/rstudio,maligulzar/Rstudio-instrumented,nvoron23/rstudio,pssguy/rstudio,piersharding/rstudio,more1/rstudio,thklaus/rstudio,suribes/rstudio,suribes/rstudio,jrnold/rstudio,jar1karp/rstudio,JanMarvin/rstudio,thklaus/rstudio,piersharding/rstudio,jrnold/rstudio,tbarrongh/rstudio,edrogers/rstudio,more1/rstudio,tbarrongh/rstudio,john-r-mcpherson/rstudio,brsimioni/rstudio,sfloresm/rstudio,vbelakov/rstudio,piersharding/rstudio,jar1karp/rstudio,john-r-mcpherson/rstudio,tbarrongh/rstudio,jzhu8803/rstudio,sfloresm/rstudio,vbelakov/rstudio,edrogers/rstudio,tbarrongh/rstudio,brsimioni/rstudio,maligulzar/Rstudio-instrumented,thklaus/rstudio,githubfun/rstudio,piersharding/rstudio,more1/rstudio,pssguy/rstudio,maligulzar/Rstudio-instrumented,jar1karp/rstudio
/* * CompilePdfOutputPresenter.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.output.compilepdf; import com.google.gwt.core.client.JsArray; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.Command; import com.google.inject.Inject; import org.rstudio.core.client.CommandUtil; import org.rstudio.core.client.FilePosition; import org.rstudio.core.client.events.HasEnsureHiddenHandlers; import org.rstudio.core.client.events.HasSelectionCommitHandlers; import org.rstudio.core.client.events.SelectionCommitEvent; import org.rstudio.core.client.events.SelectionCommitHandler; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.widget.MessageDialog; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.workbench.WorkbenchView; import org.rstudio.studio.client.workbench.views.BasePresenter; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfErrorsEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfOutputEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfStatusEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.model.CompilePdfError; import org.rstudio.studio.client.workbench.views.output.compilepdf.model.CompilePdfServerOperations; import org.rstudio.studio.client.workbench.views.output.compilepdf.model.CompilePdfState; public class CompilePdfOutputPresenter extends BasePresenter implements CompilePdfEvent.Handler, CompilePdfOutputEvent.Handler, CompilePdfErrorsEvent.Handler, CompilePdfStatusEvent.Handler { public interface Display extends WorkbenchView, HasEnsureHiddenHandlers { void compileStarted(String text); void showOutput(String output); void showErrors(JsArray<CompilePdfError> errors); void clearAll(); void compileCompleted(); HasClickHandlers stopButton(); HasSelectionCommitHandlers<CompilePdfError> errorList(); } @Inject public CompilePdfOutputPresenter(Display view, GlobalDisplay globalDisplay, CompilePdfServerOperations server, FileTypeRegistry fileTypeRegistry) { super(view); view_ = view; globalDisplay_ = globalDisplay; server_ = server; fileTypeRegistry_ = fileTypeRegistry; view_.stopButton().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { terminateCompilePdf(null); } }); view_.errorList().addSelectionCommitHandler( new SelectionCommitHandler<CompilePdfError>() { @Override public void onSelectionCommit( SelectionCommitEvent<CompilePdfError> event) { CompilePdfError error = event.getSelectedItem(); FileSystemItem fsi = FileSystemItem.createFile(error.getPath()); FilePosition pos = FilePosition.create(error.getLine(), 1); fileTypeRegistry_.editFile(fsi, pos); } }); } public void initialize(CompilePdfState compilePdfState) { // TODO: this should really just ensure that the tab is available // rather than brinning it to the front view_.bringToFront(); view_.clearAll(); view_.compileStarted(compilePdfState.getTargetFile()); view_.showOutput(compilePdfState.getOutput()); if (compilePdfState.getErrors().length() > 0) view_.showErrors(compilePdfState.getErrors()); if (!compilePdfState.isRunning()) view_.compileCompleted(); } public void confirmClose(Command onConfirmed) { // wrap the onConfirmed in another command which notifies the server // that we've closed the tab final Command confirmedCommand = CommandUtil.join(onConfirmed, new Command() { @Override public void execute() { server_.compilePdfClosed(new VoidServerRequestCallback()); } }); server_.isCompilePdfRunning( new RequestCallback<Boolean>("Closing Compile PDF...") { @Override public void onSuccess(Boolean isRunning) { if (isRunning) { confirmTerminateRunningCompile("close the Compile PDF tab", confirmedCommand); } else { confirmedCommand.execute(); } } }); } @Override public void onCompilePdf(CompilePdfEvent event) { view_.bringToFront(); compilePdf(event.getTargetFile(), event.getCompletedAction()); } @Override public void onCompilePdfOutput(CompilePdfOutputEvent event) { view_.showOutput(event.getOutput()); } @Override public void onCompilePdfErrors(CompilePdfErrorsEvent event) { view_.showErrors(event.getErrors()); } @Override public void onCompilePdfStatus(CompilePdfStatusEvent event) { if (event.getStatus() == CompilePdfStatusEvent.STARTED) view_.compileStarted(event.getText()); else if (event.getStatus() == CompilePdfStatusEvent.COMPLETED) view_.compileCompleted(); } private void compilePdf(final FileSystemItem targetFile, final String completedAction) { server_.compilePdf( targetFile, completedAction, new RequestCallback<Boolean>("Compiling PDF...") { @Override protected void onSuccess(Boolean started) { if (started) { view_.clearAll(); } else { confirmTerminateRunningCompile( "start a new compilation", new Command() { @Override public void execute() { compilePdf(targetFile, completedAction); } }); } } }); } private void confirmTerminateRunningCompile(String operation, final Command onTerminated) { globalDisplay_.showYesNoMessage( MessageDialog.WARNING, "Stop Running Compile", "There is a PDF compilation currently running. If you " + operation + " it will be terminated. Are you " + "sure you want to stop the running PDF compilation?", new Operation() { @Override public void execute() { terminateCompilePdf(onTerminated); }}, false); } private void terminateCompilePdf(final Command onTerminated) { server_.terminateCompilePdf(new RequestCallback<Boolean>( "Terminating PDF compilation...") { @Override protected void onSuccess(Boolean wasTerminated) { if (wasTerminated) { if (onTerminated != null) onTerminated.execute(); } else { globalDisplay_.showErrorMessage( "Compile PDF", "Unable to terminate PDF compilation. Please try again."); } } }); } private abstract class RequestCallback<T> extends ServerRequestCallback<T> { public RequestCallback(String progressMessage) { indicator_ = new GlobalProgressDelayer( globalDisplay_, 500, progressMessage).getIndicator(); } @Override public void onResponseReceived(T response) { indicator_.onCompleted(); onSuccess(response); } protected abstract void onSuccess(T response); @Override public void onError(ServerError error) { indicator_.onError(error.getUserMessage()); } private ProgressIndicator indicator_; }; private final Display view_; private final GlobalDisplay globalDisplay_; private final CompilePdfServerOperations server_; private final FileTypeRegistry fileTypeRegistry_; }
src/gwt/src/org/rstudio/studio/client/workbench/views/output/compilepdf/CompilePdfOutputPresenter.java
/* * CompilePdfOutputPresenter.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.output.compilepdf; import com.google.gwt.core.client.JsArray; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.Command; import com.google.inject.Inject; import org.rstudio.core.client.CommandUtil; import org.rstudio.core.client.FilePosition; import org.rstudio.core.client.events.HasEnsureHiddenHandlers; import org.rstudio.core.client.events.HasSelectionCommitHandlers; import org.rstudio.core.client.events.SelectionCommitEvent; import org.rstudio.core.client.events.SelectionCommitHandler; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.widget.MessageDialog; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.GlobalProgressDelayer; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.workbench.WorkbenchView; import org.rstudio.studio.client.workbench.views.BasePresenter; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfErrorsEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfOutputEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfStatusEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.model.CompilePdfError; import org.rstudio.studio.client.workbench.views.output.compilepdf.model.CompilePdfServerOperations; import org.rstudio.studio.client.workbench.views.output.compilepdf.model.CompilePdfState; public class CompilePdfOutputPresenter extends BasePresenter implements CompilePdfEvent.Handler, CompilePdfOutputEvent.Handler, CompilePdfErrorsEvent.Handler, CompilePdfStatusEvent.Handler { public interface Display extends WorkbenchView, HasEnsureHiddenHandlers { void compileStarted(String text); void showOutput(String output); void showErrors(JsArray<CompilePdfError> errors); void clearAll(); void compileCompleted(); HasClickHandlers stopButton(); HasSelectionCommitHandlers<CompilePdfError> errorList(); } @Inject public CompilePdfOutputPresenter(Display view, GlobalDisplay globalDisplay, CompilePdfServerOperations server, FileTypeRegistry fileTypeRegistry) { super(view); view_ = view; globalDisplay_ = globalDisplay; server_ = server; fileTypeRegistry_ = fileTypeRegistry; view_.stopButton().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { terminateCompilePdf(null); } }); view_.errorList().addSelectionCommitHandler( new SelectionCommitHandler<CompilePdfError>() { @Override public void onSelectionCommit( SelectionCommitEvent<CompilePdfError> event) { CompilePdfError error = event.getSelectedItem(); FileSystemItem fsi = FileSystemItem.createFile(error.getPath()); FilePosition pos = FilePosition.create(error.getLine(), 1); fileTypeRegistry_.editFile(fsi, pos); } }); } public void initialize(CompilePdfState compilePdfState) { // TODO: this should really just ensure that the tab is available // rather than brinning it to the front view_.bringToFront(); view_.clearAll(); view_.compileStarted(compilePdfState.getTargetFile()); view_.showOutput(compilePdfState.getOutput()); if (compilePdfState.getErrors().length() > 0) view_.showErrors(compilePdfState.getErrors()); if (!compilePdfState.isRunning()) view_.compileCompleted(); } public void confirmClose(Command onConfirmed) { // wrap the onConfirmed in another command which notifies the server // that we've closed the tab final Command confirmedCommand = CommandUtil.join(onConfirmed, new Command() { @Override public void execute() { server_.compilePdfClosed(new VoidServerRequestCallback()); } }); server_.isCompilePdfRunning( new RequestCallback<Boolean>("Closing Compile PDF...") { @Override public void onSuccess(Boolean isRunning) { if (isRunning) { confirmTerminateRunningCompile("close the Compile PDF tab", confirmedCommand); } else { confirmedCommand.execute(); } } }); } @Override public void onCompilePdf(CompilePdfEvent event) { view_.bringToFront(); compilePdf(event.getTargetFile(), event.getCompletedAction()); } @Override public void onCompilePdfOutput(CompilePdfOutputEvent event) { view_.showOutput(event.getOutput()); } @Override public void onCompilePdfErrors(CompilePdfErrorsEvent event) { view_.showErrors(event.getErrors()); } @Override public void onCompilePdfStatus(CompilePdfStatusEvent event) { if (event.getStatus() == CompilePdfStatusEvent.STARTED) view_.compileStarted(event.getText()); else if (event.getStatus() == CompilePdfStatusEvent.COMPLETED) view_.compileCompleted(); } private void compilePdf(final FileSystemItem targetFile, final String completedAction) { server_.compilePdf( targetFile, completedAction, new RequestCallback<Boolean>("Compiling PDF...") { @Override protected void onSuccess(Boolean started) { if (started) { view_.clearAll(); } else { confirmTerminateRunningCompile( "start a new compilation", new Command() { @Override public void execute() { compilePdf(targetFile, completedAction); } }); } } }); } private void confirmTerminateRunningCompile(String operation, final Command onTerminated) { globalDisplay_.showYesNoMessage( MessageDialog.WARNING, "Stop Running Compile", "There is a PDF compilation currently running. If you " + operation + " it will be terminated. Are you " + "sure you want to stop the running PDF compilation?", new Operation() { @Override public void execute() { terminateCompilePdf(onTerminated); }}, false); } private void terminateCompilePdf(final Command onTerminated) { server_.terminateCompilePdf(new RequestCallback<Boolean>( "Terminating PDF compilation...") { @Override protected void onSuccess(Boolean wasTerminated) { if (wasTerminated && (onTerminated != null)) onTerminated.execute(); } }); } private abstract class RequestCallback<T> extends ServerRequestCallback<T> { public RequestCallback(String progressMessage) { indicator_ = new GlobalProgressDelayer( globalDisplay_, 500, progressMessage).getIndicator(); } @Override public void onResponseReceived(T response) { indicator_.onCompleted(); onSuccess(response); } protected abstract void onSuccess(T response); @Override public void onError(ServerError error) { indicator_.onError(error.getUserMessage()); } private ProgressIndicator indicator_; }; private final Display view_; private final GlobalDisplay globalDisplay_; private final CompilePdfServerOperations server_; private final FileTypeRegistry fileTypeRegistry_; }
show error message if we are unable to terminate a pdf compilation
src/gwt/src/org/rstudio/studio/client/workbench/views/output/compilepdf/CompilePdfOutputPresenter.java
show error message if we are unable to terminate a pdf compilation
<ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/output/compilepdf/CompilePdfOutputPresenter.java <ide> @Override <ide> protected void onSuccess(Boolean wasTerminated) <ide> { <del> if (wasTerminated && (onTerminated != null)) <del> onTerminated.execute(); <add> if (wasTerminated) <add> { <add> if (onTerminated != null) <add> onTerminated.execute(); <add> } <add> else <add> { <add> globalDisplay_.showErrorMessage( <add> "Compile PDF", <add> "Unable to terminate PDF compilation. Please try again."); <add> } <ide> } <ide> }); <ide> }
Java
apache-2.0
b07d93ef940c5be57ea058e478895a76731e5419
0
IvatSan/bigfish
package com.doit.bigfish; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Wellcome to BigFish Application ! - DEV" ); } }
bigfish-app/src/main/java/com/doit/bigfish/App.java
package com.doit.bigfish; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Wellcome to BigFish Application !" ); } }
comit - dev branch
bigfish-app/src/main/java/com/doit/bigfish/App.java
comit - dev branch
<ide><path>igfish-app/src/main/java/com/doit/bigfish/App.java <ide> { <ide> public static void main( String[] args ) <ide> { <del> System.out.println( "Wellcome to BigFish Application !" ); <add> System.out.println( "Wellcome to BigFish Application ! - DEV" ); <ide> } <ide> }
JavaScript
mit
6b73850c33bf9a1e3a7ef9e6f2807a2813bada37
0
fnogatz/tconsole
module.exports = createConsole; module.exports.load = load; module.exports.combine = combine; module.exports.getCellContent = getCellContent; module.exports.insert = insert; module.exports.insert.Array = insertArray; module.exports.insert.Object = insertObject; var Table = require('cli-table'); var requireAll = require('require-all'); function createConsole(objects) { var oldLog = console.log; var konsole = function printObject(input, fields) { var str = toString(objects, input, fields); if (str) { oldLog(str); } else { oldLog(input); } }; // populate methods from console for (var key in console) { konsole[key] = console[key]; } // replace .log() konsole.log = function log() { var args = []; var str; for (var i = 0; i < arguments.length; i++) { str = toString(objects, arguments[i]); if (str) { oldLog(str); } else { args.push(arguments[i]); } } oldLog.apply(this, args); }; // add .toString() konsole.toString = function objectToString(input, fields) { return toString(objects, input, fields); }; // save config konsole._tconsoleConfig = objects; return konsole; } function toString(objects, input, fields) { for (var type in objects) { if (objects[type].test && objects[type].test.call(input)) { fields = fields || objects[type].defaultFields || Object.keys(objects[type].fields); if (fields === '*') fields = Object.keys(objects[type].fields); return fromObject(objects, input, type, fields); } } if (input instanceof Array) { var satisfiesAll = false; var tester; for (var type in objects) { tester = objects[type].test; if (!tester && /^array:/.test(type) && objects[type.replace(/^array:/, '')]) { tester = objects[type.replace(/^array:/, '')].test; } satisfiesAll = input.every(function(row) { return tester.call(row); }); if (satisfiesAll) { if (!fields && objects['array:'+type]) fields = objects['array:'+type].defaultFields || Object.keys(objects['array:'+type].fields); if (!fields) fields = objects[type].defaultFields || Object.keys(objects[type].fields); return fromObject(objects, input, type, fields, true); } } } if (typeof input === 'object') { var satisfiesAll = false; var tester; var keys = Object.keys(input).filter(function(key) { return key[0] !== '_'; }); for (var type in objects) { tester = objects[type].test; if (!tester) { if (/^array:/.test(type) && objects[type.replace(/^array:/, '')]) { tester = objects[type.replace(/^array:/, '')].test; } else { throw new Error('No tester for type '+type); } } satisfiesAll = keys.every(function(key) { return tester.call(input[key]); }); if (satisfiesAll) { if (!fields && objects['array:'+type]) fields = objects['array:'+type].defaultFields || Object.keys(objects['array:'+type].fields); if (!fields) fields = objects[type].defaultFields || Object.keys(objects[type].fields); var arr = keys.map(function(key) { return input[key]; }); return fromObject(objects, arr, type, fields); } } } return false; } function fromObject(objects, input, type, fields) { var fieldNames = fields.map(function(field) { if (typeof field === 'string') return field; if (typeof field === 'object' && field.hasOwnProperty('name')) return field.name; return ''; }); if (input instanceof Array || objects[type].headers) { var colAligns = []; fields.forEach(function(field, ix) { if (typeof field === 'object' && field.align) colAligns[ix] = field.align; }); var headers = objects[type].header ? objects[type].header(fieldNames, input) : fieldNames; var table = new Table({ head: headers, colAligns: colAligns }); } else { // Vertical table var table = new Table(); } if (objects[type].insert) { objects[type].insert.call(input, table, objects[type], fieldNames); } else { if (!objects[type].fields && /^array:/.test(type)) { insert.call(input, table, objects[type.replace(/^array:/, '')], fieldNames); } else { insert.call(input, table, objects[type], fieldNames); } } return table.toString(); } /** * Default renderer.insert function, `this` bound to the input. * @param {Table} table cli-table * @param {Object} object renderer object * @param {Array} fields fields to show */ function insert(table, object, fields) { var input = this; if (input instanceof Array) { insertArray.call(input, table, object, fields); } else { insertObject.call(input, table, object, fields); } } /** * renderer.insert function for rendering arrays, * `this` bound to the input. * @param {Table} table cli-table * @param {Object} object renderer object * @param {Array} fields fields to show */ function insertArray(table, object, fields) { var input = this; input.forEach(function addRow(entry, rowNo) { var tableRow = fields.map(function cell(fieldName) { return getCellContent.call(entry, object.fields[fieldName], rowNo); }); table.push(tableRow); }); } /** * renderer.insert function for rendering objects, * `this` bound to the input. * @param {Table} table cli-table * @param {Object} object renderer object * @param {Array} fields fields to show */ function insertObject(table, object, fields) { var input = this; fields.forEach(function addField(field) { var cells = {}; cells[field] = getCellContent.call(input, object.fields[field]); table.push(cells); }); } /** * Get the content of a cell. `field` is the function or string * to use. `this` should be bound to the actual entry. * Additional parameters are forwarded to the function `field`. * @param {Function|String} field * @return {String} */ function getCellContent(field) { var entry = this; var args = Array.prototype.slice.call(arguments, 1); if (typeof field === 'string') return field; if (typeof field === 'function') { var value; try { value = field.apply(entry, args); } catch (e) { value = '(err)'; } if (value === undefined || value === null) return ''; return value.toString(); } return ''; } /** * Create a console by requiring all renderers in a given * location. * @param {String} location Filesystem path to use with require-all * @return {tconsole} */ function load(location) { var required = requireAll(location); var config = {}; for (var key in required) { config[key.replace(/^array\./, 'array:')] = required[key]; } var konsole = createConsole(config); return konsole; } /** * Combine multiple tconsole instances. * @return {tconsole} */ function combine() { var config = {}; Array.prototype.forEach.call(arguments, function(tconsoleInstance) { mergeObject(config, tconsoleInstance._tconsoleConfig); }); return createConsole(config); } /** * Merge properties of obj2 into obj1. * @param {Object} obj1 * @param {Object} obj2 * @return {Object} */ function mergeObject(obj1, obj2){ for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; } }
index.js
module.exports = createConsole; module.exports.load = load; module.exports.combine = combine; module.exports.getCellContent = getCellContent; module.exports.insert = insert; module.exports.insert.Array = insertArray; module.exports.insert.Object = insertObject; var Table = require('cli-table'); var requireAll = require('require-all'); function createConsole(objects) { var oldLog = console.log; var konsole = function printObject(input, fields) { var str = toString(objects, input, fields); if (str) { oldLog(str); } else { oldLog(input); } }; // populate methods from console for (var key in console) { konsole[key] = console[key]; } // replace .log() konsole.log = function log() { var args = []; var str; for (var i = 0; i < arguments.length; i++) { str = toString(objects, arguments[i]); if (str) { oldLog(str); } else { args.push(arguments[i]); } } oldLog.apply(this, args); }; // add .toString() konsole.toString = function objectToString(input, fields) { return toString(objects, input, fields); }; // save config konsole._tconsoleConfig = objects; return konsole; } function toString(objects, input, fields) { for (var type in objects) { if (objects[type].test && objects[type].test.call(input)) { fields = fields || objects[type].defaultFields || Object.keys(objects[type].fields); if (fields === '*') fields = Object.keys(objects[type].fields); return fromObject(objects, input, type, fields); } } if (input instanceof Array) { var satisfiesAll = false; var tester; for (var type in objects) { tester = objects[type].test; if (!tester && /^array:/.test(type) && objects[type.replace(/^array:/, '')]) { tester = objects[type.replace(/^array:/, '')].test; } satisfiesAll = input.every(function(row) { return tester.call(row); }); if (satisfiesAll) { if (!fields && objects['array:'+type]) fields = objects['array:'+type].defaultFields || Object.keys(objects['array:'+type].fields); if (!fields) fields = objects[type].defaultFields || Object.keys(objects[type].fields); return fromObject(objects, input, type, fields, true); } } } if (typeof input === 'object') { var satisfiesAll = false; var tester; var keys = Object.keys(input).filter(function(key) { return key[0] !== '_'; }); for (var type in objects) { tester = objects[type].test; if (!tester && /^array:/.test(type) && objects[type.replace(/^array:/, '')]) { tester = objects[type.replace(/^array:/, '')].test; } satisfiesAll = keys.every(function(key) { return tester.call(input[key]); }); if (satisfiesAll) { if (!fields && objects['array:'+type]) fields = objects['array:'+type].defaultFields || Object.keys(objects['array:'+type].fields); if (!fields) fields = objects[type].defaultFields || Object.keys(objects[type].fields); var arr = keys.map(function(key) { return input[key]; }); return fromObject(objects, arr, type, fields); } } } return false; } function fromObject(objects, input, type, fields) { var fieldNames = fields.map(function(field) { if (typeof field === 'string') return field; if (typeof field === 'object' && field.hasOwnProperty('name')) return field.name; return ''; }); if (input instanceof Array || objects[type].headers) { var colAligns = []; fields.forEach(function(field, ix) { if (typeof field === 'object' && field.align) colAligns[ix] = field.align; }); var headers = objects[type].header ? objects[type].header(fieldNames, input) : fieldNames; var table = new Table({ head: headers, colAligns: colAligns }); } else { // Vertical table var table = new Table(); } if (objects[type].insert) { objects[type].insert.call(input, table, objects[type], fieldNames); } else { if (!objects[type].fields && /^array:/.test(type)) { insert.call(input, table, objects[type.replace(/^array:/, '')], fieldNames); } else { insert.call(input, table, objects[type], fieldNames); } } return table.toString(); } /** * Default renderer.insert function, `this` bound to the input. * @param {Table} table cli-table * @param {Object} object renderer object * @param {Array} fields fields to show */ function insert(table, object, fields) { var input = this; if (input instanceof Array) { insertArray.call(input, table, object, fields); } else { insertObject.call(input, table, object, fields); } } /** * renderer.insert function for rendering arrays, * `this` bound to the input. * @param {Table} table cli-table * @param {Object} object renderer object * @param {Array} fields fields to show */ function insertArray(table, object, fields) { var input = this; input.forEach(function addRow(entry, rowNo) { var tableRow = fields.map(function cell(fieldName) { return getCellContent.call(entry, object.fields[fieldName], rowNo); }); table.push(tableRow); }); } /** * renderer.insert function for rendering objects, * `this` bound to the input. * @param {Table} table cli-table * @param {Object} object renderer object * @param {Array} fields fields to show */ function insertObject(table, object, fields) { var input = this; fields.forEach(function addField(field) { var cells = {}; cells[field] = getCellContent.call(input, object.fields[field]); table.push(cells); }); } /** * Get the content of a cell. `field` is the function or string * to use. `this` should be bound to the actual entry. * Additional parameters are forwarded to the function `field`. * @param {Function|String} field * @return {String} */ function getCellContent(field) { var entry = this; var args = Array.prototype.slice.call(arguments, 1); if (typeof field === 'string') return field; if (typeof field === 'function') { var value; try { value = field.apply(entry, args); } catch (e) { value = '(err)'; } if (value === undefined || value === null) return ''; return value.toString(); } return ''; } /** * Create a console by requiring all renderers in a given * location. * @param {String} location Filesystem path to use with require-all * @return {tconsole} */ function load(location) { var required = requireAll(location); var config = {}; for (var key in required) { config[key.replace(/^array\./, 'array:')] = required[key]; } var konsole = createConsole(config); return konsole; } /** * Combine multiple tconsole instances. * @return {tconsole} */ function combine() { var config = {}; Array.prototype.forEach.call(arguments, function(tconsoleInstance) { mergeObject(config, tconsoleInstance._tconsoleConfig); }); return createConsole(config); } /** * Merge properties of obj2 into obj1. * @param {Object} obj1 * @param {Object} obj2 * @return {Object} */ function mergeObject(obj1, obj2){ for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; } }
Throw Error for undefined tester
index.js
Throw Error for undefined tester
<ide><path>ndex.js <ide> <ide> for (var type in objects) { <ide> tester = objects[type].test; <del> if (!tester && /^array:/.test(type) && objects[type.replace(/^array:/, '')]) { <del> tester = objects[type.replace(/^array:/, '')].test; <add> if (!tester) { <add> if (/^array:/.test(type) && objects[type.replace(/^array:/, '')]) { <add> tester = objects[type.replace(/^array:/, '')].test; <add> } <add> else { <add> throw new Error('No tester for type '+type); <add> } <ide> } <ide> <ide> satisfiesAll = keys.every(function(key) {
Java
apache-2.0
97895bf0e346cf47b6611c19a6bc6a9d604eaaed
0
monkeymq/jgossip
// Copyright (c) 2017 The jgossip Authors. 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 net.lvsq.jgossip.handler; import io.vertx.core.json.JsonObject; import net.lvsq.jgossip.core.GossipManager; import net.lvsq.jgossip.model.GossipMember; /** * @author lvsq */ public class ShutdownMessageHandler implements MessageHandler { @Override public void handle(String cluster, String data, String from) { JsonObject dj = new JsonObject(data); GossipMember whoShutdown = dj.mapTo(GossipMember.class); if (whoShutdown != null) { GossipManager.getInstance().down(whoShutdown); } } }
src/main/java/net/lvsq/jgossip/handler/ShutdownMessageHandler.java
package net.lvsq.jgossip.handler; import io.vertx.core.json.JsonObject; import net.lvsq.jgossip.core.GossipManager; import net.lvsq.jgossip.model.GossipMember; /** * Created by silv on 7/31/2017. */ public class ShutdownMessageHandler implements MessageHandler { @Override public void handle(String cluster, String data, String from) { JsonObject dj = new JsonObject(data); GossipMember whoShutdown = dj.mapTo(GossipMember.class); if (whoShutdown != null) { GossipManager.getInstance().down(whoShutdown); } } }
Update ShutdownMessageHandler.java
src/main/java/net/lvsq/jgossip/handler/ShutdownMessageHandler.java
Update ShutdownMessageHandler.java
<ide><path>rc/main/java/net/lvsq/jgossip/handler/ShutdownMessageHandler.java <add>// Copyright (c) 2017 The jgossip Authors. All rights reserved. <add>// <add>// Licensed under the Apache License, Version 2.0 (the "License"); <add>// you may not use this file except in compliance with the License. <add>// You may obtain a copy of the License at <add>// <add>// http://www.apache.org/licenses/LICENSE-2.0 <add>// <add>// Unless required by applicable law or agreed to in writing, software <add>// distributed under the License is distributed on an "AS IS" BASIS, <add>// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add>// See the License for the specific language governing permissions and <add>// limitations under the License. <add> <ide> package net.lvsq.jgossip.handler; <ide> <ide> import io.vertx.core.json.JsonObject; <ide> import net.lvsq.jgossip.model.GossipMember; <ide> <ide> /** <del> * Created by silv on 7/31/2017. <add> * @author lvsq <ide> */ <ide> public class ShutdownMessageHandler implements MessageHandler { <ide> @Override
Java
apache-2.0
37ce79e3ca871d06667fe40f80dc4af0b8b4d5e0
0
mizdebsk/xmvn,fedora-java/xmvn,fedora-java/xmvn,mizdebsk/xmvn,mizdebsk/xmvn,mizdebsk/xmvn,rvais/xmvn,rvais/xmvn,rvais/xmvn,rvais/xmvn,fedora-java/xmvn
/*- * Copyright (c) 2014 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fedoraproject.xmvn.tools.install.condition; import java.util.ArrayList; import java.util.List; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.fedoraproject.xmvn.repository.ArtifactContext; /** * @author Mikolaj Izdebski */ public class Condition { private final BooleanExpression expr; private void requireText( Xpp3Dom dom, boolean require ) { String name = dom.getName(); if ( require && ( dom.getChildCount() != 0 || dom.getValue() == null ) ) throw new RuntimeException( "XML node " + name + " must have text content." ); if ( !require && StringUtils.isNotEmpty( dom.getValue() ) ) throw new RuntimeException( "XML node " + name + " doesn't allow text content." ); } private void requireChildreen( Xpp3Dom dom, int n ) { if ( dom.getChildCount() == n ) return; String name = dom.getName(); if ( n == 0 ) throw new RuntimeException( "XML node " + name + " doesn't allow any childreen." ); if ( n == 1 ) throw new RuntimeException( "XML node " + name + " requires exactly one child node." ); throw new RuntimeException( "XML node " + name + " must have exactly " + n + " childreen." ); } private StringExpression parseString( Xpp3Dom dom ) { switch ( dom.getName() ) { case "groupId": requireText( dom, false ); requireChildreen( dom, 0 ); return new GroupId(); case "artifactId": requireText( dom, false ); requireChildreen( dom, 0 ); return new ArtifactId(); case "extension": requireText( dom, false ); requireChildreen( dom, 0 ); return new Extension(); case "classifier": requireText( dom, false ); requireChildreen( dom, 0 ); return new Classifier(); case "version": requireText( dom, false ); requireChildreen( dom, 0 ); return new Version(); case "string": requireText( dom, true ); requireChildreen( dom, 0 ); return new StringLiteral( dom.getValue() ); case "property": requireText( dom, true ); requireChildreen( dom, 0 ); return new Property( dom.getValue() ); case "null": requireText( dom, false ); requireChildreen( dom, 0 ); return new Null(); default: throw new RuntimeException( "Unable to parse string expression: unknown XML node name: " + dom.getName() ); } } private BooleanExpression parseBoolean( Xpp3Dom dom ) { switch ( dom.getName() ) { case "true": requireText( dom, false ); requireChildreen( dom, 0 ); return new BooleanLiteral( true ); case "false": requireText( dom, false ); requireChildreen( dom, 0 ); return new BooleanLiteral( true ); case "not": requireText( dom, false ); requireChildreen( dom, 1 ); return new Not( parseBoolean( dom.getChild( 0 ) ) ); case "and": requireText( dom, false ); return new And( parseBooleans( dom.getChildren() ) ); case "or": requireText( dom, false ); return new Or( parseBooleans( dom.getChildren() ) ); case "xor": requireText( dom, false ); return new Xor( parseBooleans( dom.getChildren() ) ); case "equals": requireText( dom, false ); requireChildreen( dom, 2 ); return new Equals( parseString( dom.getChild( 0 ) ), parseString( dom.getChild( 1 ) ) ); case "defined": requireText( dom, true ); requireChildreen( dom, 0 ); return new Defined( dom.getValue() ); default: throw new RuntimeException( "Unable to parse string expression: unknown XML node name: " + dom.getName() ); } } private List<BooleanExpression> parseBooleans( Xpp3Dom[] doms ) { List<BooleanExpression> result = new ArrayList<>(); for ( Xpp3Dom dom : doms ) { result.add( parseBoolean( dom ) ); } return result; } public Condition( Xpp3Dom dom ) { if ( dom == null ) { dom = new Xpp3Dom( "condition" ); dom.addChild( new Xpp3Dom( "true" ) ); } requireChildreen( dom, 1 ); this.expr = parseBoolean( dom.getChild( 0 ) ); } public boolean getValue( ArtifactContext context ) { return expr.getValue( context ); } }
xmvn-tools/xmvn-install/src/main/java/org/fedoraproject/xmvn/tools/install/condition/Condition.java
/*- * Copyright (c) 2014 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fedoraproject.xmvn.tools.install.condition; import java.util.ArrayList; import java.util.List; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.fedoraproject.xmvn.repository.ArtifactContext; /** * @author Mikolaj Izdebski */ public class Condition { private final BooleanExpression expr; private void requireText( Xpp3Dom dom, boolean require ) { if ( require == ( dom.getValue() != null ) ) return; String name = dom.getName(); if ( require ) throw new RuntimeException( "XML node " + name + " must have text content." ); throw new RuntimeException( "XML node " + name + " doesn't allow text content." ); } private void requireChildreen( Xpp3Dom dom, int n ) { if ( dom.getChildCount() == n ) return; String name = dom.getName(); if ( n == 0 ) throw new RuntimeException( "XML node " + name + " doesn't allow any childreen." ); if ( n == 1 ) throw new RuntimeException( "XML node " + name + " requires exactly one child node." ); throw new RuntimeException( "XML node " + name + " must have exactly " + n + " childreen." ); } private StringExpression parseString( Xpp3Dom dom ) { switch ( dom.getName() ) { case "groupId": requireText( dom, false ); requireChildreen( dom, 0 ); return new GroupId(); case "artifactId": requireText( dom, false ); requireChildreen( dom, 0 ); return new ArtifactId(); case "extension": requireText( dom, false ); requireChildreen( dom, 0 ); return new Extension(); case "classifier": requireText( dom, false ); requireChildreen( dom, 0 ); return new Classifier(); case "version": requireText( dom, false ); requireChildreen( dom, 0 ); return new Version(); case "string": requireText( dom, true ); requireChildreen( dom, 0 ); return new StringLiteral( dom.getValue() ); case "property": requireText( dom, true ); requireChildreen( dom, 0 ); return new Property( dom.getValue() ); case "null": requireText( dom, false ); requireChildreen( dom, 0 ); return new Null(); default: throw new RuntimeException( "Unable to parse string expression: unknown XML node name: " + dom.getName() ); } } private BooleanExpression parseBoolean( Xpp3Dom dom ) { switch ( dom.getName() ) { case "true": requireText( dom, false ); requireChildreen( dom, 0 ); return new BooleanLiteral( true ); case "false": requireText( dom, false ); requireChildreen( dom, 0 ); return new BooleanLiteral( true ); case "not": requireText( dom, false ); requireChildreen( dom, 1 ); return new Not( parseBoolean( dom.getChild( 0 ) ) ); case "and": requireText( dom, false ); return new And( parseBooleans( dom.getChildren() ) ); case "or": requireText( dom, false ); return new Or( parseBooleans( dom.getChildren() ) ); case "xor": requireText( dom, false ); return new Xor( parseBooleans( dom.getChildren() ) ); case "equals": requireText( dom, false ); requireChildreen( dom, 2 ); return new Equals( parseString( dom.getChild( 0 ) ), parseString( dom.getChild( 1 ) ) ); case "defined": requireText( dom, true ); requireChildreen( dom, 0 ); return new Defined( dom.getValue() ); default: throw new RuntimeException( "Unable to parse string expression: unknown XML node name: " + dom.getName() ); } } private List<BooleanExpression> parseBooleans( Xpp3Dom[] doms ) { List<BooleanExpression> result = new ArrayList<>(); for ( Xpp3Dom dom : doms ) { result.add( parseBoolean( dom ) ); } return result; } public Condition( Xpp3Dom dom ) { if ( dom == null ) { dom = new Xpp3Dom( "condition" ); dom.addChild( new Xpp3Dom( "true" ) ); } requireChildreen( dom, 1 ); this.expr = parseBoolean( dom.getChild( 0 ) ); } public boolean getValue( ArtifactContext context ) { return expr.getValue( context ); } }
Rework checks for empty XML text
xmvn-tools/xmvn-install/src/main/java/org/fedoraproject/xmvn/tools/install/condition/Condition.java
Rework checks for empty XML text
<ide><path>mvn-tools/xmvn-install/src/main/java/org/fedoraproject/xmvn/tools/install/condition/Condition.java <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> <add>import org.codehaus.plexus.util.StringUtils; <ide> import org.codehaus.plexus.util.xml.Xpp3Dom; <ide> <ide> import org.fedoraproject.xmvn.repository.ArtifactContext; <ide> <ide> private void requireText( Xpp3Dom dom, boolean require ) <ide> { <del> if ( require == ( dom.getValue() != null ) ) <del> return; <del> <ide> String name = dom.getName(); <ide> <del> if ( require ) <add> if ( require && ( dom.getChildCount() != 0 || dom.getValue() == null ) ) <ide> throw new RuntimeException( "XML node " + name + " must have text content." ); <ide> <del> throw new RuntimeException( "XML node " + name + " doesn't allow text content." ); <add> if ( !require && StringUtils.isNotEmpty( dom.getValue() ) ) <add> throw new RuntimeException( "XML node " + name + " doesn't allow text content." ); <ide> } <ide> <ide> private void requireChildreen( Xpp3Dom dom, int n )
Java
lgpl-2.1
31287d8e896fc5548e37530b3ccc12e9ad8acd14
0
ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,jbarriosc/ACSUFRO,csrg-utfsm/acscb,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO
/* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2004 * Copyright by ESO (in the framework of the ALMA collaboration), * All rights reserved * * 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 */ package alma.acs.classloading; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** * Helps sort a list of jar files so that more important jar files appear first. * The more important jar files are listed in {@link #orderedAcsJarNames} and optionally also * in the property <code>acs.system.classpath.appltopjars</code>. * <p> * The classloader will then not have to read through unimportant jar files first, * which should improve class loading performance on IO-challenged machines. * * @author hsommer * created Sep 21, 2004 2:28:51 PM */ public class JarOrderOptimizer implements Comparator<File> { private boolean verbose = false; public static final String PROPERTY_APPLICATION_TOPJARS = "acs.system.classpath.appltopjars"; /** * Hardcoded list of jar files that are sufficient to start an ACS container or other basic ACS software. * The class loader will sort these jar files toward the beginning of the classpath (in the given order), * and will append jar files from the optional property <code>acs.system.classpath.appltopjars</code>. */ public static final String[] orderedAcsJarNames = { "jcont.jar", "jACSUtil.jar", "acsjlog.jar", "maci.jar", "jacorb.jar", "acscomponent.jar", "jmanager.jar", "cdbDAL.jar", "cdbErrType.jar", "archive_xmlstore_if.jar", "xmlentity.jar", "systementities.jar", "acserr.jar", "acserrj.jar", "acsnc.jar", "baci.jar", // "xercesImpl.jar", currently separate, location defined by -Djava.endorsed.dirs=... "xmljbind.jar", "junit.jar", "oe.jar", "abeansR2Components.jar", "acscommandcenter.jar", "AcsCommandCenterEntities.jar", "lc.jar", // cosylab logging client "jdom.jar", "acsASsources.jar", "acsErrTypeAlarmSourceFactory.jar" }; /** * key = (String) jarname, value = (Integer) position. */ private Map<String, Integer> topJarMap; JarOrderOptimizer(boolean verbose) { this.verbose = verbose; // use a map for more efficient lookup of jarfile names topJarMap = new HashMap<String, Integer>(); int i = 0; for (i = 0; i < orderedAcsJarNames.length; i++) { topJarMap.put(orderedAcsJarNames[i], new Integer(i)); } String applJarPath = System.getProperty(PROPERTY_APPLICATION_TOPJARS); if (applJarPath != null) { String[] applJarNames = parseJarNames(applJarPath); for (int j=0; j < applJarNames.length; j++) { if (!topJarMap.containsKey(applJarNames[j])) { topJarMap.put(applJarNames[j], new Integer(i+j)); } } } // if (verbose) { // for (Iterator iter = topJarMap.keySet().iterator(); iter.hasNext();) { // String jarName = (String) iter.next(); // Integer pos = topJarMap.get(jarName); // System.out.print(pos.toString() + "-" + jarName + " "); // } // System.out.println(); // } } public int compare(File f1, File f2) { int ret = 0; if (f1 == null || f2 == null) { // todo: check if this can happen throw new NullPointerException("bad null arg"); } String n1 = f1.getName(); String n2 = f2.getName(); Integer i1 = topJarMap.get(n1); Integer i2 = topJarMap.get(n2); if (i1 != null) { if (i2 != null) { ret = i1.compareTo(i2); } else { ret = -1; } } else { if (i2 != null) { ret = 1; } else { // both not in list -- need to find some sorting criterium, why not alphabetically return n1.compareTo(n2); } } return ret; } /** * Sorts <code>jars</code> using {@link #compare(Object, Object)}. * @see Arrays#sort(java.lang.Object[], java.util.Comparator) */ void sortJars(List<File> jarlist) { Collections.sort(jarlist, this); } /** * To be used for testing only -- allows to filter out all jar files from a list which are not * given priority by the <code>compare</code> method of this class. * This allows to write tests that will fail unless all required classes are listed explicitly. * @param allJars jar files to be filtered * @return those whose name matches one from the prio list */ List<File> getTopJarsOnly(List<File> allJars) { List<File> topJars = new ArrayList<File>(); for (Iterator<File> iter = allJars.iterator(); iter.hasNext();) { File jarfile = iter.next(); if (topJarMap.containsKey(jarfile.getName())) { topJars.add(jarfile); } } return topJars; } /** * Parses a string of concatenated jar file names. * For example, the string "ab:cd.jar:ef" should yield {"ab.jar", "cd.jar", "ef.jar"}. */ private String[] parseJarNames(String jarNamePath) { StringTokenizer tok = new StringTokenizer(jarNamePath, ":" + File.pathSeparatorChar); // to also allow platform style separator List jarNameList = new ArrayList(); for (int i = 0; tok.hasMoreTokens(); i++) { String jarName = tok.nextToken(); if (jarName != null && jarName.trim().length() > 0) { jarName = jarName.trim(); if (!jarName.toLowerCase().endsWith(".jar")) { jarName += ".jar"; } jarNameList.add(jarName); } } return (String[]) jarNameList.toArray(new String[jarNameList.size()]); } /** * Checks if a class comes from any of the subpackages of <code>sun.</code> or <code>com.sun.</code> * which we strongly assume to not be contained in any jar files that our classloaders have to deal with. * These classes should either be loaded by the real system class loader, and when it fails, we assume that they * don't exist anywhere so we can skip searching for them. * @param name * @return */ boolean isClassKnownToBeUnavailable(String name) { return (name.startsWith("sun.util.logging.") || name.startsWith("sun.text.resources.") || name.startsWith("sun.awt.resources.") || name.startsWith("com.sun.swing.internal.plaf.") ); } }
LGPL/CommonSoftware/jacsutil/src/alma/acs/classloading/JarOrderOptimizer.java
/* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2004 * Copyright by ESO (in the framework of the ALMA collaboration), * All rights reserved * * 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 */ package alma.acs.classloading; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; /** * Helps sort a list of jar files so that more important jar files appear first. * The more important jar files are listed in {@link #orderedAcsJarNames} and optionally also * in the property <code>acs.system.classpath.appltopjars</code>. * <p> * The classloader will then not have to read through unimportant jar files first, * which should improve class loading performance on IO-challenged machines. * * @author hsommer * created Sep 21, 2004 2:28:51 PM */ public class JarOrderOptimizer implements Comparator<File> { private boolean verbose = false; public static final String PROPERTY_APPLICATION_TOPJARS = "acs.system.classpath.appltopjars"; /** * Hardcoded list of jar files that are sufficient to start an ACS container or other basic ACS software. * The class loader will sort these jar files toward the beginning of the classpath (in the given order), * and will append jar files from the optional property <code>acs.system.classpath.appltopjars</code>. */ public static final String[] orderedAcsJarNames = { "jcont.jar", "jACSUtil.jar", "acsjlog.jar", "maci.jar", "jacorb.jar", "acscomponent.jar", "jmanager.jar", "cdbDAL.jar", "archive_xmlstore_if.jar", "xmlentity.jar", "systementities.jar", "acserr.jar", "acserrj.jar", "cdbErrType.jar", "acsnc.jar", "baci.jar", // "xercesImpl.jar", currently separate, location defined by -Djava.endorsed.dirs=... "xmljbind.jar", "junit.jar", "oe.jar", "abeansR2Components.jar", "acscommandcenter.jar", "AcsCommandCenterEntities.jar", "lc.jar", // cosylab logging client "jdom.jar" }; /** * key = (String) jarname, value = (Integer) position. */ private Map<String, Integer> topJarMap; JarOrderOptimizer(boolean verbose) { this.verbose = verbose; // use a map for more efficient lookup of jarfile names topJarMap = new HashMap<String, Integer>(); int i = 0; for (i = 0; i < orderedAcsJarNames.length; i++) { topJarMap.put(orderedAcsJarNames[i], new Integer(i)); } String applJarPath = System.getProperty(PROPERTY_APPLICATION_TOPJARS); if (applJarPath != null) { String[] applJarNames = parseJarNames(applJarPath); for (int j=0; j < applJarNames.length; j++) { if (!topJarMap.containsKey(applJarNames[j])) { topJarMap.put(applJarNames[j], new Integer(i+j)); } } } // if (verbose) { // for (Iterator iter = topJarMap.keySet().iterator(); iter.hasNext();) { // String jarName = (String) iter.next(); // Integer pos = topJarMap.get(jarName); // System.out.print(pos.toString() + "-" + jarName + " "); // } // System.out.println(); // } } public int compare(File f1, File f2) { int ret = 0; if (f1 == null || f2 == null) { // todo: check if this can happen throw new NullPointerException("bad null arg"); } String n1 = f1.getName(); String n2 = f2.getName(); Integer i1 = topJarMap.get(n1); Integer i2 = topJarMap.get(n2); if (i1 != null) { if (i2 != null) { ret = i1.compareTo(i2); } else { ret = -1; } } else { if (i2 != null) { ret = 1; } else { // both not in list -- need to find some sorting criterium, why not alphabetically return n1.compareTo(n2); } } return ret; } /** * Sorts <code>jars</code> using {@link #compare(Object, Object)}. * @see Arrays#sort(java.lang.Object[], java.util.Comparator) */ void sortJars(List<File> jarlist) { Collections.sort(jarlist, this); } /** * To be used for testing only -- allows to filter out all jar files from a list which are not * given priority by the <code>compare</code> method of this class. * This allows to write tests that will fail unless all required classes are listed explicitly. * @param allJars jar files to be filtered * @return those whose name matches one from the prio list */ List<File> getTopJarsOnly(List<File> allJars) { List<File> topJars = new ArrayList<File>(); for (Iterator<File> iter = allJars.iterator(); iter.hasNext();) { File jarfile = iter.next(); if (topJarMap.containsKey(jarfile.getName())) { topJars.add(jarfile); } } return topJars; } /** * Parses a string of concatenated jar file names. * For example, the string "ab:cd.jar:ef" should yield {"ab.jar", "cd.jar", "ef.jar"}. */ private String[] parseJarNames(String jarNamePath) { StringTokenizer tok = new StringTokenizer(jarNamePath, ":" + File.pathSeparatorChar); // to also allow platform style separator List jarNameList = new ArrayList(); for (int i = 0; tok.hasMoreTokens(); i++) { String jarName = tok.nextToken(); if (jarName != null && jarName.trim().length() > 0) { jarName = jarName.trim(); if (!jarName.toLowerCase().endsWith(".jar")) { jarName += ".jar"; } jarNameList.add(jarName); } } return (String[]) jarNameList.toArray(new String[jarNameList.size()]); } /** * Checks if a class comes from any of the subpackages of <code>sun.</code> or <code>com.sun.</code> * which we strongly assume to not be contained in any jar files that our classloaders have to deal with. * These classes should either be loaded by the real system class loader, and when it fails, we assume that they * don't exist anywhere so we can skip searching for them. * @param name * @return */ boolean isClassKnownToBeUnavailable(String name) { return (name.startsWith("sun.util.logging.") || name.startsWith("sun.text.resources.") || name.startsWith("sun.awt.resources.") || name.startsWith("com.sun.swing.internal.plaf.") ); } }
added jars for alarm system initialization at container start to the top-jars-list git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@59358 523d945c-050c-4681-91ec-863ad3bb968a
LGPL/CommonSoftware/jacsutil/src/alma/acs/classloading/JarOrderOptimizer.java
added jars for alarm system initialization at container start to the top-jars-list
<ide><path>GPL/CommonSoftware/jacsutil/src/alma/acs/classloading/JarOrderOptimizer.java <ide> "acscomponent.jar", <ide> "jmanager.jar", <ide> "cdbDAL.jar", <add> "cdbErrType.jar", <ide> "archive_xmlstore_if.jar", <ide> "xmlentity.jar", <ide> "systementities.jar", <ide> "acserr.jar", <ide> "acserrj.jar", <del> "cdbErrType.jar", <ide> "acsnc.jar", <ide> "baci.jar", <ide> // "xercesImpl.jar", currently separate, location defined by -Djava.endorsed.dirs=... <ide> "acscommandcenter.jar", <ide> "AcsCommandCenterEntities.jar", <ide> "lc.jar", // cosylab logging client <del> "jdom.jar" <add> "jdom.jar", <add> "acsASsources.jar", <add> "acsErrTypeAlarmSourceFactory.jar" <ide> }; <ide> <ide> /**
Java
mit
cd801fc3e9ceaaa79fcba17926bab6c225988c63
0
sunnydas/grokkingalgos,sunnydas/grokkingalgos
package com.sunny.grokkingalgorithms.basic_2020.warmup; public class CoinChange { /* * Given a value V, if we want to make a change for V Rs, and we have an infinite supply of each of the denominations in Indian currency, i.e., we have an infinite supply of { 1, 2, 5, 10, 20, 50, 100, 500, 1000} valued coins/notes, what is the minimum number of coins and/or notes needed to make the change? Examples: Input: V = 70 Output: 2 We need a 50 Rs note and a 20 Rs note. Input: V = 121 Output: 3 We need a 100 Rs note, a 20 Rs note and a 1 Rs coin. */ public static int coinChange(int[] coins,int v) { int[] cache = new int[v+1]; for(int i = 1; i < cache.length ; i++) { cache[i] = Integer.MAX_VALUE; } for(int i = 1; i <= v ; i++) { for(int j = 0 ; j < coins.length ; j++) { if(coins[j] <= i) { int result = cache[i - coins[j]]; if(result != Integer.MAX_VALUE) { cache[i] = Math.min(cache[i], result + 1); } } } } return cache[v]; } public static int coinChangeAlt(int[] coins,int v) { if(v <= 0) { return 0; } int minChange = Integer.MAX_VALUE; for(int i = 0 ; i < coins.length ; i++) { if(coins[i] <= v) { int res = coinChange(v - coins[i]); if(res != Integer.MAX_VALUE) { System.out.println(res); minChange = Math.min(res + 1, minChange); } } } return minChange; } public static int coinChange(int v) { int minChanges = 0; int[] denominations = new int[] {1,2,5,10,20,50,100,500,1000}; int start = denominations.length - 1; while(v > 0) { int index = findHighestValueThatFulFillsCriteria(v, denominations,start); if(index >= 0) { //System.out.println(denominations[index]); v -= denominations[index]; minChanges++; start = index; } } return minChanges; } public static int findHighestValueThatFulFillsCriteria(int v,int[] denoms,int start) { int index = -1; for(int i = start; i >= 0 ; i--) { if(denoms[i] <= v) { index = i; break; } } return index; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(coinChange(70)); System.out.println(coinChange(121)); System.out.println(coinChange(93)); int coins[] = {9, 6, 5, 1}; int v = 11; System.out.println(coinChange(coins, v)); coins = new int[]{25,10,5}; v = 30; System.out.println(coinChange(coins,v)); } }
src/main/java/com/sunny/grokkingalgorithms/basic_2020/warmup/CoinChange.java
package com.sunny.grokkingalgorithms.basic_2020.warmup; public class CoinChange { /* * Given a value V, if we want to make a change for V Rs, and we have an infinite supply of each of the denominations in Indian currency, i.e., we have an infinite supply of { 1, 2, 5, 10, 20, 50, 100, 500, 1000} valued coins/notes, what is the minimum number of coins and/or notes needed to make the change? Examples: Input: V = 70 Output: 2 We need a 50 Rs note and a 20 Rs note. Input: V = 121 Output: 3 We need a 100 Rs note, a 20 Rs note and a 1 Rs coin. */ public static int coinChange(int[] coins,int v) { if(v <= 0) { return 0; } int minChange = Integer.MAX_VALUE; for(int i = 0 ; i < coins.length ; i++) { if(coins[i] <= v) { int res = coinChange(v - coins[i]); if(res != Integer.MAX_VALUE) { System.out.println(res); minChange = Math.min(res + 1, minChange); } } } return minChange; } public static int coinChange(int v) { int minChanges = 0; int[] denominations = new int[] {1,2,5,10,20,50,100,500,1000}; int start = denominations.length - 1; while(v > 0) { int index = findHighestValueThatFulFillsCriteria(v, denominations,start); if(index >= 0) { //System.out.println(denominations[index]); v -= denominations[index]; minChanges++; start = index; } } return minChanges; } public static int findHighestValueThatFulFillsCriteria(int v,int[] denoms,int start) { int index = -1; for(int i = start; i >= 0 ; i--) { if(denoms[i] <= v) { index = i; break; } } return index; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(coinChange(70)); System.out.println(coinChange(121)); System.out.println(coinChange(93)); int coins[] = {9, 6, 5, 1}; int v = 11; System.out.println(coinChange(coins, v)); coins = new int[]{25,10,5}; v = 30; System.out.println(coinChange(coins,v)); } }
Coin change dp based.`
src/main/java/com/sunny/grokkingalgorithms/basic_2020/warmup/CoinChange.java
Coin change dp based.`
<ide><path>rc/main/java/com/sunny/grokkingalgorithms/basic_2020/warmup/CoinChange.java <ide> */ <ide> <ide> public static int coinChange(int[] coins,int v) { <add> int[] cache = new int[v+1]; <add> for(int i = 1; i < cache.length ; i++) { <add> cache[i] = Integer.MAX_VALUE; <add> } <add> for(int i = 1; i <= v ; i++) { <add> for(int j = 0 ; j < coins.length ; j++) { <add> if(coins[j] <= i) { <add> int result = cache[i - coins[j]]; <add> if(result != Integer.MAX_VALUE) { <add> cache[i] = Math.min(cache[i], result + 1); <add> } <add> } <add> } <add> } <add> return cache[v]; <add> } <add> <add> public static int coinChangeAlt(int[] coins,int v) { <ide> if(v <= 0) { <ide> return 0; <ide> }
Java
apache-2.0
2dc6e94a950688b6cbf5a66c9d89b4c010b6fd32
0
electrum/presto,mpilman/presto,11xor6/presto,DanielTing/presto,kietly/presto,mugglmenzel/presto,Zoomdata/presto,Svjard/presto,aramesh117/presto,xiangel/presto,y-lan/presto,soz-fb/presto,erichwang/presto,cawallin/presto,ebyhr/presto,elonazoulay/presto,pwz3n0/presto,erichwang/presto,mbeitchman/presto,miquelruiz/presto,jiekechoo/presto,denizdemir/presto,DanielTing/presto,elonazoulay/presto,miniway/presto,fiedukow/presto,Yaliang/presto,fipar/presto,jf367/presto,kaschaeffer/presto,toyama0919/presto,wrmsr/presto,bloomberg/presto,elonazoulay/presto,springning/presto,toxeh/presto,smartpcr/presto,dongjoon-hyun/presto,arhimondr/presto,dongjoon-hyun/presto,geraint0923/presto,ipros-team/presto,joy-yao/presto,mpilman/presto,avasilevskiy/presto,facebook/presto,fiedukow/presto,prateek1306/presto,tomz/presto,kaschaeffer/presto,Jimexist/presto,11xor6/presto,mbeitchman/presto,gcnonato/presto,idemura/presto,pwz3n0/presto,damiencarol/presto,siddhartharay007/presto,troels/nz-presto,troels/nz-presto,hgschmie/presto,miquelruiz/presto,totticarter/presto,smartpcr/presto,tomz/presto,jf367/presto,treasure-data/presto,haitaoyao/presto,y-lan/presto,Jimexist/presto,fipar/presto,dongjoon-hyun/presto,fipar/presto,prateek1306/presto,Zoomdata/presto,sopel39/presto,cawallin/presto,yu-yamada/presto,tellproject/presto,mpilman/presto,wyukawa/presto,prestodb/presto,soz-fb/presto,mvp/presto,takari/presto,kined/presto,cberner/presto,tellproject/presto,EvilMcJerkface/presto,zofuthan/presto,rockerbox/presto,takari/presto,martint/presto,nileema/presto,stewartpark/presto,TeradataCenterForHadoop/bootcamp,hulu/presto,mcanthony/presto,ebd2/presto,gh351135612/presto,geraint0923/presto,gcnonato/presto,joshk/presto,pnowojski/presto,nvoron23/presto,damiencarol/presto,Svjard/presto,facebook/presto,vermaravikant/presto,dain/presto,jekey/presto,dabaitu/presto,ajoabraham/presto,fengshao0907/presto,zjshen/presto,albertocsm/presto,stewartpark/presto,fengshao0907/presto,vermaravikant/presto,mode/presto,sumanth232/presto,xiangel/presto,nezihyigitbasi/presto,miquelruiz/presto,suyucs/presto,mode/presto,XiaominZhang/presto,tellproject/presto,sopel39/presto,wagnermarkd/presto,fengshao0907/presto,haozhun/presto,dongjoon-hyun/presto,smartnews/presto,springning/presto,tomz/presto,cawallin/presto,shubham166/presto,nakajijiji/presto,arhimondr/presto,CHINA-JD/presto,kingland/presto,dain/presto,nileema/presto,svstanev/presto,erichwang/presto,Myrthan/presto,suyucs/presto,kuzemchik/presto,springning/presto,mvp/presto,martint/presto,nakajijiji/presto,shubham166/presto,saidalaoui/presto,geraint0923/presto,lingochamp/presto,haozhun/presto,jxiang/presto,svstanev/presto,deciament/presto,nezihyigitbasi/presto,zhenxiao/presto,saidalaoui/presto,sunchao/presto,ebd2/presto,haozhun/presto,twitter-forks/presto,saidalaoui/presto,wrmsr/presto,wagnermarkd/presto,cberner/presto,geraint0923/presto,jekey/presto,propene/presto,cosinequanon/presto,miniway/presto,shixuan-fan/presto,Yaliang/presto,nsabharwal/presto,zzhao0/presto,jf367/presto,smartnews/presto,suyucs/presto,zofuthan/presto,mcanthony/presto,siddhartharay007/presto,xiangel/presto,joshk/presto,RobinUS2/presto,idemura/presto,deciament/presto,jiekechoo/presto,mvp/presto,pnowojski/presto,cberner/presto,aramesh117/presto,sunchao/presto,mono-plane/presto,deciament/presto,pwz3n0/presto,zzhao0/presto,electrum/presto,kietly/presto,chrisunder/presto,ptkool/presto,kined/presto,losipiuk/presto,wrmsr/presto,prestodb/presto,propene/presto,ipros-team/presto,ArturGajowy/presto,jiangyifangh/presto,tellproject/presto,sumitkgec/presto,DanielTing/presto,nsabharwal/presto,joy-yao/presto,youngwookim/presto,toxeh/presto,TeradataCenterForHadoop/bootcamp,bloomberg/presto,kined/presto,rockerbox/presto,jxiang/presto,aglne/presto,harunurhan/presto,suyucs/presto,sunchao/presto,fengshao0907/presto,denizdemir/presto,kuzemchik/presto,jekey/presto,mattyb149/presto,bloomberg/presto,harunurhan/presto,hulu/presto,ipros-team/presto,electrum/presto,albertocsm/presto,youngwookim/presto,DanielTing/presto,gh351135612/presto,shixuan-fan/presto,11xor6/presto,raghavsethi/presto,mugglmenzel/presto,sumitkgec/presto,jxiang/presto,haozhun/presto,mono-plane/presto,denizdemir/presto,joy-yao/presto,hulu/presto,ArturGajowy/presto,wagnermarkd/presto,hgschmie/presto,tellproject/presto,damiencarol/presto,prateek1306/presto,CHINA-JD/presto,dongjoon-hyun/presto,jacobgao/presto,ajoabraham/presto,erichwang/presto,joshk/presto,yuananf/presto,joy-yao/presto,kingland/presto,aglne/presto,nvoron23/presto,jekey/presto,treasure-data/presto,nezihyigitbasi/presto,toyama0919/presto,deciament/presto,xiangel/presto,losipiuk/presto,totticarter/presto,ArturGajowy/presto,sumanth232/presto,11xor6/presto,haitaoyao/presto,RobinUS2/presto,pwz3n0/presto,yu-yamada/presto,ocono-tech/presto,zjshen/presto,dabaitu/presto,kietly/presto,treasure-data/presto,takari/presto,mbeitchman/presto,vermaravikant/presto,ebyhr/presto,kingland/presto,nileema/presto,RobinUS2/presto,springning/presto,toxeh/presto,ipros-team/presto,miquelruiz/presto,DanielTing/presto,bloomberg/presto,cosinequanon/presto,prestodb/presto,vermaravikant/presto,cberner/presto,zjshen/presto,facebook/presto,aramesh117/presto,zofuthan/presto,nsabharwal/presto,electrum/presto,ArturGajowy/presto,mcanthony/presto,zjshen/presto,jxiang/presto,wyukawa/presto,EvilMcJerkface/presto,denizdemir/presto,geraint0923/presto,wangcan2014/presto,lingochamp/presto,elonazoulay/presto,propene/presto,siddhartharay007/presto,kined/presto,jacobgao/presto,Jimexist/presto,lingochamp/presto,pwz3n0/presto,hgschmie/presto,lingochamp/presto,wrmsr/presto,Myrthan/presto,wyukawa/presto,yu-yamada/presto,wangcan2014/presto,ArturGajowy/presto,sunchao/presto,yu-yamada/presto,sumanth232/presto,aleph-zero/presto,nileema/presto,takari/presto,gcnonato/presto,Praveen2112/presto,EvilMcJerkface/presto,ptkool/presto,cawallin/presto,nakajijiji/presto,fengshao0907/presto,kingland/presto,aglne/presto,sumitkgec/presto,dain/presto,cosinequanon/presto,vermaravikant/presto,TeradataCenterForHadoop/bootcamp,zhenyuy-fb/presto,Myrthan/presto,yuananf/presto,shixuan-fan/presto,Svjard/presto,treasure-data/presto,tomz/presto,prestodb/presto,saidalaoui/presto,elonazoulay/presto,Teradata/presto,stewartpark/presto,twitter-forks/presto,siddhartharay007/presto,mpilman/presto,mbeitchman/presto,toyama0919/presto,raghavsethi/presto,zhenxiao/presto,Praveen2112/presto,troels/nz-presto,springning/presto,zzhao0/presto,kuzemchik/presto,toxeh/presto,Yaliang/presto,ajoabraham/presto,raghavsethi/presto,harunurhan/presto,sumitkgec/presto,Teradata/presto,troels/nz-presto,electrum/presto,XiaominZhang/presto,prestodb/presto,Svjard/presto,stewartpark/presto,xiangel/presto,nezihyigitbasi/presto,mandusm/presto,mvp/presto,zofuthan/presto,dabaitu/presto,ebd2/presto,Praveen2112/presto,idemura/presto,mugglmenzel/presto,CHINA-JD/presto,sunchao/presto,zhenyuy-fb/presto,TeradataCenterForHadoop/bootcamp,twitter-forks/presto,ocono-tech/presto,damiencarol/presto,miniway/presto,totticarter/presto,Myrthan/presto,gcnonato/presto,Nasdaq/presto,aramesh117/presto,hulu/presto,gh351135612/presto,zhenxiao/presto,wrmsr/presto,tellproject/presto,chrisunder/presto,mpilman/presto,Svjard/presto,mattyb149/presto,ajoabraham/presto,ipros-team/presto,yuananf/presto,cawallin/presto,zzhao0/presto,damiencarol/presto,toyama0919/presto,toxeh/presto,kietly/presto,fipar/presto,jf367/presto,fiedukow/presto,haitaoyao/presto,prateek1306/presto,mugglmenzel/presto,haozhun/presto,shixuan-fan/presto,pnowojski/presto,propene/presto,nvoron23/presto,miquelruiz/presto,lingochamp/presto,aleph-zero/presto,zhenyuy-fb/presto,gh351135612/presto,jiekechoo/presto,martint/presto,kuzemchik/presto,Teradata/presto,zzhao0/presto,ajoabraham/presto,ebyhr/presto,hulu/presto,mandusm/presto,cosinequanon/presto,smartnews/presto,smartnews/presto,twitter-forks/presto,treasure-data/presto,XiaominZhang/presto,arhimondr/presto,ocono-tech/presto,youngwookim/presto,nileema/presto,mode/presto,kaschaeffer/presto,mugglmenzel/presto,treasure-data/presto,mcanthony/presto,haitaoyao/presto,totticarter/presto,Zoomdata/presto,smartnews/presto,arhimondr/presto,harunurhan/presto,fiedukow/presto,svstanev/presto,kietly/presto,pnowojski/presto,ocono-tech/presto,aramesh117/presto,zhenxiao/presto,propene/presto,aleph-zero/presto,takari/presto,mattyb149/presto,dabaitu/presto,mode/presto,prestodb/presto,sopel39/presto,yuananf/presto,wyukawa/presto,y-lan/presto,mpilman/presto,Zoomdata/presto,totticarter/presto,yuananf/presto,erichwang/presto,kingland/presto,raghavsethi/presto,mattyb149/presto,prateek1306/presto,aglne/presto,Nasdaq/presto,joy-yao/presto,CHINA-JD/presto,CHINA-JD/presto,smartpcr/presto,losipiuk/presto,avasilevskiy/presto,Jimexist/presto,siddhartharay007/presto,dabaitu/presto,dain/presto,albertocsm/presto,mandusm/presto,Jimexist/presto,svstanev/presto,Teradata/presto,Nasdaq/presto,ebd2/presto,cosinequanon/presto,youngwookim/presto,jiangyifangh/presto,miniway/presto,nakajijiji/presto,haitaoyao/presto,wangcan2014/presto,jxiang/presto,raghavsethi/presto,XiaominZhang/presto,twitter-forks/presto,smartpcr/presto,sumanth232/presto,saidalaoui/presto,rockerbox/presto,idemura/presto,sopel39/presto,deciament/presto,bloomberg/presto,sumitkgec/presto,fiedukow/presto,rockerbox/presto,aleph-zero/presto,hgschmie/presto,ptkool/presto,kaschaeffer/presto,mbeitchman/presto,soz-fb/presto,facebook/presto,Myrthan/presto,RobinUS2/presto,nsabharwal/presto,wyukawa/presto,Yaliang/presto,ptkool/presto,svstanev/presto,mode/presto,shixuan-fan/presto,toyama0919/presto,zhenyuy-fb/presto,jacobgao/presto,wrmsr/presto,shubham166/presto,facebook/presto,wangcan2014/presto,jf367/presto,Zoomdata/presto,TeradataCenterForHadoop/bootcamp,aglne/presto,sumanth232/presto,jiekechoo/presto,cberner/presto,hgschmie/presto,wangcan2014/presto,mono-plane/presto,mcanthony/presto,Yaliang/presto,Nasdaq/presto,ebd2/presto,nsabharwal/presto,y-lan/presto,losipiuk/presto,mattyb149/presto,avasilevskiy/presto,suyucs/presto,EvilMcJerkface/presto,ebyhr/presto,stewartpark/presto,avasilevskiy/presto,XiaominZhang/presto,smartpcr/presto,jacobgao/presto,sopel39/presto,mandusm/presto,shubham166/presto,y-lan/presto,tomz/presto,jiekechoo/presto,Teradata/presto,idemura/presto,jiangyifangh/presto,RobinUS2/presto,ebyhr/presto,EvilMcJerkface/presto,jiangyifangh/presto,zofuthan/presto,soz-fb/presto,mandusm/presto,avasilevskiy/presto,jekey/presto,zhenyuy-fb/presto,wagnermarkd/presto,arhimondr/presto,aleph-zero/presto,dain/presto,youngwookim/presto,martint/presto,11xor6/presto,kined/presto,Praveen2112/presto,ocono-tech/presto,chrisunder/presto,gh351135612/presto,troels/nz-presto,ptkool/presto,kuzemchik/presto,martint/presto,losipiuk/presto,zjshen/presto,chrisunder/presto,miniway/presto,albertocsm/presto,yu-yamada/presto,nvoron23/presto,nakajijiji/presto,harunurhan/presto,fipar/presto,Praveen2112/presto,rockerbox/presto,nezihyigitbasi/presto,chrisunder/presto,joshk/presto,jiangyifangh/presto,kaschaeffer/presto,soz-fb/presto,wagnermarkd/presto,Nasdaq/presto,mono-plane/presto,albertocsm/presto,mvp/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.cli; import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; import java.io.StringWriter; import java.util.List; import static com.facebook.presto.cli.TestAlignedTablePrinter.row; import static com.facebook.presto.cli.TestAlignedTablePrinter.rows; import static org.testng.Assert.assertEquals; public class TestVerticalRecordPrinter { @Test public void testVerticalPrinting() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("first", "last", "quantity"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.printRows(rows( row("hello", "world", 123), row("a", null, 4.5), row("some long\ntext that\ndoes not\nfit on\none line", "more\ntext", 4567), row("bye", "done", -15)), true); printer.finish(); String expected = "" + "-[ RECORD 1 ]-------\n" + "first | hello\n" + "last | world\n" + "quantity | 123\n" + "-[ RECORD 2 ]-------\n" + "first | a\n" + "last | NULL\n" + "quantity | 4.5\n" + "-[ RECORD 3 ]-------\n" + "first | some long\n" + " | text that\n" + " | does not\n" + " | fit on\n" + " | one line\n" + "last | more\n" + " | text\n" + "quantity | 4567\n" + "-[ RECORD 4 ]-------\n" + "first | bye\n" + "last | done\n" + "quantity | -15\n"; assertEquals(writer.getBuffer().toString(), expected); } @Test public void testVerticalShortName() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("a"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.printRows(rows(row("x")), true); printer.finish(); String expected = "" + "-[ RECORD 1 ]\n" + "a | x\n"; assertEquals(writer.getBuffer().toString(), expected); } @Test public void testVerticalLongName() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("shippriority"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.printRows(rows(row("hello")), true); printer.finish(); String expected = "" + "-[ RECORD 1 ]+------\n" + "shippriority | hello\n"; assertEquals(writer.getBuffer().toString(), expected); } @Test public void testVerticalLongerName() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("order_priority"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.printRows(rows(row("hello")), true); printer.finish(); String expected = "" + "-[ RECORD 1 ]--+------\n" + "order_priority | hello\n"; assertEquals(writer.getBuffer().toString(), expected); } @Test public void testVerticalPrintingNoRows() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("none"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.finish(); assertEquals(writer.getBuffer().toString(), "(no rows)\n"); } }
presto-cli/src/test/java/com/facebook/presto/cli/TestVerticalRecordPrinter.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.cli; import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; import java.io.StringWriter; import java.util.List; import static java.util.Arrays.asList; import static org.testng.Assert.assertEquals; public class TestVerticalRecordPrinter { @Test public void testVerticalPrinting() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("first", "last", "quantity"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.printRows(rows( row("hello", "world", 123), row("a", null, 4.5), row("some long\ntext that\ndoes not\nfit on\none line", "more\ntext", 4567), row("bye", "done", -15)), true); printer.finish(); String expected = "" + "-[ RECORD 1 ]-------\n" + "first | hello\n" + "last | world\n" + "quantity | 123\n" + "-[ RECORD 2 ]-------\n" + "first | a\n" + "last | NULL\n" + "quantity | 4.5\n" + "-[ RECORD 3 ]-------\n" + "first | some long\n" + " | text that\n" + " | does not\n" + " | fit on\n" + " | one line\n" + "last | more\n" + " | text\n" + "quantity | 4567\n" + "-[ RECORD 4 ]-------\n" + "first | bye\n" + "last | done\n" + "quantity | -15\n"; assertEquals(writer.getBuffer().toString(), expected); } @Test public void testVerticalShortName() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("a"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.printRows(rows(row("x")), true); printer.finish(); String expected = "" + "-[ RECORD 1 ]\n" + "a | x\n"; assertEquals(writer.getBuffer().toString(), expected); } @Test public void testVerticalLongName() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("shippriority"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.printRows(rows(row("hello")), true); printer.finish(); String expected = "" + "-[ RECORD 1 ]+------\n" + "shippriority | hello\n"; assertEquals(writer.getBuffer().toString(), expected); } @Test public void testVerticalLongerName() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("order_priority"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.printRows(rows(row("hello")), true); printer.finish(); String expected = "" + "-[ RECORD 1 ]--+------\n" + "order_priority | hello\n"; assertEquals(writer.getBuffer().toString(), expected); } @Test public void testVerticalPrintingNoRows() throws Exception { StringWriter writer = new StringWriter(); List<String> fieldNames = ImmutableList.of("none"); OutputPrinter printer = new VerticalRecordPrinter(fieldNames, writer); printer.finish(); assertEquals(writer.getBuffer().toString(), "(no rows)\n"); } private static List<?> row(Object... values) { return asList(values); } private static List<List<?>> rows(List<?>... rows) { return asList(rows); } }
Remove duplicate helper functions in test
presto-cli/src/test/java/com/facebook/presto/cli/TestVerticalRecordPrinter.java
Remove duplicate helper functions in test
<ide><path>resto-cli/src/test/java/com/facebook/presto/cli/TestVerticalRecordPrinter.java <ide> import java.io.StringWriter; <ide> import java.util.List; <ide> <del>import static java.util.Arrays.asList; <add>import static com.facebook.presto.cli.TestAlignedTablePrinter.row; <add>import static com.facebook.presto.cli.TestAlignedTablePrinter.rows; <ide> import static org.testng.Assert.assertEquals; <ide> <ide> public class TestVerticalRecordPrinter <ide> <ide> assertEquals(writer.getBuffer().toString(), "(no rows)\n"); <ide> } <del> <del> private static List<?> row(Object... values) <del> { <del> return asList(values); <del> } <del> <del> private static List<List<?>> rows(List<?>... rows) <del> { <del> return asList(rows); <del> } <ide> }
Java
bsd-3-clause
757ffcab526b63fb8deb9b2b37a9fa0a4d8a971c
0
andrewkatis/jkind-1,andrewkatis/jkind-1,backesj/jkind,agacek/jkind,agacek/jkind,backesj/jkind,lgwagner/jkind,lgwagner/jkind
package jkind.processes; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.JKindException; import jkind.invariant.Candidate; import jkind.invariant.CandidateGenerator; import jkind.invariant.Graph; import jkind.invariant.Invariant; import jkind.processes.messages.InvariantMessage; import jkind.processes.messages.Message; import jkind.processes.messages.StopMessage; import jkind.sexp.Cons; import jkind.sexp.Sexp; import jkind.solvers.Model; import jkind.solvers.NumericValue; import jkind.solvers.Result; import jkind.solvers.SatResult; import jkind.solvers.StreamDecl; import jkind.solvers.StreamDef; import jkind.translation.Keywords; import jkind.translation.Specification; public class InvariantProcess extends Process { private InductiveProcess inductiveProcess; private Map<String, StreamDef> definitions; private Map<String, StreamDecl> declarations; public InvariantProcess(Specification spec) { super("Invariant", spec, null); definitions = new HashMap<String, StreamDef>(); declarations = new HashMap<String, StreamDecl>(); for (StreamDecl decl : spec.translation.getDeclarations()) { declarations.put(decl.getId().toString(), decl); } } public void setInductiveProcess(InductiveProcess inductiveProcess) { this.inductiveProcess = inductiveProcess; } @Override protected void initializeSolver() { super.initializeSolver(); declareN(); } @Override public void main() { try { Graph graph = createGraph(); if (graph.isTrivial()) { debug("No invariants proposed"); return; } for (int k = 1; k <= kMax; k++) { debug("K = " + k); refineBaseStep(k, graph); if (graph.isTrivial()) { debug("No invariants remaining after base step"); return; } sendInvariant(refineInductiveStep(k, graph)); } } catch (StopException se) { } } private class StopException extends RuntimeException { private static final long serialVersionUID = 1L; }; private boolean checkForStopMessage() { while (!incoming.isEmpty()) { Message message = incoming.poll(); if (message instanceof StopMessage) { throw new StopException(); } else { throw new JKindException("Unknown message type in inductive process: " + message.getClass().getCanonicalName()); } } return false; } private Graph createGraph() { List<Candidate> candidates = new CandidateGenerator(spec).generate(); debug("Proposed " + candidates.size() + " candidates"); Graph graph = new Graph(candidates); defineCandidates(candidates); return graph; } private void defineCandidates(List<Candidate> candidates) { for (Candidate candidate : candidates) { definitions.put(candidate.def.getId().toString(), candidate.def); solver.send(candidate.def); } } private void refineBaseStep(int k, Graph graph) { solver.push(); Result result; for (int i = 0; i < k; i++) { assertBaseTransition(i); } do { checkForStopMessage(); result = solver.query(graph.toInvariant(Sexp.fromInt(k - 1))); if (result instanceof SatResult) { Model model = getModel(result); graph.refine(model, BigInteger.valueOf(k - 1)); debug("Base step refinement, graph size = " + graph.size()); } } while (!graph.isTrivial() && result instanceof SatResult); solver.pop(); } private Model getModel(Result result) { Model model = ((SatResult) result).getModel(); model.setDefinitions(definitions); model.setDeclarations(declarations); return model; } private void assertBaseTransition(int i) { solver.send(new Cons("assert", new Cons(Keywords.T, Sexp.fromInt(i)))); } private Graph refineInductiveStep(int k, Graph original) { solver.push(); Graph graph = new Graph(original); Result result; for (int i = 0; i <= k; i++) { assertInductiveTransition(i); } do { checkForStopMessage(); result = solver.query(getInductiveQuery(k, graph)); if (result instanceof SatResult) { Model model = getModel(result); BigInteger index = getN(model).add(BigInteger.valueOf(k)); graph.refine(model, index); debug("Inductive step refinement, graph size = " + graph.size()); } } while (!graph.isTrivial() && result instanceof SatResult); solver.pop(); return graph; } private void assertInductiveTransition(int k) { solver.send(new Cons("assert", new Cons(Keywords.T, getInductiveIndex(k)))); } private Sexp getInductiveIndex(int offset) { return new Cons("+", Keywords.N, Sexp.fromInt(offset)); } private BigInteger getN(Model model) { NumericValue value = (NumericValue) model.getValue(Keywords.N); return new BigInteger(value.toString()); } private Sexp getInductiveQuery(int k, Graph graph) { List<Sexp> hyps = new ArrayList<Sexp>(); for (int i = 0; i < k; i++) { hyps.add(graph.toInvariant(getInductiveIndex(i))); } Sexp conc = graph.toInvariant(getInductiveIndex(k)); return new Cons("=>", new Cons("and", hyps), conc); } private void sendInvariant(Graph graph) { List<Invariant> invs = graph.toFinalInvariants(); debug("Sending invariants:"); for (Invariant invariant : invs) { debug(" " + invariant.toString()); } inductiveProcess.incoming.add(new InvariantMessage(invs)); } }
src/jkind/processes/InvariantProcess.java
package jkind.processes; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.JKindException; import jkind.invariant.Candidate; import jkind.invariant.CandidateGenerator; import jkind.invariant.Graph; import jkind.invariant.Invariant; import jkind.processes.messages.InvariantMessage; import jkind.processes.messages.Message; import jkind.processes.messages.StopMessage; import jkind.sexp.Cons; import jkind.sexp.Sexp; import jkind.solvers.Model; import jkind.solvers.NumericValue; import jkind.solvers.Result; import jkind.solvers.SatResult; import jkind.solvers.StreamDecl; import jkind.solvers.StreamDef; import jkind.translation.Keywords; import jkind.translation.Specification; public class InvariantProcess extends Process { private InductiveProcess inductiveProcess; private Map<String, StreamDef> definitions; private Map<String, StreamDecl> declarations; public InvariantProcess(Specification spec) { super("Invariant", spec, null); definitions = new HashMap<String, StreamDef>(); declarations = new HashMap<String, StreamDecl>(); for (StreamDecl decl : spec.translation.getDeclarations()) { declarations.put(decl.getId().toString(), decl); } } public void setInductiveProcess(InductiveProcess inductiveProcess) { this.inductiveProcess = inductiveProcess; } @Override protected void initializeSolver() { super.initializeSolver(); declareN(); } @Override public void main() { try { Graph graph = createGraph(); if (graph.isTrivial()) { debug("No invariants proposed"); return; } for (int k = 1; k <= kMax; k++) { debug("K = " + k); refineBaseStep(k, graph); if (graph.isTrivial()) { debug("No invariants remaining after base step"); return; } assertInductiveTransition(k); sendInvariant(refineInductiveStep(k, graph)); } } catch (StopException se) { } } private class StopException extends RuntimeException { private static final long serialVersionUID = 1L; }; private boolean checkForStopMessage() { while (!incoming.isEmpty()) { Message message = incoming.poll(); if (message instanceof StopMessage) { throw new StopException(); } else { throw new JKindException("Unknown message type in inductive process: " + message.getClass().getCanonicalName()); } } return false; } private Graph createGraph() { List<Candidate> candidates = new CandidateGenerator(spec).generate(); debug("Proposed " + candidates.size() + " candidates"); Graph graph = new Graph(candidates); defineCandidates(candidates); return graph; } private void defineCandidates(List<Candidate> candidates) { for (Candidate candidate : candidates) { definitions.put(candidate.def.getId().toString(), candidate.def); solver.send(candidate.def); } } private void refineBaseStep(int k, Graph graph) { solver.push(); Result result; for (int i = 0; i < k; i++) { assertBaseTransition(i); } do { checkForStopMessage(); result = solver.query(graph.toInvariant(Sexp.fromInt(k - 1))); if (result instanceof SatResult) { Model model = getModel(result); graph.refine(model, BigInteger.valueOf(k - 1)); debug("Base step refinement, graph size = " + graph.size()); } } while (!graph.isTrivial() && result instanceof SatResult); solver.pop(); } private Model getModel(Result result) { Model model = ((SatResult) result).getModel(); model.setDefinitions(definitions); model.setDeclarations(declarations); return model; } private void assertBaseTransition(int i) { solver.send(new Cons("assert", new Cons(Keywords.T, Sexp.fromInt(i)))); } private Graph refineInductiveStep(int k, Graph original) { solver.push(); Graph graph = new Graph(original); Result result; for (int i = 0; i <= k; i++) { assertInductiveTransition(i); } do { checkForStopMessage(); result = solver.query(getInductiveQuery(k, graph)); if (result instanceof SatResult) { Model model = getModel(result); BigInteger index = getN(model).add(BigInteger.valueOf(k)); graph.refine(model, index); debug("Inductive step refinement, graph size = " + graph.size()); } } while (!graph.isTrivial() && result instanceof SatResult); solver.pop(); return graph; } private void assertInductiveTransition(int k) { solver.send(new Cons("assert", new Cons(Keywords.T, getInductiveIndex(k)))); } private Sexp getInductiveIndex(int offset) { return new Cons("+", Keywords.N, Sexp.fromInt(offset)); } private BigInteger getN(Model model) { NumericValue value = (NumericValue) model.getValue(Keywords.N); return new BigInteger(value.toString()); } private Sexp getInductiveQuery(int k, Graph graph) { List<Sexp> hyps = new ArrayList<Sexp>(); for (int i = 0; i < k; i++) { hyps.add(graph.toInvariant(getInductiveIndex(i))); } Sexp conc = graph.toInvariant(getInductiveIndex(k)); return new Cons("=>", new Cons("and", hyps), conc); } private void sendInvariant(Graph graph) { List<Invariant> invs = graph.toFinalInvariants(); debug("Sending invariants:"); for (Invariant invariant : invs) { debug(" " + invariant.toString()); } inductiveProcess.incoming.add(new InvariantMessage(invs)); } }
Remove wrong line of code left over from months ago
src/jkind/processes/InvariantProcess.java
Remove wrong line of code left over from months ago
<ide><path>rc/jkind/processes/InvariantProcess.java <ide> return; <ide> } <ide> <del> assertInductiveTransition(k); <ide> sendInvariant(refineInductiveStep(k, graph)); <ide> } <ide> } catch (StopException se) {
Java
apache-2.0
d96149bd34074c669b6435d2ce570b8388537efd
0
NateShoffner/Seachem-Doser
package com.nateshoffner.seachemdoser.core.model.products.gravel; import com.nateshoffner.seachemdoser.DoserApplication; import com.nateshoffner.seachemdoser.R; import com.nateshoffner.seachemdoser.core.model.SeachemDosage; import com.nateshoffner.seachemdoser.core.model.UnitMeasurement; public class FlouriteSand extends Gravel { public FlouriteSand() { super(DoserApplication.getContext().getString(R.string.product_flourite_sand)); addNote(DoserApplication.getContext().getString(R.string.product_comment_flourite_sand)); } @Override public SeachemDosage[] calculateDosage(UnitMeasurement unitMeasurement) { return CalculateDosage(unitMeasurement, 260, 130); } }
app/src/main/java/com/nateshoffner/seachemdoser/core/model/products/gravel/FlouriteSand.java
package com.nateshoffner.seachemdoser.core.model.products.gravel; import com.nateshoffner.seachemdoser.DoserApplication; import com.nateshoffner.seachemdoser.R; import com.nateshoffner.seachemdoser.core.model.SeachemDosage; import com.nateshoffner.seachemdoser.core.model.UnitMeasurement; public class FlouriteSand extends Gravel { public FlouriteSand() { super(DoserApplication.getContext().getString(R.string.product_flourite_sand)); addNote(DoserApplication.getContext().getString(R.string.product_flourite_sand)); } @Override public SeachemDosage[] calculateDosage(UnitMeasurement unitMeasurement) { return CalculateDosage(unitMeasurement, 260, 130); } }
Fixed note
app/src/main/java/com/nateshoffner/seachemdoser/core/model/products/gravel/FlouriteSand.java
Fixed note
<ide><path>pp/src/main/java/com/nateshoffner/seachemdoser/core/model/products/gravel/FlouriteSand.java <ide> public FlouriteSand() { <ide> super(DoserApplication.getContext().getString(R.string.product_flourite_sand)); <ide> <del> addNote(DoserApplication.getContext().getString(R.string.product_flourite_sand)); <add> addNote(DoserApplication.getContext().getString(R.string.product_comment_flourite_sand)); <ide> } <ide> <ide> @Override
Java
apache-2.0
75428ec75d5811b49521d5300f050ce7ca720bb3
0
speedment/speedment,speedment/speedment
/** * * Copyright (c) 2006-2016, Speedment, Inc. 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 com.speedment.common.tuple; import java.util.stream.Stream; /** * {@inheritDoc} * * This {@link Tuple} holds one non-null element. * * @author pemi * @param <T0> Type of 0:th argument */ public interface Tuple1<T0> extends Tuple { T0 get0(); @Override default Stream<Object> stream() { return Stream.of(get0()); } @Override default int length() { return 1; } @Override default Object get(int index) { if (index == 0) { return get0(); } else { throw new IllegalArgumentException(String.format( "Index %d is outside bounds of tuple of length %s", index, length() )); } } }
common/tuple/src/main/java/com/speedment/common/tuple/Tuple1.java
/** * * Copyright (c) 2006-2016, Speedment, Inc. 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 com.speedment.common.tuple; import java.util.stream.Stream; /** * {@inheritDoc} * * This {@link Tuple} holds one non-null element. * * @author pemi * @param <T0> Type of 0:th argument */ public interface Tuple1<T0> extends Tuple { T0 get0(); @Override default Stream<Object> stream() { return Stream.of(get0()); } @Override default int length() { return 1; } @Override default Object get(int index) { if (index == 1) { return get0(); } else { throw new IllegalArgumentException(String.format( "Index %d is outside bounds of tuple of length %s", index, length() )); } } }
Tuple: Fix bug that Tuple1 indexed from 1 instead of 0
common/tuple/src/main/java/com/speedment/common/tuple/Tuple1.java
Tuple: Fix bug that Tuple1 indexed from 1 instead of 0
<ide><path>ommon/tuple/src/main/java/com/speedment/common/tuple/Tuple1.java <ide> <ide> @Override <ide> default Object get(int index) { <del> if (index == 1) { <add> if (index == 0) { <ide> return get0(); <ide> } else { <ide> throw new IllegalArgumentException(String.format(
JavaScript
isc
bc1e5755a9a9e247099872cc64f2fe498847ec1a
0
npm/slide-flow-control
/* usage: // do something to a list of things asyncMap(myListOfStuff, function (thing, cb) { doSomething(thing.foo, cb) }, cb) // do more than one thing to each item asyncMap(list, fooFn, barFn, cb) */ module.exports = asyncMap function asyncMap () { var steps = Array.prototype.slice.call(arguments) , list = steps.shift() || [] , cb_ = steps.pop() if (typeof cb_ !== "function") throw new Error( "No callback provided to asyncMap") if (!list) return cb_(null, []) if (!Array.isArray(list)) list = [list] var n = steps.length , data = [] // 2d array , errState = null , l = list.length , a = l * n if (!a) return cb_(null, []) function cb (er) { if (er && !errState) errState = er var argLen = arguments.length for (var i = 1; i < argLen; i ++) if (arguments[i] !== undefined) { data[i - 1] = (data[i - 1] || []).concat(arguments[i]) } // see if any new things have been added. if (list.length > l) { var newList = list.slice(l) a += (list.length - l) * n l = list.length process.nextTick(function () { newList.forEach(function (ar) { steps.forEach(function (fn) { fn(ar, cb) }) }) }) } if (--a === 0) cb_.apply(null, [errState].concat(data)) } // expect the supplied cb function to be called // "n" times for each thing in the array. list.forEach(function (ar) { steps.forEach(function (fn) { fn(ar, cb) }) }) }
lib/async-map.js
/* usage: // do something to a list of things asyncMap(myListOfStuff, function (thing, cb) { doSomething(thing.foo, cb) }, cb) // do more than one thing to each item asyncMap(list, fooFn, barFn, cb) */ module.exports = asyncMap function asyncMap () { var steps = Array.prototype.slice.call(arguments) , list = steps.shift() || [] , cb_ = steps.pop() if (typeof cb_ !== "function") throw new Error( "No callback provided to asyncMap") if (!list) return cb_(null, []) if (!Array.isArray(list)) list = [list] var n = steps.length , data = [] // 2d array , errState = null , l = list.length , a = l * n if (!a) return cb_(null, []) function cb (er) { if (errState) return var argLen = arguments.length for (var i = 1; i < argLen; i ++) if (arguments[i] !== undefined) { data[i - 1] = (data[i - 1] || []).concat(arguments[i]) } // see if any new things have been added. if (list.length > l) { var newList = list.slice(l) a += (list.length - l) * n l = list.length process.nextTick(function () { newList.forEach(function (ar) { steps.forEach(function (fn) { fn(ar, cb) }) }) }) } if (er || --a === 0) { errState = er cb_.apply(null, [errState].concat(data)) } } // expect the supplied cb function to be called // "n" times for each thing in the array. list.forEach(function (ar) { steps.forEach(function (fn) { fn(ar, cb) }) }) }
wait for all callbacks to complete
lib/async-map.js
wait for all callbacks to complete
<ide><path>ib/async-map.js <ide> , a = l * n <ide> if (!a) return cb_(null, []) <ide> function cb (er) { <del> if (errState) return <add> if (er && !errState) errState = er <add> <ide> var argLen = arguments.length <ide> for (var i = 1; i < argLen; i ++) if (arguments[i] !== undefined) { <ide> data[i - 1] = (data[i - 1] || []).concat(arguments[i]) <ide> }) <ide> } <ide> <del> if (er || --a === 0) { <del> errState = er <del> cb_.apply(null, [errState].concat(data)) <del> } <add> if (--a === 0) cb_.apply(null, [errState].concat(data)) <ide> } <ide> // expect the supplied cb function to be called <ide> // "n" times for each thing in the array.
Java
mit
f157eb4a1d5918dcb57f5515d47c1b086a90d8f7
0
Ziftr/nxt,fimkrypto/nxt,fimkrypto/nxt,fimkrypto/nxt,Ziftr/nxt,Ziftr/nxt,fimkrypto/nxt
package nxt; import nxt.db.Db; import nxt.db.DbIterator; import nxt.db.DbKey; import nxt.db.VersionedEntityDbTable; import nxt.peer.Peer; import nxt.peer.Peers; import nxt.util.Convert; import nxt.util.JSON; import nxt.util.Listener; import nxt.util.Listeners; import nxt.util.Logger; import nxt.util.ThreadPool; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; final class TransactionProcessorImpl implements TransactionProcessor { private static final TransactionProcessorImpl instance = new TransactionProcessorImpl(); static TransactionProcessorImpl getInstance() { return instance; } final DbKey.LongKeyFactory<TransactionImpl> unconfirmedTransactionDbKeyFactory = new DbKey.LongKeyFactory<TransactionImpl>("id") { @Override public DbKey newKey(TransactionImpl transaction) { return transaction.getDbKey(); } }; private final VersionedEntityDbTable<TransactionImpl> unconfirmedTransactionTable = new VersionedEntityDbTable<TransactionImpl>(unconfirmedTransactionDbKeyFactory) { @Override protected TransactionImpl load(Connection con, ResultSet rs) throws SQLException { byte[] transactionBytes = rs.getBytes("transaction_bytes"); try { TransactionImpl transaction = TransactionImpl.parseTransaction(transactionBytes); transaction.setHeight(rs.getInt("transaction_height")); return transaction; } catch (NxtException.ValidationException e) { throw new RuntimeException(e.toString(), e); } } @Override protected void save(Connection con, TransactionImpl transaction) throws SQLException { try (PreparedStatement pstmt = con.prepareStatement("MERGE INTO unconfirmed_transaction (id, transaction_height, " + "fee_per_byte, timestamp, expiration, transaction_bytes, height, latest) " + "KEY (id, height) VALUES (?, ?, ?, ?, ?, ?, ?, TRUE)")) { int i = 0; pstmt.setLong(++i, transaction.getId()); pstmt.setInt(++i, transaction.getHeight()); pstmt.setLong(++i, transaction.getFeeNQT() / transaction.getSize()); pstmt.setInt(++i, transaction.getTimestamp()); pstmt.setInt(++i, transaction.getExpiration()); pstmt.setBytes(++i, transaction.getBytes()); pstmt.setInt(++i, Nxt.getBlockchain().getHeight()); pstmt.executeUpdate(); } } @Override protected String table() { return "unconfirmed_transaction"; } @Override public void rollback(int height) { List<TransactionImpl> transactions = new ArrayList<>(); try (Connection con = Db.getConnection(); PreparedStatement pstmt = con.prepareStatement("SELECT * FROM unconfirmed_transaction WHERE height > ? AND latest = TRUE")) { pstmt.setInt(1, height); try (ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { transactions.add(load(con, rs)); } } } catch (SQLException e) { throw new RuntimeException(e.toString(), e); } super.rollback(height); TransactionProcessorImpl.this.processLater(transactions); } @Override protected String defaultSort() { return " ORDER BY transaction_height ASC, fee_per_byte DESC, timestamp ASC, id ASC "; } }; private final ConcurrentMap<Long, TransactionImpl> nonBroadcastedTransactions = new ConcurrentHashMap<>(); private final Listeners<List<Transaction>,Event> transactionListeners = new Listeners<>(); private final Set<TransactionImpl> lostTransactions = new HashSet<>(); private final Runnable removeUnconfirmedTransactionsThread = new Runnable() { @Override public void run() { try { try { int minHeight = 0; synchronized (Nxt.getBlockchain()) { try (Connection con = Db.beginTransaction(); PreparedStatement pstmt = con.prepareStatement("SELECT MIN(height) AS min_height FROM unconfirmed_transaction " + "WHERE expiration < ?")) { unconfirmedTransactionTable.trim(Nxt.getBlockchain().getHeight() - Constants.MAX_ROLLBACK); pstmt.setInt(1, Convert.getEpochTime()); try (ResultSet rs = pstmt.executeQuery()) { if (rs.next()) { minHeight = rs.getInt("min_height"); } } Db.commitTransaction(); } catch (Exception e) { Logger.logErrorMessage(e.toString(), e); Db.rollbackTransaction(); } finally { Db.endTransaction(); } } if (minHeight > 0) { Logger.logDebugMessage("Transaction accepted at height " + minHeight + " expired, will rescan"); Nxt.getBlockchainProcessor().scan(minHeight); } } catch (Exception e) { Logger.logDebugMessage("Error removing unconfirmed transactions", e); } } catch (Throwable t) { Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }; private final Runnable rebroadcastTransactionsThread = new Runnable() { @Override public void run() { try { try { List<Transaction> transactionList = new ArrayList<>(); int curTime = Convert.getEpochTime(); for (TransactionImpl transaction : nonBroadcastedTransactions.values()) { if (TransactionDb.hasTransaction(transaction.getId()) || transaction.getExpiration() < curTime) { nonBroadcastedTransactions.remove(transaction.getId()); } else if (transaction.getTimestamp() < curTime - 30) { transactionList.add(transaction); } } if (transactionList.size() > 0) { Peers.sendToSomePeers(transactionList); } } catch (Exception e) { Logger.logDebugMessage("Error in transaction re-broadcasting thread", e); } } catch (Throwable t) { Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }; private final Runnable processTransactionsThread = new Runnable() { private final JSONStreamAware getUnconfirmedTransactionsRequest; { JSONObject request = new JSONObject(); request.put("requestType", "getUnconfirmedTransactions"); getUnconfirmedTransactionsRequest = JSON.prepareRequest(request); } @Override public void run() { try { try { synchronized (BlockchainImpl.getInstance()) { processTransactions(lostTransactions, false); lostTransactions.clear(); } Peer peer = Peers.getAnyPeer(Peer.State.CONNECTED, true); if (peer == null) { return; } JSONObject response = peer.send(getUnconfirmedTransactionsRequest); if (response == null) { return; } JSONArray transactionsData = (JSONArray)response.get("unconfirmedTransactions"); if (transactionsData == null || transactionsData.size() == 0) { return; } try { processPeerTransactions(transactionsData, false); } catch (NxtException.ValidationException|RuntimeException e) { peer.blacklist(e); } } catch (Exception e) { Logger.logDebugMessage("Error processing unconfirmed transactions", e); } } catch (Throwable t) { Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }; private TransactionProcessorImpl() { ThreadPool.scheduleThread(processTransactionsThread, 5); ThreadPool.scheduleThread(removeUnconfirmedTransactionsThread, 1); ThreadPool.scheduleThread(rebroadcastTransactionsThread, 60); } @Override public boolean addListener(Listener<List<Transaction>> listener, Event eventType) { return transactionListeners.addListener(listener, eventType); } @Override public boolean removeListener(Listener<List<Transaction>> listener, Event eventType) { return transactionListeners.removeListener(listener, eventType); } @Override public DbIterator<TransactionImpl> getAllUnconfirmedTransactions() { return unconfirmedTransactionTable.getAll(0, -1); } @Override public Transaction getUnconfirmedTransaction(Long transactionId) { return unconfirmedTransactionTable.get(unconfirmedTransactionDbKeyFactory.newKey(transactionId)); } public Transaction.Builder newTransactionBuilder(byte[] senderPublicKey, long amountNQT, long feeNQT, short deadline, Attachment attachment) throws NxtException.ValidationException { byte version = (byte) getTransactionVersion(Nxt.getBlockchain().getHeight()); int timestamp = Convert.getEpochTime(); TransactionImpl.BuilderImpl builder = new TransactionImpl.BuilderImpl(version, senderPublicKey, amountNQT, feeNQT, timestamp, deadline, (Attachment.AbstractAttachment)attachment); if (version > 0) { Block ecBlock = EconomicClustering.getECBlockId(timestamp); builder.ecBlockHeight(ecBlock.getHeight()); builder.ecBlockId(ecBlock.getId()); } return builder; } @Override public void broadcast(Transaction transaction) throws NxtException.ValidationException { if (! transaction.verifySignature()) { throw new NxtException.NotValidException("Transaction signature verification failed"); } List<Transaction> validTransactions = processTransactions(Collections.singleton((TransactionImpl) transaction), true); if (validTransactions.contains(transaction)) { nonBroadcastedTransactions.put(transaction.getId(), (TransactionImpl) transaction); Logger.logDebugMessage("Accepted new transaction " + transaction.getStringId()); } else { Logger.logDebugMessage("Rejecting double spending transaction " + transaction.getStringId()); throw new NxtException.NotValidException("Double spending transaction"); } } @Override public void processPeerTransactions(JSONObject request) throws NxtException.ValidationException { JSONArray transactionsData = (JSONArray)request.get("transactions"); processPeerTransactions(transactionsData, true); } @Override public Transaction parseTransaction(byte[] bytes) throws NxtException.ValidationException { return TransactionImpl.parseTransaction(bytes); } @Override public TransactionImpl parseTransaction(JSONObject transactionData) throws NxtException.NotValidException { return TransactionImpl.parseTransaction(transactionData); } void clear() { nonBroadcastedTransactions.clear(); } void applyUnconfirmed(Set<TransactionImpl> unapplied) { List<Transaction> removedUnconfirmedTransactions = new ArrayList<>(); for (TransactionImpl transaction : unapplied) { if (! transaction.applyUnconfirmed()) { removedUnconfirmedTransactions.add(transaction); unconfirmedTransactionTable.delete(transaction); } } if (removedUnconfirmedTransactions.size() > 0) { transactionListeners.notify(removedUnconfirmedTransactions, TransactionProcessor.Event.REMOVED_UNCONFIRMED_TRANSACTIONS); } } Set<TransactionImpl> undoAllUnconfirmed() { Set<TransactionImpl> undone = new HashSet<>(); try (DbIterator<TransactionImpl> transactions = unconfirmedTransactionTable.getAll(0, -1)) { while (transactions.hasNext()) { TransactionImpl transaction = transactions.next(); transaction.undoUnconfirmed(); undone.add(transaction); } } return undone; } void updateUnconfirmedTransactions(BlockImpl block) { List<Transaction> addedConfirmedTransactions = new ArrayList<>(); List<Transaction> removedUnconfirmedTransactions = new ArrayList<>(); for (TransactionImpl transaction : block.getTransactions()) { addedConfirmedTransactions.add(transaction); TransactionImpl unconfirmedTransaction = unconfirmedTransactionTable.get(transaction.getDbKey()); if (unconfirmedTransaction != null) { unconfirmedTransactionTable.delete(unconfirmedTransaction); removedUnconfirmedTransactions.add(unconfirmedTransaction); } } if (removedUnconfirmedTransactions.size() > 0) { transactionListeners.notify(removedUnconfirmedTransactions, TransactionProcessor.Event.REMOVED_UNCONFIRMED_TRANSACTIONS); } if (addedConfirmedTransactions.size() > 0) { transactionListeners.notify(addedConfirmedTransactions, TransactionProcessor.Event.ADDED_CONFIRMED_TRANSACTIONS); } } void removeUnconfirmedTransactions(Iterable<TransactionImpl> transactions) { List<Transaction> removedList = new ArrayList<>(); synchronized (BlockchainImpl.getInstance()) { try { Db.beginTransaction(); for (TransactionImpl transaction : transactions) { if (unconfirmedTransactionTable.get(transaction.getDbKey()) != null) { unconfirmedTransactionTable.delete(transaction); transaction.undoUnconfirmed(); removedList.add(transaction); } } Db.commitTransaction(); } catch (Exception e) { Logger.logErrorMessage(e.toString(), e); Db.rollbackTransaction(); } finally { Db.endTransaction(); } } transactionListeners.notify(removedList, Event.REMOVED_UNCONFIRMED_TRANSACTIONS); } void shutdown() { try (DbIterator<TransactionImpl> transactions = unconfirmedTransactionTable.getAll(0, -1)) { removeUnconfirmedTransactions(transactions); } } int getTransactionVersion(int previousBlockHeight) { return previousBlockHeight < Constants.DIGITAL_GOODS_STORE_BLOCK ? 0 : 1; } void processLater(Collection<TransactionImpl> transactions) { synchronized (BlockchainImpl.getInstance()) { lostTransactions.addAll(transactions); } } private void processPeerTransactions(JSONArray transactionsData, final boolean sendToPeers) throws NxtException.ValidationException { if (Nxt.getBlockchainProcessor().isDownloading() || Nxt.getBlockchain().getHeight() < Constants.DIGITAL_GOODS_STORE_BLOCK) { return; } List<TransactionImpl> transactions = new ArrayList<>(); for (Object transactionData : transactionsData) { try { TransactionImpl transaction = parseTransaction((JSONObject) transactionData); transaction.validate(); transactions.add(transaction); } catch (NxtException.NotCurrentlyValidException ignore) { } catch (NxtException.NotValidException e) { Logger.logDebugMessage("Invalid transaction from peer: " + ((JSONObject) transactionData).toJSONString()); throw e; } } processTransactions(transactions, sendToPeers); for (TransactionImpl transaction : transactions) { nonBroadcastedTransactions.remove(transaction.getId()); } } List<Transaction> processTransactions(Collection<TransactionImpl> transactions, final boolean sendToPeers) { List<Transaction> sendToPeersTransactions = new ArrayList<>(); List<Transaction> addedUnconfirmedTransactions = new ArrayList<>(); List<Transaction> addedDoubleSpendingTransactions = new ArrayList<>(); for (TransactionImpl transaction : transactions) { try { int curTime = Convert.getEpochTime(); if (transaction.getTimestamp() > curTime + 15 || transaction.getExpiration() < curTime || transaction.getDeadline() > 1440) { continue; } if (transaction.getVersion() < 1) { continue; } synchronized (BlockchainImpl.getInstance()) { try { Db.beginTransaction(); if (Nxt.getBlockchain().getHeight() < Constants.NQT_BLOCK) { break; // not ready to process transactions } Long id = transaction.getId(); if (TransactionDb.hasTransaction(id) || unconfirmedTransactionTable.get(transaction.getDbKey()) != null) { continue; } if (! transaction.verifySignature()) { if (Account.getAccount(transaction.getSenderId()) != null) { Logger.logDebugMessage("Transaction " + transaction.getJSONObject().toJSONString() + " failed to verify"); } continue; } if (transaction.applyUnconfirmed()) { if (sendToPeers) { if (nonBroadcastedTransactions.containsKey(id)) { Logger.logDebugMessage("Received back transaction " + transaction.getStringId() + " that we generated, will not forward to peers"); nonBroadcastedTransactions.remove(id); } else { sendToPeersTransactions.add(transaction); } } unconfirmedTransactionTable.insert(transaction); addedUnconfirmedTransactions.add(transaction); } else { addedDoubleSpendingTransactions.add(transaction); } Db.commitTransaction(); } catch (Exception e) { Db.rollbackTransaction(); throw e; } finally { Db.endTransaction(); } } } catch (RuntimeException e) { Logger.logMessage("Error processing transaction", e); } } if (sendToPeersTransactions.size() > 0) { Peers.sendToSomePeers(sendToPeersTransactions); } if (addedUnconfirmedTransactions.size() > 0) { transactionListeners.notify(addedUnconfirmedTransactions, Event.ADDED_UNCONFIRMED_TRANSACTIONS); } if (addedDoubleSpendingTransactions.size() > 0) { transactionListeners.notify(addedDoubleSpendingTransactions, Event.ADDED_DOUBLESPENDING_TRANSACTIONS); } return addedUnconfirmedTransactions; } }
src/java/nxt/TransactionProcessorImpl.java
package nxt; import nxt.db.Db; import nxt.db.DbIterator; import nxt.db.DbKey; import nxt.db.VersionedEntityDbTable; import nxt.peer.Peer; import nxt.peer.Peers; import nxt.util.Convert; import nxt.util.JSON; import nxt.util.Listener; import nxt.util.Listeners; import nxt.util.Logger; import nxt.util.ThreadPool; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; final class TransactionProcessorImpl implements TransactionProcessor { private static final TransactionProcessorImpl instance = new TransactionProcessorImpl(); static TransactionProcessorImpl getInstance() { return instance; } final DbKey.LongKeyFactory<TransactionImpl> unconfirmedTransactionDbKeyFactory = new DbKey.LongKeyFactory<TransactionImpl>("id") { @Override public DbKey newKey(TransactionImpl transaction) { return transaction.getDbKey(); } }; private final VersionedEntityDbTable<TransactionImpl> unconfirmedTransactionTable = new VersionedEntityDbTable<TransactionImpl>(unconfirmedTransactionDbKeyFactory) { @Override protected TransactionImpl load(Connection con, ResultSet rs) throws SQLException { byte[] transactionBytes = rs.getBytes("transaction_bytes"); try { TransactionImpl transaction = TransactionImpl.parseTransaction(transactionBytes); transaction.setHeight(rs.getInt("transaction_height")); return transaction; } catch (NxtException.ValidationException e) { throw new RuntimeException(e.toString(), e); } } @Override protected void save(Connection con, TransactionImpl transaction) throws SQLException { try (PreparedStatement pstmt = con.prepareStatement("MERGE INTO unconfirmed_transaction (id, transaction_height, " + "fee_per_byte, timestamp, expiration, transaction_bytes, height, latest) " + "KEY (id, height) VALUES (?, ?, ?, ?, ?, ?, ?, TRUE)")) { int i = 0; pstmt.setLong(++i, transaction.getId()); pstmt.setInt(++i, transaction.getHeight()); pstmt.setLong(++i, transaction.getFeeNQT() / transaction.getSize()); pstmt.setInt(++i, transaction.getTimestamp()); pstmt.setInt(++i, transaction.getExpiration()); pstmt.setBytes(++i, transaction.getBytes()); pstmt.setInt(++i, Nxt.getBlockchain().getHeight()); pstmt.executeUpdate(); } } @Override protected String table() { return "unconfirmed_transaction"; } @Override public void rollback(int height) { List<TransactionImpl> transactions = new ArrayList<>(); try (Connection con = Db.getConnection(); PreparedStatement pstmt = con.prepareStatement("SELECT * FROM unconfirmed_transaction WHERE height > ? AND latest = TRUE")) { pstmt.setInt(1, height); try (ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { transactions.add(load(con, rs)); } } } catch (SQLException e) { throw new RuntimeException(e.toString(), e); } super.rollback(height); TransactionProcessorImpl.this.processLater(transactions); } @Override protected String defaultSort() { return " ORDER BY transaction_height ASC, fee_per_byte DESC, timestamp ASC, id ASC "; } }; private final ConcurrentMap<Long, TransactionImpl> nonBroadcastedTransactions = new ConcurrentHashMap<>(); private final Listeners<List<Transaction>,Event> transactionListeners = new Listeners<>(); private final Set<TransactionImpl> lostTransactions = new HashSet<>(); private final Runnable removeUnconfirmedTransactionsThread = new Runnable() { @Override public void run() { try { try { int minHeight = 0; try (Connection con = Db.getConnection(); PreparedStatement pstmt = con.prepareStatement("SELECT MIN(height) AS min_height FROM unconfirmed_transaction " + "WHERE expiration < ?")) { pstmt.setInt(1, Convert.getEpochTime()); try (ResultSet rs = pstmt.executeQuery()) { if (rs.next()) { minHeight = rs.getInt("min_height"); } } } if (minHeight > 0) { Logger.logDebugMessage("Transaction accepted at height " + minHeight + " expired, will rescan"); Nxt.getBlockchainProcessor().scan(minHeight); } } catch (Exception e) { Logger.logDebugMessage("Error removing unconfirmed transactions", e); } } catch (Throwable t) { Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }; private final Runnable rebroadcastTransactionsThread = new Runnable() { @Override public void run() { try { try { List<Transaction> transactionList = new ArrayList<>(); int curTime = Convert.getEpochTime(); for (TransactionImpl transaction : nonBroadcastedTransactions.values()) { if (TransactionDb.hasTransaction(transaction.getId()) || transaction.getExpiration() < curTime) { nonBroadcastedTransactions.remove(transaction.getId()); } else if (transaction.getTimestamp() < curTime - 30) { transactionList.add(transaction); } } if (transactionList.size() > 0) { Peers.sendToSomePeers(transactionList); } } catch (Exception e) { Logger.logDebugMessage("Error in transaction re-broadcasting thread", e); } } catch (Throwable t) { Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }; private final Runnable processTransactionsThread = new Runnable() { private final JSONStreamAware getUnconfirmedTransactionsRequest; { JSONObject request = new JSONObject(); request.put("requestType", "getUnconfirmedTransactions"); getUnconfirmedTransactionsRequest = JSON.prepareRequest(request); } @Override public void run() { try { try { synchronized (BlockchainImpl.getInstance()) { processTransactions(lostTransactions, false); lostTransactions.clear(); } Peer peer = Peers.getAnyPeer(Peer.State.CONNECTED, true); if (peer == null) { return; } JSONObject response = peer.send(getUnconfirmedTransactionsRequest); if (response == null) { return; } JSONArray transactionsData = (JSONArray)response.get("unconfirmedTransactions"); if (transactionsData == null || transactionsData.size() == 0) { return; } try { processPeerTransactions(transactionsData, false); } catch (NxtException.ValidationException|RuntimeException e) { peer.blacklist(e); } } catch (Exception e) { Logger.logDebugMessage("Error processing unconfirmed transactions", e); } } catch (Throwable t) { Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }; private TransactionProcessorImpl() { ThreadPool.scheduleThread(processTransactionsThread, 5); ThreadPool.scheduleThread(removeUnconfirmedTransactionsThread, 1); ThreadPool.scheduleThread(rebroadcastTransactionsThread, 60); } @Override public boolean addListener(Listener<List<Transaction>> listener, Event eventType) { return transactionListeners.addListener(listener, eventType); } @Override public boolean removeListener(Listener<List<Transaction>> listener, Event eventType) { return transactionListeners.removeListener(listener, eventType); } @Override public DbIterator<TransactionImpl> getAllUnconfirmedTransactions() { return unconfirmedTransactionTable.getAll(0, -1); } @Override public Transaction getUnconfirmedTransaction(Long transactionId) { return unconfirmedTransactionTable.get(unconfirmedTransactionDbKeyFactory.newKey(transactionId)); } public Transaction.Builder newTransactionBuilder(byte[] senderPublicKey, long amountNQT, long feeNQT, short deadline, Attachment attachment) throws NxtException.ValidationException { byte version = (byte) getTransactionVersion(Nxt.getBlockchain().getHeight()); int timestamp = Convert.getEpochTime(); TransactionImpl.BuilderImpl builder = new TransactionImpl.BuilderImpl(version, senderPublicKey, amountNQT, feeNQT, timestamp, deadline, (Attachment.AbstractAttachment)attachment); if (version > 0) { Block ecBlock = EconomicClustering.getECBlockId(timestamp); builder.ecBlockHeight(ecBlock.getHeight()); builder.ecBlockId(ecBlock.getId()); } return builder; } @Override public void broadcast(Transaction transaction) throws NxtException.ValidationException { if (! transaction.verifySignature()) { throw new NxtException.NotValidException("Transaction signature verification failed"); } List<Transaction> validTransactions = processTransactions(Collections.singleton((TransactionImpl) transaction), true); if (validTransactions.contains(transaction)) { nonBroadcastedTransactions.put(transaction.getId(), (TransactionImpl) transaction); Logger.logDebugMessage("Accepted new transaction " + transaction.getStringId()); } else { Logger.logDebugMessage("Rejecting double spending transaction " + transaction.getStringId()); throw new NxtException.NotValidException("Double spending transaction"); } } @Override public void processPeerTransactions(JSONObject request) throws NxtException.ValidationException { JSONArray transactionsData = (JSONArray)request.get("transactions"); processPeerTransactions(transactionsData, true); } @Override public Transaction parseTransaction(byte[] bytes) throws NxtException.ValidationException { return TransactionImpl.parseTransaction(bytes); } @Override public TransactionImpl parseTransaction(JSONObject transactionData) throws NxtException.NotValidException { return TransactionImpl.parseTransaction(transactionData); } void clear() { nonBroadcastedTransactions.clear(); } void applyUnconfirmed(Set<TransactionImpl> unapplied) { List<Transaction> removedUnconfirmedTransactions = new ArrayList<>(); for (TransactionImpl transaction : unapplied) { if (! transaction.applyUnconfirmed()) { removedUnconfirmedTransactions.add(transaction); unconfirmedTransactionTable.delete(transaction); } } if (removedUnconfirmedTransactions.size() > 0) { transactionListeners.notify(removedUnconfirmedTransactions, TransactionProcessor.Event.REMOVED_UNCONFIRMED_TRANSACTIONS); } } Set<TransactionImpl> undoAllUnconfirmed() { Set<TransactionImpl> undone = new HashSet<>(); try (DbIterator<TransactionImpl> transactions = unconfirmedTransactionTable.getAll(0, -1)) { while (transactions.hasNext()) { TransactionImpl transaction = transactions.next(); transaction.undoUnconfirmed(); undone.add(transaction); } } return undone; } void updateUnconfirmedTransactions(BlockImpl block) { List<Transaction> addedConfirmedTransactions = new ArrayList<>(); List<Transaction> removedUnconfirmedTransactions = new ArrayList<>(); for (TransactionImpl transaction : block.getTransactions()) { addedConfirmedTransactions.add(transaction); TransactionImpl unconfirmedTransaction = unconfirmedTransactionTable.get(transaction.getDbKey()); if (unconfirmedTransaction != null) { unconfirmedTransactionTable.delete(unconfirmedTransaction); removedUnconfirmedTransactions.add(unconfirmedTransaction); } } if (removedUnconfirmedTransactions.size() > 0) { transactionListeners.notify(removedUnconfirmedTransactions, TransactionProcessor.Event.REMOVED_UNCONFIRMED_TRANSACTIONS); } if (addedConfirmedTransactions.size() > 0) { transactionListeners.notify(addedConfirmedTransactions, TransactionProcessor.Event.ADDED_CONFIRMED_TRANSACTIONS); } } void removeUnconfirmedTransactions(Iterable<TransactionImpl> transactions) { List<Transaction> removedList = new ArrayList<>(); synchronized (BlockchainImpl.getInstance()) { try { Db.beginTransaction(); for (TransactionImpl transaction : transactions) { if (unconfirmedTransactionTable.get(transaction.getDbKey()) != null) { unconfirmedTransactionTable.delete(transaction); transaction.undoUnconfirmed(); removedList.add(transaction); } } Db.commitTransaction(); } catch (Exception e) { Logger.logErrorMessage(e.toString(), e); Db.rollbackTransaction(); } finally { Db.endTransaction(); } } transactionListeners.notify(removedList, Event.REMOVED_UNCONFIRMED_TRANSACTIONS); } void shutdown() { try (DbIterator<TransactionImpl> transactions = unconfirmedTransactionTable.getAll(0, -1)) { removeUnconfirmedTransactions(transactions); } } int getTransactionVersion(int previousBlockHeight) { return previousBlockHeight < Constants.DIGITAL_GOODS_STORE_BLOCK ? 0 : 1; } void processLater(Collection<TransactionImpl> transactions) { synchronized (BlockchainImpl.getInstance()) { lostTransactions.addAll(transactions); } } private void processPeerTransactions(JSONArray transactionsData, final boolean sendToPeers) throws NxtException.ValidationException { if (Nxt.getBlockchainProcessor().isDownloading() || Nxt.getBlockchain().getHeight() < Constants.DIGITAL_GOODS_STORE_BLOCK) { return; } List<TransactionImpl> transactions = new ArrayList<>(); for (Object transactionData : transactionsData) { try { TransactionImpl transaction = parseTransaction((JSONObject) transactionData); transaction.validate(); transactions.add(transaction); } catch (NxtException.NotCurrentlyValidException ignore) { } catch (NxtException.NotValidException e) { Logger.logDebugMessage("Invalid transaction from peer: " + ((JSONObject) transactionData).toJSONString()); throw e; } } processTransactions(transactions, sendToPeers); for (TransactionImpl transaction : transactions) { nonBroadcastedTransactions.remove(transaction.getId()); } } List<Transaction> processTransactions(Collection<TransactionImpl> transactions, final boolean sendToPeers) { List<Transaction> sendToPeersTransactions = new ArrayList<>(); List<Transaction> addedUnconfirmedTransactions = new ArrayList<>(); List<Transaction> addedDoubleSpendingTransactions = new ArrayList<>(); for (TransactionImpl transaction : transactions) { try { int curTime = Convert.getEpochTime(); if (transaction.getTimestamp() > curTime + 15 || transaction.getExpiration() < curTime || transaction.getDeadline() > 1440) { continue; } if (transaction.getVersion() < 1) { continue; } synchronized (BlockchainImpl.getInstance()) { try { Db.beginTransaction(); if (Nxt.getBlockchain().getHeight() < Constants.NQT_BLOCK) { break; // not ready to process transactions } Long id = transaction.getId(); if (TransactionDb.hasTransaction(id) || unconfirmedTransactionTable.get(transaction.getDbKey()) != null) { continue; } if (! transaction.verifySignature()) { if (Account.getAccount(transaction.getSenderId()) != null) { Logger.logDebugMessage("Transaction " + transaction.getJSONObject().toJSONString() + " failed to verify"); } continue; } if (transaction.applyUnconfirmed()) { if (sendToPeers) { if (nonBroadcastedTransactions.containsKey(id)) { Logger.logDebugMessage("Received back transaction " + transaction.getStringId() + " that we generated, will not forward to peers"); nonBroadcastedTransactions.remove(id); } else { sendToPeersTransactions.add(transaction); } } unconfirmedTransactionTable.insert(transaction); addedUnconfirmedTransactions.add(transaction); } else { addedDoubleSpendingTransactions.add(transaction); } Db.commitTransaction(); } catch (Exception e) { Db.rollbackTransaction(); throw e; } finally { Db.endTransaction(); } } } catch (RuntimeException e) { Logger.logMessage("Error processing transaction", e); } } if (sendToPeersTransactions.size() > 0) { Peers.sendToSomePeers(sendToPeersTransactions); } if (addedUnconfirmedTransactions.size() > 0) { transactionListeners.notify(addedUnconfirmedTransactions, Event.ADDED_UNCONFIRMED_TRANSACTIONS); } if (addedDoubleSpendingTransactions.size() > 0) { transactionListeners.notify(addedDoubleSpendingTransactions, Event.ADDED_DOUBLESPENDING_TRANSACTIONS); } return addedUnconfirmedTransactions; } }
trim unconfirmed transaction table before each expiration check
src/java/nxt/TransactionProcessorImpl.java
trim unconfirmed transaction table before each expiration check
<ide><path>rc/java/nxt/TransactionProcessorImpl.java <ide> try { <ide> try { <ide> int minHeight = 0; <del> try (Connection con = Db.getConnection(); <del> PreparedStatement pstmt = con.prepareStatement("SELECT MIN(height) AS min_height FROM unconfirmed_transaction " <del> + "WHERE expiration < ?")) { <del> pstmt.setInt(1, Convert.getEpochTime()); <del> try (ResultSet rs = pstmt.executeQuery()) { <del> if (rs.next()) { <del> minHeight = rs.getInt("min_height"); <add> synchronized (Nxt.getBlockchain()) { <add> try (Connection con = Db.beginTransaction(); <add> PreparedStatement pstmt = con.prepareStatement("SELECT MIN(height) AS min_height FROM unconfirmed_transaction " <add> + "WHERE expiration < ?")) { <add> unconfirmedTransactionTable.trim(Nxt.getBlockchain().getHeight() - Constants.MAX_ROLLBACK); <add> pstmt.setInt(1, Convert.getEpochTime()); <add> try (ResultSet rs = pstmt.executeQuery()) { <add> if (rs.next()) { <add> minHeight = rs.getInt("min_height"); <add> } <ide> } <add> Db.commitTransaction(); <add> } catch (Exception e) { <add> Logger.logErrorMessage(e.toString(), e); <add> Db.rollbackTransaction(); <add> } finally { <add> Db.endTransaction(); <ide> } <ide> } <ide> if (minHeight > 0) {
Java
apache-2.0
49a5587558d8183f5a054156f59a8bd5bacc9c67
0
lexandro/spring-boot,eddumelendez/spring-boot,isopov/spring-boot,mbogoevici/spring-boot,lucassaldanha/spring-boot,olivergierke/spring-boot,ihoneymon/spring-boot,bclozel/spring-boot,jvz/spring-boot,tiarebalbi/spring-boot,htynkn/spring-boot,javyzheng/spring-boot,Buzzardo/spring-boot,NetoDevel/spring-boot,vakninr/spring-boot,olivergierke/spring-boot,eddumelendez/spring-boot,joansmith/spring-boot,jvz/spring-boot,sbcoba/spring-boot,michael-simons/spring-boot,NetoDevel/spring-boot,lucassaldanha/spring-boot,eddumelendez/spring-boot,joshthornhill/spring-boot,spring-projects/spring-boot,wilkinsona/spring-boot,vpavic/spring-boot,shakuzen/spring-boot,bbrouwer/spring-boot,lburgazzoli/spring-boot,joshiste/spring-boot,habuma/spring-boot,sbuettner/spring-boot,spring-projects/spring-boot,rweisleder/spring-boot,thomasdarimont/spring-boot,cleverjava/jenkins2-course-spring-boot,sebastiankirsch/spring-boot,philwebb/spring-boot-concourse,herau/spring-boot,Buzzardo/spring-boot,eddumelendez/spring-boot,joansmith/spring-boot,mevasaroj/jenkins2-course-spring-boot,shakuzen/spring-boot,ptahchiev/spring-boot,aahlenst/spring-boot,qerub/spring-boot,htynkn/spring-boot,sbuettner/spring-boot,DeezCashews/spring-boot,zhanhb/spring-boot,RichardCSantana/spring-boot,Nowheresly/spring-boot,mdeinum/spring-boot,akmaharshi/jenkins,zhanhb/spring-boot,bjornlindstrom/spring-boot,izeye/spring-boot,SaravananParthasarathy/SPSDemo,deki/spring-boot,mdeinum/spring-boot,afroje-reshma/spring-boot-sample,rweisleder/spring-boot,wilkinsona/spring-boot,aahlenst/spring-boot,izeye/spring-boot,joshiste/spring-boot,kdvolder/spring-boot,dreis2211/spring-boot,ihoneymon/spring-boot,chrylis/spring-boot,tsachev/spring-boot,minmay/spring-boot,donhuvy/spring-boot,mrumpf/spring-boot,xiaoleiPENG/my-project,SaravananParthasarathy/SPSDemo,Nowheresly/spring-boot,drumonii/spring-boot,vpavic/spring-boot,habuma/spring-boot,wilkinsona/spring-boot,deki/spring-boot,royclarkson/spring-boot,akmaharshi/jenkins,felipeg48/spring-boot,zhangshuangquan/spring-root,DeezCashews/spring-boot,RichardCSantana/spring-boot,qerub/spring-boot,donhuvy/spring-boot,rweisleder/spring-boot,qerub/spring-boot,linead/spring-boot,ameraljovic/spring-boot,rajendra-chola/jenkins2-course-spring-boot,tsachev/spring-boot,ptahchiev/spring-boot,shangyi0102/spring-boot,qerub/spring-boot,bjornlindstrom/spring-boot,lenicliu/spring-boot,vakninr/spring-boot,yangdd1205/spring-boot,hqrt/jenkins2-course-spring-boot,spring-projects/spring-boot,michael-simons/spring-boot,eddumelendez/spring-boot,pvorb/spring-boot,shangyi0102/spring-boot,kamilszymanski/spring-boot,habuma/spring-boot,aahlenst/spring-boot,DeezCashews/spring-boot,mevasaroj/jenkins2-course-spring-boot,linead/spring-boot,afroje-reshma/spring-boot-sample,ollie314/spring-boot,xiaoleiPENG/my-project,ilayaperumalg/spring-boot,habuma/spring-boot,joansmith/spring-boot,bclozel/spring-boot,mbogoevici/spring-boot,mdeinum/spring-boot,mrumpf/spring-boot,hqrt/jenkins2-course-spring-boot,jbovet/spring-boot,shakuzen/spring-boot,thomasdarimont/spring-boot,javyzheng/spring-boot,afroje-reshma/spring-boot-sample,dfa1/spring-boot,bjornlindstrom/spring-boot,bijukunjummen/spring-boot,rajendra-chola/jenkins2-course-spring-boot,scottfrederick/spring-boot,aahlenst/spring-boot,ilayaperumalg/spring-boot,mbogoevici/spring-boot,candrews/spring-boot,kdvolder/spring-boot,thomasdarimont/spring-boot,spring-projects/spring-boot,philwebb/spring-boot,olivergierke/spring-boot,hello2009chen/spring-boot,i007422/jenkins2-course-spring-boot,mevasaroj/jenkins2-course-spring-boot,zhangshuangquan/spring-root,eddumelendez/spring-boot,kamilszymanski/spring-boot,bclozel/spring-boot,ihoneymon/spring-boot,bijukunjummen/spring-boot,bijukunjummen/spring-boot,olivergierke/spring-boot,lenicliu/spring-boot,vpavic/spring-boot,michael-simons/spring-boot,mbenson/spring-boot,deki/spring-boot,rweisleder/spring-boot,tsachev/spring-boot,mrumpf/spring-boot,bclozel/spring-boot,joshiste/spring-boot,yangdd1205/spring-boot,tiarebalbi/spring-boot,cleverjava/jenkins2-course-spring-boot,isopov/spring-boot,izeye/spring-boot,minmay/spring-boot,ollie314/spring-boot,philwebb/spring-boot,lexandro/spring-boot,mrumpf/spring-boot,wilkinsona/spring-boot,ilayaperumalg/spring-boot,jxblum/spring-boot,htynkn/spring-boot,xiaoleiPENG/my-project,brettwooldridge/spring-boot,drumonii/spring-boot,wilkinsona/spring-boot,ameraljovic/spring-boot,mdeinum/spring-boot,spring-projects/spring-boot,lucassaldanha/spring-boot,ptahchiev/spring-boot,lucassaldanha/spring-boot,tsachev/spring-boot,brettwooldridge/spring-boot,bjornlindstrom/spring-boot,linead/spring-boot,yangdd1205/spring-boot,tiarebalbi/spring-boot,rajendra-chola/jenkins2-course-spring-boot,isopov/spring-boot,jxblum/spring-boot,shakuzen/spring-boot,jxblum/spring-boot,michael-simons/spring-boot,hqrt/jenkins2-course-spring-boot,htynkn/spring-boot,yhj630520/spring-boot,felipeg48/spring-boot,akmaharshi/jenkins,jmnarloch/spring-boot,SaravananParthasarathy/SPSDemo,vakninr/spring-boot,drumonii/spring-boot,isopov/spring-boot,ptahchiev/spring-boot,zhangshuangquan/spring-root,dfa1/spring-boot,philwebb/spring-boot,chrylis/spring-boot,michael-simons/spring-boot,lexandro/spring-boot,bclozel/spring-boot,NetoDevel/spring-boot,philwebb/spring-boot,joshthornhill/spring-boot,lburgazzoli/spring-boot,jayarampradhan/spring-boot,neo4j-contrib/spring-boot,habuma/spring-boot,izeye/spring-boot,herau/spring-boot,dfa1/spring-boot,SaravananParthasarathy/SPSDemo,dfa1/spring-boot,lburgazzoli/spring-boot,neo4j-contrib/spring-boot,neo4j-contrib/spring-boot,candrews/spring-boot,isopov/spring-boot,i007422/jenkins2-course-spring-boot,pvorb/spring-boot,i007422/jenkins2-course-spring-boot,ihoneymon/spring-boot,sbcoba/spring-boot,herau/spring-boot,NetoDevel/spring-boot,aahlenst/spring-boot,michael-simons/spring-boot,scottfrederick/spring-boot,bbrouwer/spring-boot,joansmith/spring-boot,jayarampradhan/spring-boot,lucassaldanha/spring-boot,kamilszymanski/spring-boot,javyzheng/spring-boot,NetoDevel/spring-boot,deki/spring-boot,sebastiankirsch/spring-boot,donhuvy/spring-boot,sbcoba/spring-boot,royclarkson/spring-boot,lenicliu/spring-boot,drumonii/spring-boot,felipeg48/spring-boot,SaravananParthasarathy/SPSDemo,zhanhb/spring-boot,xiaoleiPENG/my-project,zhanhb/spring-boot,akmaharshi/jenkins,bijukunjummen/spring-boot,candrews/spring-boot,nebhale/spring-boot,mosoft521/spring-boot,bjornlindstrom/spring-boot,royclarkson/spring-boot,habuma/spring-boot,herau/spring-boot,felipeg48/spring-boot,minmay/spring-boot,joshthornhill/spring-boot,sebastiankirsch/spring-boot,drumonii/spring-boot,rajendra-chola/jenkins2-course-spring-boot,Buzzardo/spring-boot,jbovet/spring-boot,RichardCSantana/spring-boot,spring-projects/spring-boot,chrylis/spring-boot,javyzheng/spring-boot,zhanhb/spring-boot,donhuvy/spring-boot,yhj630520/spring-boot,bbrouwer/spring-boot,tsachev/spring-boot,mevasaroj/jenkins2-course-spring-boot,joansmith/spring-boot,neo4j-contrib/spring-boot,minmay/spring-boot,DeezCashews/spring-boot,jvz/spring-boot,jbovet/spring-boot,i007422/jenkins2-course-spring-boot,sbuettner/spring-boot,olivergierke/spring-boot,mbenson/spring-boot,hello2009chen/spring-boot,royclarkson/spring-boot,lburgazzoli/spring-boot,mbenson/spring-boot,jvz/spring-boot,pvorb/spring-boot,yhj630520/spring-boot,donhuvy/spring-boot,isopov/spring-boot,scottfrederick/spring-boot,vpavic/spring-boot,zhangshuangquan/spring-root,lenicliu/spring-boot,mbenson/spring-boot,vpavic/spring-boot,shangyi0102/spring-boot,shakuzen/spring-boot,tiarebalbi/spring-boot,izeye/spring-boot,kamilszymanski/spring-boot,hello2009chen/spring-boot,scottfrederick/spring-boot,cleverjava/jenkins2-course-spring-boot,htynkn/spring-boot,dreis2211/spring-boot,shangyi0102/spring-boot,rweisleder/spring-boot,shangyi0102/spring-boot,scottfrederick/spring-boot,ptahchiev/spring-boot,yhj630520/spring-boot,candrews/spring-boot,philwebb/spring-boot-concourse,nebhale/spring-boot,nebhale/spring-boot,royclarkson/spring-boot,ilayaperumalg/spring-boot,pvorb/spring-boot,ihoneymon/spring-boot,jmnarloch/spring-boot,yhj630520/spring-boot,scottfrederick/spring-boot,mdeinum/spring-boot,hqrt/jenkins2-course-spring-boot,jayarampradhan/spring-boot,jbovet/spring-boot,Nowheresly/spring-boot,jvz/spring-boot,lenicliu/spring-boot,drumonii/spring-boot,jayarampradhan/spring-boot,cleverjava/jenkins2-course-spring-boot,pvorb/spring-boot,felipeg48/spring-boot,chrylis/spring-boot,bbrouwer/spring-boot,tsachev/spring-boot,ollie314/spring-boot,akmaharshi/jenkins,nebhale/spring-boot,ollie314/spring-boot,donhuvy/spring-boot,vakninr/spring-boot,afroje-reshma/spring-boot-sample,mbogoevici/spring-boot,joshthornhill/spring-boot,zhanhb/spring-boot,joshthornhill/spring-boot,mosoft521/spring-boot,ameraljovic/spring-boot,ilayaperumalg/spring-boot,kdvolder/spring-boot,ameraljovic/spring-boot,qerub/spring-boot,ptahchiev/spring-boot,chrylis/spring-boot,mbenson/spring-boot,sbcoba/spring-boot,javyzheng/spring-boot,jmnarloch/spring-boot,jxblum/spring-boot,lexandro/spring-boot,deki/spring-boot,dreis2211/spring-boot,tiarebalbi/spring-boot,hello2009chen/spring-boot,philwebb/spring-boot,thomasdarimont/spring-boot,RichardCSantana/spring-boot,rweisleder/spring-boot,hello2009chen/spring-boot,brettwooldridge/spring-boot,ollie314/spring-boot,RichardCSantana/spring-boot,cleverjava/jenkins2-course-spring-boot,tiarebalbi/spring-boot,i007422/jenkins2-course-spring-boot,kdvolder/spring-boot,thomasdarimont/spring-boot,herau/spring-boot,Buzzardo/spring-boot,kdvolder/spring-boot,aahlenst/spring-boot,mbogoevici/spring-boot,brettwooldridge/spring-boot,mevasaroj/jenkins2-course-spring-boot,candrews/spring-boot,ameraljovic/spring-boot,sbcoba/spring-boot,wilkinsona/spring-boot,neo4j-contrib/spring-boot,mosoft521/spring-boot,sebastiankirsch/spring-boot,brettwooldridge/spring-boot,felipeg48/spring-boot,sbuettner/spring-boot,mbenson/spring-boot,htynkn/spring-boot,dreis2211/spring-boot,philwebb/spring-boot-concourse,philwebb/spring-boot,linead/spring-boot,zhangshuangquan/spring-root,xiaoleiPENG/my-project,linead/spring-boot,vakninr/spring-boot,joshiste/spring-boot,jmnarloch/spring-boot,mrumpf/spring-boot,chrylis/spring-boot,rajendra-chola/jenkins2-course-spring-boot,shakuzen/spring-boot,Nowheresly/spring-boot,jxblum/spring-boot,ilayaperumalg/spring-boot,hqrt/jenkins2-course-spring-boot,bbrouwer/spring-boot,philwebb/spring-boot-concourse,kdvolder/spring-boot,mosoft521/spring-boot,jbovet/spring-boot,jxblum/spring-boot,dreis2211/spring-boot,ihoneymon/spring-boot,lburgazzoli/spring-boot,kamilszymanski/spring-boot,jmnarloch/spring-boot,vpavic/spring-boot,afroje-reshma/spring-boot-sample,bclozel/spring-boot,dfa1/spring-boot,dreis2211/spring-boot,DeezCashews/spring-boot,Buzzardo/spring-boot,mosoft521/spring-boot,mdeinum/spring-boot,jayarampradhan/spring-boot,joshiste/spring-boot,philwebb/spring-boot-concourse,joshiste/spring-boot,bijukunjummen/spring-boot,nebhale/spring-boot,minmay/spring-boot,Buzzardo/spring-boot,sebastiankirsch/spring-boot,lexandro/spring-boot,Nowheresly/spring-boot,sbuettner/spring-boot
/* * Copyright 2012-2014 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.boot.cli.command.options; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import groovy.lang.Closure; import joptsimple.BuiltinHelpFormatter; import joptsimple.HelpFormatter; import joptsimple.OptionDescriptor; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpecBuilder; import org.springframework.boot.cli.command.OptionParsingCommand; import org.springframework.boot.cli.command.status.ExitStatus; /** * Delegate used by {@link OptionParsingCommand} to parse options and run the command. * * @author Dave Syer * @see OptionParsingCommand * @see #run(OptionSet) */ public class OptionHandler { private OptionParser parser; private Closure<?> closure; private String help; private Collection<OptionHelp> optionHelp; public OptionSpecBuilder option(String name, String description) { return getParser().accepts(name, description); } public OptionSpecBuilder option(Collection<String> aliases, String description) { return getParser().acceptsAll(aliases, description); } public OptionParser getParser() { if (this.parser == null) { this.parser = new OptionParser(); options(); } return this.parser; } protected void options() { } public void setClosure(Closure<?> closure) { this.closure = closure; } public final ExitStatus run(String... args) throws Exception { String[] argsToUse = args.clone(); for (int i = 0; i < argsToUse.length; i++) { if ("-cp".equals(argsToUse[i])) { argsToUse[i] = "--cp"; } } OptionSet options = getParser().parse(argsToUse); return run(options); } /** * Run the command using the specified parsed {@link OptionSet}. * @param options the parsed option set * @return an ExitStatus * @throws Exception */ protected ExitStatus run(OptionSet options) throws Exception { if (this.closure != null) { Object result = this.closure.call(options); if (result instanceof ExitStatus) { return (ExitStatus) result; } if (result instanceof Boolean) { return (Boolean) result ? ExitStatus.OK : ExitStatus.ERROR; } if (result instanceof Integer) { return new ExitStatus((Integer) result, "Finished"); } } return ExitStatus.OK; } public String getHelp() { if (this.help == null) { getParser().formatHelpWith(new BuiltinHelpFormatter(80, 2)); OutputStream out = new ByteArrayOutputStream(); try { getParser().printHelpOn(out); } catch (IOException ex) { return "Help not available"; } this.help = out.toString().replace(" --cp ", " -cp "); } return this.help; } public Collection<OptionHelp> getOptionsHelp() { if (this.optionHelp == null) { OptionHelpFormatter formatter = new OptionHelpFormatter(); getParser().formatHelpWith(formatter); try { getParser().printHelpOn(new ByteArrayOutputStream()); } catch (Exception ex) { // Ignore and provide no hints } this.optionHelp = formatter.getOptionHelp(); } return this.optionHelp; } private static class OptionHelpFormatter implements HelpFormatter { private final List<OptionHelp> help = new ArrayList<OptionHelp>(); @Override public String format(Map<String, ? extends OptionDescriptor> options) { Comparator<OptionDescriptor> comparator = new Comparator<OptionDescriptor>() { @Override public int compare(OptionDescriptor first, OptionDescriptor second) { return first.options().iterator().next() .compareTo(second.options().iterator().next()); } }; Set<OptionDescriptor> sorted = new TreeSet<OptionDescriptor>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) { if (!descriptor.representsNonOptions()) { this.help.add(new OptionHelpAdapter(descriptor)); } } return ""; } public Collection<OptionHelp> getOptionHelp() { return Collections.unmodifiableList(this.help); } } private static class OptionHelpAdapter implements OptionHelp { private final LinkedHashSet<String> options; private final String description; public OptionHelpAdapter(OptionDescriptor descriptor) { this.options = new LinkedHashSet<String>(); for (String option : descriptor.options()) { this.options.add((option.length() == 1 ? "-" : "--") + option); } if (this.options.contains("--cp")) { this.options.remove("--cp"); this.options.add("-cp"); } this.description = descriptor.description(); } @Override public Set<String> getOptions() { return this.options; } @Override public String getUsageHelp() { return this.description; } } }
spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java
/* * Copyright 2012-2014 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.boot.cli.command.options; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import groovy.lang.Closure; import joptsimple.BuiltinHelpFormatter; import joptsimple.HelpFormatter; import joptsimple.OptionDescriptor; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpecBuilder; import org.springframework.boot.cli.command.OptionParsingCommand; import org.springframework.boot.cli.command.status.ExitStatus; /** * Delegate used by {@link OptionParsingCommand} to parse options and run the command. * * @author Dave Syer * @see OptionParsingCommand * @see #run(OptionSet) */ public class OptionHandler { private OptionParser parser; private Closure<?> closure; private String help; private Collection<OptionHelp> optionHelp; public OptionSpecBuilder option(String name, String description) { return getParser().accepts(name, description); } public OptionSpecBuilder option(Collection<String> aliases, String description) { return getParser().acceptsAll(aliases, description); } public OptionParser getParser() { if (this.parser == null) { this.parser = new OptionParser(); options(); } return this.parser; } protected void options() { } public void setClosure(Closure<?> closure) { this.closure = closure; } public final ExitStatus run(String... args) throws Exception { String[] argsToUse = args.clone(); for (int i = 0; i < argsToUse.length; i++) { if ("-cp".equals(argsToUse[i])) { argsToUse[i] = "--cp"; } } OptionSet options = getParser().parse(args); return run(options); } /** * Run the command using the specified parsed {@link OptionSet}. * @param options the parsed option set * @return an ExitStatus * @throws Exception */ protected ExitStatus run(OptionSet options) throws Exception { if (this.closure != null) { Object result = this.closure.call(options); if (result instanceof ExitStatus) { return (ExitStatus) result; } if (result instanceof Boolean) { return (Boolean) result ? ExitStatus.OK : ExitStatus.ERROR; } if (result instanceof Integer) { return new ExitStatus((Integer) result, "Finished"); } } return ExitStatus.OK; } public String getHelp() { if (this.help == null) { getParser().formatHelpWith(new BuiltinHelpFormatter(80, 2)); OutputStream out = new ByteArrayOutputStream(); try { getParser().printHelpOn(out); } catch (IOException ex) { return "Help not available"; } this.help = out.toString().replace(" --cp ", " -cp "); } return this.help; } public Collection<OptionHelp> getOptionsHelp() { if (this.optionHelp == null) { OptionHelpFormatter formatter = new OptionHelpFormatter(); getParser().formatHelpWith(formatter); try { getParser().printHelpOn(new ByteArrayOutputStream()); } catch (Exception ex) { // Ignore and provide no hints } this.optionHelp = formatter.getOptionHelp(); } return this.optionHelp; } private static class OptionHelpFormatter implements HelpFormatter { private final List<OptionHelp> help = new ArrayList<OptionHelp>(); @Override public String format(Map<String, ? extends OptionDescriptor> options) { Comparator<OptionDescriptor> comparator = new Comparator<OptionDescriptor>() { @Override public int compare(OptionDescriptor first, OptionDescriptor second) { return first.options().iterator().next() .compareTo(second.options().iterator().next()); } }; Set<OptionDescriptor> sorted = new TreeSet<OptionDescriptor>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) { if (!descriptor.representsNonOptions()) { this.help.add(new OptionHelpAdapter(descriptor)); } } return ""; } public Collection<OptionHelp> getOptionHelp() { return Collections.unmodifiableList(this.help); } } private static class OptionHelpAdapter implements OptionHelp { private final LinkedHashSet<String> options; private final String description; public OptionHelpAdapter(OptionDescriptor descriptor) { this.options = new LinkedHashSet<String>(); for (String option : descriptor.options()) { this.options.add((option.length() == 1 ? "-" : "--") + option); } if (this.options.contains("--cp")) { this.options.remove("--cp"); this.options.add("-cp"); } this.description = descriptor.description(); } @Override public Set<String> getOptions() { return this.options; } @Override public String getUsageHelp() { return this.description; } } }
Fully support `-cp` arguments The CLI application advertises `-cp` support but it appears that only `--cp` is really supported. The fix for gh-178 forgot to update the call to `getParser().parse(...)`. See gh-178
spring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java
Fully support `-cp` arguments
<ide><path>pring-boot-cli/src/main/java/org/springframework/boot/cli/command/options/OptionHandler.java <ide> argsToUse[i] = "--cp"; <ide> } <ide> } <del> OptionSet options = getParser().parse(args); <add> OptionSet options = getParser().parse(argsToUse); <ide> return run(options); <ide> } <ide>
Java
apache-2.0
4974dc35f8f02bece1d189719857452b364bb6f4
0
apache/pdfbox,apache/pdfbox
/* * 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.pdfbox.rendering; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.Image; import java.awt.Paint; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.TexturePaint; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.common.function.PDFunction; import org.apache.pdfbox.pdmodel.documentinterchange.markedcontent.PDPropertyList; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType3Font; import org.apache.pdfbox.pdmodel.font.PDVectorFont; import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern; import org.apache.pdfbox.pdmodel.graphics.PDXObject; import org.apache.pdfbox.pdmodel.graphics.blend.BlendMode; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray; import org.apache.pdfbox.pdmodel.graphics.color.PDICCBased; import org.apache.pdfbox.pdmodel.graphics.color.PDPattern; import org.apache.pdfbox.pdmodel.graphics.color.PDSeparation; import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; import org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroup; import org.apache.pdfbox.pdmodel.graphics.image.PDImage; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentGroup; import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentGroup.RenderState; import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentMembershipDictionary; import org.apache.pdfbox.pdmodel.graphics.pattern.PDAbstractPattern; import org.apache.pdfbox.pdmodel.graphics.pattern.PDShadingPattern; import org.apache.pdfbox.pdmodel.graphics.pattern.PDTilingPattern; import org.apache.pdfbox.pdmodel.graphics.shading.PDShading; import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState; import org.apache.pdfbox.pdmodel.graphics.state.PDSoftMask; import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode; import org.apache.pdfbox.pdmodel.interactive.annotation.AnnotationFilter; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationUnknown; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary; import org.apache.pdfbox.util.Matrix; import org.apache.pdfbox.util.Vector; /** * Paints a page in a PDF document to a Graphics context. May be subclassed to provide custom * rendering. * * <p> * If you want to do custom graphics processing rather than Graphics2D rendering, then you should * subclass {@link PDFGraphicsStreamEngine} instead. Subclassing PageDrawer is only suitable for * cases where the goal is to render onto a {@link Graphics2D} surface. In that case you'll also * have to subclass {@link PDFRenderer} and modify * {@link PDFRenderer#createPageDrawer(PageDrawerParameters)}. * * @author Ben Litchfield */ public class PageDrawer extends PDFGraphicsStreamEngine { private static final Log LOG = LogFactory.getLog(PageDrawer.class); // parent document renderer - note: this is needed for not-yet-implemented resource caching private final PDFRenderer renderer; private final boolean subsamplingAllowed; // the graphics device to draw to, xform is the initial transform of the device (i.e. DPI) private Graphics2D graphics; private AffineTransform xform; // the page box to draw (usually the crop box but may be another) private PDRectangle pageSize; // whether image of a transparency group must be flipped // needed when in a tiling pattern private boolean flipTG = false; // clipping winding rule used for the clipping path private int clipWindingRule = -1; private GeneralPath linePath = new GeneralPath(); // last clipping path private List<Path2D> lastClips; // clip when drawPage() is called, can be null, must be intersected when clipping private Shape initialClip; // shapes of glyphs being drawn to be used for clipping private List<Shape> textClippings; // glyph caches private final Map<PDFont, GlyphCache> glyphCaches = new HashMap<>(); private final TilingPaintFactory tilingPaintFactory = new TilingPaintFactory(this); private final Deque<TransparencyGroup> transparencyGroupStack = new ArrayDeque<>(); // if greater zero the content is hidden and will not be rendered private int nestedHiddenOCGCount; private final RenderDestination destination; private final RenderingHints renderingHints; private final float imageDownscalingOptimizationThreshold; static final int JAVA_VERSION = PageDrawer.getJavaVersion(); /** * Default annotations filter, returns all annotations */ private AnnotationFilter annotationFilter = annotation -> true; /** * Constructor. * * @param parameters Parameters for page drawing. * @throws IOException If there is an error loading properties from the file. */ public PageDrawer(PageDrawerParameters parameters) throws IOException { super(parameters.getPage()); this.renderer = parameters.getRenderer(); this.subsamplingAllowed = parameters.isSubsamplingAllowed(); this.destination = parameters.getDestination(); this.renderingHints = parameters.getRenderingHints(); this.imageDownscalingOptimizationThreshold = parameters.getImageDownscalingOptimizationThreshold(); } /** * Return the AnnotationFilter. * * @return the AnnotationFilter */ public AnnotationFilter getAnnotationFilter() { return annotationFilter; } /** * Set the AnnotationFilter. * * <p>Allows to only render annotation accepted by the filter. * * @param annotationFilter the AnnotationFilter */ public void setAnnotationFilter(AnnotationFilter annotationFilter) { this.annotationFilter = annotationFilter; } /** * Returns the parent renderer. */ public final PDFRenderer getRenderer() { return renderer; } /** * Returns the underlying Graphics2D. May be null if drawPage has not yet been called. */ protected final Graphics2D getGraphics() { return graphics; } /** * Returns the current line path. This is reset to empty after each fill/stroke. */ protected final GeneralPath getLinePath() { return linePath; } /** * Sets high-quality rendering hints on the current Graphics2D. */ private void setRenderingHints() { graphics.addRenderingHints(renderingHints); } /** * Draws the page to the requested context. * * @param g The graphics context to draw onto. * @param pageSize The size of the page to draw. * @throws IOException If there is an IO error while drawing the page. */ public void drawPage(Graphics g, PDRectangle pageSize) throws IOException { graphics = (Graphics2D) g; xform = graphics.getTransform(); initialClip = graphics.getClip(); this.pageSize = pageSize; setRenderingHints(); graphics.translate(0, pageSize.getHeight()); graphics.scale(1, -1); // adjust for non-(0,0) crop box graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY()); processPage(getPage()); for (PDAnnotation annotation : getPage().getAnnotations(annotationFilter)) { showAnnotation(annotation); } graphics = null; } /** * Draws the pattern stream to the requested context. * * @param g The graphics context to draw onto. * @param pattern The tiling pattern to be used. * @param colorSpace color space for this tiling. * @param color color for this tiling. * @param patternMatrix the pattern matrix * @throws IOException If there is an IO error while drawing the page. */ void drawTilingPattern(Graphics2D g, PDTilingPattern pattern, PDColorSpace colorSpace, PDColor color, Matrix patternMatrix) throws IOException { Graphics2D savedGraphics = graphics; graphics = g; GeneralPath savedLinePath = linePath; linePath = new GeneralPath(); int savedClipWindingRule = clipWindingRule; clipWindingRule = -1; List<Path2D> savedLastClips = lastClips; lastClips = null; Shape savedInitialClip = initialClip; initialClip = null; boolean savedFlipTG = flipTG; flipTG = true; setRenderingHints(); processTilingPattern(pattern, color, colorSpace, patternMatrix); flipTG = savedFlipTG; graphics = savedGraphics; linePath = savedLinePath; lastClips = savedLastClips; initialClip = savedInitialClip; clipWindingRule = savedClipWindingRule; } private float clampColor(float color) { return color < 0 ? 0 : (color > 1 ? 1 : color); } /** * Returns an AWT paint for the given PDColor. * * @param color The color to get a paint for. This can be an actual color or a pattern. * @throws IOException */ protected Paint getPaint(PDColor color) throws IOException { PDColorSpace colorSpace = color.getColorSpace(); if (colorSpace instanceof PDSeparation && "None".equals(((PDSeparation) colorSpace).getColorantName())) { // PDFBOX-4900: "The special colorant name None shall not produce any visible output" //TODO better solution needs to be found for all occurences where toRGB is called return new Color(0, 0, 0, 0); } else if (!(colorSpace instanceof PDPattern)) { float[] rgb = colorSpace.toRGB(color.getComponents()); return new Color(clampColor(rgb[0]), clampColor(rgb[1]), clampColor(rgb[2])); } else { PDPattern patternSpace = (PDPattern)colorSpace; PDAbstractPattern pattern = patternSpace.getPattern(color); if (pattern instanceof PDTilingPattern) { PDTilingPattern tilingPattern = (PDTilingPattern) pattern; if (tilingPattern.getPaintType() == PDTilingPattern.PAINT_COLORED) { // colored tiling pattern return tilingPaintFactory.create(tilingPattern, null, null, xform); } else { // uncolored tiling pattern return tilingPaintFactory.create(tilingPattern, patternSpace.getUnderlyingColorSpace(), color, xform); } } else { PDShadingPattern shadingPattern = (PDShadingPattern)pattern; PDShading shading = shadingPattern.getShading(); if (shading == null) { LOG.error("shadingPattern is null, will be filled with transparency"); return new Color(0,0,0,0); } return shading.toPaint(Matrix.concatenate(getInitialMatrix(), shadingPattern.getMatrix())); } } } /** * Sets the clipping path using caching for performance. We track lastClip manually because * {@link Graphics2D#getClip()} returns a new object instead of the same one passed to * {@link Graphics2D#setClip(java.awt.Shape) setClip()}. You may need to call this if you override * {@link #showGlyph(Matrix, PDFont, int, Vector) showGlyph()}. See * <a href="https://issues.apache.org/jira/browse/PDFBOX-5093">PDFBOX-5093</a> for more. */ protected final void setClip() { List<Path2D> clippingPaths = getGraphicsState().getCurrentClippingPaths(); if (clippingPaths != lastClips) { transferClip(graphics); if (initialClip != null) { // apply the remembered initial clip, but transform it first //TODO see PDFBOX-4583 } lastClips = clippingPaths; } } /** * Transfer clip to the destination device. Override this if you want to avoid to do slow * intersecting operations but want the destination device to do this (e.g. SVG). You can get * the individual clippings via {@link PDGraphicsState#getCurrentClippingPaths()}. See * <a href="https://issues.apache.org/jira/browse/PDFBOX-5258">PDFBOX-5258</a> for sample code. * * @param graphics graphics device */ protected void transferClip(Graphics2D graphics) { Area clippingPath = getGraphicsState().getCurrentClippingPath(); if (clippingPath.getPathIterator(null).isDone()) { // PDFBOX-4821: avoid bug with java printing that empty clipping path is ignored by // replacing with empty rectangle, works because this is not an empty path graphics.setClip(new Rectangle()); } else { graphics.setClip(clippingPath); } } @Override public void beginText() throws IOException { setClip(); beginTextClip(); } @Override public void endText() throws IOException { endTextClip(); } /** * Begin buffering the text clipping path, if any. */ private void beginTextClip() { // buffer the text clippings because they represents a single clipping area textClippings = new ArrayList<>(); } /** * End buffering the text clipping path, if any. */ private void endTextClip() { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); // apply the buffered clip as one area if (renderingMode.isClip() && !textClippings.isEmpty()) { // PDFBOX-4150: this is much faster than using textClippingArea.add(new Area(glyph)) // https://stackoverflow.com/questions/21519007/fast-union-of-shapes-in-java GeneralPath path = new GeneralPath(Path2D.WIND_NON_ZERO, textClippings.size()); for (Shape shape : textClippings) { path.append(shape, false); } state.intersectClippingPath(path); textClippings = new ArrayList<>(); // PDFBOX-3681: lastClip needs to be reset, because after intersection it is still the same // object, thus setClip() would believe that it is cached. lastClips = null; } } @Override protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, Vector displacement) throws IOException { AffineTransform at = textRenderingMatrix.createAffineTransform(); at.concatenate(font.getFontMatrix().createAffineTransform()); // create cache if it does not exist PDVectorFont vectorFont = (PDVectorFont) font; GlyphCache cache = glyphCaches.get(font); if (cache == null) { cache = new GlyphCache(vectorFont); glyphCaches.put(font, cache); } GeneralPath path = cache.getPathForCharacterCode(code); drawGlyph(path, font, code, displacement, at); } /** * Renders a glyph. * * @param path the GeneralPath for the glyph * @param font the font * @param code character code * @param displacement the glyph's displacement (advance) * @param at the transformation * @throws IOException if something went wrong */ private void drawGlyph(GeneralPath path, PDFont font, int code, Vector displacement, AffineTransform at) throws IOException { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); if (path != null) { // Stretch non-embedded glyph if it does not match the height/width contained in the PDF. // Vertical fonts have zero X displacement, so the following code scales to 0 if we don't skip it. // TODO: How should vertical fonts be handled? if (!font.isEmbedded() && !font.isVertical() && !font.isStandard14() && font.hasExplicitWidth(code)) { float fontWidth = font.getWidthFromFont(code); if (fontWidth > 0 && // ignore spaces Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001) { float pdfWidth = displacement.getX() * 1000; at.scale(pdfWidth / fontWidth, 1); } } // render glyph Shape glyph = at.createTransformedShape(path); if (isContentRendered()) { if (renderingMode.isFill()) { graphics.setComposite(state.getNonStrokingJavaComposite()); graphics.setPaint(getNonStrokingPaint()); setClip(); graphics.fill(glyph); } if (renderingMode.isStroke()) { graphics.setComposite(state.getStrokingJavaComposite()); graphics.setPaint(getStrokingPaint()); graphics.setStroke(getStroke()); setClip(); graphics.draw(glyph); } } if (renderingMode.isClip()) { textClippings.add(glyph); } } } @Override protected void showType3Glyph(Matrix textRenderingMatrix, PDType3Font font, int code, Vector displacement) throws IOException { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); if (!RenderingMode.NEITHER.equals(renderingMode)) { super.showType3Glyph(textRenderingMatrix, font, code, displacement); } } @Override public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) { // to ensure that the path is created in the right direction, we have to create // it by combining single lines instead of creating a simple rectangle linePath.moveTo((float) p0.getX(), (float) p0.getY()); linePath.lineTo((float) p1.getX(), (float) p1.getY()); linePath.lineTo((float) p2.getX(), (float) p2.getY()); linePath.lineTo((float) p3.getX(), (float) p3.getY()); // close the subpath instead of adding the last line so that a possible set line // cap style isn't taken into account at the "beginning" of the rectangle linePath.closePath(); } //TODO: move soft mask apply to getPaint()? private Paint applySoftMaskToPaint(Paint parentPaint, PDSoftMask softMask) throws IOException { if (softMask == null || softMask.getGroup() == null) { return parentPaint; } PDColor backdropColor = null; if (COSName.LUMINOSITY.equals(softMask.getSubType())) { COSArray backdropColorArray = softMask.getBackdropColor(); if (backdropColorArray != null) { PDTransparencyGroup form = softMask.getGroup(); PDColorSpace colorSpace = form.getGroup().getColorSpace(form.getResources()); if (colorSpace != null) { backdropColor = new PDColor(backdropColorArray, colorSpace); } } } TransparencyGroup transparencyGroup = new TransparencyGroup(softMask.getGroup(), true, softMask.getInitialTransformationMatrix(), backdropColor); BufferedImage image = transparencyGroup.getImage(); if (image == null) { // Adobe Reader ignores empty softmasks instead of using bc color // sample file: PDFJS-6967_reduced_outside_softmask.pdf return parentPaint; } BufferedImage gray = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY); if (COSName.ALPHA.equals(softMask.getSubType())) { gray.setData(image.getAlphaRaster()); } else if (COSName.LUMINOSITY.equals(softMask.getSubType())) { Graphics g = gray.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); } else { throw new IOException("Invalid soft mask subtype."); } gray = adjustImage(gray); Rectangle2D tpgBounds = transparencyGroup.getBounds(); adjustRectangle(tpgBounds); return new SoftMask(parentPaint, gray, tpgBounds, backdropColor, softMask.getTransferFunction()); } // this adjusts the rectangle to the rotated image to put the soft mask at the correct position //TODO after all transparency problems have been solved: // 1. shouldn't this be done in transparencyGroup.getBounds() ? // 2. change transparencyGroup.getBounds() to getOrigin(), because size isn't used in SoftMask // 3. Is it possible to create the softmask and transparency group in the correct rotation? // (needs rendering identity testing before committing!) private void adjustRectangle(Rectangle2D r) { Matrix m = new Matrix(xform); float scaleX = Math.abs(m.getScalingFactorX()); float scaleY = Math.abs(m.getScalingFactorY()); AffineTransform adjustedTransform = new AffineTransform(xform); adjustedTransform.scale(1.0 / scaleX, 1.0 / scaleY); r.setRect(adjustedTransform.createTransformedShape(r).getBounds2D()); } // returns the image adjusted for applySoftMaskToPaint(). private BufferedImage adjustImage(BufferedImage gray) { AffineTransform at = new AffineTransform(xform); Matrix m = new Matrix(at); at.scale(1.0 / Math.abs(m.getScalingFactorX()), 1.0 / Math.abs(m.getScalingFactorY())); Rectangle originalBounds = new Rectangle(gray.getWidth(), gray.getHeight()); Rectangle2D transformedBounds = at.createTransformedShape(originalBounds).getBounds2D(); at.preConcatenate(AffineTransform.getTranslateInstance(-transformedBounds.getMinX(), -transformedBounds.getMinY())); int width = (int) Math.ceil(transformedBounds.getWidth()); int height = (int) Math.ceil(transformedBounds.getHeight()); BufferedImage transformedGray = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g2 = (Graphics2D) transformedGray.getGraphics(); g2.drawImage(gray, at, null); g2.dispose(); return transformedGray; } // returns the stroking AWT Paint private Paint getStrokingPaint() throws IOException { PDGraphicsState graphicsState = getGraphicsState(); return applySoftMaskToPaint( getPaint(graphicsState.getStrokingColor()), graphicsState.getSoftMask()); } /** * Returns the non-stroking AWT Paint. You may need to call this if you override * {@link #showGlyph(Matrix, PDFont, int, Vector) showGlyph()}. See * <a href="https://issues.apache.org/jira/browse/PDFBOX-5093">PDFBOX-5093</a> for more. * * @return The non-stroking AWT Paint. * @throws IOException */ protected final Paint getNonStrokingPaint() throws IOException { PDGraphicsState graphicsState = getGraphicsState(); return applySoftMaskToPaint( getPaint(graphicsState.getNonStrokingColor()), graphicsState.getSoftMask()); } // create a new stroke based on the current CTM and the current stroke private Stroke getStroke() { PDGraphicsState state = getGraphicsState(); // apply the CTM float lineWidth = transformWidth(state.getLineWidth()); // minimum line width as used by Adobe Reader if (lineWidth < 0.25) { lineWidth = 0.25f; } PDLineDashPattern dashPattern = state.getLineDashPattern(); // PDFBOX-5168: show an all-zero dash array line invisible like Adobe does // must do it here because getDashArray() sets minimum width because of JVM bugs float[] dashArray = dashPattern.getDashArray(); if (isAllZeroDash(dashArray)) { return (Shape p) -> new Area(); } float phaseStart = dashPattern.getPhase(); dashArray = getDashArray(dashPattern); phaseStart = transformWidth(phaseStart); int lineCap = Math.min(2, Math.max(0, state.getLineCap())); // legal values 0..2 int lineJoin = Math.min(2, Math.max(0, state.getLineJoin())); float miterLimit = state.getMiterLimit(); if (miterLimit < 1) { LOG.warn("Miter limit must be >= 1, value " + miterLimit + " is ignored"); miterLimit = 10; } return new BasicStroke(lineWidth, lineCap, lineJoin, miterLimit, dashArray, phaseStart); } private boolean isAllZeroDash(float[] dashArray) { if (dashArray.length > 0) { for (int i = 0; i < dashArray.length; ++i) { if (dashArray[i] != 0) { return false; } } return true; } return false; } private float[] getDashArray(PDLineDashPattern dashPattern) { float[] dashArray = dashPattern.getDashArray(); int phase = dashPattern.getPhase(); // avoid empty, infinite and NaN values (PDFBOX-3360) if (dashArray.length == 0 || Float.isInfinite(phase) || Float.isNaN(phase)) { return null; } for (int i = 0; i < dashArray.length; ++i) { if (Float.isInfinite(dashArray[i]) || Float.isNaN(dashArray[i])) { return null; } } if (JAVA_VERSION < 10) { float scalingFactorX = new Matrix(xform).getScalingFactorX(); for (int i = 0; i < dashArray.length; ++i) { // apply the CTM float w = transformWidth(dashArray[i]); // minimum line dash width avoids JVM crash, // see PDFBOX-2373, PDFBOX-2929, PDFBOX-3204, PDFBOX-3813 // also avoid 0 in array like "[ 0 1000 ] 0 d", see PDFBOX-3724 if (scalingFactorX < 0.5f) { // PDFBOX-4492 dashArray[i] = Math.max(w, 0.2f); } else { dashArray[i] = Math.max(w, 0.062f); } } } else { for (int i = 0; i < dashArray.length; ++i) { // apply the CTM dashArray[i] = transformWidth(dashArray[i]); } } return dashArray; } @Override public void strokePath() throws IOException { //TODO bbox of shading pattern should be used here? (see fillPath) if (isContentRendered()) { graphics.setComposite(getGraphicsState().getStrokingJavaComposite()); graphics.setPaint(getStrokingPaint()); graphics.setStroke(getStroke()); setClip(); graphics.draw(linePath); } linePath.reset(); } @Override public void fillPath(int windingRule) throws IOException { graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.setPaint(getNonStrokingPaint()); setClip(); linePath.setWindingRule(windingRule); // disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes // which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302 // note that we ignore paths with a width/height under 1 as these are fills used as strokes, // see PDFBOX-1658 for an example Rectangle2D bounds = linePath.getBounds2D(); boolean noAntiAlias = isRectangular(linePath) && bounds.getWidth() > 1 && bounds.getHeight() > 1; if (noAntiAlias) { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } Shape shape; if (!(graphics.getPaint() instanceof Color)) { // apply clip to path to avoid oversized device bounds in shading contexts (PDFBOX-2901) Area area = new Area(linePath); area.intersect(new Area(graphics.getClip())); intersectShadingBBox(getGraphicsState().getNonStrokingColor(), area); shape = area; } else { shape = linePath; } if (isContentRendered()) { graphics.fill(shape); } linePath.reset(); if (noAntiAlias) { // JDK 1.7 has a bug where rendering hints are reset by the above call to // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302 setRenderingHints(); } } // checks whether this is a shading pattern and if yes, // get the transformed BBox and intersect with current paint area // need to do it here and not in shading getRaster() because it may have been rotated private void intersectShadingBBox(PDColor color, Area area) throws IOException { if (color.getColorSpace() instanceof PDPattern) { PDColorSpace colorSpace = color.getColorSpace(); PDAbstractPattern pat = ((PDPattern) colorSpace).getPattern(color); if (pat instanceof PDShadingPattern) { PDShading shading = ((PDShadingPattern) pat).getShading(); PDRectangle bbox = shading.getBBox(); if (bbox != null) { Matrix m = Matrix.concatenate(getInitialMatrix(), pat.getMatrix()); Area bboxArea = new Area(bbox.transform(m)); area.intersect(bboxArea); } } } } /** * Returns true if the given path is rectangular. */ private boolean isRectangular(GeneralPath path) { PathIterator iter = path.getPathIterator(null); double[] coords = new double[6]; int count = 0; int[] xs = new int[4]; int[] ys = new int[4]; while (!iter.isDone()) { switch(iter.currentSegment(coords)) { case PathIterator.SEG_MOVETO: if (count == 0) { xs[count] = (int)Math.floor(coords[0]); ys[count] = (int)Math.floor(coords[1]); } else { return false; } count++; break; case PathIterator.SEG_LINETO: if (count < 4) { xs[count] = (int)Math.floor(coords[0]); ys[count] = (int)Math.floor(coords[1]); } else { return false; } count++; break; case PathIterator.SEG_CUBICTO: return false; default: break; } iter.next(); } if (count == 4) { return xs[0] == xs[1] || xs[0] == xs[2] || ys[0] == ys[1] || ys[0] == ys[3]; } return false; } /** * Fills and then strokes the path. * * @param windingRule The winding rule this path will use. * @throws IOException If there is an IO error while filling the path. */ @Override public void fillAndStrokePath(int windingRule) throws IOException { // TODO can we avoid cloning the path? GeneralPath path = (GeneralPath)linePath.clone(); fillPath(windingRule); linePath = path; strokePath(); } @Override public void clip(int windingRule) { // the clipping path will not be updated until the succeeding painting operator is called clipWindingRule = windingRule; } @Override public void moveTo(float x, float y) { linePath.moveTo(x, y); } @Override public void lineTo(float x, float y) { linePath.lineTo(x, y); } @Override public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) { linePath.curveTo(x1, y1, x2, y2, x3, y3); } @Override public Point2D getCurrentPoint() { return linePath.getCurrentPoint(); } @Override public void closePath() { linePath.closePath(); } @Override public void endPath() { if (clipWindingRule != -1) { linePath.setWindingRule(clipWindingRule); if (!linePath.getPathIterator(null).isDone()) { // PDFBOX-4949 / PDF.js 12306: don't clip if "W n" only getGraphicsState().intersectClippingPath(linePath); } // PDFBOX-3836: lastClip needs to be reset, because after intersection it is still the same // object, thus setClip() would believe that it is cached. lastClips = null; clipWindingRule = -1; } linePath.reset(); } @Override public void drawImage(PDImage pdImage) throws IOException { if (pdImage instanceof PDImageXObject && isHiddenOCG(((PDImageXObject) pdImage).getOptionalContent())) { return; } if (!isContentRendered()) { return; } Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); AffineTransform at = ctm.createAffineTransform(); if (!pdImage.getInterpolate()) { // if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364 // only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf // PDFBOX-4930: we use the sizes of the ARGB image. These can be different // than the original sizes of the base image, when the mask is bigger. // PDFBOX-5091: also consider subsampling, the sizes are different too. BufferedImage bim; if (subsamplingAllowed) { bim = pdImage.getImage(null, getSubsampling(pdImage, at)); } else { bim = pdImage.getImage(); } Matrix xformMatrix = new Matrix(xform); boolean isScaledUp = bim.getWidth() <= Math.round(ctm.getScalingFactorX() * xformMatrix.getScalingFactorX()) || bim.getHeight() <= Math.round(ctm.getScalingFactorY() * xformMatrix.getScalingFactorY()); if (isScaledUp) { graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } } if (pdImage.isStencil()) { if (getGraphicsState().getNonStrokingColor().getColorSpace() instanceof PDPattern) { // The earlier code for stencils (see "else") doesn't work with patterns because the // CTM is not taken into consideration. // this code is based on the fact that it is easily possible to draw the mask and // the paint at the correct place with the existing code, but not in one step. // Thus what we do is to draw both in separate images, then combine the two and draw // the result. // Note that the device scale is not used. In theory, some patterns can get better // at higher resolutions but the stencil would become more and more "blocky". // If anybody wants to do this, have a look at the code in showTransparencyGroup(). // draw the paint Paint paint = getNonStrokingPaint(); Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1); Rectangle2D bounds = at.createTransformedShape(unitRect).getBounds2D(); GraphicsConfiguration deviceConfiguration = graphics.getDeviceConfiguration(); int w; int h; if (deviceConfiguration != null && deviceConfiguration.getBounds() != null) { // PDFBOX-4690: bounds doesn't need to be larger than device bounds (OOM risk) Rectangle deviceBounds = deviceConfiguration.getBounds(); w = (int) Math.ceil(Math.min(bounds.getWidth(), deviceBounds.getWidth())); h = (int) Math.ceil(Math.min(bounds.getHeight(), deviceBounds.getHeight())); } else { w = (int) Math.ceil(bounds.getWidth()); h = (int) Math.ceil(bounds.getHeight()); } BufferedImage renderedPaint = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) renderedPaint.getGraphics(); g.translate(-bounds.getMinX(), -bounds.getMinY()); g.setPaint(paint); g.setRenderingHints(graphics.getRenderingHints()); g.fill(bounds); g.dispose(); // draw the mask BufferedImage mask = pdImage.getImage(); BufferedImage renderedMask = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); g = (Graphics2D) renderedMask.getGraphics(); g.translate(-bounds.getMinX(), -bounds.getMinY()); AffineTransform imageTransform = new AffineTransform(at); imageTransform.scale(1.0 / mask.getWidth(), -1.0 / mask.getHeight()); imageTransform.translate(0, -mask.getHeight()); g.setRenderingHints(graphics.getRenderingHints()); g.drawImage(mask, imageTransform, null); g.dispose(); // apply the mask final int[] transparent = new int[4]; int[] alphaPixel = null; WritableRaster raster = renderedPaint.getRaster(); WritableRaster alpha = renderedMask.getRaster(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { alphaPixel = alpha.getPixel(x, y, alphaPixel); if (alphaPixel[0] == 255) { raster.setPixel(x, y, transparent); } } } // draw the image setClip(); graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.drawImage(renderedPaint, AffineTransform.getTranslateInstance(bounds.getMinX(), bounds.getMinY()), null); } else { // fill the image with stenciled paint BufferedImage image = pdImage.getStencilImage(getNonStrokingPaint()); // draw the image drawBufferedImage(image, at); } } else { if (subsamplingAllowed) { int subsampling = getSubsampling(pdImage, at); // draw the subsampled image drawBufferedImage(pdImage.getImage(null, subsampling), at); } else { // subsampling not allowed, draw the image drawBufferedImage(pdImage.getImage(), at); } } if (!pdImage.getInterpolate()) { // JDK 1.7 has a bug where rendering hints are reset by the above call to // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302 setRenderingHints(); } } /** * Calculated the subsampling frequency for a given PDImage based on the current transformation * and its calculated transform * * @param pdImage PDImage to be drawn * @param at Transform that will be applied to the image when drawing * @return The rounded-down ratio of image pixels to drawn pixels. Returned value will always be * >=1. */ private int getSubsampling(PDImage pdImage, AffineTransform at) { // calculate subsampling according to the resulting image size double scale = Math.abs(at.getDeterminant() * xform.getDeterminant()); int subsampling = (int) Math.floor(Math.sqrt(pdImage.getWidth() * pdImage.getHeight() / scale)); if (subsampling > 8) { subsampling = 8; } if (subsampling < 1) { subsampling = 1; } if (subsampling > pdImage.getWidth() || subsampling > pdImage.getHeight()) { // For very small images it is possible that the subsampling would imply 0 size. // To avoid problems, the subsampling is set to no less than the smallest dimension. subsampling = Math.min(pdImage.getWidth(), pdImage.getHeight()); } return subsampling; } private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException { graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); setClip(); AffineTransform imageTransform = new AffineTransform(at); int width = image.getWidth(); int height = image.getHeight(); imageTransform.scale(1.0 / width, -1.0 / height); imageTransform.translate(0, -height); PDSoftMask softMask = getGraphicsState().getSoftMask(); if( softMask != null ) { Rectangle2D rectangle = new Rectangle2D.Float(0, 0, width, height); Paint awtPaint = new TexturePaint(image, rectangle); awtPaint = applySoftMaskToPaint(awtPaint, softMask); graphics.setPaint(awtPaint); AffineTransform originalTransform = graphics.getTransform(); graphics.transform(imageTransform); graphics.fill(rectangle); graphics.setTransform(originalTransform); } else { COSBase transfer = getGraphicsState().getTransfer(); if (transfer instanceof COSArray || transfer instanceof COSDictionary) { image = applyTransferFunction(image, transfer); } // PDFBOX-4516, PDFBOX-4527, PDFBOX-4815, PDFBOX-4886, PDFBOX-4863: // graphics.drawImage() has terrible quality when scaling down, even when // RenderingHints.VALUE_INTERPOLATION_BICUBIC, VALUE_ALPHA_INTERPOLATION_QUALITY, // VALUE_COLOR_RENDER_QUALITY and VALUE_RENDER_QUALITY are all set. // A workaround is to get a pre-scaled image with Image.getScaledInstance() // and then draw that one. To reduce differences in testing // (partly because the method needs integer parameters), only smaller scalings // will trigger the workaround. Because of the slowness we only do it if the user // expects quality rendering and interpolation. Matrix imageTransformMatrix = new Matrix(imageTransform); AffineTransform graphicsTransformA = graphics.getTransform(); Matrix graphicsTransformMatrix = new Matrix(graphicsTransformA); float scaleX = Math.abs(imageTransformMatrix.getScalingFactorX() * graphicsTransformMatrix.getScalingFactorX()); float scaleY = Math.abs(imageTransformMatrix.getScalingFactorY() * graphicsTransformMatrix.getScalingFactorY()); if ((scaleX < imageDownscalingOptimizationThreshold || scaleY < imageDownscalingOptimizationThreshold) && RenderingHints.VALUE_RENDER_QUALITY.equals(graphics.getRenderingHint(RenderingHints.KEY_RENDERING)) && RenderingHints.VALUE_INTERPOLATION_BICUBIC.equals(graphics.getRenderingHint(RenderingHints.KEY_INTERPOLATION))) { int w = Math.round(image.getWidth() * scaleX); int h = Math.round(image.getHeight() * scaleY); if (w < 1 || h < 1) { graphics.drawImage(image, imageTransform, null); return; } Image imageToDraw = image.getScaledInstance(w, h, Image.SCALE_SMOOTH); // remove the scale (extracted from w and h, to have it from the rounded values // hoping to reverse the rounding: without this, we get an horizontal line // when rendering PDFJS-8860-Pattern-Size1.pdf at 100% ) imageTransform.scale(1f / w * image.getWidth(), 1f / h * image.getHeight()); imageTransform.preConcatenate(graphicsTransformA); graphics.setTransform(new AffineTransform()); graphics.drawImage(imageToDraw, imageTransform, null); graphics.setTransform(graphicsTransformA); } else { graphics.drawImage(image, imageTransform, null); } } } private BufferedImage applyTransferFunction(BufferedImage image, COSBase transfer) throws IOException { BufferedImage bim; if (image.getColorModel().hasAlpha()) { bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); } else { bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); } // prepare transfer functions (either one per color or one for all) // and maps (actually arrays[256] to be faster) to avoid calculating values several times Integer[] rMap; Integer[] gMap; Integer[] bMap; PDFunction rf; PDFunction gf; PDFunction bf; if (transfer instanceof COSArray) { COSArray ar = (COSArray) transfer; rf = PDFunction.create(ar.getObject(0)); gf = PDFunction.create(ar.getObject(1)); bf = PDFunction.create(ar.getObject(2)); rMap = new Integer[256]; gMap = new Integer[256]; bMap = new Integer[256]; } else { rf = PDFunction.create(transfer); gf = rf; bf = rf; rMap = new Integer[256]; gMap = rMap; bMap = rMap; } // apply the transfer function to each color, but keep alpha float[] input = new float[1]; for (int x = 0; x < image.getWidth(); ++x) { for (int y = 0; y < image.getHeight(); ++y) { int rgb = image.getRGB(x, y); int ri = (rgb >> 16) & 0xFF; int gi = (rgb >> 8) & 0xFF; int bi = rgb & 0xFF; int ro; int go; int bo; if (rMap[ri] != null) { ro = rMap[ri]; } else { input[0] = (ri & 0xFF) / 255f; ro = (int) (rf.eval(input)[0] * 255); rMap[ri] = ro; } if (gMap[gi] != null) { go = gMap[gi]; } else { input[0] = (gi & 0xFF) / 255f; go = (int) (gf.eval(input)[0] * 255); gMap[gi] = go; } if (bMap[bi] != null) { bo = bMap[bi]; } else { input[0] = (bi & 0xFF) / 255f; bo = (int) (bf.eval(input)[0] * 255); bMap[bi] = bo; } bim.setRGB(x, y, (rgb & 0xFF000000) | (ro << 16) | (go << 8) | bo); } } return bim; } @Override public void shadingFill(COSName shadingName) throws IOException { if (!isContentRendered()) { return; } PDShading shading = getResources().getShading(shadingName); if (shading == null) { LOG.error("shading " + shadingName + " does not exist in resources dictionary"); return; } Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Paint paint = shading.toPaint(ctm); paint = applySoftMaskToPaint(paint, getGraphicsState().getSoftMask()); graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.setPaint(paint); graphics.setClip(null); lastClips = null; // get the transformed BBox and intersect with current clipping path // need to do it here and not in shading getRaster() because it may have been rotated PDRectangle bbox = shading.getBBox(); Area area; if (bbox != null) { area = new Area(bbox.transform(ctm)); area.intersect(getGraphicsState().getCurrentClippingPath()); } else { Rectangle2D bounds = shading.getBounds(new AffineTransform(), ctm); if (bounds != null) { bounds.add(new Point2D.Double(Math.floor(bounds.getMinX() - 1), Math.floor(bounds.getMinY() - 1))); bounds.add(new Point2D.Double(Math.ceil(bounds.getMaxX() + 1), Math.ceil(bounds.getMaxY() + 1))); area = new Area(bounds); area.intersect(getGraphicsState().getCurrentClippingPath()); } else { area = getGraphicsState().getCurrentClippingPath(); } } graphics.fill(area); } @Override public void showAnnotation(PDAnnotation annotation) throws IOException { lastClips = null; int deviceType = -1; GraphicsConfiguration graphicsConfiguration = graphics.getDeviceConfiguration(); if (graphicsConfiguration != null) { GraphicsDevice graphicsDevice = graphicsConfiguration.getDevice(); if (graphicsDevice != null) { deviceType = graphicsDevice.getType(); } } if (deviceType == GraphicsDevice.TYPE_PRINTER && !annotation.isPrinted()) { return; } if (deviceType == GraphicsDevice.TYPE_RASTER_SCREEN && annotation.isNoView()) { return; } if (annotation.isHidden()) { return; } if (annotation.isInvisible() && annotation instanceof PDAnnotationUnknown) { // "If set, do not display the annotation if it does not belong to one // of the standard annotation types and no annotation handler is available." return; } //TODO support NoZoom, example can be found in p5 of PDFBOX-2348 if (isHiddenOCG(annotation.getOptionalContent())) { return; } PDAppearanceDictionary appearance = annotation.getAppearance(); if (appearance == null || appearance.getNormalAppearance() == null) { annotation.constructAppearances(renderer.document); } if (annotation.isNoRotate() && getCurrentPage().getRotation() != 0) { PDRectangle rect = annotation.getRectangle(); AffineTransform savedTransform = graphics.getTransform(); // "The upper-left corner of the annotation remains at the same point in // default user space; the annotation pivots around that point." graphics.rotate(Math.toRadians(getCurrentPage().getRotation()), rect.getLowerLeftX(), rect.getUpperRightY()); super.showAnnotation(annotation); graphics.setTransform(savedTransform); } else { super.showAnnotation(annotation); } } /** * {@inheritDoc} */ @Override public void showForm(PDFormXObject form) throws IOException { if (isHiddenOCG(form.getOptionalContent())) { return; } if (isContentRendered()) { super.showForm(form); } } @Override public void showTransparencyGroup(PDTransparencyGroup form) throws IOException { if (isHiddenOCG(form.getOptionalContent())) { return; } if (!isContentRendered()) { return; } TransparencyGroup group = new TransparencyGroup(form, false, getGraphicsState().getCurrentTransformationMatrix(), null); BufferedImage image = group.getImage(); if (image == null) { // image is empty, don't bother return; } graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); setClip(); // both the DPI xform and the CTM were already applied to the group, so all we do // here is draw it directly onto the Graphics2D device at the appropriate position PDRectangle bbox = group.getBBox(); AffineTransform savedTransform = graphics.getTransform(); Matrix m = new Matrix(xform); float xScale = Math.abs(m.getScalingFactorX()); float yScale = Math.abs(m.getScalingFactorY()); AffineTransform transform = new AffineTransform(xform); transform.scale(1.0 / xScale, 1.0 / yScale); graphics.setTransform(transform); // adjust bbox (x,y) position at the initial scale + cropbox float x = bbox.getLowerLeftX() - pageSize.getLowerLeftX(); float y = pageSize.getUpperRightY() - bbox.getUpperRightY(); if (flipTG) { graphics.translate(0, image.getHeight()); graphics.scale(1, -1); } else { graphics.translate(x * xScale, y * yScale); } PDSoftMask softMask = getGraphicsState().getSoftMask(); if (softMask != null) { Paint awtPaint = new TexturePaint(image, new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight())); awtPaint = applySoftMaskToPaint(awtPaint, softMask); graphics.setPaint(awtPaint); graphics.fill( new Rectangle2D.Float(0, 0, bbox.getWidth() * xScale, bbox.getHeight() * yScale)); } else { try { graphics.drawImage(image, null, null); } catch (InternalError ie) { LOG.error("Exception drawing image, see JDK-6689349, " + "try rendering into a BufferedImage instead", ie); } } graphics.setTransform(savedTransform); } /** * Transparency group. **/ private final class TransparencyGroup { private final BufferedImage image; private final PDRectangle bbox; private final int minX; private final int minY; private final int maxX; private final int maxY; private final int width; private final int height; private final float scaleX; private final float scaleY; /** * Creates a buffered image for a transparency group result. * * @param form the transparency group of the form or soft mask. * @param isSoftMask true if this is a soft mask. * @param ctm the relevant current transformation matrix. For soft masks, this is the CTM at * the time the soft mask is set (not at the time the soft mask is used for fill/stroke!), * for forms, this is the CTM at the time the form is invoked. * @param backdropColor the color according to the /bc entry to be used for luminosity soft * masks. * @throws IOException */ private TransparencyGroup(PDTransparencyGroup form, boolean isSoftMask, Matrix ctm, PDColor backdropColor) throws IOException { Graphics2D savedGraphics = graphics; List<Path2D> savedLastClips = lastClips; Shape savedInitialClip = initialClip; // get the CTM x Form Matrix transform Matrix transform = Matrix.concatenate(ctm, form.getMatrix()); // transform the bbox GeneralPath transformedBox = form.getBBox().transform(transform); // clip the bbox to prevent giant bboxes from consuming all memory Area transformed = new Area(transformedBox); transformed.intersect(getGraphicsState().getCurrentClippingPath()); Rectangle2D clipRect = transformed.getBounds2D(); Matrix m = new Matrix(xform); scaleX = Math.abs(m.getScalingFactorX()); scaleY = Math.abs(m.getScalingFactorY()); if (clipRect.isEmpty()) { image = null; bbox = null; minX = 0; minY = 0; maxX = 0; maxY = 0; width = 0; height = 0; return; } this.bbox = new PDRectangle((float)clipRect.getX(), (float)clipRect.getY(), (float)clipRect.getWidth(), (float)clipRect.getHeight()); // apply the underlying Graphics2D device's DPI transform AffineTransform dpiTransform = AffineTransform.getScaleInstance(scaleX, scaleY); Rectangle2D bounds = dpiTransform.createTransformedShape(clipRect).getBounds2D(); minX = (int) Math.floor(bounds.getMinX()); minY = (int) Math.floor(bounds.getMinY()); maxX = (int) Math.floor(bounds.getMaxX()) + 1; maxY = (int) Math.floor(bounds.getMaxY()) + 1; width = maxX - minX; height = maxY - minY; // FIXME - color space if (isGray(form.getGroup().getColorSpace(form.getResources()))) { image = create2ByteGrayAlphaImage(width, height); } else { image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } boolean needsBackdrop = !isSoftMask && !form.getGroup().isIsolated() && hasBlendMode(form, new HashSet<>()); BufferedImage backdropImage = null; // Position of this group in parent group's coordinates int backdropX = 0; int backdropY = 0; if (needsBackdrop) { if (transparencyGroupStack.isEmpty()) { // Use the current page as the parent group. backdropImage = renderer.getPageImage(); if (backdropImage == null) { needsBackdrop = false; } else { backdropX = minX; backdropY = backdropImage.getHeight() - maxY; } } else { TransparencyGroup parentGroup = transparencyGroupStack.peek(); backdropImage = parentGroup.image; backdropX = minX - parentGroup.minX; backdropY = parentGroup.maxY - maxY; } } Graphics2D g = image.createGraphics(); if (needsBackdrop) { // backdropImage must be included in group image but not in group alpha. g.drawImage(backdropImage, 0, 0, width, height, backdropX, backdropY, backdropX + width, backdropY + height, null); g = new GroupGraphics(image, g); } if (isSoftMask && backdropColor != null) { // "If the subtype is Luminosity, the transparency group XObject G shall be // composited with a fully opaque backdrop whose colour is everywhere defined // by the soft-mask dictionary's BC entry." g.setBackground(new Color(backdropColor.toRGB())); g.clearRect(0, 0, width, height); } // flip y-axis g.translate(0, image.getHeight()); g.scale(1, -1); boolean savedFlipTG = flipTG; flipTG = false; // apply device transform (DPI) // the initial translation is ignored, because we're not writing into the initial graphics device g.transform(dpiTransform); AffineTransform xformOriginal = xform; xform = AffineTransform.getScaleInstance(scaleX, scaleY); PDRectangle pageSizeOriginal = pageSize; pageSize = new PDRectangle(minX / scaleX, minY / scaleY, (float) bounds.getWidth() / scaleX, (float) bounds.getHeight() / scaleY); int clipWindingRuleOriginal = clipWindingRule; clipWindingRule = -1; GeneralPath linePathOriginal = linePath; linePath = new GeneralPath(); // adjust the origin g.translate(-clipRect.getX(), -clipRect.getY()); graphics = g; setRenderingHints(); try { if (isSoftMask) { processSoftMask(form); } else { transparencyGroupStack.push(this); processTransparencyGroup(form); if (!transparencyGroupStack.isEmpty()) { transparencyGroupStack.pop(); } } } finally { flipTG = savedFlipTG; lastClips = savedLastClips; graphics.dispose(); graphics = savedGraphics; initialClip = savedInitialClip; clipWindingRule = clipWindingRuleOriginal; linePath = linePathOriginal; pageSize = pageSizeOriginal; xform = xformOriginal; } if (needsBackdrop) { ((GroupGraphics) g).removeBackdrop(backdropImage, backdropX, backdropY); } } // http://stackoverflow.com/a/21181943/535646 private BufferedImage create2ByteGrayAlphaImage(int width, int height) { // gray + alpha int[] bandOffsets = new int[] {1, 0}; int bands = bandOffsets.length; // Color Model used for raw GRAY + ALPHA final ColorModel CM_GRAY_ALPHA = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); // Init data buffer of type byte DataBuffer buffer = new DataBufferByte(width * height * bands); // Wrap the data buffer in a raster WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, width * bands, bands, bandOffsets, new Point(0, 0)); // Create a custom BufferedImage with the raster and a suitable color model return new BufferedImage(CM_GRAY_ALPHA, raster, false, null); } private boolean isGray(PDColorSpace colorSpace) { if (colorSpace instanceof PDDeviceGray) { return true; } if (colorSpace instanceof PDICCBased) { try { return ((PDICCBased) colorSpace).getAlternateColorSpace() instanceof PDDeviceGray; } catch (IOException ex) { LOG.debug("Couldn't get an alternate ColorSpace", ex); return false; } } return false; } public BufferedImage getImage() { return image; } public PDRectangle getBBox() { return bbox; } public Rectangle2D getBounds() { Point2D size = new Point2D.Double(pageSize.getWidth(), pageSize.getHeight()); // apply the underlying Graphics2D device's DPI transform and y-axis flip AffineTransform dpiTransform = AffineTransform.getScaleInstance(scaleX, scaleY); size = dpiTransform.transform(size, size); // Flip y return new Rectangle2D.Double(minX - pageSize.getLowerLeftX() * scaleX, size.getY() - minY - height + pageSize.getLowerLeftY() * scaleY, width, height); } } private boolean hasBlendMode(PDTransparencyGroup group, Set<COSBase> groupsDone) { if (groupsDone.contains(group.getCOSObject())) { // The group was already processed. Avoid endless recursion. return false; } groupsDone.add(group.getCOSObject()); PDResources resources = group.getResources(); if (resources == null) { return false; } for (COSName name : resources.getExtGStateNames()) { PDExtendedGraphicsState extGState = resources.getExtGState(name); if (extGState == null) { continue; } BlendMode blendMode = extGState.getBlendMode(); if (blendMode != BlendMode.NORMAL) { return true; } } // Recursively process nested transparency groups for (COSName name : resources.getXObjectNames()) { PDXObject xObject; try { xObject = resources.getXObject(name); } catch (IOException ex) { continue; } if (xObject instanceof PDTransparencyGroup && hasBlendMode((PDTransparencyGroup)xObject, groupsDone)) { return true; } } return false; } /** * {@inheritDoc} */ @Override public void beginMarkedContentSequence(COSName tag, COSDictionary properties) { if (nestedHiddenOCGCount > 0) { nestedHiddenOCGCount++; return; } if (tag == null || getPage().getResources() == null) { return; } if (isHiddenOCG(getPage().getResources().getProperties(tag))) { nestedHiddenOCGCount = 1; } } /** * {@inheritDoc} */ @Override public void endMarkedContentSequence() { if (nestedHiddenOCGCount > 0) { nestedHiddenOCGCount--; } } private boolean isContentRendered() { return nestedHiddenOCGCount <= 0; } private boolean isHiddenOCG(PDPropertyList propertyList) { if (propertyList instanceof PDOptionalContentGroup) { PDOptionalContentGroup group = (PDOptionalContentGroup) propertyList; RenderState printState = group.getRenderState(destination); if (printState == null) { if (!getRenderer().isGroupEnabled(group)) { return true; } } else if (RenderState.OFF.equals(printState)) { return true; } } else if (propertyList instanceof PDOptionalContentMembershipDictionary) { return isHiddenOCMD((PDOptionalContentMembershipDictionary) propertyList); } return false; } private boolean isHiddenOCMD(PDOptionalContentMembershipDictionary ocmd) { if (ocmd.getCOSObject().getCOSArray(COSName.VE) != null) { // support seems to be optional, and is approximated by /P and /OCGS LOG.info("/VE entry ignored in Optional Content Membership Dictionary"); } List<PDPropertyList> oCGs = ocmd.getOCGs(); if (oCGs.isEmpty()) { return false; } List<Boolean> visibles = new ArrayList<>(); oCGs.forEach(prop -> visibles.add(!isHiddenOCG(prop))); COSName visibilityPolicy = ocmd.getVisibilityPolicy(); // visible if any of the entries in OCGs are OFF if (COSName.ANY_OFF.equals(visibilityPolicy)) { return visibles.stream().noneMatch(v -> !v); } // visible only if all of the entries in OCGs are ON if (COSName.ALL_ON.equals(visibilityPolicy)) { return visibles.stream().anyMatch(v -> !v); } // visible only if all of the entries in OCGs are OFF if (COSName.ALL_OFF.equals(visibilityPolicy)) { return visibles.stream().anyMatch(v -> v); } // visible if any of the entries in OCGs are ON // AnyOn is default return visibles.stream().noneMatch(v -> v); } private static int getJavaVersion() { // strategy from lucene-solr/lucene/core/src/java/org/apache/lucene/util/Constants.java String version = System.getProperty("java.specification.version"); final StringTokenizer st = new StringTokenizer(version, "."); try { int major = Integer.parseInt(st.nextToken()); int minor = 0; if (st.hasMoreTokens()) { minor = Integer.parseInt(st.nextToken()); } return major == 1 ? minor : major; } catch (NumberFormatException nfe) { // maybe some new numbering scheme in the 22nd century return 0; } } }
pdfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.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.pdfbox.rendering; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.Image; import java.awt.Paint; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.TexturePaint; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.Path2D; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ComponentColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine; import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.common.function.PDFunction; import org.apache.pdfbox.pdmodel.documentinterchange.markedcontent.PDPropertyList; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType3Font; import org.apache.pdfbox.pdmodel.font.PDVectorFont; import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern; import org.apache.pdfbox.pdmodel.graphics.PDXObject; import org.apache.pdfbox.pdmodel.graphics.blend.BlendMode; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace; import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray; import org.apache.pdfbox.pdmodel.graphics.color.PDICCBased; import org.apache.pdfbox.pdmodel.graphics.color.PDPattern; import org.apache.pdfbox.pdmodel.graphics.color.PDSeparation; import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; import org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroup; import org.apache.pdfbox.pdmodel.graphics.image.PDImage; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentGroup; import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentGroup.RenderState; import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentMembershipDictionary; import org.apache.pdfbox.pdmodel.graphics.pattern.PDAbstractPattern; import org.apache.pdfbox.pdmodel.graphics.pattern.PDShadingPattern; import org.apache.pdfbox.pdmodel.graphics.pattern.PDTilingPattern; import org.apache.pdfbox.pdmodel.graphics.shading.PDShading; import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState; import org.apache.pdfbox.pdmodel.graphics.state.PDSoftMask; import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode; import org.apache.pdfbox.pdmodel.interactive.annotation.AnnotationFilter; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationUnknown; import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary; import org.apache.pdfbox.util.Matrix; import org.apache.pdfbox.util.Vector; /** * Paints a page in a PDF document to a Graphics context. May be subclassed to provide custom * rendering. * * <p> * If you want to do custom graphics processing rather than Graphics2D rendering, then you should * subclass {@link PDFGraphicsStreamEngine} instead. Subclassing PageDrawer is only suitable for * cases where the goal is to render onto a {@link Graphics2D} surface. In that case you'll also * have to subclass {@link PDFRenderer} and modify * {@link PDFRenderer#createPageDrawer(PageDrawerParameters)}. * * @author Ben Litchfield */ public class PageDrawer extends PDFGraphicsStreamEngine { private static final Log LOG = LogFactory.getLog(PageDrawer.class); // parent document renderer - note: this is needed for not-yet-implemented resource caching private final PDFRenderer renderer; private final boolean subsamplingAllowed; // the graphics device to draw to, xform is the initial transform of the device (i.e. DPI) private Graphics2D graphics; private AffineTransform xform; // the page box to draw (usually the crop box but may be another) private PDRectangle pageSize; // whether image of a transparency group must be flipped // needed when in a tiling pattern private boolean flipTG = false; // clipping winding rule used for the clipping path private int clipWindingRule = -1; private GeneralPath linePath = new GeneralPath(); // last clipping path private List<Path2D> lastClips; // clip when drawPage() is called, can be null, must be intersected when clipping private Shape initialClip; // shapes of glyphs being drawn to be used for clipping private List<Shape> textClippings; // glyph caches private final Map<PDFont, GlyphCache> glyphCaches = new HashMap<>(); private final TilingPaintFactory tilingPaintFactory = new TilingPaintFactory(this); private final Deque<TransparencyGroup> transparencyGroupStack = new ArrayDeque<>(); // if greater zero the content is hidden and will not be rendered private int nestedHiddenOCGCount; private final RenderDestination destination; private final RenderingHints renderingHints; private final float imageDownscalingOptimizationThreshold; static final int JAVA_VERSION = PageDrawer.getJavaVersion(); /** * Default annotations filter, returns all annotations */ private AnnotationFilter annotationFilter = annotation -> true; /** * Constructor. * * @param parameters Parameters for page drawing. * @throws IOException If there is an error loading properties from the file. */ public PageDrawer(PageDrawerParameters parameters) throws IOException { super(parameters.getPage()); this.renderer = parameters.getRenderer(); this.subsamplingAllowed = parameters.isSubsamplingAllowed(); this.destination = parameters.getDestination(); this.renderingHints = parameters.getRenderingHints(); this.imageDownscalingOptimizationThreshold = parameters.getImageDownscalingOptimizationThreshold(); } /** * Return the AnnotationFilter. * * @return the AnnotationFilter */ public AnnotationFilter getAnnotationFilter() { return annotationFilter; } /** * Set the AnnotationFilter. * * <p>Allows to only render annotation accepted by the filter. * * @param annotationFilter the AnnotationFilter */ public void setAnnotationFilter(AnnotationFilter annotationFilter) { this.annotationFilter = annotationFilter; } /** * Returns the parent renderer. */ public final PDFRenderer getRenderer() { return renderer; } /** * Returns the underlying Graphics2D. May be null if drawPage has not yet been called. */ protected final Graphics2D getGraphics() { return graphics; } /** * Returns the current line path. This is reset to empty after each fill/stroke. */ protected final GeneralPath getLinePath() { return linePath; } /** * Sets high-quality rendering hints on the current Graphics2D. */ private void setRenderingHints() { graphics.addRenderingHints(renderingHints); } /** * Draws the page to the requested context. * * @param g The graphics context to draw onto. * @param pageSize The size of the page to draw. * @throws IOException If there is an IO error while drawing the page. */ public void drawPage(Graphics g, PDRectangle pageSize) throws IOException { graphics = (Graphics2D) g; xform = graphics.getTransform(); initialClip = graphics.getClip(); this.pageSize = pageSize; setRenderingHints(); graphics.translate(0, pageSize.getHeight()); graphics.scale(1, -1); // adjust for non-(0,0) crop box graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY()); processPage(getPage()); for (PDAnnotation annotation : getPage().getAnnotations(annotationFilter)) { showAnnotation(annotation); } graphics = null; } /** * Draws the pattern stream to the requested context. * * @param g The graphics context to draw onto. * @param pattern The tiling pattern to be used. * @param colorSpace color space for this tiling. * @param color color for this tiling. * @param patternMatrix the pattern matrix * @throws IOException If there is an IO error while drawing the page. */ void drawTilingPattern(Graphics2D g, PDTilingPattern pattern, PDColorSpace colorSpace, PDColor color, Matrix patternMatrix) throws IOException { Graphics2D savedGraphics = graphics; graphics = g; GeneralPath savedLinePath = linePath; linePath = new GeneralPath(); int savedClipWindingRule = clipWindingRule; clipWindingRule = -1; List<Path2D> savedLastClips = lastClips; lastClips = null; Shape savedInitialClip = initialClip; initialClip = null; boolean savedFlipTG = flipTG; flipTG = true; setRenderingHints(); processTilingPattern(pattern, color, colorSpace, patternMatrix); flipTG = savedFlipTG; graphics = savedGraphics; linePath = savedLinePath; lastClips = savedLastClips; initialClip = savedInitialClip; clipWindingRule = savedClipWindingRule; } private float clampColor(float color) { return color < 0 ? 0 : (color > 1 ? 1 : color); } /** * Returns an AWT paint for the given PDColor. * * @param color The color to get a paint for. This can be an actual color or a pattern. * @throws IOException */ protected Paint getPaint(PDColor color) throws IOException { PDColorSpace colorSpace = color.getColorSpace(); if (colorSpace instanceof PDSeparation && "None".equals(((PDSeparation) colorSpace).getColorantName())) { // PDFBOX-4900: "The special colorant name None shall not produce any visible output" //TODO better solution needs to be found for all occurences where toRGB is called return new Color(0, 0, 0, 0); } else if (!(colorSpace instanceof PDPattern)) { float[] rgb = colorSpace.toRGB(color.getComponents()); return new Color(clampColor(rgb[0]), clampColor(rgb[1]), clampColor(rgb[2])); } else { PDPattern patternSpace = (PDPattern)colorSpace; PDAbstractPattern pattern = patternSpace.getPattern(color); if (pattern instanceof PDTilingPattern) { PDTilingPattern tilingPattern = (PDTilingPattern) pattern; if (tilingPattern.getPaintType() == PDTilingPattern.PAINT_COLORED) { // colored tiling pattern return tilingPaintFactory.create(tilingPattern, null, null, xform); } else { // uncolored tiling pattern return tilingPaintFactory.create(tilingPattern, patternSpace.getUnderlyingColorSpace(), color, xform); } } else { PDShadingPattern shadingPattern = (PDShadingPattern)pattern; PDShading shading = shadingPattern.getShading(); if (shading == null) { LOG.error("shadingPattern is null, will be filled with transparency"); return new Color(0,0,0,0); } return shading.toPaint(Matrix.concatenate(getInitialMatrix(), shadingPattern.getMatrix())); } } } /** * Sets the clipping path using caching for performance. We track lastClip manually because * {@link Graphics2D#getClip()} returns a new object instead of the same one passed to * {@link Graphics2D#setClip(java.awt.Shape) setClip()}. You may need to call this if you override * {@link #showGlyph(Matrix, PDFont, int, Vector) showGlyph()}. See * <a href="https://issues.apache.org/jira/browse/PDFBOX-5093">PDFBOX-5093</a> for more. */ protected final void setClip() { List<Path2D> clippingPaths = getGraphicsState().getCurrentClippingPaths(); if (clippingPaths != lastClips) { transferClip(graphics); if (initialClip != null) { // apply the remembered initial clip, but transform it first //TODO see PDFBOX-4583 } lastClips = clippingPaths; } } /** * Transfer clip to the destination device. Override this if you want to avoid to do slow * intersecting operations but want the destination device to do this (e.g. SVG). You can get * the individual clippings via {@link PDGraphicsState#getCurrentClippingPaths()}. See * <a href="https://issues.apache.org/jira/browse/PDFBOX-5258">PDFBOX-5258</a> for sample code. * * @param graphics graphics device */ protected void transferClip(Graphics2D graphics) { Area clippingPath = getGraphicsState().getCurrentClippingPath(); if (clippingPath.getPathIterator(null).isDone()) { // PDFBOX-4821: avoid bug with java printing that empty clipping path is ignored by // replacing with empty rectangle, works because this is not an empty path graphics.setClip(new Rectangle()); } else { graphics.setClip(clippingPath); } } @Override public void beginText() throws IOException { setClip(); beginTextClip(); } @Override public void endText() throws IOException { endTextClip(); } /** * Begin buffering the text clipping path, if any. */ private void beginTextClip() { // buffer the text clippings because they represents a single clipping area textClippings = new ArrayList<>(); } /** * End buffering the text clipping path, if any. */ private void endTextClip() { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); // apply the buffered clip as one area if (renderingMode.isClip() && !textClippings.isEmpty()) { // PDFBOX-4150: this is much faster than using textClippingArea.add(new Area(glyph)) // https://stackoverflow.com/questions/21519007/fast-union-of-shapes-in-java GeneralPath path = new GeneralPath(Path2D.WIND_NON_ZERO, textClippings.size()); for (Shape shape : textClippings) { path.append(shape, false); } state.intersectClippingPath(path); textClippings = new ArrayList<>(); // PDFBOX-3681: lastClip needs to be reset, because after intersection it is still the same // object, thus setClip() would believe that it is cached. lastClips = null; } } @Override protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, Vector displacement) throws IOException { AffineTransform at = textRenderingMatrix.createAffineTransform(); at.concatenate(font.getFontMatrix().createAffineTransform()); // create cache if it does not exist PDVectorFont vectorFont = (PDVectorFont) font; GlyphCache cache = glyphCaches.get(font); if (cache == null) { cache = new GlyphCache(vectorFont); glyphCaches.put(font, cache); } GeneralPath path = cache.getPathForCharacterCode(code); drawGlyph(path, font, code, displacement, at); } /** * Renders a glyph. * * @param path the GeneralPath for the glyph * @param font the font * @param code character code * @param displacement the glyph's displacement (advance) * @param at the transformation * @throws IOException if something went wrong */ private void drawGlyph(GeneralPath path, PDFont font, int code, Vector displacement, AffineTransform at) throws IOException { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); if (path != null) { // Stretch non-embedded glyph if it does not match the height/width contained in the PDF. // Vertical fonts have zero X displacement, so the following code scales to 0 if we don't skip it. // TODO: How should vertical fonts be handled? if (!font.isEmbedded() && !font.isVertical() && !font.isStandard14() && font.hasExplicitWidth(code)) { float fontWidth = font.getWidthFromFont(code); if (fontWidth > 0 && // ignore spaces Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001) { float pdfWidth = displacement.getX() * 1000; at.scale(pdfWidth / fontWidth, 1); } } // render glyph Shape glyph = at.createTransformedShape(path); if (isContentRendered()) { if (renderingMode.isFill()) { graphics.setComposite(state.getNonStrokingJavaComposite()); graphics.setPaint(getNonStrokingPaint()); setClip(); graphics.fill(glyph); } if (renderingMode.isStroke()) { graphics.setComposite(state.getStrokingJavaComposite()); graphics.setPaint(getStrokingPaint()); graphics.setStroke(getStroke()); setClip(); graphics.draw(glyph); } } if (renderingMode.isClip()) { textClippings.add(glyph); } } } @Override protected void showType3Glyph(Matrix textRenderingMatrix, PDType3Font font, int code, Vector displacement) throws IOException { PDGraphicsState state = getGraphicsState(); RenderingMode renderingMode = state.getTextState().getRenderingMode(); if (!RenderingMode.NEITHER.equals(renderingMode)) { super.showType3Glyph(textRenderingMatrix, font, code, displacement); } } @Override public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) { // to ensure that the path is created in the right direction, we have to create // it by combining single lines instead of creating a simple rectangle linePath.moveTo((float) p0.getX(), (float) p0.getY()); linePath.lineTo((float) p1.getX(), (float) p1.getY()); linePath.lineTo((float) p2.getX(), (float) p2.getY()); linePath.lineTo((float) p3.getX(), (float) p3.getY()); // close the subpath instead of adding the last line so that a possible set line // cap style isn't taken into account at the "beginning" of the rectangle linePath.closePath(); } //TODO: move soft mask apply to getPaint()? private Paint applySoftMaskToPaint(Paint parentPaint, PDSoftMask softMask) throws IOException { if (softMask == null || softMask.getGroup() == null) { return parentPaint; } PDColor backdropColor = null; if (COSName.LUMINOSITY.equals(softMask.getSubType())) { COSArray backdropColorArray = softMask.getBackdropColor(); if (backdropColorArray != null) { PDTransparencyGroup form = softMask.getGroup(); PDColorSpace colorSpace = form.getGroup().getColorSpace(form.getResources()); if (colorSpace != null) { backdropColor = new PDColor(backdropColorArray, colorSpace); } } } TransparencyGroup transparencyGroup = new TransparencyGroup(softMask.getGroup(), true, softMask.getInitialTransformationMatrix(), backdropColor); BufferedImage image = transparencyGroup.getImage(); if (image == null) { // Adobe Reader ignores empty softmasks instead of using bc color // sample file: PDFJS-6967_reduced_outside_softmask.pdf return parentPaint; } BufferedImage gray = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY); if (COSName.ALPHA.equals(softMask.getSubType())) { gray.setData(image.getAlphaRaster()); } else if (COSName.LUMINOSITY.equals(softMask.getSubType())) { Graphics g = gray.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); } else { throw new IOException("Invalid soft mask subtype."); } gray = adjustImage(gray); Rectangle2D tpgBounds = transparencyGroup.getBounds(); adjustRectangle(tpgBounds); return new SoftMask(parentPaint, gray, tpgBounds, backdropColor, softMask.getTransferFunction()); } // this adjusts the rectangle to the rotated image to put the soft mask at the correct position //TODO after all transparency problems have been solved: // 1. shouldn't this be done in transparencyGroup.getBounds() ? // 2. change transparencyGroup.getBounds() to getOrigin(), because size isn't used in SoftMask // 3. Is it possible to create the softmask and transparency group in the correct rotation? // (needs rendering identity testing before committing!) private void adjustRectangle(Rectangle2D r) { Matrix m = new Matrix(xform); float scaleX = Math.abs(m.getScalingFactorX()); float scaleY = Math.abs(m.getScalingFactorY()); AffineTransform adjustedTransform = new AffineTransform(xform); adjustedTransform.scale(1.0 / scaleX, 1.0 / scaleY); r.setRect(adjustedTransform.createTransformedShape(r).getBounds2D()); } // returns the image adjusted for applySoftMaskToPaint(). private BufferedImage adjustImage(BufferedImage gray) { AffineTransform at = new AffineTransform(xform); Matrix m = new Matrix(at); at.scale(1.0 / Math.abs(m.getScalingFactorX()), 1.0 / Math.abs(m.getScalingFactorY())); Rectangle originalBounds = new Rectangle(gray.getWidth(), gray.getHeight()); Rectangle2D transformedBounds = at.createTransformedShape(originalBounds).getBounds2D(); at.preConcatenate(AffineTransform.getTranslateInstance(-transformedBounds.getMinX(), -transformedBounds.getMinY())); int width = (int) Math.ceil(transformedBounds.getWidth()); int height = (int) Math.ceil(transformedBounds.getHeight()); BufferedImage transformedGray = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g2 = (Graphics2D) transformedGray.getGraphics(); g2.drawImage(gray, at, null); g2.dispose(); return transformedGray; } // returns the stroking AWT Paint private Paint getStrokingPaint() throws IOException { PDGraphicsState graphicsState = getGraphicsState(); return applySoftMaskToPaint( getPaint(graphicsState.getStrokingColor()), graphicsState.getSoftMask()); } /** * Returns the non-stroking AWT Paint. You may need to call this if you override * {@link #showGlyph(Matrix, PDFont, int, Vector) showGlyph()}. See * <a href="https://issues.apache.org/jira/browse/PDFBOX-5093">PDFBOX-5093</a> for more. * * @return The non-stroking AWT Paint. * @throws IOException */ protected final Paint getNonStrokingPaint() throws IOException { PDGraphicsState graphicsState = getGraphicsState(); return applySoftMaskToPaint( getPaint(graphicsState.getNonStrokingColor()), graphicsState.getSoftMask()); } // create a new stroke based on the current CTM and the current stroke private Stroke getStroke() { PDGraphicsState state = getGraphicsState(); // apply the CTM float lineWidth = transformWidth(state.getLineWidth()); // minimum line width as used by Adobe Reader if (lineWidth < 0.25) { lineWidth = 0.25f; } PDLineDashPattern dashPattern = state.getLineDashPattern(); // PDFBOX-5168: show an all-zero dash array line invisible like Adobe does // must do it here because getDashArray() sets minimum width because of JVM bugs float[] dashArray = dashPattern.getDashArray(); if (isAllZeroDash(dashArray)) { return (Shape p) -> new Area(); } float phaseStart = dashPattern.getPhase(); dashArray = getDashArray(dashPattern); phaseStart = transformWidth(phaseStart); int lineCap = Math.min(2, Math.max(0, state.getLineCap())); // legal values 0..2 int lineJoin = Math.min(2, Math.max(0, state.getLineJoin())); float miterLimit = state.getMiterLimit(); if (miterLimit < 1) { LOG.warn("Miter limit must be >= 1, value " + miterLimit + " is ignored"); miterLimit = 10; } return new BasicStroke(lineWidth, lineCap, lineJoin, miterLimit, dashArray, phaseStart); } private boolean isAllZeroDash(float[] dashArray) { if (dashArray.length > 0) { for (int i = 0; i < dashArray.length; ++i) { if (dashArray[i] != 0) { return false; } } return true; } return false; } private float[] getDashArray(PDLineDashPattern dashPattern) { float[] dashArray = dashPattern.getDashArray(); int phase = dashPattern.getPhase(); // avoid empty, infinite and NaN values (PDFBOX-3360) if (dashArray.length == 0 || Float.isInfinite(phase) || Float.isNaN(phase)) { return null; } for (int i = 0; i < dashArray.length; ++i) { if (Float.isInfinite(dashArray[i]) || Float.isNaN(dashArray[i])) { return null; } } if (JAVA_VERSION < 10) { float scalingFactorX = new Matrix(xform).getScalingFactorX(); for (int i = 0; i < dashArray.length; ++i) { // apply the CTM float w = transformWidth(dashArray[i]); // minimum line dash width avoids JVM crash, // see PDFBOX-2373, PDFBOX-2929, PDFBOX-3204, PDFBOX-3813 // also avoid 0 in array like "[ 0 1000 ] 0 d", see PDFBOX-3724 if (scalingFactorX < 0.5f) { // PDFBOX-4492 dashArray[i] = Math.max(w, 0.2f); } else { dashArray[i] = Math.max(w, 0.062f); } } } else { for (int i = 0; i < dashArray.length; ++i) { // apply the CTM dashArray[i] = transformWidth(dashArray[i]); } } return dashArray; } @Override public void strokePath() throws IOException { //TODO bbox of shading pattern should be used here? (see fillPath) if (isContentRendered()) { graphics.setComposite(getGraphicsState().getStrokingJavaComposite()); graphics.setPaint(getStrokingPaint()); graphics.setStroke(getStroke()); setClip(); graphics.draw(linePath); } linePath.reset(); } @Override public void fillPath(int windingRule) throws IOException { graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.setPaint(getNonStrokingPaint()); setClip(); linePath.setWindingRule(windingRule); // disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes // which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302 // note that we ignore paths with a width/height under 1 as these are fills used as strokes, // see PDFBOX-1658 for an example Rectangle2D bounds = linePath.getBounds2D(); boolean noAntiAlias = isRectangular(linePath) && bounds.getWidth() > 1 && bounds.getHeight() > 1; if (noAntiAlias) { graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } Shape shape; if (!(graphics.getPaint() instanceof Color)) { // apply clip to path to avoid oversized device bounds in shading contexts (PDFBOX-2901) Area area = new Area(linePath); area.intersect(new Area(graphics.getClip())); intersectShadingBBox(getGraphicsState().getNonStrokingColor(), area); shape = area; } else { shape = linePath; } if (isContentRendered()) { graphics.fill(shape); } linePath.reset(); if (noAntiAlias) { // JDK 1.7 has a bug where rendering hints are reset by the above call to // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302 setRenderingHints(); } } // checks whether this is a shading pattern and if yes, // get the transformed BBox and intersect with current paint area // need to do it here and not in shading getRaster() because it may have been rotated private void intersectShadingBBox(PDColor color, Area area) throws IOException { if (color.getColorSpace() instanceof PDPattern) { PDColorSpace colorSpace = color.getColorSpace(); PDAbstractPattern pat = ((PDPattern) colorSpace).getPattern(color); if (pat instanceof PDShadingPattern) { PDShading shading = ((PDShadingPattern) pat).getShading(); PDRectangle bbox = shading.getBBox(); if (bbox != null) { Matrix m = Matrix.concatenate(getInitialMatrix(), pat.getMatrix()); Area bboxArea = new Area(bbox.transform(m)); area.intersect(bboxArea); } } } } /** * Returns true if the given path is rectangular. */ private boolean isRectangular(GeneralPath path) { PathIterator iter = path.getPathIterator(null); double[] coords = new double[6]; int count = 0; int[] xs = new int[4]; int[] ys = new int[4]; while (!iter.isDone()) { switch(iter.currentSegment(coords)) { case PathIterator.SEG_MOVETO: if (count == 0) { xs[count] = (int)Math.floor(coords[0]); ys[count] = (int)Math.floor(coords[1]); } else { return false; } count++; break; case PathIterator.SEG_LINETO: if (count < 4) { xs[count] = (int)Math.floor(coords[0]); ys[count] = (int)Math.floor(coords[1]); } else { return false; } count++; break; case PathIterator.SEG_CUBICTO: return false; default: break; } iter.next(); } if (count == 4) { return xs[0] == xs[1] || xs[0] == xs[2] || ys[0] == ys[1] || ys[0] == ys[3]; } return false; } /** * Fills and then strokes the path. * * @param windingRule The winding rule this path will use. * @throws IOException If there is an IO error while filling the path. */ @Override public void fillAndStrokePath(int windingRule) throws IOException { // TODO can we avoid cloning the path? GeneralPath path = (GeneralPath)linePath.clone(); fillPath(windingRule); linePath = path; strokePath(); } @Override public void clip(int windingRule) { // the clipping path will not be updated until the succeeding painting operator is called clipWindingRule = windingRule; } @Override public void moveTo(float x, float y) { linePath.moveTo(x, y); } @Override public void lineTo(float x, float y) { linePath.lineTo(x, y); } @Override public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) { linePath.curveTo(x1, y1, x2, y2, x3, y3); } @Override public Point2D getCurrentPoint() { return linePath.getCurrentPoint(); } @Override public void closePath() { linePath.closePath(); } @Override public void endPath() { if (clipWindingRule != -1) { linePath.setWindingRule(clipWindingRule); if (!linePath.getPathIterator(null).isDone()) { // PDFBOX-4949 / PDF.js 12306: don't clip if "W n" only getGraphicsState().intersectClippingPath(linePath); } // PDFBOX-3836: lastClip needs to be reset, because after intersection it is still the same // object, thus setClip() would believe that it is cached. lastClips = null; clipWindingRule = -1; } linePath.reset(); } @Override public void drawImage(PDImage pdImage) throws IOException { if (pdImage instanceof PDImageXObject && isHiddenOCG(((PDImageXObject) pdImage).getOptionalContent())) { return; } if (!isContentRendered()) { return; } Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); AffineTransform at = ctm.createAffineTransform(); if (!pdImage.getInterpolate()) { // if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364 // only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf // PDFBOX-4930: we use the sizes of the ARGB image. These can be different // than the original sizes of the base image, when the mask is bigger. // PDFBOX-5091: also consider subsampling, the sizes are different too. BufferedImage bim; if (subsamplingAllowed) { bim = pdImage.getImage(null, getSubsampling(pdImage, at)); } else { bim = pdImage.getImage(); } boolean isScaledUp = bim.getWidth() < Math.round(at.getScaleX()) || bim.getHeight() < Math.round(at.getScaleY()); if (isScaledUp) { graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } } if (pdImage.isStencil()) { if (getGraphicsState().getNonStrokingColor().getColorSpace() instanceof PDPattern) { // The earlier code for stencils (see "else") doesn't work with patterns because the // CTM is not taken into consideration. // this code is based on the fact that it is easily possible to draw the mask and // the paint at the correct place with the existing code, but not in one step. // Thus what we do is to draw both in separate images, then combine the two and draw // the result. // Note that the device scale is not used. In theory, some patterns can get better // at higher resolutions but the stencil would become more and more "blocky". // If anybody wants to do this, have a look at the code in showTransparencyGroup(). // draw the paint Paint paint = getNonStrokingPaint(); Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1); Rectangle2D bounds = at.createTransformedShape(unitRect).getBounds2D(); GraphicsConfiguration deviceConfiguration = graphics.getDeviceConfiguration(); int w; int h; if (deviceConfiguration != null && deviceConfiguration.getBounds() != null) { // PDFBOX-4690: bounds doesn't need to be larger than device bounds (OOM risk) Rectangle deviceBounds = deviceConfiguration.getBounds(); w = (int) Math.ceil(Math.min(bounds.getWidth(), deviceBounds.getWidth())); h = (int) Math.ceil(Math.min(bounds.getHeight(), deviceBounds.getHeight())); } else { w = (int) Math.ceil(bounds.getWidth()); h = (int) Math.ceil(bounds.getHeight()); } BufferedImage renderedPaint = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) renderedPaint.getGraphics(); g.translate(-bounds.getMinX(), -bounds.getMinY()); g.setPaint(paint); g.setRenderingHints(graphics.getRenderingHints()); g.fill(bounds); g.dispose(); // draw the mask BufferedImage mask = pdImage.getImage(); BufferedImage renderedMask = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); g = (Graphics2D) renderedMask.getGraphics(); g.translate(-bounds.getMinX(), -bounds.getMinY()); AffineTransform imageTransform = new AffineTransform(at); imageTransform.scale(1.0 / mask.getWidth(), -1.0 / mask.getHeight()); imageTransform.translate(0, -mask.getHeight()); g.setRenderingHints(graphics.getRenderingHints()); g.drawImage(mask, imageTransform, null); g.dispose(); // apply the mask final int[] transparent = new int[4]; int[] alphaPixel = null; WritableRaster raster = renderedPaint.getRaster(); WritableRaster alpha = renderedMask.getRaster(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { alphaPixel = alpha.getPixel(x, y, alphaPixel); if (alphaPixel[0] == 255) { raster.setPixel(x, y, transparent); } } } // draw the image setClip(); graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.drawImage(renderedPaint, AffineTransform.getTranslateInstance(bounds.getMinX(), bounds.getMinY()), null); } else { // fill the image with stenciled paint BufferedImage image = pdImage.getStencilImage(getNonStrokingPaint()); // draw the image drawBufferedImage(image, at); } } else { if (subsamplingAllowed) { int subsampling = getSubsampling(pdImage, at); // draw the subsampled image drawBufferedImage(pdImage.getImage(null, subsampling), at); } else { // subsampling not allowed, draw the image drawBufferedImage(pdImage.getImage(), at); } } if (!pdImage.getInterpolate()) { // JDK 1.7 has a bug where rendering hints are reset by the above call to // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302 setRenderingHints(); } } /** * Calculated the subsampling frequency for a given PDImage based on the current transformation * and its calculated transform * * @param pdImage PDImage to be drawn * @param at Transform that will be applied to the image when drawing * @return The rounded-down ratio of image pixels to drawn pixels. Returned value will always be * >=1. */ private int getSubsampling(PDImage pdImage, AffineTransform at) { // calculate subsampling according to the resulting image size double scale = Math.abs(at.getDeterminant() * xform.getDeterminant()); int subsampling = (int) Math.floor(Math.sqrt(pdImage.getWidth() * pdImage.getHeight() / scale)); if (subsampling > 8) { subsampling = 8; } if (subsampling < 1) { subsampling = 1; } if (subsampling > pdImage.getWidth() || subsampling > pdImage.getHeight()) { // For very small images it is possible that the subsampling would imply 0 size. // To avoid problems, the subsampling is set to no less than the smallest dimension. subsampling = Math.min(pdImage.getWidth(), pdImage.getHeight()); } return subsampling; } private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException { graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); setClip(); AffineTransform imageTransform = new AffineTransform(at); int width = image.getWidth(); int height = image.getHeight(); imageTransform.scale(1.0 / width, -1.0 / height); imageTransform.translate(0, -height); PDSoftMask softMask = getGraphicsState().getSoftMask(); if( softMask != null ) { Rectangle2D rectangle = new Rectangle2D.Float(0, 0, width, height); Paint awtPaint = new TexturePaint(image, rectangle); awtPaint = applySoftMaskToPaint(awtPaint, softMask); graphics.setPaint(awtPaint); AffineTransform originalTransform = graphics.getTransform(); graphics.transform(imageTransform); graphics.fill(rectangle); graphics.setTransform(originalTransform); } else { COSBase transfer = getGraphicsState().getTransfer(); if (transfer instanceof COSArray || transfer instanceof COSDictionary) { image = applyTransferFunction(image, transfer); } // PDFBOX-4516, PDFBOX-4527, PDFBOX-4815, PDFBOX-4886, PDFBOX-4863: // graphics.drawImage() has terrible quality when scaling down, even when // RenderingHints.VALUE_INTERPOLATION_BICUBIC, VALUE_ALPHA_INTERPOLATION_QUALITY, // VALUE_COLOR_RENDER_QUALITY and VALUE_RENDER_QUALITY are all set. // A workaround is to get a pre-scaled image with Image.getScaledInstance() // and then draw that one. To reduce differences in testing // (partly because the method needs integer parameters), only smaller scalings // will trigger the workaround. Because of the slowness we only do it if the user // expects quality rendering and interpolation. Matrix imageTransformMatrix = new Matrix(imageTransform); AffineTransform graphicsTransformA = graphics.getTransform(); Matrix graphicsTransformMatrix = new Matrix(graphicsTransformA); float scaleX = Math.abs(imageTransformMatrix.getScalingFactorX() * graphicsTransformMatrix.getScalingFactorX()); float scaleY = Math.abs(imageTransformMatrix.getScalingFactorY() * graphicsTransformMatrix.getScalingFactorY()); if ((scaleX < imageDownscalingOptimizationThreshold || scaleY < imageDownscalingOptimizationThreshold) && RenderingHints.VALUE_RENDER_QUALITY.equals(graphics.getRenderingHint(RenderingHints.KEY_RENDERING)) && RenderingHints.VALUE_INTERPOLATION_BICUBIC.equals(graphics.getRenderingHint(RenderingHints.KEY_INTERPOLATION))) { int w = Math.round(image.getWidth() * scaleX); int h = Math.round(image.getHeight() * scaleY); if (w < 1 || h < 1) { graphics.drawImage(image, imageTransform, null); return; } Image imageToDraw = image.getScaledInstance(w, h, Image.SCALE_SMOOTH); // remove the scale (extracted from w and h, to have it from the rounded values // hoping to reverse the rounding: without this, we get an horizontal line // when rendering PDFJS-8860-Pattern-Size1.pdf at 100% ) imageTransform.scale(1f / w * image.getWidth(), 1f / h * image.getHeight()); imageTransform.preConcatenate(graphicsTransformA); graphics.setTransform(new AffineTransform()); graphics.drawImage(imageToDraw, imageTransform, null); graphics.setTransform(graphicsTransformA); } else { graphics.drawImage(image, imageTransform, null); } } } private BufferedImage applyTransferFunction(BufferedImage image, COSBase transfer) throws IOException { BufferedImage bim; if (image.getColorModel().hasAlpha()) { bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); } else { bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); } // prepare transfer functions (either one per color or one for all) // and maps (actually arrays[256] to be faster) to avoid calculating values several times Integer[] rMap; Integer[] gMap; Integer[] bMap; PDFunction rf; PDFunction gf; PDFunction bf; if (transfer instanceof COSArray) { COSArray ar = (COSArray) transfer; rf = PDFunction.create(ar.getObject(0)); gf = PDFunction.create(ar.getObject(1)); bf = PDFunction.create(ar.getObject(2)); rMap = new Integer[256]; gMap = new Integer[256]; bMap = new Integer[256]; } else { rf = PDFunction.create(transfer); gf = rf; bf = rf; rMap = new Integer[256]; gMap = rMap; bMap = rMap; } // apply the transfer function to each color, but keep alpha float[] input = new float[1]; for (int x = 0; x < image.getWidth(); ++x) { for (int y = 0; y < image.getHeight(); ++y) { int rgb = image.getRGB(x, y); int ri = (rgb >> 16) & 0xFF; int gi = (rgb >> 8) & 0xFF; int bi = rgb & 0xFF; int ro; int go; int bo; if (rMap[ri] != null) { ro = rMap[ri]; } else { input[0] = (ri & 0xFF) / 255f; ro = (int) (rf.eval(input)[0] * 255); rMap[ri] = ro; } if (gMap[gi] != null) { go = gMap[gi]; } else { input[0] = (gi & 0xFF) / 255f; go = (int) (gf.eval(input)[0] * 255); gMap[gi] = go; } if (bMap[bi] != null) { bo = bMap[bi]; } else { input[0] = (bi & 0xFF) / 255f; bo = (int) (bf.eval(input)[0] * 255); bMap[bi] = bo; } bim.setRGB(x, y, (rgb & 0xFF000000) | (ro << 16) | (go << 8) | bo); } } return bim; } @Override public void shadingFill(COSName shadingName) throws IOException { if (!isContentRendered()) { return; } PDShading shading = getResources().getShading(shadingName); if (shading == null) { LOG.error("shading " + shadingName + " does not exist in resources dictionary"); return; } Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Paint paint = shading.toPaint(ctm); paint = applySoftMaskToPaint(paint, getGraphicsState().getSoftMask()); graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); graphics.setPaint(paint); graphics.setClip(null); lastClips = null; // get the transformed BBox and intersect with current clipping path // need to do it here and not in shading getRaster() because it may have been rotated PDRectangle bbox = shading.getBBox(); Area area; if (bbox != null) { area = new Area(bbox.transform(ctm)); area.intersect(getGraphicsState().getCurrentClippingPath()); } else { Rectangle2D bounds = shading.getBounds(new AffineTransform(), ctm); if (bounds != null) { bounds.add(new Point2D.Double(Math.floor(bounds.getMinX() - 1), Math.floor(bounds.getMinY() - 1))); bounds.add(new Point2D.Double(Math.ceil(bounds.getMaxX() + 1), Math.ceil(bounds.getMaxY() + 1))); area = new Area(bounds); area.intersect(getGraphicsState().getCurrentClippingPath()); } else { area = getGraphicsState().getCurrentClippingPath(); } } graphics.fill(area); } @Override public void showAnnotation(PDAnnotation annotation) throws IOException { lastClips = null; int deviceType = -1; GraphicsConfiguration graphicsConfiguration = graphics.getDeviceConfiguration(); if (graphicsConfiguration != null) { GraphicsDevice graphicsDevice = graphicsConfiguration.getDevice(); if (graphicsDevice != null) { deviceType = graphicsDevice.getType(); } } if (deviceType == GraphicsDevice.TYPE_PRINTER && !annotation.isPrinted()) { return; } if (deviceType == GraphicsDevice.TYPE_RASTER_SCREEN && annotation.isNoView()) { return; } if (annotation.isHidden()) { return; } if (annotation.isInvisible() && annotation instanceof PDAnnotationUnknown) { // "If set, do not display the annotation if it does not belong to one // of the standard annotation types and no annotation handler is available." return; } //TODO support NoZoom, example can be found in p5 of PDFBOX-2348 if (isHiddenOCG(annotation.getOptionalContent())) { return; } PDAppearanceDictionary appearance = annotation.getAppearance(); if (appearance == null || appearance.getNormalAppearance() == null) { annotation.constructAppearances(renderer.document); } if (annotation.isNoRotate() && getCurrentPage().getRotation() != 0) { PDRectangle rect = annotation.getRectangle(); AffineTransform savedTransform = graphics.getTransform(); // "The upper-left corner of the annotation remains at the same point in // default user space; the annotation pivots around that point." graphics.rotate(Math.toRadians(getCurrentPage().getRotation()), rect.getLowerLeftX(), rect.getUpperRightY()); super.showAnnotation(annotation); graphics.setTransform(savedTransform); } else { super.showAnnotation(annotation); } } /** * {@inheritDoc} */ @Override public void showForm(PDFormXObject form) throws IOException { if (isHiddenOCG(form.getOptionalContent())) { return; } if (isContentRendered()) { super.showForm(form); } } @Override public void showTransparencyGroup(PDTransparencyGroup form) throws IOException { if (isHiddenOCG(form.getOptionalContent())) { return; } if (!isContentRendered()) { return; } TransparencyGroup group = new TransparencyGroup(form, false, getGraphicsState().getCurrentTransformationMatrix(), null); BufferedImage image = group.getImage(); if (image == null) { // image is empty, don't bother return; } graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite()); setClip(); // both the DPI xform and the CTM were already applied to the group, so all we do // here is draw it directly onto the Graphics2D device at the appropriate position PDRectangle bbox = group.getBBox(); AffineTransform savedTransform = graphics.getTransform(); Matrix m = new Matrix(xform); float xScale = Math.abs(m.getScalingFactorX()); float yScale = Math.abs(m.getScalingFactorY()); AffineTransform transform = new AffineTransform(xform); transform.scale(1.0 / xScale, 1.0 / yScale); graphics.setTransform(transform); // adjust bbox (x,y) position at the initial scale + cropbox float x = bbox.getLowerLeftX() - pageSize.getLowerLeftX(); float y = pageSize.getUpperRightY() - bbox.getUpperRightY(); if (flipTG) { graphics.translate(0, image.getHeight()); graphics.scale(1, -1); } else { graphics.translate(x * xScale, y * yScale); } PDSoftMask softMask = getGraphicsState().getSoftMask(); if (softMask != null) { Paint awtPaint = new TexturePaint(image, new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight())); awtPaint = applySoftMaskToPaint(awtPaint, softMask); graphics.setPaint(awtPaint); graphics.fill( new Rectangle2D.Float(0, 0, bbox.getWidth() * xScale, bbox.getHeight() * yScale)); } else { try { graphics.drawImage(image, null, null); } catch (InternalError ie) { LOG.error("Exception drawing image, see JDK-6689349, " + "try rendering into a BufferedImage instead", ie); } } graphics.setTransform(savedTransform); } /** * Transparency group. **/ private final class TransparencyGroup { private final BufferedImage image; private final PDRectangle bbox; private final int minX; private final int minY; private final int maxX; private final int maxY; private final int width; private final int height; private final float scaleX; private final float scaleY; /** * Creates a buffered image for a transparency group result. * * @param form the transparency group of the form or soft mask. * @param isSoftMask true if this is a soft mask. * @param ctm the relevant current transformation matrix. For soft masks, this is the CTM at * the time the soft mask is set (not at the time the soft mask is used for fill/stroke!), * for forms, this is the CTM at the time the form is invoked. * @param backdropColor the color according to the /bc entry to be used for luminosity soft * masks. * @throws IOException */ private TransparencyGroup(PDTransparencyGroup form, boolean isSoftMask, Matrix ctm, PDColor backdropColor) throws IOException { Graphics2D savedGraphics = graphics; List<Path2D> savedLastClips = lastClips; Shape savedInitialClip = initialClip; // get the CTM x Form Matrix transform Matrix transform = Matrix.concatenate(ctm, form.getMatrix()); // transform the bbox GeneralPath transformedBox = form.getBBox().transform(transform); // clip the bbox to prevent giant bboxes from consuming all memory Area transformed = new Area(transformedBox); transformed.intersect(getGraphicsState().getCurrentClippingPath()); Rectangle2D clipRect = transformed.getBounds2D(); Matrix m = new Matrix(xform); scaleX = Math.abs(m.getScalingFactorX()); scaleY = Math.abs(m.getScalingFactorY()); if (clipRect.isEmpty()) { image = null; bbox = null; minX = 0; minY = 0; maxX = 0; maxY = 0; width = 0; height = 0; return; } this.bbox = new PDRectangle((float)clipRect.getX(), (float)clipRect.getY(), (float)clipRect.getWidth(), (float)clipRect.getHeight()); // apply the underlying Graphics2D device's DPI transform AffineTransform dpiTransform = AffineTransform.getScaleInstance(scaleX, scaleY); Rectangle2D bounds = dpiTransform.createTransformedShape(clipRect).getBounds2D(); minX = (int) Math.floor(bounds.getMinX()); minY = (int) Math.floor(bounds.getMinY()); maxX = (int) Math.floor(bounds.getMaxX()) + 1; maxY = (int) Math.floor(bounds.getMaxY()) + 1; width = maxX - minX; height = maxY - minY; // FIXME - color space if (isGray(form.getGroup().getColorSpace(form.getResources()))) { image = create2ByteGrayAlphaImage(width, height); } else { image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } boolean needsBackdrop = !isSoftMask && !form.getGroup().isIsolated() && hasBlendMode(form, new HashSet<>()); BufferedImage backdropImage = null; // Position of this group in parent group's coordinates int backdropX = 0; int backdropY = 0; if (needsBackdrop) { if (transparencyGroupStack.isEmpty()) { // Use the current page as the parent group. backdropImage = renderer.getPageImage(); if (backdropImage == null) { needsBackdrop = false; } else { backdropX = minX; backdropY = backdropImage.getHeight() - maxY; } } else { TransparencyGroup parentGroup = transparencyGroupStack.peek(); backdropImage = parentGroup.image; backdropX = minX - parentGroup.minX; backdropY = parentGroup.maxY - maxY; } } Graphics2D g = image.createGraphics(); if (needsBackdrop) { // backdropImage must be included in group image but not in group alpha. g.drawImage(backdropImage, 0, 0, width, height, backdropX, backdropY, backdropX + width, backdropY + height, null); g = new GroupGraphics(image, g); } if (isSoftMask && backdropColor != null) { // "If the subtype is Luminosity, the transparency group XObject G shall be // composited with a fully opaque backdrop whose colour is everywhere defined // by the soft-mask dictionary's BC entry." g.setBackground(new Color(backdropColor.toRGB())); g.clearRect(0, 0, width, height); } // flip y-axis g.translate(0, image.getHeight()); g.scale(1, -1); boolean savedFlipTG = flipTG; flipTG = false; // apply device transform (DPI) // the initial translation is ignored, because we're not writing into the initial graphics device g.transform(dpiTransform); AffineTransform xformOriginal = xform; xform = AffineTransform.getScaleInstance(scaleX, scaleY); PDRectangle pageSizeOriginal = pageSize; pageSize = new PDRectangle(minX / scaleX, minY / scaleY, (float) bounds.getWidth() / scaleX, (float) bounds.getHeight() / scaleY); int clipWindingRuleOriginal = clipWindingRule; clipWindingRule = -1; GeneralPath linePathOriginal = linePath; linePath = new GeneralPath(); // adjust the origin g.translate(-clipRect.getX(), -clipRect.getY()); graphics = g; setRenderingHints(); try { if (isSoftMask) { processSoftMask(form); } else { transparencyGroupStack.push(this); processTransparencyGroup(form); if (!transparencyGroupStack.isEmpty()) { transparencyGroupStack.pop(); } } } finally { flipTG = savedFlipTG; lastClips = savedLastClips; graphics.dispose(); graphics = savedGraphics; initialClip = savedInitialClip; clipWindingRule = clipWindingRuleOriginal; linePath = linePathOriginal; pageSize = pageSizeOriginal; xform = xformOriginal; } if (needsBackdrop) { ((GroupGraphics) g).removeBackdrop(backdropImage, backdropX, backdropY); } } // http://stackoverflow.com/a/21181943/535646 private BufferedImage create2ByteGrayAlphaImage(int width, int height) { // gray + alpha int[] bandOffsets = new int[] {1, 0}; int bands = bandOffsets.length; // Color Model used for raw GRAY + ALPHA final ColorModel CM_GRAY_ALPHA = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); // Init data buffer of type byte DataBuffer buffer = new DataBufferByte(width * height * bands); // Wrap the data buffer in a raster WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, width * bands, bands, bandOffsets, new Point(0, 0)); // Create a custom BufferedImage with the raster and a suitable color model return new BufferedImage(CM_GRAY_ALPHA, raster, false, null); } private boolean isGray(PDColorSpace colorSpace) { if (colorSpace instanceof PDDeviceGray) { return true; } if (colorSpace instanceof PDICCBased) { try { return ((PDICCBased) colorSpace).getAlternateColorSpace() instanceof PDDeviceGray; } catch (IOException ex) { LOG.debug("Couldn't get an alternate ColorSpace", ex); return false; } } return false; } public BufferedImage getImage() { return image; } public PDRectangle getBBox() { return bbox; } public Rectangle2D getBounds() { Point2D size = new Point2D.Double(pageSize.getWidth(), pageSize.getHeight()); // apply the underlying Graphics2D device's DPI transform and y-axis flip AffineTransform dpiTransform = AffineTransform.getScaleInstance(scaleX, scaleY); size = dpiTransform.transform(size, size); // Flip y return new Rectangle2D.Double(minX - pageSize.getLowerLeftX() * scaleX, size.getY() - minY - height + pageSize.getLowerLeftY() * scaleY, width, height); } } private boolean hasBlendMode(PDTransparencyGroup group, Set<COSBase> groupsDone) { if (groupsDone.contains(group.getCOSObject())) { // The group was already processed. Avoid endless recursion. return false; } groupsDone.add(group.getCOSObject()); PDResources resources = group.getResources(); if (resources == null) { return false; } for (COSName name : resources.getExtGStateNames()) { PDExtendedGraphicsState extGState = resources.getExtGState(name); if (extGState == null) { continue; } BlendMode blendMode = extGState.getBlendMode(); if (blendMode != BlendMode.NORMAL) { return true; } } // Recursively process nested transparency groups for (COSName name : resources.getXObjectNames()) { PDXObject xObject; try { xObject = resources.getXObject(name); } catch (IOException ex) { continue; } if (xObject instanceof PDTransparencyGroup && hasBlendMode((PDTransparencyGroup)xObject, groupsDone)) { return true; } } return false; } /** * {@inheritDoc} */ @Override public void beginMarkedContentSequence(COSName tag, COSDictionary properties) { if (nestedHiddenOCGCount > 0) { nestedHiddenOCGCount++; return; } if (tag == null || getPage().getResources() == null) { return; } if (isHiddenOCG(getPage().getResources().getProperties(tag))) { nestedHiddenOCGCount = 1; } } /** * {@inheritDoc} */ @Override public void endMarkedContentSequence() { if (nestedHiddenOCGCount > 0) { nestedHiddenOCGCount--; } } private boolean isContentRendered() { return nestedHiddenOCGCount <= 0; } private boolean isHiddenOCG(PDPropertyList propertyList) { if (propertyList instanceof PDOptionalContentGroup) { PDOptionalContentGroup group = (PDOptionalContentGroup) propertyList; RenderState printState = group.getRenderState(destination); if (printState == null) { if (!getRenderer().isGroupEnabled(group)) { return true; } } else if (RenderState.OFF.equals(printState)) { return true; } } else if (propertyList instanceof PDOptionalContentMembershipDictionary) { return isHiddenOCMD((PDOptionalContentMembershipDictionary) propertyList); } return false; } private boolean isHiddenOCMD(PDOptionalContentMembershipDictionary ocmd) { if (ocmd.getCOSObject().getCOSArray(COSName.VE) != null) { // support seems to be optional, and is approximated by /P and /OCGS LOG.info("/VE entry ignored in Optional Content Membership Dictionary"); } List<PDPropertyList> oCGs = ocmd.getOCGs(); if (oCGs.isEmpty()) { return false; } List<Boolean> visibles = new ArrayList<>(); oCGs.forEach(prop -> visibles.add(!isHiddenOCG(prop))); COSName visibilityPolicy = ocmd.getVisibilityPolicy(); // visible if any of the entries in OCGs are OFF if (COSName.ANY_OFF.equals(visibilityPolicy)) { return visibles.stream().noneMatch(v -> !v); } // visible only if all of the entries in OCGs are ON if (COSName.ALL_ON.equals(visibilityPolicy)) { return visibles.stream().anyMatch(v -> !v); } // visible only if all of the entries in OCGs are OFF if (COSName.ALL_OFF.equals(visibilityPolicy)) { return visibles.stream().anyMatch(v -> v); } // visible if any of the entries in OCGs are ON // AnyOn is default return visibles.stream().noneMatch(v -> v); } private static int getJavaVersion() { // strategy from lucene-solr/lucene/core/src/java/org/apache/lucene/util/Constants.java String version = System.getProperty("java.specification.version"); final StringTokenizer st = new StringTokenizer(version, "."); try { int major = Integer.parseInt(st.nextToken()); int minor = 0; if (st.hasMoreTokens()) { minor = Integer.parseInt(st.nextToken()); } return major == 1 ? minor : major; } catch (NumberFormatException nfe) { // maybe some new numbering scheme in the 22nd century return 0; } } }
PDFBOX-4831: also consider rendering resolution when investigating whether the image is scaled up, as suggested by Gábor Stefanik git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1894101 13f79535-47bb-0310-9956-ffa450edef68
pdfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java
PDFBOX-4831: also consider rendering resolution when investigating whether the image is scaled up, as suggested by Gábor Stefanik
<ide><path>dfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java <ide> { <ide> bim = pdImage.getImage(); <ide> } <del> boolean isScaledUp = bim.getWidth() < Math.round(at.getScaleX()) || <del> bim.getHeight() < Math.round(at.getScaleY()); <del> <add> Matrix xformMatrix = new Matrix(xform); <add> boolean isScaledUp = <add> bim.getWidth() <= Math.round(ctm.getScalingFactorX() * xformMatrix.getScalingFactorX()) || <add> bim.getHeight() <= Math.round(ctm.getScalingFactorY() * xformMatrix.getScalingFactorY()); <ide> if (isScaledUp) <ide> { <ide> graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
Java
mit
1cb6efc556d8ae261d70f6b6d719006a8f7210b6
0
Azerom/tcpmfa
package fr.tcpmfa.display; import java.awt.Image; import fr.tcpmfa.util.Coordinate; public interface GraphicalElement { public Image getImage(Image){ return Image; } public void setImage(Image Image){ this.Image = Image; } public Coordinate getCoordinates(){ return Coordinate; } public void setCoordinates(Coordinate Coordinates){ this.Coordinates = Coordinates; } }
src/fr/tcpmfa/display/GraphicalElement.java
package fr.tcpmfa.display; public interface GraphicalElement { public default Image getImage(java.awt.Image Image){ return Image; } public default void setImage(java.awt.Image newImage){ } public Coordonnees getCoordinates(){ return Coordonnees; } public Coordonnees setCoordinates(){ } }
Low update GraphicalElement
src/fr/tcpmfa/display/GraphicalElement.java
Low update GraphicalElement
<ide><path>rc/fr/tcpmfa/display/GraphicalElement.java <ide> package fr.tcpmfa.display; <add> <add>import java.awt.Image; <add> <add>import fr.tcpmfa.util.Coordinate; <ide> <ide> <ide> public interface GraphicalElement { <ide> <del> public default Image getImage(java.awt.Image Image){ <add> public Image getImage(Image){ <ide> return Image; <ide> } <ide> <del> public default void setImage(java.awt.Image newImage){ <del> <add> public void setImage(Image Image){ <add> this.Image = Image; <ide> } <ide> <del> public Coordonnees getCoordinates(){ <del> return Coordonnees; <add> public Coordinate getCoordinates(){ <add> return Coordinate; <ide> } <ide> <del> public Coordonnees setCoordinates(){ <del> <add> public void setCoordinates(Coordinate Coordinates){ <add> this.Coordinates = Coordinates; <ide> } <ide> <ide> }
Java
bsd-3-clause
116f455a2a585b6b699f421c96904e4a92c26137
0
drkabob/UltAscent1836
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package com.milkenknights; import com.milkenknights.InsightLT.DecimalData; import com.milkenknights.InsightLT.InsightLT; import com.milkenknights.InsightLT.StringData; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.Counter; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SafePWM; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Knight extends IterativeRobot { private static final double JITTER_RANGE = 0.008; JStick xbox; // XBox controller JStick atk; // Logitech ATK3 controller private boolean usingCheesy; private DriverStationLCD lcd; private Compressor compressor; // Pair state "true" means high gear, // Pair state "false" means low gear private SolenoidPair driveGear; // used to remember the gear that is being used // while in and out of slow mode private boolean normalGear; private SolenoidPair hookClimb; //public final static PrefsHelper prefs = new PrefsHelper(); public static PrefsHelper prefs; private Drive drive; private SpeedController shooter; private PulseTalon actuator; private SpeedController kicker; private Counter shooterEnc; private Encoder lWheels; private Encoder rWheels; // stuff for the InsightLT display private InsightLT display; private DecimalData disp_batteryVoltage; private StringData disp_message; public Knight() { prefs = new PrefsHelper(); // get robot preferences, stored on the cRIO drive = new Drive(new Talon(prefs.getInt("leftmotor",4)), new Talon(prefs.getInt("rightmotor",9))); shooter = new Talon(prefs.getInt("shooter", 6)); actuator = new PulseTalon(prefs.getInt("actuator", 1),0.22,1.75); kicker = new Talon(prefs.getInt("kicker",5)); xbox = new JStick(1); atk = new JStick(2); lcd = DriverStationLCD.getInstance(); usingCheesy = false; integral_err = 0; prev_err = 0; // pressure sensor is 3 compressor = new Compressor(5,1); driveGear = new SolenoidXORPair(1,2); normalGear = driveGear.get(); hookClimb = new SolenoidXANDPair(3,4); shooterEnc = new Counter(1); lWheels = new Encoder(3,4); rWheels = new Encoder(6,7); // configure the display to have two lines of text display = new InsightLT(InsightLT.TWO_ONE_LINE_ZONES); display.startDisplay(); // add battery display disp_batteryVoltage = new DecimalData("Bat:"); display.registerData(disp_batteryVoltage,1); // this shows what mode the robot is in // i.e. teleop, autonomous, disabled disp_message = new StringData(); display.registerData(disp_message,2); } /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { compressor.start(); driveGear.set(true); drive.setInvertedMotor(RobotDrive.MotorType.kRearRight, true); drive.setInvertedMotor(RobotDrive.MotorType.kRearLeft,true); shooterEnc.start(); } //This function is called at the start of autonomous Timer timer; double autonStart; int frisbeesThrown; public void autonomousInit() { shooter.set(0.9); kicker.set(0.9); autonStart = Timer.getFPGATimestamp(); frisbeesThrown = 0; driveGear.set(true); } /** * This function is called periodically during autonomous */ double integral_err; double prev_err; double last_timer; boolean frisbeeDone; final double WAIT_AFTER_ACTUATOR = 5; final double DELAY_BETWEEN_FRISBEES = 2.25; final double FRISBEE_SHOOT_TIME = 0.25; final double DRIVE_FORWARD_TIME = 2; public void autonomousPeriodic() { /* //drive.tankDrive(0.4, 0.4); disp_batteryVoltage.setData(DriverStation.getInstance().getBatteryVoltage()); disp_message.setData("autonomous"); if (timer.get() > 1000) { shooter.set(-1); } if (timer.get() > 6000) { actuator.set(0.4); } lcd.println(DriverStationLCD.Line.kUser1, 1, "" + timer.get()); lcd.updateLCD(); */ /* double currentTime = Timer.getFPGATimestamp() - autonStart; double cycleTime = currentTime - WAIT_AFTER_ACTUATOR - (frisbeesThrown*DELAY_BETWEEN_FRISBEES); SmartDashboard.putNumber("current time", currentTime); SmartDashboard.putNumber("cycle time", cycleTime); if (cycleTime > 0) { if (cycleTime < FRISBEE_SHOOT_TIME) { frisbeeDone = false; actuator.set(1); } else { if (!frisbeeDone) { frisbeeDone = true; frisbeesThrown++; actuator.set(0); } } } else { actuator.set(0); } SmartDashboard.putBoolean("Frisbee done",frisbeeDone); SmartDashboard.putNumber("Frisbees thrown",frisbeesThrown); */ /* if (currentTime < DRIVE_FORWARD_TIME) { drive.tankDrive(0.4,0.4); } else { drive.tankDrive(0,0); actuator.set(1); } */ if (Timer.getFPGATimestamp() - autonStart > WAIT_AFTER_ACTUATOR) { actuator.set(1); } } /** * This function is called periodically during operator control */ public void teleopPeriodic() { xbox.update(); atk.update(); // Press A to toggle cheesy drive if (xbox.isReleased(JStick.XBOX_A)) { usingCheesy = !usingCheesy; } // use LB to toggle high and low gear if (xbox.isReleased(JStick.XBOX_LB)) { driveGear.toggle(); normalGear = !normalGear; } // show the solenoids status lcd.println(DriverStationLCD.Line.kUser3,1,driveGear.get()?"High Gear":"Low Gear "); // show if the compressor is running if (compressor.getPressureSwitchValue()) { lcd.println(DriverStationLCD.Line.kUser6,1,"Compressor is off "); } else { lcd.println(DriverStationLCD.Line.kUser6,1,"Compressor is running"); } /* // Old control system // joystick button 1 should spin the shooter and kicker // but the actuator shouldn't run unless the // shooter is at full speed if (atk.isPressed(1)) { shooter.set(-1); kicker.set(-1); // replace the 0.001 with the actual speed if (shooterEnc.getPeriod() < 0.001) { actuator.set(1); } else { actuator.set(0); } } else { shooter.set(0); kicker.set(0); actuator.set(0); } */ // New control system // joystick button 1 spins the actuator // joystick button 2 spins the shooter and kicker // joystick button 3 revereses the shooter and kicker // this control system does not use the optical encoders actuator.set(atk.isPressed(1) ? 1 : 0); shooter.set(atk.isPressed(2) ? 1 : atk.isPressed(3) ? -1 : 0); kicker.set(atk.isPressed(2) ? 1 : atk.isPressed(3) ? -1 : 0); // toggle the hook climb if (xbox.isReleased(JStick.XBOX_RB)) { hookClimb.toggle(); } //double leftStickX = JStick.removeJitter(xbox.getAxis(JStick.XBOX_LSX), JITTER_RANGE); double leftStickY = JStick.removeJitter(xbox.getAxis(JStick.XBOX_LSY), JITTER_RANGE); double rightStickX = JStick.removeJitter(xbox.getAxis(JStick.XBOX_RSX), JITTER_RANGE); double rightStickY = JStick.removeJitter(xbox.getAxis(JStick.XBOX_RSY), JITTER_RANGE); boolean slowMode = xbox.getAxis(JStick.XBOX_TRIG) < -0.5; if (slowMode) { driveGear.set(false); } else { driveGear.set(normalGear); } if (usingCheesy) { drive.cheesyDrive(leftStickY*(slowMode?0.6:1), rightStickX, xbox.isPressed(JStick.XBOX_LJ)); lcd.println(DriverStationLCD.Line.kUser4,1,"cheesy drive"); } else { if (!drive.straightDrive(xbox.getAxis(JStick.XBOX_TRIG))) { drive.tankDrive(leftStickY*(slowMode?0.6:1), rightStickY*(slowMode?0.6:1)); lcd.println(DriverStationLCD.Line.kUser4,1,"tank drive "); } else { lcd.println(DriverStationLCD.Line.kUser4,1,"straightDrive"); } } // print encoder values to see if they're working lcd.println(DriverStationLCD.Line.kUser2,1,""+shooterEnc.getPeriod()); lcd.println(DriverStationLCD.Line.kUser5, 1,""+lWheels.get()+" "+rWheels.get()); SmartDashboard.putNumber("Shooter speed", shooterEnc.getPeriod()); lcd.updateLCD(); // update the display disp_batteryVoltage.setData(DriverStation.getInstance().getBatteryVoltage()); disp_message.setData("teleop"); } public void disabledPeriodic() { disp_batteryVoltage.setData(DriverStation.getInstance().getBatteryVoltage()); disp_message.setData("disabled"); } private boolean shootTester; private boolean pwmtest; private SafePWM[] pwms; public void testInit() { timer.start(); pwmtest = false; pwms = new SafePWM[10]; for (int i = 0; i < 10; ++i) { pwms[i] = new SafePWM(i+1); } } /** * This function is called periodically during test mode */ public void testPeriodic() { xbox.update(); atk.update(); // toggle between PWM test and austin's thing if (xbox.isPressed(JStick.XBOX_LB)) { pwmtest = false; } if (xbox.isPressed(JStick.XBOX_RB)) { pwmtest = true; } if (pwmtest) { for (int i = 0; i < 10; ++i) { if (atk.isPressed(i+1)) { pwms[i].setRaw(143); } } } else { if (xbox.isReleased(JStick.XBOX_A)) { shootTester = !shootTester; lcd.println(DriverStationLCD.Line.kUser1, 1, "Shooter Tester "); } else { lcd.println(DriverStationLCD.Line.kUser1, 1, "Normal Tester "); } //Only spins shooter shooter.set((atk.isPressed(7)) ? -1 : 0); //Only spins the kicker kicker.set((atk.isPressed(6)) ? 1 : 0); //Slow start for shooting 1 if(shootTester && atk.isPressed(1)) { if(timer.get() > 2) { shooter.set(1); lcd.println(DriverStationLCD.Line.kUser2, 1, "Shooter: On "); } if(timer.get() > 4) { kicker.set(1); lcd.println(DriverStationLCD.Line.kUser3, 1, "Kicker: On "); } if(timer.get() > 7) { //actuator.set(1); lcd.println(DriverStationLCD.Line.kUser4, 1, "CAM: On "); } else { timer.reset(); shooter.set(0); kicker.set(0); actuator.set(0); lcd.println(DriverStationLCD.Line.kUser2, 1, "Shooter: Off "); lcd.println(DriverStationLCD.Line.kUser3, 1, "Kicker: Off "); lcd.println(DriverStationLCD.Line.kUser4, 1, "CAM: Off "); } } lcd.println(DriverStationLCD.Line.kUser1, 1, "" + timer.get()); lcd.updateLCD(); } } }
Knight.java
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package com.milkenknights; import com.milkenknights.InsightLT.DecimalData; import com.milkenknights.InsightLT.InsightLT; import com.milkenknights.InsightLT.StringData; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.Counter; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SafePWM; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Knight extends IterativeRobot { private static final double JITTER_RANGE = 0.008; JStick xbox; // XBox controller JStick atk; // Logitech ATK3 controller private boolean usingCheesy; private DriverStationLCD lcd; private Compressor compressor; // Pair state "true" means high gear, // Pair state "false" means low gear private SolenoidPair driveGear; // used to remember the gear that is being used // while in and out of slow mode private boolean normalGear; private SolenoidPair hookClimb; //public final static PrefsHelper prefs = new PrefsHelper(); public static PrefsHelper prefs; private Drive drive; private SpeedController shooter; private PulseTalon actuator; private SpeedController kicker; private Counter shooterEnc; private Encoder lWheels; private Encoder rWheels; // stuff for the InsightLT display private InsightLT display; private DecimalData disp_batteryVoltage; private StringData disp_message; public Knight() { prefs = new PrefsHelper(); // get robot preferences, stored on the cRIO drive = new Drive(new Talon(prefs.getInt("leftmotor",4)), new Talon(prefs.getInt("rightmotor",9))); shooter = new Talon(prefs.getInt("shooter", 6)); actuator = new PulseTalon(prefs.getInt("actuator", 1),0.22,1.75); kicker = new Talon(prefs.getInt("kicker",5)); xbox = new JStick(1); atk = new JStick(2); lcd = DriverStationLCD.getInstance(); usingCheesy = false; integral_err = 0; prev_err = 0; // pressure sensor is 3 compressor = new Compressor(5,1); driveGear = new SolenoidXORPair(1,2); normalGear = driveGear.get(); hookClimb = new SolenoidXANDPair(3,4); shooterEnc = new Counter(1); lWheels = new Encoder(3,4); rWheels = new Encoder(6,7); // configure the display to have two lines of text display = new InsightLT(InsightLT.TWO_ONE_LINE_ZONES); display.startDisplay(); // add battery display disp_batteryVoltage = new DecimalData("Bat:"); display.registerData(disp_batteryVoltage,1); // this shows what mode the robot is in // i.e. teleop, autonomous, disabled disp_message = new StringData(); display.registerData(disp_message,2); } /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { compressor.start(); driveGear.set(true); drive.setInvertedMotor(RobotDrive.MotorType.kRearRight, true); drive.setInvertedMotor(RobotDrive.MotorType.kRearLeft,true); shooterEnc.start(); } //This function is called at the start of autonomous Timer timer; double autonStart; int frisbeesThrown; public void autonomousInit() { shooter.set(1); kicker.set(1); autonStart = Timer.getFPGATimestamp(); frisbeesThrown = 0; driveGear.set(true); } /** * This function is called periodically during autonomous */ double integral_err; double prev_err; double last_timer; boolean frisbeeDone; final double WAIT_AFTER_ACTUATOR = 5; final double DELAY_BETWEEN_FRISBEES = 2.25; final double FRISBEE_SHOOT_TIME = 0.25; final double DRIVE_FORWARD_TIME = 2; public void autonomousPeriodic() { /* //drive.tankDrive(0.4, 0.4); disp_batteryVoltage.setData(DriverStation.getInstance().getBatteryVoltage()); disp_message.setData("autonomous"); if (timer.get() > 1000) { shooter.set(-1); } if (timer.get() > 6000) { actuator.set(0.4); } lcd.println(DriverStationLCD.Line.kUser1, 1, "" + timer.get()); lcd.updateLCD(); */ /* double currentTime = Timer.getFPGATimestamp() - autonStart; double cycleTime = currentTime - WAIT_AFTER_ACTUATOR - (frisbeesThrown*DELAY_BETWEEN_FRISBEES); SmartDashboard.putNumber("current time", currentTime); SmartDashboard.putNumber("cycle time", cycleTime); if (cycleTime > 0) { if (cycleTime < FRISBEE_SHOOT_TIME) { frisbeeDone = false; actuator.set(1); } else { if (!frisbeeDone) { frisbeeDone = true; frisbeesThrown++; actuator.set(0); } } } else { actuator.set(0); } SmartDashboard.putBoolean("Frisbee done",frisbeeDone); SmartDashboard.putNumber("Frisbees thrown",frisbeesThrown); */ /* if (currentTime < DRIVE_FORWARD_TIME) { drive.tankDrive(0.4,0.4); } else { drive.tankDrive(0,0); actuator.set(1); } */ if (Timer.getFPGATimestamp() - autonStart > WAIT_AFTER_ACTUATOR) { actuator.set(1); } } /** * This function is called periodically during operator control */ public void teleopPeriodic() { xbox.update(); atk.update(); // Press A to toggle cheesy drive if (xbox.isReleased(JStick.XBOX_A)) { usingCheesy = !usingCheesy; } // use LB to toggle high and low gear if (xbox.isReleased(JStick.XBOX_LB)) { driveGear.toggle(); normalGear = !normalGear; } // show the solenoids status lcd.println(DriverStationLCD.Line.kUser3,1,driveGear.get()?"High Gear":"Low Gear "); // show if the compressor is running if (compressor.getPressureSwitchValue()) { lcd.println(DriverStationLCD.Line.kUser6,1,"Compressor is off "); } else { lcd.println(DriverStationLCD.Line.kUser6,1,"Compressor is running"); } /* // Old control system // joystick button 1 should spin the shooter and kicker // but the actuator shouldn't run unless the // shooter is at full speed if (atk.isPressed(1)) { shooter.set(-1); kicker.set(-1); // replace the 0.001 with the actual speed if (shooterEnc.getPeriod() < 0.001) { actuator.set(1); } else { actuator.set(0); } } else { shooter.set(0); kicker.set(0); actuator.set(0); } */ // New control system // joystick button 1 spins the actuator // joystick button 2 spins the shooter and kicker // joystick button 3 revereses the shooter and kicker // this control system does not use the optical encoders actuator.set(atk.isPressed(1) ? 1 : 0); shooter.set(atk.isPressed(2) ? 1 : atk.isPressed(3) ? -1 : 0); kicker.set(atk.isPressed(2) ? 1 : atk.isPressed(3) ? -1 : 0); // toggle the hook climb if (xbox.isReleased(JStick.XBOX_RB)) { hookClimb.toggle(); } //double leftStickX = JStick.removeJitter(xbox.getAxis(JStick.XBOX_LSX), JITTER_RANGE); double leftStickY = JStick.removeJitter(xbox.getAxis(JStick.XBOX_LSY), JITTER_RANGE); double rightStickX = JStick.removeJitter(xbox.getAxis(JStick.XBOX_RSX), JITTER_RANGE); double rightStickY = JStick.removeJitter(xbox.getAxis(JStick.XBOX_RSY), JITTER_RANGE); boolean slowMode = xbox.getAxis(JStick.XBOX_TRIG) < -0.5; if (slowMode) { driveGear.set(false); } else { driveGear.set(normalGear); } if (usingCheesy) { drive.cheesyDrive(leftStickY*(slowMode?0.6:1), rightStickX, xbox.isPressed(JStick.XBOX_LJ)); lcd.println(DriverStationLCD.Line.kUser4,1,"cheesy drive"); } else { if (!drive.straightDrive(xbox.getAxis(JStick.XBOX_TRIG))) { drive.tankDrive(leftStickY*(slowMode?0.6:1), rightStickY*(slowMode?0.6:1)); lcd.println(DriverStationLCD.Line.kUser4,1,"tank drive "); } else { lcd.println(DriverStationLCD.Line.kUser4,1,"straightDrive"); } } // print encoder values to see if they're working lcd.println(DriverStationLCD.Line.kUser2,1,""+shooterEnc.getPeriod()); lcd.println(DriverStationLCD.Line.kUser5, 1,""+lWheels.get()+" "+rWheels.get()); SmartDashboard.putNumber("Shooter speed", shooterEnc.getPeriod()); lcd.updateLCD(); // update the display disp_batteryVoltage.setData(DriverStation.getInstance().getBatteryVoltage()); disp_message.setData("teleop"); } public void disabledPeriodic() { disp_batteryVoltage.setData(DriverStation.getInstance().getBatteryVoltage()); disp_message.setData("disabled"); } private boolean shootTester; private boolean pwmtest; private SafePWM[] pwms; public void testInit() { timer.start(); pwmtest = false; pwms = new SafePWM[10]; for (int i = 0; i < 10; ++i) { pwms[i] = new SafePWM(i+1); } } /** * This function is called periodically during test mode */ public void testPeriodic() { xbox.update(); atk.update(); // toggle between PWM test and austin's thing if (xbox.isPressed(JStick.XBOX_LB)) { pwmtest = false; } if (xbox.isPressed(JStick.XBOX_RB)) { pwmtest = true; } if (pwmtest) { for (int i = 0; i < 10; ++i) { if (atk.isPressed(i+1)) { pwms[i].setRaw(143); } } } else { if (xbox.isReleased(JStick.XBOX_A)) { shootTester = !shootTester; lcd.println(DriverStationLCD.Line.kUser1, 1, "Shooter Tester "); } else { lcd.println(DriverStationLCD.Line.kUser1, 1, "Normal Tester "); } //Only spins shooter shooter.set((atk.isPressed(7)) ? -1 : 0); //Only spins the kicker kicker.set((atk.isPressed(6)) ? 1 : 0); //Slow start for shooting 1 if(shootTester && atk.isPressed(1)) { if(timer.get() > 2) { shooter.set(1); lcd.println(DriverStationLCD.Line.kUser2, 1, "Shooter: On "); } if(timer.get() > 4) { kicker.set(1); lcd.println(DriverStationLCD.Line.kUser3, 1, "Kicker: On "); } if(timer.get() > 7) { //actuator.set(1); lcd.println(DriverStationLCD.Line.kUser4, 1, "CAM: On "); } else { timer.reset(); shooter.set(0); kicker.set(0); actuator.set(0); lcd.println(DriverStationLCD.Line.kUser2, 1, "Shooter: Off "); lcd.println(DriverStationLCD.Line.kUser3, 1, "Kicker: Off "); lcd.println(DriverStationLCD.Line.kUser4, 1, "CAM: Off "); } } lcd.println(DriverStationLCD.Line.kUser1, 1, "" + timer.get()); lcd.updateLCD(); } } }
lowered the shooter and kicker speed in autonomous to 90%
Knight.java
lowered the shooter and kicker speed in autonomous to 90%
<ide><path>night.java <ide> double autonStart; <ide> int frisbeesThrown; <ide> public void autonomousInit() { <del> shooter.set(1); <del> kicker.set(1); <add> shooter.set(0.9); <add> kicker.set(0.9); <ide> autonStart = Timer.getFPGATimestamp(); <ide> frisbeesThrown = 0; <ide> driveGear.set(true);
JavaScript
mit
e61981a65a17a72f444765a1243f0fb9f3e7fd40
0
bkimminich/juice-shop,bonze/juice-shop,bkimminich/juice-shop,m4l1c3/juice-shop,bkimminich/juice-shop,m4l1c3/juice-shop,m4l1c3/juice-shop,bkimminich/juice-shop,bonze/juice-shop,m4l1c3/juice-shop,bonze/juice-shop,bonze/juice-shop,m4l1c3/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bonze/juice-shop
var db = require('./index') var reviews = [ { _id: '3QxALD3cSdZ7ekW63', product: 1, message: 'One of my favorites!', author: '[email protected]' }, { product: 17, message: 'Has a nice flavor!', author: '[email protected]' }, { product: 3, message: 'I bought it, would buy again. 5/7', author: '[email protected]' }, { product: 14, message: 'Fresh out of a replicator.', author: '[email protected]' }, { product: 6, message: 'Fry liked it too.', author: '[email protected]' }, { product: 19, message: 'A vital ingredient for a succesful playthrough.', author: '[email protected]' } ] module.exports = function datacreator() { return Promise.all(reviews.map(function (review) { return db.reviews.insert(review) })) }
mongodb/datacreator.js
var db = require('./index') var reviews = [ { product: 1, message: 'One of my favorites!', author: '[email protected]' }, { product: 17, message: 'Has a nice flavor!', author: '[email protected]' }, { product: 3, message: 'I bought it, would buy again. 5/7', author: '[email protected]' }, { product: 14, message: 'Fresh out of a replicator.', author: '[email protected]' }, { product: 6, message: 'Fry liked it too.', author: '[email protected]' }, { product: 19, message: 'A vital ingredient for a succesful playthrough.', author: '[email protected]' } ] module.exports = function datacreator () { return Promise.all(reviews.map(function (review) { return db.reviews.insert(review) })) }
Added a fixed id for the first review, which is used in tests
mongodb/datacreator.js
Added a fixed id for the first review, which is used in tests
<ide><path>ongodb/datacreator.js <ide> var db = require('./index') <ide> <ide> var reviews = [ <del> { product: 1, message: 'One of my favorites!', author: '[email protected]' }, <add> { _id: '3QxALD3cSdZ7ekW63', product: 1, message: 'One of my favorites!', author: '[email protected]' }, <ide> { product: 17, message: 'Has a nice flavor!', author: '[email protected]' }, <ide> { product: 3, message: 'I bought it, would buy again. 5/7', author: '[email protected]' }, <ide> { product: 14, message: 'Fresh out of a replicator.', author: '[email protected]' }, <ide> { product: 19, message: 'A vital ingredient for a succesful playthrough.', author: '[email protected]' } <ide> ] <ide> <del>module.exports = function datacreator () { <add>module.exports = function datacreator() { <ide> return Promise.all(reviews.map(function (review) { <ide> return db.reviews.insert(review) <ide> }))
Java
apache-2.0
dc42425e5f6318c80cec6d53280c17324060f9bf
0
gustavoleitao/Easy-Cassandra,otaviojava/Easy-Cassandra
/* * Copyright 2012 Otávio Gonçalves de Santana (otaviojava) * 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.easycassandra.persistence.cassandra; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Embedded; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.Table; import javax.persistence.Version; import org.easycassandra.CustomData; import org.easycassandra.Index; import org.easycassandra.IndexProblemException; import org.easycassandra.ListData; import org.easycassandra.MapData; import org.easycassandra.SetData; /** * Class Util for Column * * @author otavio * */ public enum ColumnUtil { INTANCE; /** * The integer class is used to enum how default */ public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class; /** * list contains the annotations to map a bean */ private List<String> annotations; { annotations=new LinkedList<String>(); annotations.add(Id.class.getName()); annotations.add(SetData.class.getName()); annotations.add(ListData.class.getName()); annotations.add(MapData.class.getName()); annotations.add(Column.class.getName()); annotations.add(Embedded.class.getName()); annotations.add(EmbeddedId.class.getName()); annotations.add(Enumerated.class.getName()); annotations.add(Index.class.getName()); annotations.add(CustomData.class.getName()); Collections.sort(annotations); } /** * Get The Column name from an Object * * @param object * - Class of the object viewed * @return The name of Column name if there are not will be return null */ public String getColumnFamilyNameSchema(Class<?> object) { String schema = getSchemaConcat(object); return schema.concat(getColumnFamily(object)); } private String getColumnFamily(Class<?> object) { Entity columnFamily = (Entity) object.getAnnotation(Entity.class); Table columnFamilyTable = (Table) object.getAnnotation(Table.class); if (columnFamily != null) { return columnFamily.name().equals("") ? object.getSimpleName() : columnFamily.name(); } else if (columnFamilyTable != null) { return columnFamilyTable.name().equals("") ? object.getSimpleName() : columnFamilyTable.name(); } return object.getSimpleName(); } private String getSchemaConcat(Class<?> class1) { String schema = getSchema(class1); if (!"".equals(schema)) { return schema.concat("."); } return ""; } public String getSchema(Class<?> class1) { Table columnFamily = (Table) class1.getAnnotation(Table.class); if (columnFamily != null) { return columnFamily.schema().equals("") ? null : columnFamily.schema(); } return ""; } /** * verifies that the name of the annotation is empty if you take the field * name * * @param field * - field for viewd * @return The name inside annotations or the field's name */ public String getColumnName(Field field) { if (field.getAnnotation(javax.persistence.Column.class) == null) { return field.getName(); } return field.getAnnotation(javax.persistence.Column.class).name().equals("") ? field.getName() : field.getAnnotation(javax.persistence.Column.class).name(); } /** * verifies that the name of the annotation is empty if you take the field * name * * @param field * @return The name inside annotations or the field's name */ public String getEnumeratedName(Field field) { if (isNormalField(field)) { return getColumnName(field); } return field.getName(); } /** * Return the Field with the KeyValue Annotations * * @see KeyValue * @param persistenceClass * - Class of the object viewed * @return the Field if there are not will be return null */ public Field getKeyField(Class<?> persistenceClass) { return getField(persistenceClass, Id.class); } /** * Return the Field with the complex key Annotations * * @see KeyValue * @param persistenceClass * - Class of the object viewed * @return the Field if there are not will be return null */ public Field getKeyComplexField(Class<?> persistenceClass) { return getField(persistenceClass, EmbeddedId.class); } /** * Return the Field with the IndexValue Annotations * * @see Index * @param persistenceClass * - Class of the object viewed * @return the Field if there are not will be return null */ public Field getIndexField(Class<?> persistenceClass) { return getField(persistenceClass, Index.class); } /** * Return the Fields with the IndexValue Annotations * @author Dinusha Nandika * @see Index * @param persistenceClass * - Class of the object viewed * @return the Fields if there are not will be return empty list */ public List<Field> getIndexFields(Class<?> persistenceClass) { List<Field> indexFieldList = new ArrayList<Field>(); for (Field field : persistenceClass.getDeclaredFields()) { if (field.getAnnotation(Index.class) != null) { indexFieldList.add(field); } else if (field.getAnnotation(Embedded.class) != null) { indexFieldList.addAll(getIndexFields(field.getType())); } } return indexFieldList; } /** * Get the Field of the Object from annotation if there are not return will * be null * * @param object * - Class of the object viewed * @param annotation * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Field getField(Class object, Class annotation) { for (Field field : object.getDeclaredFields()) { if (field.getAnnotation(annotation) != null) { return field; } else if (field.getAnnotation(Embeddable.class) != null) { return getField(field.getType(), annotation); } } return null; } /** * list the fields in the class * * @param class1 * @return list of the fields */ public List<Field> listFields(Class<?> class1) { List<Field> fields = new ArrayList<Field>(); feedFieldList(class1, fields); if (isMappedSuperclass(class1)) { feedFieldList(class1.getSuperclass(), fields); } return fields; } /** * feed the list com Fields * * @param class1 * @param fields */ private void feedFieldList(Class<?> class1, List<Field> fields) { for (Field field : class1.getDeclaredFields()) { if(isColumnToPersist(field)){ fields.add(field); } } } /** * verify is field has some annotations within * {@link #ColumnUtil#annotations} * @param field * @return */ private boolean isColumnToPersist(Field field) { for(Annotation annotation:field.getAnnotations()){ int result=Collections.binarySearch(annotations,annotation.annotationType().getName()); if(result >= 0){ return true; } } return false; } /** * verify if this is key of the column * * @param field * @return */ public boolean isIdField(Field field) { return field.getAnnotation(Id.class) != null; } /** * verify if this is index of the column * * @param field * @return */ public boolean isIndexField(Field field) { return field.getAnnotation(Index.class) != null; } @GeneratedValue public boolean isGeneratedValue(Field field) { return field.getAnnotation(GeneratedValue.class) != null; } /** * verify if this is secundary index of the column * * @param field * @return */ public boolean isSecundaryIndexField(Field field) { return field.getAnnotation(Index.class) != null; } /** * verify if this is a normal column * * @param field * @return */ public boolean isNormalField(Field field) { return field.getAnnotation(javax.persistence.Column.class) != null; } /** * verify if this is a enum column * * @param field * @return */ public boolean isEnumField(Field field) { return field.getAnnotation(Enumerated.class) != null; } /** * verify if this is a Embedded column * * @param field * @return */ public boolean isEmbeddedField(Field field) { return field.getAnnotation(Embedded.class) != null; } /** * verify if this is a Embedded id column * * @param field * @return */ public boolean isEmbeddedIdField(Field field) { return field.getAnnotation(EmbeddedId.class) != null; } /** * verify if this is a Version column * * @param field * @return */ public boolean isVersionField(Field field) { return field.getAnnotation(Version.class) != null; } /** * verify is exist father to persist * * @param class1 * @return */ public boolean isMappedSuperclass(Class<?> class1) { return class1.getSuperclass().getAnnotation(MappedSuperclass.class) != null; } /** * verify if the field is a list * @param field * @return */ public boolean isList(Field field){ return field.getAnnotation(ListData.class) != null; } /** * verify if the field is a map * @param field * @return */ public boolean isMap(Field field){ return field.getAnnotation(MapData.class) != null; } /** * verify if the field is a set * @param field * @return */ public boolean isSet(Field field){ return field.getAnnotation(SetData.class) != null; } /** * verify if the field is custom * @param field * @return */ public boolean isCustom(Field field) { return field.getAnnotation(CustomData.class) != null; } /** * get the Field for parsing <b>columnName</b> in the <b>class1</b>. if there is no such column name or if it denies access return null. * @param columnName * @param class1 * @return */ public Field getFieldByColumnName(String columnName, Class<?> class1) { for(Field index:getIndexFields(class1)){ if(index.getName().equals(columnName)){ return index; } } StringBuilder erro=new StringBuilder(); erro.append("Not found index on ").append(class1.getName()); erro.append(" with name ").append(columnName); throw new IndexProblemException(erro.toString()); } public KeySpaceInformation getKeySpace(String keySpace,Class<?> bean){ String keySchema=getSchema(bean); KeySpaceInformation key=new KeySpaceInformation(); key.keySpace="".equals(keySchema)?keySpace:keySchema; key.columnFamily=getColumnFamily(bean); return key ; } public class KeySpaceInformation{ private String keySpace; private String columnFamily; public String getKeySpace() { return keySpace; } public String getColumnFamily() { return columnFamily; } } }
src/main/java/org/easycassandra/persistence/cassandra/ColumnUtil.java
/* * Copyright 2012 Otávio Gonçalves de Santana (otaviojava) * 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.easycassandra.persistence.cassandra; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Embedded; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.Table; import javax.persistence.Version; import org.easycassandra.CustomData; import org.easycassandra.Index; import org.easycassandra.IndexProblemException; import org.easycassandra.ListData; import org.easycassandra.MapData; import org.easycassandra.SetData; /** * Class Util for Column * * @author otavio * */ public enum ColumnUtil { INTANCE; /** * The integer class is used to enum how default */ public static final Class<?> DEFAULT_ENUM_CLASS = Integer.class; /** * list contains the annotations to map a bean */ private List<String> annotations; { annotations=new LinkedList<String>(); annotations.add(Id.class.getName()); annotations.add(SetData.class.getName()); annotations.add(ListData.class.getName()); annotations.add(MapData.class.getName()); annotations.add(Column.class.getName()); annotations.add(Embedded.class.getName()); annotations.add(EmbeddedId.class.getName()); annotations.add(Enumerated.class.getName()); annotations.add(Index.class.getName()); annotations.add(CustomData.class.getName()); Collections.sort(annotations); } /** * Get The Column name from an Object * * @param object * - Class of the object viewed * @return The name of Column name if there are not will be return null */ public String getColumnFamilyNameSchema(Class<?> object) { String schema = getSchemaConcat(object); return schema.concat(getColumnFamily(object)); } private String getColumnFamily(Class<?> object) { Entity columnFamily = (Entity) object.getAnnotation(Entity.class); Table columnFamilyTable = (Table) object.getAnnotation(Table.class); if (columnFamily != null) { return columnFamily.name().equals("") ? object.getSimpleName() : columnFamily.name(); } else if (columnFamilyTable != null) { return columnFamilyTable.name().equals("") ? object.getSimpleName() : columnFamilyTable.name(); } return object.getSimpleName(); } private String getSchemaConcat(Class<?> class1) { String schema = getSchema(class1); if (!"".equals(schema)) { return schema.concat("."); } return ""; } public String getSchema(Class<?> class1) { Table columnFamily = (Table) class1.getAnnotation(Table.class); if (columnFamily != null) { return columnFamily.schema().equals("") ? null : columnFamily.schema(); } return ""; } /** * verifies that the name of the annotation is empty if you take the field * name * * @param field * - field for viewd * @return The name inside annotations or the field's name */ public String getColumnName(Field field) { if (field.getAnnotation(javax.persistence.Column.class) == null) { return field.getName(); } return field.getAnnotation(javax.persistence.Column.class).name().equals("") ? field.getName() : field.getAnnotation(javax.persistence.Column.class).name(); } /** * verifies that the name of the annotation is empty if you take the field * name * * @param field * @return The name inside annotations or the field's name */ public String getEnumeratedName(Field field) { if (isNormalField(field)) { return getColumnName(field); } return field.getName(); } /** * Return the Field with the KeyValue Annotations * * @see KeyValue * @param persistenceClass * - Class of the object viewed * @return the Field if there are not will be return null */ public Field getKeyField(Class<?> persistenceClass) { return getField(persistenceClass, Id.class); } /** * Return the Field with the complex key Annotations * * @see KeyValue * @param persistenceClass * - Class of the object viewed * @return the Field if there are not will be return null */ public Field getKeyComplexField(Class<?> persistenceClass) { return getField(persistenceClass, EmbeddedId.class); } /** * Return the Field with the IndexValue Annotations * * @see Index * @param persistenceClass * - Class of the object viewed * @return the Field if there are not will be return null */ public Field getIndexField(Class<?> persistenceClass) { return getField(persistenceClass, Index.class); } /** * Return the Fields with the IndexValue Annotations * @author Dinusha Nandika * @see Index * @param persistenceClass * - Class of the object viewed * @return the Fields if there are not will be return empty list */ public List<Field> getIndexFields(Class<?> persistenceClass) { List<Field> indexFieldList = new ArrayList<Field>(); for (Field field : persistenceClass.getDeclaredFields()) { if (field.getAnnotation(Index.class) != null) { indexFieldList.add(field); } else if (field.getAnnotation(Embeddable.class) != null) { indexFieldList.add( getField(field.getType(), Index.class)); } } return indexFieldList; } /** * Get the Field of the Object from annotation if there are not return will * be null * * @param object * - Class of the object viewed * @param annotation * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Field getField(Class object, Class annotation) { for (Field field : object.getDeclaredFields()) { if (field.getAnnotation(annotation) != null) { return field; } else if (field.getAnnotation(Embeddable.class) != null) { return getField(field.getType(), annotation); } } return null; } /** * list the fields in the class * * @param class1 * @return list of the fields */ public List<Field> listFields(Class<?> class1) { List<Field> fields = new ArrayList<Field>(); feedFieldList(class1, fields); if (isMappedSuperclass(class1)) { feedFieldList(class1.getSuperclass(), fields); } return fields; } /** * feed the list com Fields * * @param class1 * @param fields */ private void feedFieldList(Class<?> class1, List<Field> fields) { for (Field field : class1.getDeclaredFields()) { if(isColumnToPersist(field)){ fields.add(field); } } } /** * verify is field has some annotations within * {@link #ColumnUtil#annotations} * @param field * @return */ private boolean isColumnToPersist(Field field) { for(Annotation annotation:field.getAnnotations()){ int result=Collections.binarySearch(annotations,annotation.annotationType().getName()); if(result >= 0){ return true; } } return false; } /** * verify if this is key of the column * * @param field * @return */ public boolean isIdField(Field field) { return field.getAnnotation(Id.class) != null; } /** * verify if this is index of the column * * @param field * @return */ public boolean isIndexField(Field field) { return field.getAnnotation(Index.class) != null; } @GeneratedValue public boolean isGeneratedValue(Field field) { return field.getAnnotation(GeneratedValue.class) != null; } /** * verify if this is secundary index of the column * * @param field * @return */ public boolean isSecundaryIndexField(Field field) { return field.getAnnotation(Index.class) != null; } /** * verify if this is a normal column * * @param field * @return */ public boolean isNormalField(Field field) { return field.getAnnotation(javax.persistence.Column.class) != null; } /** * verify if this is a enum column * * @param field * @return */ public boolean isEnumField(Field field) { return field.getAnnotation(Enumerated.class) != null; } /** * verify if this is a Embedded column * * @param field * @return */ public boolean isEmbeddedField(Field field) { return field.getAnnotation(Embedded.class) != null; } /** * verify if this is a Embedded id column * * @param field * @return */ public boolean isEmbeddedIdField(Field field) { return field.getAnnotation(EmbeddedId.class) != null; } /** * verify if this is a Version column * * @param field * @return */ public boolean isVersionField(Field field) { return field.getAnnotation(Version.class) != null; } /** * verify is exist father to persist * * @param class1 * @return */ public boolean isMappedSuperclass(Class<?> class1) { return class1.getSuperclass().getAnnotation(MappedSuperclass.class) != null; } /** * verify if the field is a list * @param field * @return */ public boolean isList(Field field){ return field.getAnnotation(ListData.class) != null; } /** * verify if the field is a map * @param field * @return */ public boolean isMap(Field field){ return field.getAnnotation(MapData.class) != null; } /** * verify if the field is a set * @param field * @return */ public boolean isSet(Field field){ return field.getAnnotation(SetData.class) != null; } /** * verify if the field is custom * @param field * @return */ public boolean isCustom(Field field) { return field.getAnnotation(CustomData.class) != null; } /** * get the Field for parsing <b>columnName</b> in the <b>class1</b>. if there is no such column name or if it denies access return null. * @param columnName * @param class1 * @return */ public Field getFieldByColumnName(String columnName, Class<?> class1) { for(Field index:getIndexFields(class1)){ if(index.getName().equals(columnName)){ return index; } } StringBuilder erro=new StringBuilder(); erro.append("Not found index on ").append(class1.getName()); erro.append(" with name ").append(columnName); throw new IndexProblemException(erro.toString()); } public KeySpaceInformation getKeySpace(String keySpace,Class<?> bean){ String keySchema=getSchema(bean); KeySpaceInformation key=new KeySpaceInformation(); key.keySpace="".equals(keySchema)?keySpace:keySchema; key.columnFamily=getColumnFamily(bean); return key ; } public class KeySpaceInformation{ private String keySpace; private String columnFamily; public String getKeySpace() { return keySpace; } public String getColumnFamily() { return columnFamily; } } }
fix a bug
src/main/java/org/easycassandra/persistence/cassandra/ColumnUtil.java
fix a bug
<ide><path>rc/main/java/org/easycassandra/persistence/cassandra/ColumnUtil.java <ide> for (Field field : persistenceClass.getDeclaredFields()) { <ide> if (field.getAnnotation(Index.class) != null) { <ide> indexFieldList.add(field); <del> } else if (field.getAnnotation(Embeddable.class) != null) { <del> indexFieldList.add( getField(field.getType(), Index.class)); <add> } else if (field.getAnnotation(Embedded.class) != null) { <add> indexFieldList.addAll(getIndexFields(field.getType())); <ide> } <ide> } <ide> return indexFieldList;
Java
apache-2.0
7ade603569510ecbd100f3e50cd98ed9a33f1312
0
nielsbasjes/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa,nielsbasjes/yauaa
/* * Yet Another UserAgent Analyzer * Copyright (C) 2013-2022 Niels Basjes * * 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 nl.basjes.parse.useragent.servlet.user; import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.tags.Tag; import nl.basjes.parse.useragent.AbstractUserAgentAnalyzerDirect.HeaderSpecification; import nl.basjes.parse.useragent.UserAgent; import nl.basjes.parse.useragent.Version; import nl.basjes.parse.useragent.servlet.ParseService; import nl.basjes.parse.useragent.servlet.exceptions.MissingUserAgentException; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.text.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedCaseInsensitiveMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static java.nio.charset.StandardCharsets.UTF_8; import static nl.basjes.parse.useragent.UserAgent.DEVICE_CLASS; import static nl.basjes.parse.useragent.UserAgent.STANDARD_FIELDS; import static nl.basjes.parse.useragent.UserAgent.USERAGENT_HEADER; import static nl.basjes.parse.useragent.classify.UserAgentClassifier.isDeliberateMisuse; import static nl.basjes.parse.useragent.classify.UserAgentClassifier.isHuman; import static nl.basjes.parse.useragent.classify.UserAgentClassifier.isMobile; import static nl.basjes.parse.useragent.classify.UserAgentClassifier.isNormalConsumerDevice; import static nl.basjes.parse.useragent.servlet.api.Utils.splitPerFilledLine; import static nl.basjes.parse.useragent.servlet.graphql.utils.FieldsAndSchema.getAllFieldsForGraphQL; import static nl.basjes.parse.useragent.servlet.graphql.utils.FieldsAndSchema.getSchemaFieldName; import static nl.basjes.parse.useragent.servlet.utils.Constants.GIT_REPO_URL; import static nl.basjes.parse.useragent.utils.YauaaVersion.getVersion; import static org.apache.commons.text.StringEscapeUtils.escapeHtml4; import static org.springframework.http.HttpStatus.OK; @Tag(name = "Yauaa", description = "Analyzing the useragents") @RestController public class HumanHtml { private final ParseService parseService; @Autowired public HumanHtml(ParseService parseService) { this.parseService = parseService; } // =============== Memory Usage =============== private static final long MEGABYTE = 1024L * 1024L; public static long bytesToMegabytes(long bytes) { return bytes / MEGABYTE; } private static String getMemoryUsage() { // Get the Java runtime Runtime runtime = Runtime.getRuntime(); runtime.gc(); // NOSONAR: We do gc to get a bit more accurate number of the actual memory usage (java:S1215) // Calculate the used memory long memory = runtime.totalMemory() - runtime.freeMemory(); return String.format("Used memory is %d MiB", bytesToMegabytes(memory)); } // =============== HTML (Human usable) OUTPUT =============== @Hidden @GetMapping( value = "/", produces = MediaType.TEXT_HTML_VALUE ) public ResponseEntity<String> getHtml(@RequestHeader Map<String, String> requestHeaders, @RequestParam(name = "ua", required = false) String userAgentStringParam) { if (userAgentStringParam == null || userAgentStringParam.isEmpty()) { return doHTML(requestHeaders); } else { return doHTML(userAgentStringParam); } } @Hidden @PostMapping( value = "/", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.TEXT_HTML_VALUE ) public ResponseEntity<String> getHtmlPOST(@ModelAttribute("useragent") String userAgent) { return doHTML(userAgent); } // =========================================== private ResponseEntity<String> doHTML(String userAgentString) { return doHTML(Collections.singletonMap(USERAGENT_HEADER, userAgentString), false); } private ResponseEntity<String> doHTML(Map<String, String> rawRequestHeaders) { return doHTML(rawRequestHeaders, true); } private ResponseEntity<String> doHTML(Map<String, String> rawRequestHeaders, boolean useClientHints) { LinkedCaseInsensitiveMap<String> requestHeaders = new LinkedCaseInsensitiveMap<>(); requestHeaders.putAll(rawRequestHeaders); String userAgentString = requestHeaders.get(USERAGENT_HEADER); long start = System.nanoTime(); long startParse = 0; long stopParse = 0; if (userAgentString == null) { throw new MissingUserAgentException(); } StringBuilder sb = new StringBuilder(4096); try { htmlHead(sb); if (parseService.userAgentAnalyzerIsAvailable()) { startParse = System.nanoTime(); List<UserAgent> userAgents = new ArrayList<>(); if (useClientHints) { userAgents.add(parseService.getUserAgentAnalyzer().parse(requestHeaders)); } else { final List<String> userAgentStrings = splitPerFilledLine(userAgentString); for (String ua : userAgentStrings) { userAgents.add(parseService.getUserAgentAnalyzer().parse(ua)); } } stopParse = System.nanoTime(); int i = 0; for (UserAgent userAgent: userAgents) { i++; sb.append("<hr/>"); sb.append("<h2 class=\"title\">The UserAgent"); copyTestcaseToClipboard(sb, userAgent, i); copyGraphQLQueryToClipboard(sb, userAgent, i); if (!useClientHints) { sb .append(" <a class=\"hideLink\" href=\"?ua=") .append(URLEncoder.encode(userAgent.getUserAgentString(), UTF_8)) // �� == U+1F517 == 3 bytes == In Java 2 chars "Surrogate Pair" : D83D + DD17 .append("\">\uD83D\uDD17</a>"); } sb.append("</h2>"); sb.append("<div class=\"input\">"); if (useClientHints) { sb.append("<table class=\"clientHints\">"); sb.append("<tr><th colspan=2><b><center>User-Agent and Client Hints</center></b></th></tr>"); sb.append("<tr><th>Usable header</th><th>Value</th></tr>"); List<String> showHeaders = new ArrayList<>(); showHeaders.add(USERAGENT_HEADER); showHeaders.addAll(parseService.getUserAgentAnalyzer().supportedClientHintHeaders()); for (String header : showHeaders) { String value = requestHeaders.get(header); if (value != null) { sb.append("<tr><td class=\"tooltip\">"); HeaderSpecification specification = parseService.getUserAgentAnalyzer().getAllSupportedHeaders().get(header); if (specification != null) { // �� == U+1F517 == 3 bytes == In Java 2 chars "Surrogate Pair" : D83D + DD17 sb.append("<a href=\"").append(specification.getSpecificationUrl()).append("\" style='text-decoration: none;' >\uD83D\uDD17 </a>"); } sb.append(escapeHtml4(header)); if (specification != null) { sb .append("<span class=\"tooltiptext\">") .append(escapeHtml4(specification.getSpecificationSummary())) .append("</span>"); } sb .append("</td><td>") .append(escapeHtml4(value)) .append("</td></tr>"); } } sb.append("</table>"); } else { sb.append("<p>").append(escapeHtml4(userAgent.getUserAgentString())).append("</p>"); } sb.append("</div>"); sb.append("<h2 class=\"title\">The analysis result</h2>"); List<String> tags = getClassificationTags(userAgent); sb .append("<p class=\"tags\">") .append("DeviceClass : ").append(userAgent.getValue(DEVICE_CLASS)).append("<br/>") .append(String.join(" - ", tags)).append("</p>"); sb.append("<table id=\"result\">"); sb.append("<tr><th colspan=2>Field</th><th>Value</th></tr>"); Map<String, Integer> fieldGroupCounts = new HashMap<>(); List<Pair<String, Pair<String, String>>> fields = new ArrayList<>(32); for (String fieldname : userAgent.getAvailableFieldNamesSorted()) { Pair<String, String> split = prefixSplitter(fieldname); if (!STANDARD_FIELDS.contains(fieldname)) { if (userAgent.get(fieldname).isDefaultValue()) { // Skip the "non-standard" fields that do not have a relevant value. continue; } } fields.add(new ImmutablePair<>(fieldname, split)); Integer count = fieldGroupCounts.get(split.getLeft()); if (count == null) { count = 1; } else { count++; } fieldGroupCounts.put(split.getLeft(), count); } String currentGroup = ""; for (Pair<String, Pair<String, String>> field : fields) { String fieldname = field.getLeft(); String groupName = field.getRight().getLeft(); String fieldLabel = field.getRight().getRight(); sb.append("<tr>"); if (!currentGroup.equals(groupName)) { currentGroup = groupName; sb .append("<td rowspan=").append(fieldGroupCounts.get(currentGroup)).append("><b><u>") .append(escapeHtml4(currentGroup)).append("</u></b></td>"); } sb .append("<td>").append(camelStretcher(escapeHtml4(fieldLabel))).append("</td>") .append("<td>").append(escapeHtml4(userAgent.getValue(fieldname))).append("</td>") .append("</tr>"); } sb.append("</table>"); } documentationBlock(sb, userAgents); sb.append("<hr/>"); sb.append("<form class=\"logobar tryyourown\" action=\"\" method=\"post\">"); sb.append("<label for=\"useragent\">Manual testing of a useragent:</label>"); sb.append("<textarea id=\"useragent\" name=\"useragent\" maxlength=\"2000\" rows=\"4\" " + "placeholder=\"Paste the useragent you want to test...\">") // .append(escapeHtml4(userAgentString)) .append("</textarea>"); sb.append("<input class=\"testButton\" type=\"submit\" value=\"Analyze\">"); sb.append("</form>"); sb.append("<hr/>"); } else { stillStartingUp(sb); } } catch (Exception e) { sb.append("<div class=\"failureBorder\">"); sb.append("<p class=\"failureContent\">An exception occurred during parsing</p>"); sb.append("<p class=\"failureContent\">Exception: ").append(e.getClass().getSimpleName()).append("</p>"); sb.append("<p class=\"failureContent\">Message: ").append(e.getMessage().replace("\\n", "<br/>")).append("</p>"); sb.append("</div>"); } finally { long stop = System.nanoTime(); double pageMilliseconds = (stop - start) / 1000000.0; double parseMilliseconds = (stopParse - startParse) / 1000000.0; sb.append("<p class=\"speed\">Building this page took ") .append(String.format(Locale.ENGLISH, "%3.3f", pageMilliseconds)) .append(" ms.</p>"); if (parseMilliseconds > 0) { sb.append("<p class=\"speed\">Parsing took ") .append(String.format(Locale.ENGLISH, "%3.3f", parseMilliseconds)) .append(" ms.</p>"); } htmlFooter(sb); } HttpHeaders responseHeaders = new HttpHeaders(); if (parseService.userAgentAnalyzerIsAvailable()) { responseHeaders.add("Accept-CH", String.join(", ", parseService.getUserAgentAnalyzer().supportedClientHintHeaders())); // responseHeaders.add("Critical-CH", String.join(", ", parseService.getUserAgentAnalyzer().supportedClientHintHeaders())); } return new ResponseEntity<>(sb.toString(), responseHeaders, OK); } private static List<String> getClassificationTags(UserAgent userAgent) { List<String> tags = new ArrayList<>(); if (isHuman(userAgent)) { tags.add("Human"); } else { tags.add("NOT Human"); } if (isNormalConsumerDevice(userAgent)) { tags.add("Normal consumer device"); } if (isMobile(userAgent)) { tags.add("Mobile"); } if (isDeliberateMisuse(userAgent)) { tags.add("Deliberate Misuse"); } return tags; } private void stillStartingUp(StringBuilder sb) { String userAgentAnalyzerFailureMessage = parseService.getUserAgentAnalyzerFailureMessage(); if (userAgentAnalyzerFailureMessage == null) { long now = System.currentTimeMillis(); long millisBusy = now - parseService.getInitStartMoment(); String timeString = String.format("%3.1f", millisBusy / 1000.0); sb .append("<div class=\"notYetStartedBorder\">") .append("<p class=\"notYetStarted\">The analyzer is currently starting up.</p>") .append("<p class=\"notYetStarted\">It has been starting up for <u>").append(timeString).append("</u> seconds</p>") .append("<p class=\"notYetStarted\">Anything between 5-15 seconds is normal.</p>") .append("<p class=\"notYetStartedAppEngine\">On a free AppEngine 50 seconds is 'normal'.</p>") .append("</div>"); } else { sb .append("<div class=\"failureBorder\">") .append("<p class=\"failureContent\">The analyzer startup failed with this message</p>") .append("<p class=\"failureContent\">").append(userAgentAnalyzerFailureMessage).append("</p>") .append("</div>"); } } private void documentationBlock(StringBuilder sb, List<UserAgent> userAgents) { sb.append("<hr/>"); sb.append("<p class=\"logobar documentation\">Read the online documentation at <a href=\"https://yauaa.basjes.nl\">" + "https://yauaa.basjes.nl</a></p>"); sb.append("<p class=\"logobar forum\">I you have a question or an idea we can have a discussion <a href=\"https://github.com/nielsbasjes/yauaa/discussions\">" + "here</a></p>"); sb.append("<p class=\"logobar bug\">"); addBugReportButton(sb, userAgents.get(0)); sb.append("</p>"); sb.append("<p class=\"logobar swagger\">A simple Swagger based API has been created for testing purposes: " + "<a href=\"/swagger-ui.html\">Swagger UI</a></p>"); sb.append("<p class=\"logobar graphql\">A simple GraphQL based API has been created for testing purposes: " + "<a href=\"/graphiql\">GraphQL UI</a> [" + "<a href=\"/graphql\">Endpoint</a>, " + "<a href=\"/graphql/schema\">Schema</a>]</p>" ); sb.append("<p class=\"logobar source\">This project is opensource: <a href=\"https://github.com/nielsbasjes/yauaa\">" + "https://github.com/nielsbasjes/yauaa</a></p>"); sb.append("<p class=\"logobar contribute\">Creating this free software is a lot of work. " + "If this has business value for your then don't hesitate to " + "<a href=\"https://www.paypal.me/nielsbasjes\">contribute a little something back</a>.</p>"); } private void htmlFooter(StringBuilder sb) { sb.append("<p class=\"speed\">").append(getMemoryUsage()).append("</p>"); sb .append("<p class=\"copyright\">") .append(Version.COPYRIGHT.replace("Niels Basjes", "<a href=\"https://niels.basjes.nl\">Niels Basjes</a>")) .append("</p>") .append("</body>") .append("</html>"); } private static final String CACHE_BUSTER = Version.GIT_COMMIT_ID.substring(0, 8); private void htmlHead(StringBuilder sb) { sb.append("<!DOCTYPE html>"); sb.append("<html lang=\"en\" ><head profile=\"http://www.w3.org/2005/10/profile\">"); sb.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"); sb.append("<meta name=viewport content=\"width=device-width, initial-scale=1\">"); insertFavIcons(sb); sb.append("<meta name=\"theme-color\" content=\"dodgerblue\" />"); // While initializing automatically reload the page. if (!parseService.userAgentAnalyzerIsAvailable() && parseService.getUserAgentAnalyzerFailureMessage() == null) { sb.append("<meta http-equiv=\"refresh\" content=\"1\" >"); } sb.append("<link rel=\"stylesheet\" href=\"style.css?").append(CACHE_BUSTER).append("\">"); sb.append("<title>Analyzing the useragent</title>"); sb.append("</head>"); sb.append("<body>"); sb.append("<div class=\"header\">"); sb.append("<h1 class=\"title\">Yet Another UserAgent Analyzer.</h1>"); sb.append("<p class=\"version\">").append(getVersion()).append(" (<a href=\"").append(GIT_REPO_URL).append("\">commit</a>)</p>"); sb.append("</div>"); } private void insertFavIcons(StringBuilder sb) { sb.append("<link rel=\"apple-touch-icon\" href=\"/apple-touch-icon.png\">"); sb.append("<link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/favicon-32x32.png\">"); sb.append("<link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/favicon-16x16.png\">"); sb.append("<link rel=\"manifest\" href=\"/manifest.json\">"); sb.append("<link rel=\"mask-icon\" href=\"/safari-pinned-tab.svg\" color=\"#5bbad5\">"); sb.append("<meta name=\"msapplication-TileColor\" content=\"#2d89ef\">"); sb.append("<meta name=\"msapplication-TileImage\" content=\"/mstile-144x144.png\">"); } private Pair<String, String> prefixSplitter(String input) { MutablePair<String, String> result = new MutablePair<>("", input); if (input.startsWith("Device")) { result.setLeft("Device"); result.setRight(input.replaceFirst("Device", "")); } else if (input.startsWith("OperatingSystem")) { result.setLeft("Operating System"); result.setRight(input.replaceFirst("OperatingSystem", "")); } else if (input.startsWith("LayoutEngine")) { result.setLeft("Layout Engine"); result.setRight(input.replaceFirst("LayoutEngine", "")); } else if (input.startsWith("Agent")) { result.setLeft("Agent"); result.setRight(input.replaceFirst("Agent", "")); } else if (input.startsWith("UAClientHint")) { result.setLeft("UAClientHint"); result.setRight(input.replaceFirst("UAClientHint", "")); } return result; } private String camelStretcher(String input) { String result = input.replaceAll("([A-Z])", " $1"); result = result.replace("Device", "<b><u>Device</u></b>"); result = result.replace("Operating System", "<b><u>Operating System</u></b>"); result = result.replace("Layout Engine", "<b><u>Layout Engine</u></b>"); result = result.replace("Agent", "<b><u>Agent</u></b>"); return result.trim(); } private void copyTestcaseToClipboard(StringBuilder sb, UserAgent userAgent, int index) { String baseScript = """ <script> function copyTestCaseToClipboard{INDEX}() { var copyText = document.getElementById("testCaseForClipboard{INDEX}"); copyText.select(); copyText.setSelectionRange(0, 99999); navigator.clipboard.writeText(copyText.value); var tooltip = document.getElementById("copyTestCaseToClipboardTooltip{INDEX}"); tooltip.innerHTML = "Copied to clipboard" } function closeCopyTestCaseToClipboardTooltip{INDEX}() { var tooltip = document.getElementById("copyTestCaseToClipboardTooltip{INDEX}"); tooltip.innerHTML = "Copy this as a testcase to clipboard"; } </script> """; sb.append(baseScript.replace("{INDEX}", String.valueOf(index))); sb .append("<textarea style='display:none' id=\"testCaseForClipboard").append(index).append("\">") .append(escapeHtml4(userAgent.toYamlTestCase())) // .replace("\"", "&quote;").replace("\n", "&#10;")) .append("</textarea>") .append( """ <div class="tooltip inline"> <p onclick="copyTestCaseToClipboard{INDEX}()" onmouseout="closeCopyTestCaseToClipboardTooltip{INDEX}()"> <span class="tooltiptext" id="copyTestCaseToClipboardTooltip{INDEX}">Copy this as a testcase to clipboard</span> """ .replace("{INDEX}", String.valueOf(index))) .append("&#128203;</p>") .append("</div>\n"); } private void copyGraphQLQueryToClipboard(StringBuilder sb, UserAgent userAgent, int index) { String baseScript = """ <script> function copyGraphQLToClipboard{INDEX}() { var copyText = document.getElementById("graphQLForClipboard{INDEX}"); copyText.select(); copyText.setSelectionRange(0, 99999); navigator.clipboard.writeText(copyText.value); var tooltip = document.getElementById("copyGraphQLToClipboardTooltip{INDEX}"); tooltip.innerHTML = "Copied to clipboard" } function closeCopyGraphQLToClipboardTooltip{INDEX}() { var tooltip = document.getElementById("copyGraphQLToClipboardTooltip{INDEX}"); tooltip.innerHTML = "Copy this as a graphQL to clipboard"; } </script> """; sb.append(baseScript.replace("{INDEX}", String.valueOf(index))); sb.append("<textarea style='display:none' id=\"graphQLForClipboard").append(index).append("\">"); sb.append("query {\n" + " analyze(requestHeaders: {\n"); Map<String, String> headers = userAgent.getHeaders(); for (HeaderSpecification headerSpecification : parseService .getUserAgentAnalyzer() .getAllSupportedHeaders() .values()) { addRequestHeaderToGraphQL(sb, headers.get(headerSpecification.getHeaderName()), headerSpecification.getFieldName()); } sb.append(" }) {\n"); for (String fieldName : getAllFieldsForGraphQL(parseService)) { sb.append(" ").append(getSchemaFieldName(fieldName)).append('\n'); } sb.append(" }\n"); sb.append("}"); sb.append("</textarea>"); sb.append( """ <div class="tooltip inline"> <p onclick="copyGraphQLToClipboard{INDEX}()" onmouseout="closeCopyGraphQLToClipboardTooltip{INDEX}()"> <span class="tooltiptext" id="copyGraphQLToClipboardTooltip{INDEX}">Copy this as a GraphQL query to clipboard</span>&#128203;</p> </div> """ .replace("{INDEX}", String.valueOf(index))); } private void addRequestHeaderToGraphQL(StringBuilder sb, String header, String gqlName) { if (header == null || header.trim().isEmpty()) { return; } sb.append(" ").append(gqlName).append(" : \"").append(StringEscapeUtils.escapeJson(header)).append("\"\n"); } private void addBugReportButton(StringBuilder sb, UserAgent userAgent) { // https://github.com/nielsbasjes/yauaa/issues/new?title=Bug%20report&body=bar StringBuilder reportUrl = new StringBuilder("https://github.com/nielsbasjes/yauaa/issues/new?title=Bug%20report&body="); String report = "I found a problem with this useragent.\n" + "[Please update the output below to match what you expect it should be]\n" + "\n```\n" + userAgent.toYamlTestCase().replaceAll(" +:", " :") + "\n```\n"; reportUrl.append(URLEncoder.encode(report, UTF_8)); String githubUrl = "https://github.com/login?return_to=" + URLEncoder.encode(reportUrl.toString(), UTF_8); sb.append("If you find a problem with this result then please report a bug here: " + "<a href=\"").append(githubUrl).append("\">Yauaa issue report</a>"); } }
webapp/src/main/java/nl/basjes/parse/useragent/servlet/user/HumanHtml.java
/* * Yet Another UserAgent Analyzer * Copyright (C) 2013-2022 Niels Basjes * * 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 nl.basjes.parse.useragent.servlet.user; import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.tags.Tag; import nl.basjes.parse.useragent.AbstractUserAgentAnalyzerDirect.HeaderSpecification; import nl.basjes.parse.useragent.UserAgent; import nl.basjes.parse.useragent.Version; import nl.basjes.parse.useragent.servlet.ParseService; import nl.basjes.parse.useragent.servlet.exceptions.MissingUserAgentException; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.text.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedCaseInsensitiveMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static java.nio.charset.StandardCharsets.UTF_8; import static nl.basjes.parse.useragent.UserAgent.DEVICE_CLASS; import static nl.basjes.parse.useragent.UserAgent.STANDARD_FIELDS; import static nl.basjes.parse.useragent.UserAgent.USERAGENT_HEADER; import static nl.basjes.parse.useragent.classify.UserAgentClassifier.isDeliberateMisuse; import static nl.basjes.parse.useragent.classify.UserAgentClassifier.isHuman; import static nl.basjes.parse.useragent.classify.UserAgentClassifier.isMobile; import static nl.basjes.parse.useragent.classify.UserAgentClassifier.isNormalConsumerDevice; import static nl.basjes.parse.useragent.servlet.api.Utils.splitPerFilledLine; import static nl.basjes.parse.useragent.servlet.graphql.utils.FieldsAndSchema.getAllFieldsForGraphQL; import static nl.basjes.parse.useragent.servlet.graphql.utils.FieldsAndSchema.getSchemaFieldName; import static nl.basjes.parse.useragent.servlet.utils.Constants.GIT_REPO_URL; import static nl.basjes.parse.useragent.utils.YauaaVersion.getVersion; import static org.apache.commons.text.StringEscapeUtils.escapeHtml4; import static org.springframework.http.HttpStatus.OK; @Tag(name = "Yauaa", description = "Analyzing the useragents") @RestController public class HumanHtml { private final ParseService parseService; @Autowired public HumanHtml(ParseService parseService) { this.parseService = parseService; } // =============== Memory Usage =============== private static final long MEGABYTE = 1024L * 1024L; public static long bytesToMegabytes(long bytes) { return bytes / MEGABYTE; } private static String getMemoryUsage() { // Get the Java runtime Runtime runtime = Runtime.getRuntime(); runtime.gc(); // NOSONAR: We do gc to get a bit more accurate number of the actual memory usage (java:S1215) // Calculate the used memory long memory = runtime.totalMemory() - runtime.freeMemory(); return String.format("Used memory is %d MiB", bytesToMegabytes(memory)); } // =============== HTML (Human usable) OUTPUT =============== @Hidden @GetMapping( value = "/", produces = MediaType.TEXT_HTML_VALUE ) public ResponseEntity<String> getHtml(@RequestHeader Map<String, String> requestHeaders, @RequestParam(name = "ua", required = false) String userAgentStringParam) { if (userAgentStringParam == null || userAgentStringParam.isEmpty()) { return doHTML(requestHeaders); } else { return doHTML(userAgentStringParam); } } @Hidden @PostMapping( value = "/", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.TEXT_HTML_VALUE ) public ResponseEntity<String> getHtmlPOST(@ModelAttribute("useragent") String userAgent) { return doHTML(userAgent); } // =========================================== private ResponseEntity<String> doHTML(String userAgentString) { return doHTML(Collections.singletonMap(USERAGENT_HEADER, userAgentString), false); } private ResponseEntity<String> doHTML(Map<String, String> rawRequestHeaders) { return doHTML(rawRequestHeaders, true); } private ResponseEntity<String> doHTML(Map<String, String> rawRequestHeaders, boolean useClientHints) { LinkedCaseInsensitiveMap<String> requestHeaders = new LinkedCaseInsensitiveMap<>(); requestHeaders.putAll(rawRequestHeaders); String userAgentString = requestHeaders.get(USERAGENT_HEADER); long start = System.nanoTime(); long startParse = 0; long stopParse = 0; if (userAgentString == null) { throw new MissingUserAgentException(); } StringBuilder sb = new StringBuilder(4096); try { htmlHead(sb); if (parseService.userAgentAnalyzerIsAvailable()) { startParse = System.nanoTime(); List<UserAgent> userAgents = new ArrayList<>(); if (useClientHints) { userAgents.add(parseService.getUserAgentAnalyzer().parse(requestHeaders)); } else { final List<String> userAgentStrings = splitPerFilledLine(userAgentString); for (String ua : userAgentStrings) { userAgents.add(parseService.getUserAgentAnalyzer().parse(ua)); } } stopParse = System.nanoTime(); int i = 0; for (UserAgent userAgent: userAgents) { i++; sb.append("<hr/>"); sb.append("<h2 class=\"title\">The UserAgent"); copyTestcaseToClipboard(sb, userAgent, i); copyGraphQLQueryToClipboard(sb, userAgent, i); if (!useClientHints) { sb .append(" <a class=\"hideLink\" href=\"?ua=") .append(URLEncoder.encode(userAgent.getUserAgentString(), "UTF-8")) // �� == U+1F517 == 3 bytes == In Java 2 chars "Surrogate Pair" : D83D + DD17 .append("\">\uD83D\uDD17</a>"); } sb.append("</h2>"); sb.append("<div class=\"input\">"); if (useClientHints) { sb.append("<table class=\"clientHints\">"); sb.append("<tr><th colspan=2><b><center>User-Agent and Client Hints</center></b></th></tr>"); sb.append("<tr><th>Usable header</th><th>Value</th></tr>"); List<String> showHeaders = new ArrayList<>(); showHeaders.add(USERAGENT_HEADER); showHeaders.addAll(parseService.getUserAgentAnalyzer().supportedClientHintHeaders()); for (String header : showHeaders) { String value = requestHeaders.get(header); if (value != null) { sb.append("<tr><td class=\"tooltip\">"); HeaderSpecification specification = parseService.getUserAgentAnalyzer().getAllSupportedHeaders().get(header); if (specification != null) { // �� == U+1F517 == 3 bytes == In Java 2 chars "Surrogate Pair" : D83D + DD17 sb.append("<a href=\"").append(specification.getSpecificationUrl()).append("\" style='text-decoration: none;' >\uD83D\uDD17 </a>"); } sb.append(escapeHtml4(header)); if (specification != null) { sb .append("<span class=\"tooltiptext\">") .append(escapeHtml4(specification.getSpecificationSummary())) .append("</span>"); } sb .append("</td><td>") .append(escapeHtml4(value)) .append("</td></tr>"); } } sb.append("</table>"); } else { sb.append("<p>").append(escapeHtml4(userAgent.getUserAgentString())).append("</p>"); } sb.append("</div>"); sb.append("<h2 class=\"title\">The analysis result</h2>"); List<String> tags = getClassificationTags(userAgent); sb .append("<p class=\"tags\">") .append("DeviceClass : ").append(userAgent.getValue(DEVICE_CLASS)).append("<br/>") .append(String.join(" - ", tags)).append("</p>"); sb.append("<table id=\"result\">"); sb.append("<tr><th colspan=2>Field</th><th>Value</th></tr>"); Map<String, Integer> fieldGroupCounts = new HashMap<>(); List<Pair<String, Pair<String, String>>> fields = new ArrayList<>(32); for (String fieldname : userAgent.getAvailableFieldNamesSorted()) { Pair<String, String> split = prefixSplitter(fieldname); if (!STANDARD_FIELDS.contains(fieldname)) { if (userAgent.get(fieldname).isDefaultValue()) { // Skip the "non-standard" fields that do not have a relevant value. continue; } } fields.add(new ImmutablePair<>(fieldname, split)); Integer count = fieldGroupCounts.get(split.getLeft()); if (count == null) { count = 1; } else { count++; } fieldGroupCounts.put(split.getLeft(), count); } String currentGroup = ""; for (Pair<String, Pair<String, String>> field : fields) { String fieldname = field.getLeft(); String groupName = field.getRight().getLeft(); String fieldLabel = field.getRight().getRight(); sb.append("<tr>"); if (!currentGroup.equals(groupName)) { currentGroup = groupName; sb .append("<td rowspan=").append(fieldGroupCounts.get(currentGroup)).append("><b><u>") .append(escapeHtml4(currentGroup)).append("</u></b></td>"); } sb .append("<td>").append(camelStretcher(escapeHtml4(fieldLabel))).append("</td>") .append("<td>").append(escapeHtml4(userAgent.getValue(fieldname))).append("</td>") .append("</tr>"); } sb.append("</table>"); } documentationBlock(sb, userAgents); sb.append("<hr/>"); sb.append("<form class=\"logobar tryyourown\" action=\"\" method=\"post\">"); sb.append("<label for=\"useragent\">Manual testing of a useragent:</label>"); sb.append("<textarea id=\"useragent\" name=\"useragent\" maxlength=\"2000\" rows=\"4\" " + "placeholder=\"Paste the useragent you want to test...\">") // .append(escapeHtml4(userAgentString)) .append("</textarea>"); sb.append("<input class=\"testButton\" type=\"submit\" value=\"Analyze\">"); sb.append("</form>"); sb.append("<hr/>"); } else { stillStartingUp(sb); } } catch (Exception e) { sb.append("<div class=\"failureBorder\">"); sb.append("<p class=\"failureContent\">An exception occurred during parsing</p>"); sb.append("<p class=\"failureContent\">Exception: ").append(e.getClass().getSimpleName()).append("</p>"); sb.append("<p class=\"failureContent\">Message: ").append(e.getMessage().replace("\\n", "<br/>")).append("</p>"); sb.append("</div>"); } finally { long stop = System.nanoTime(); double pageMilliseconds = (stop - start) / 1000000.0; double parseMilliseconds = (stopParse - startParse) / 1000000.0; sb.append("<p class=\"speed\">Building this page took ") .append(String.format(Locale.ENGLISH, "%3.3f", pageMilliseconds)) .append(" ms.</p>"); if (parseMilliseconds > 0) { sb.append("<p class=\"speed\">Parsing took ") .append(String.format(Locale.ENGLISH, "%3.3f", parseMilliseconds)) .append(" ms.</p>"); } htmlFooter(sb); } HttpHeaders responseHeaders = new HttpHeaders(); if (parseService.userAgentAnalyzerIsAvailable()) { responseHeaders.add("Accept-CH", String.join(", ", parseService.getUserAgentAnalyzer().supportedClientHintHeaders())); // responseHeaders.add("Critical-CH", String.join(", ", parseService.getUserAgentAnalyzer().supportedClientHintHeaders())); } return new ResponseEntity<>(sb.toString(), responseHeaders, OK); } private static List<String> getClassificationTags(UserAgent userAgent) { List<String> tags = new ArrayList<>(); if (isHuman(userAgent)) { tags.add("Human"); } else { tags.add("NOT Human"); } if (isNormalConsumerDevice(userAgent)) { tags.add("Normal consumer device"); } if (isMobile(userAgent)) { tags.add("Mobile"); } if (isDeliberateMisuse(userAgent)) { tags.add("Deliberate Misuse"); } return tags; } private void stillStartingUp(StringBuilder sb) { String userAgentAnalyzerFailureMessage = parseService.getUserAgentAnalyzerFailureMessage(); if (userAgentAnalyzerFailureMessage == null) { long now = System.currentTimeMillis(); long millisBusy = now - parseService.getInitStartMoment(); String timeString = String.format("%3.1f", millisBusy / 1000.0); sb .append("<div class=\"notYetStartedBorder\">") .append("<p class=\"notYetStarted\">The analyzer is currently starting up.</p>") .append("<p class=\"notYetStarted\">It has been starting up for <u>").append(timeString).append("</u> seconds</p>") .append("<p class=\"notYetStarted\">Anything between 5-15 seconds is normal.</p>") .append("<p class=\"notYetStartedAppEngine\">On a free AppEngine 50 seconds is 'normal'.</p>") .append("</div>"); } else { sb .append("<div class=\"failureBorder\">") .append("<p class=\"failureContent\">The analyzer startup failed with this message</p>") .append("<p class=\"failureContent\">").append(userAgentAnalyzerFailureMessage).append("</p>") .append("</div>"); } } private void documentationBlock(StringBuilder sb, List<UserAgent> userAgents) { sb.append("<hr/>"); sb.append("<p class=\"logobar documentation\">Read the online documentation at <a href=\"https://yauaa.basjes.nl\">" + "https://yauaa.basjes.nl</a></p>"); sb.append("<p class=\"logobar forum\">I you have a question or an idea we can have a discussion <a href=\"https://github.com/nielsbasjes/yauaa/discussions\">" + "here</a></p>"); sb.append("<p class=\"logobar bug\">"); addBugReportButton(sb, userAgents.get(0)); sb.append("</p>"); sb.append("<p class=\"logobar swagger\">A simple Swagger based API has been created for testing purposes: " + "<a href=\"/swagger-ui.html\">Swagger UI</a></p>"); sb.append("<p class=\"logobar graphql\">A simple GraphQL based API has been created for testing purposes: " + "<a href=\"/graphiql\">GraphQL UI</a> [" + "<a href=\"/graphql\">Endpoint</a>, " + "<a href=\"/graphql/schema\">Schema</a>]</p>" ); sb.append("<p class=\"logobar source\">This project is opensource: <a href=\"https://github.com/nielsbasjes/yauaa\">" + "https://github.com/nielsbasjes/yauaa</a></p>"); sb.append("<p class=\"logobar contribute\">Creating this free software is a lot of work. " + "If this has business value for your then don't hesitate to " + "<a href=\"https://www.paypal.me/nielsbasjes\">contribute a little something back</a>.</p>"); } private void htmlFooter(StringBuilder sb) { sb.append("<p class=\"speed\">").append(getMemoryUsage()).append("</p>"); sb .append("<p class=\"copyright\">") .append(Version.COPYRIGHT.replace("Niels Basjes", "<a href=\"https://niels.basjes.nl\">Niels Basjes</a>")) .append("</p>") .append("</body>") .append("</html>"); } private static final String CACHE_BUSTER = Version.GIT_COMMIT_ID.substring(0, 8); private void htmlHead(StringBuilder sb) { sb.append("<!DOCTYPE html>"); sb.append("<html lang=\"en\" ><head profile=\"http://www.w3.org/2005/10/profile\">"); sb.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"); sb.append("<meta name=viewport content=\"width=device-width, initial-scale=1\">"); insertFavIcons(sb); sb.append("<meta name=\"theme-color\" content=\"dodgerblue\" />"); sb.append( "<script>\n" + "function copyTestCaseToClipboard() {\n" + " var copyText = document.getElementById(\"testCaseForClipboard\");\n" + " copyText.select();\n" + " copyText.setSelectionRange(0, 99999);\n" + " navigator.clipboard.writeText(copyText.value);\n" + "\n" + " var tooltip = document.getElementById(\"copyTestCaseToClipboardTooltip\");\n" + " tooltip.innerHTML = \"Copied to clipboard\"\n" + "}\n" + "\n" + "function closeCopyTestCaseToClipboardTooltip() {\n" + " var tooltip = document.getElementById(\"copyTestCaseToClipboardTooltip\");\n" + " tooltip.innerHTML = \"Copy this as a testcase to clipboard\";\n" + "}\n" + "\n" + "function copyGraphQLToClipboard() {\n" + " var copyText = document.getElementById(\"graphQLForClipboard\");\n" + " copyText.select();\n" + " copyText.setSelectionRange(0, 99999);\n" + " navigator.clipboard.writeText(copyText.value);\n" + "\n" + " var tooltip = document.getElementById(\"copyGraphQLToClipboardTooltip\");\n" + " tooltip.innerHTML = \"Copied to clipboard\"\n" + "}\n" + "\n" + "function closeCopyGraphQLToClipboardTooltip() {\n" + " var tooltip = document.getElementById(\"copyGraphQLToClipboardTooltip\");\n" + " tooltip.innerHTML = \"Copy this as a graphQL to clipboard\";\n" + "}\n" + "\n" + "</script>" ); // While initializing automatically reload the page. if (!parseService.userAgentAnalyzerIsAvailable() && parseService.getUserAgentAnalyzerFailureMessage() == null) { sb.append("<meta http-equiv=\"refresh\" content=\"1\" >"); } sb.append("<link rel=\"stylesheet\" href=\"style.css?").append(CACHE_BUSTER).append("\">"); sb.append("<title>Analyzing the useragent</title>"); sb.append("</head>"); sb.append("<body>"); sb.append("<div class=\"header\">"); sb.append("<h1 class=\"title\">Yet Another UserAgent Analyzer.</h1>"); sb.append("<p class=\"version\">").append(getVersion()).append(" (<a href=\"").append(GIT_REPO_URL).append("\">commit</a>)</p>"); sb.append("</div>"); } private void insertFavIcons(StringBuilder sb) { sb.append("<link rel=\"apple-touch-icon\" href=\"/apple-touch-icon.png\">"); sb.append("<link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/favicon-32x32.png\">"); sb.append("<link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/favicon-16x16.png\">"); sb.append("<link rel=\"manifest\" href=\"/manifest.json\">"); sb.append("<link rel=\"mask-icon\" href=\"/safari-pinned-tab.svg\" color=\"#5bbad5\">"); sb.append("<meta name=\"msapplication-TileColor\" content=\"#2d89ef\">"); sb.append("<meta name=\"msapplication-TileImage\" content=\"/mstile-144x144.png\">"); } private Pair<String, String> prefixSplitter(String input) { MutablePair<String, String> result = new MutablePair<>("", input); if (input.startsWith("Device")) { result.setLeft("Device"); result.setRight(input.replaceFirst("Device", "")); } else if (input.startsWith("OperatingSystem")) { result.setLeft("Operating System"); result.setRight(input.replaceFirst("OperatingSystem", "")); } else if (input.startsWith("LayoutEngine")) { result.setLeft("Layout Engine"); result.setRight(input.replaceFirst("LayoutEngine", "")); } else if (input.startsWith("Agent")) { result.setLeft("Agent"); result.setRight(input.replaceFirst("Agent", "")); } else if (input.startsWith("UAClientHint")) { result.setLeft("UAClientHint"); result.setRight(input.replaceFirst("UAClientHint", "")); } return result; } private String camelStretcher(String input) { String result = input.replaceAll("([A-Z])", " $1"); result = result.replace("Device", "<b><u>Device</u></b>"); result = result.replace("Operating System", "<b><u>Operating System</u></b>"); result = result.replace("Layout Engine", "<b><u>Layout Engine</u></b>"); result = result.replace("Agent", "<b><u>Agent</u></b>"); return result.trim(); } private void copyTestcaseToClipboard(StringBuilder sb, UserAgent userAgent, int index) { // .replace("\"", "&quote;").replace("\n", "&#10;")) sb .append("<textarea style='display:none' id=\"testCaseForClipboard").append(index).append("\">") .append(escapeHtml4(userAgent.toYamlTestCase())) // .replace("\"", "&quote;").replace("\n", "&#10;")) .append("</textarea>") .append("<div class=\"tooltip inline\">" + "<p onclick=\"copyTestCaseToClipboard()\" onmouseout=\"closeCopyTestCaseToClipboardTooltip()\">" + "<span class=\"tooltiptext\" id=\"copyTestCaseToClipboardTooltip").append(index).append("\">Copy this as a testcase to clipboard</span>") .append("&#128203;</p>") .append("</div>\n"); } private void copyGraphQLQueryToClipboard(StringBuilder sb, UserAgent userAgent, int index) { sb.append("<textarea style='display:none' id=\"graphQLForClipboard\">"); sb.append("query {\n" + " analyze(requestHeaders: {\n"); Map<String, String> headers = userAgent.getHeaders(); for (HeaderSpecification headerSpecification : parseService .getUserAgentAnalyzer() .getAllSupportedHeaders() .values()) { addRequestHeaderToGraphQL(sb, headers.get(headerSpecification.getHeaderName()), headerSpecification.getFieldName()); } sb.append(" }) {\n"); for (String fieldName : getAllFieldsForGraphQL(parseService)) { sb.append(" ").append(getSchemaFieldName(fieldName)).append('\n'); } sb.append(" }\n"); sb.append("}"); sb.append("</textarea>") .append("<div class=\"tooltip inline\">" + "<p onclick=\"copyGraphQLToClipboard()\" onmouseout=\"closeCopyGraphQLToClipboardTooltip()\">" + "<span class=\"tooltiptext\" id=\"copyGraphQLToClipboardTooltip\">Copy this as a GraphQL query to clipboard</span>" + "&#128203;</p>" + "</div>\n"); } private void addRequestHeaderToGraphQL(StringBuilder sb, String header, String gqlName) { if (header == null || header.trim().isEmpty()) { return; } sb.append(" ").append(gqlName).append(" : \"").append(StringEscapeUtils.escapeJson(header)).append("\"\n"); } private void addBugReportButton(StringBuilder sb, UserAgent userAgent) { // https://github.com/nielsbasjes/yauaa/issues/new?title=Bug%20report&body=bar StringBuilder reportUrl = new StringBuilder("https://github.com/nielsbasjes/yauaa/issues/new?title=Bug%20report&body="); String report = "I found a problem with this useragent.\n" + "[Please update the output below to match what you expect it should be]\n" + "\n```\n" + userAgent.toYamlTestCase().replaceAll(" +:", " :") + "\n```\n"; reportUrl.append(URLEncoder.encode(report, UTF_8)); String githubUrl = "https://github.com/login?return_to=" + URLEncoder.encode(reportUrl.toString(), UTF_8); sb.append("If you find a problem with this result then please report a bug here: " + "<a href=\"").append(githubUrl).append("\">Yauaa issue report</a>"); } }
fix: The webservlet copy to clipboard works for multiple
webapp/src/main/java/nl/basjes/parse/useragent/servlet/user/HumanHtml.java
fix: The webservlet copy to clipboard works for multiple
<ide><path>ebapp/src/main/java/nl/basjes/parse/useragent/servlet/user/HumanHtml.java <ide> if (!useClientHints) { <ide> sb <ide> .append(" <a class=\"hideLink\" href=\"?ua=") <del> .append(URLEncoder.encode(userAgent.getUserAgentString(), "UTF-8")) <add> .append(URLEncoder.encode(userAgent.getUserAgentString(), UTF_8)) <ide> // �� == U+1F517 == 3 bytes == In Java 2 chars "Surrogate Pair" : D83D + DD17 <ide> .append("\">\uD83D\uDD17</a>"); <ide> } <ide> insertFavIcons(sb); <ide> sb.append("<meta name=\"theme-color\" content=\"dodgerblue\" />"); <ide> <del> sb.append( <del> "<script>\n" + <del> "function copyTestCaseToClipboard() {\n" + <del> " var copyText = document.getElementById(\"testCaseForClipboard\");\n" + <del> " copyText.select();\n" + <del> " copyText.setSelectionRange(0, 99999);\n" + <del> " navigator.clipboard.writeText(copyText.value);\n" + <del> "\n" + <del> " var tooltip = document.getElementById(\"copyTestCaseToClipboardTooltip\");\n" + <del> " tooltip.innerHTML = \"Copied to clipboard\"\n" + <del> "}\n" + <del> "\n" + <del> "function closeCopyTestCaseToClipboardTooltip() {\n" + <del> " var tooltip = document.getElementById(\"copyTestCaseToClipboardTooltip\");\n" + <del> " tooltip.innerHTML = \"Copy this as a testcase to clipboard\";\n" + <del> "}\n" + <del> "\n" + <del> "function copyGraphQLToClipboard() {\n" + <del> " var copyText = document.getElementById(\"graphQLForClipboard\");\n" + <del> " copyText.select();\n" + <del> " copyText.setSelectionRange(0, 99999);\n" + <del> " navigator.clipboard.writeText(copyText.value);\n" + <del> "\n" + <del> " var tooltip = document.getElementById(\"copyGraphQLToClipboardTooltip\");\n" + <del> " tooltip.innerHTML = \"Copied to clipboard\"\n" + <del> "}\n" + <del> "\n" + <del> "function closeCopyGraphQLToClipboardTooltip() {\n" + <del> " var tooltip = document.getElementById(\"copyGraphQLToClipboardTooltip\");\n" + <del> " tooltip.innerHTML = \"Copy this as a graphQL to clipboard\";\n" + <del> "}\n" + <del> "\n" + <del> "</script>" <del> ); <del> <del> <ide> // While initializing automatically reload the page. <ide> if (!parseService.userAgentAnalyzerIsAvailable() && parseService.getUserAgentAnalyzerFailureMessage() == null) { <ide> sb.append("<meta http-equiv=\"refresh\" content=\"1\" >"); <ide> } <ide> <ide> private void copyTestcaseToClipboard(StringBuilder sb, UserAgent userAgent, int index) { <del> // .replace("\"", "&quote;").replace("\n", "&#10;")) <add> String baseScript = <add> """ <add> <script> <add> function copyTestCaseToClipboard{INDEX}() { <add> var copyText = document.getElementById("testCaseForClipboard{INDEX}"); <add> copyText.select(); <add> copyText.setSelectionRange(0, 99999); <add> navigator.clipboard.writeText(copyText.value); <add> <add> var tooltip = document.getElementById("copyTestCaseToClipboardTooltip{INDEX}"); <add> tooltip.innerHTML = "Copied to clipboard" <add> } <add> <add> function closeCopyTestCaseToClipboardTooltip{INDEX}() { <add> var tooltip = document.getElementById("copyTestCaseToClipboardTooltip{INDEX}"); <add> tooltip.innerHTML = "Copy this as a testcase to clipboard"; <add> } <add> </script> <add> """; <add> <add> sb.append(baseScript.replace("{INDEX}", String.valueOf(index))); <ide> sb <ide> .append("<textarea style='display:none' id=\"testCaseForClipboard").append(index).append("\">") <ide> .append(escapeHtml4(userAgent.toYamlTestCase())) // .replace("\"", "&quote;").replace("\n", "&#10;")) <ide> .append("</textarea>") <del> .append("<div class=\"tooltip inline\">" + <del> "<p onclick=\"copyTestCaseToClipboard()\" onmouseout=\"closeCopyTestCaseToClipboardTooltip()\">" + <del> "<span class=\"tooltiptext\" id=\"copyTestCaseToClipboardTooltip").append(index).append("\">Copy this as a testcase to clipboard</span>") <add> .append( <add> """ <add> <div class="tooltip inline"> <add> <p onclick="copyTestCaseToClipboard{INDEX}()" onmouseout="closeCopyTestCaseToClipboardTooltip{INDEX}()"> <add> <span class="tooltiptext" id="copyTestCaseToClipboardTooltip{INDEX}">Copy this as a testcase to clipboard</span> <add> """ <add> .replace("{INDEX}", String.valueOf(index))) <ide> .append("&#128203;</p>") <ide> .append("</div>\n"); <ide> } <ide> <ide> private void copyGraphQLQueryToClipboard(StringBuilder sb, UserAgent userAgent, int index) { <del> sb.append("<textarea style='display:none' id=\"graphQLForClipboard\">"); <add> String baseScript = <add> """ <add> <script> <add> function copyGraphQLToClipboard{INDEX}() { <add> var copyText = document.getElementById("graphQLForClipboard{INDEX}"); <add> copyText.select(); <add> copyText.setSelectionRange(0, 99999); <add> navigator.clipboard.writeText(copyText.value); <add> <add> var tooltip = document.getElementById("copyGraphQLToClipboardTooltip{INDEX}"); <add> tooltip.innerHTML = "Copied to clipboard" <add> } <add> <add> function closeCopyGraphQLToClipboardTooltip{INDEX}() { <add> var tooltip = document.getElementById("copyGraphQLToClipboardTooltip{INDEX}"); <add> tooltip.innerHTML = "Copy this as a graphQL to clipboard"; <add> } <add> </script> <add> """; <add> <add> sb.append(baseScript.replace("{INDEX}", String.valueOf(index))); <add> sb.append("<textarea style='display:none' id=\"graphQLForClipboard").append(index).append("\">"); <ide> sb.append("query {\n" + <ide> " analyze(requestHeaders: {\n"); <ide> Map<String, String> headers = userAgent.getHeaders(); <ide> } <ide> sb.append(" }\n"); <ide> sb.append("}"); <del> sb.append("</textarea>") <del> .append("<div class=\"tooltip inline\">" + <del> "<p onclick=\"copyGraphQLToClipboard()\" onmouseout=\"closeCopyGraphQLToClipboardTooltip()\">" + <del> "<span class=\"tooltiptext\" id=\"copyGraphQLToClipboardTooltip\">Copy this as a GraphQL query to clipboard</span>" + <del> "&#128203;</p>" + <del> "</div>\n"); <add> sb.append("</textarea>"); <add> sb.append( <add> """ <add> <div class="tooltip inline"> <add> <p onclick="copyGraphQLToClipboard{INDEX}()" onmouseout="closeCopyGraphQLToClipboardTooltip{INDEX}()"> <add> <span class="tooltiptext" id="copyGraphQLToClipboardTooltip{INDEX}">Copy this as a GraphQL query to clipboard</span>&#128203;</p> <add> </div> <add> """ .replace("{INDEX}", String.valueOf(index))); <ide> } <ide> <ide> private void addRequestHeaderToGraphQL(StringBuilder sb, String header, String gqlName) {
Java
mit
4a24fc7a6028b7b2462371ee75409e68c69227cd
0
SquidDev-CC/plethora,SquidDev-CC/plethora
package org.squiddev.plethora.integration.vanilla.meta; import com.google.common.collect.Maps; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemBanner; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntityBanner; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import org.squiddev.plethora.api.meta.BasicMetaProvider; import org.squiddev.plethora.api.meta.IMetaProvider; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Map; @IMetaProvider.Inject(value = ItemStack.class, namespace = "banner") public class MetaItemBanner extends BasicMetaProvider<ItemStack> { @Nonnull @Override public Map<Object, Object> getMeta(@Nonnull ItemStack stack) { if (!(stack.getItem() instanceof ItemBanner)) return Collections.emptyMap(); int idx = 0; Map<Object, Object> out = Maps.newHashMap(); NBTTagCompound tag = stack.getSubCompound("BlockEntityTag", false); if (tag != null && tag.hasKey("Patterns")) { NBTTagList nbttaglist = tag.getTagList("Patterns", 10); for (int i = 0; i < nbttaglist.tagCount() && i < 6; ++i) { NBTTagCompound patternTag = nbttaglist.getCompoundTagAt(i); EnumDyeColor color = EnumDyeColor.byDyeDamage(patternTag.getInteger("Color")); TileEntityBanner.EnumBannerPattern pattern = getPatternByID(patternTag.getString("Pattern")); if (pattern != null) { Map<String, String> entry = Maps.newHashMap(); entry.put("id", pattern.getPatternID()); // patternName String name = ObfuscationReflectionHelper.getPrivateValue(TileEntityBanner.EnumBannerPattern.class, pattern, "field_177284_N"); entry.put("name", name); entry.put("colour", color.toString()); entry.put("color", color.toString()); out.put(++idx, entry); } } } return out; } private static TileEntityBanner.EnumBannerPattern getPatternByID(String id) { for (TileEntityBanner.EnumBannerPattern pattern : TileEntityBanner.EnumBannerPattern.values()) { if (pattern.getPatternID().equals(id)) return pattern; } return null; } }
src/main/java/org/squiddev/plethora/integration/vanilla/meta/MetaItemBanner.java
package org.squiddev.plethora.integration.vanilla.meta; import com.google.common.collect.Maps; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemBanner; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntityBanner; import org.squiddev.plethora.api.meta.BasicMetaProvider; import org.squiddev.plethora.api.meta.IMetaProvider; import javax.annotation.Nonnull; import java.util.Collections; import java.util.Map; @IMetaProvider.Inject(value = ItemStack.class, namespace = "banner") public class MetaItemBanner extends BasicMetaProvider<ItemStack> { @Nonnull @Override public Map<Object, Object> getMeta(@Nonnull ItemStack stack) { if (!(stack.getItem() instanceof ItemBanner)) return Collections.emptyMap(); int idx = 0; Map<Object, Object> out = Maps.newHashMap(); NBTTagCompound tag = stack.getSubCompound("BlockEntityTag", false); if (tag != null && tag.hasKey("Patterns")) { NBTTagList nbttaglist = tag.getTagList("Patterns", 10); for (int i = 0; i < nbttaglist.tagCount() && i < 6; ++i) { NBTTagCompound patternTag = nbttaglist.getCompoundTagAt(i); EnumDyeColor color = EnumDyeColor.byDyeDamage(patternTag.getInteger("Color")); TileEntityBanner.EnumBannerPattern pattern = TileEntityBanner.EnumBannerPattern.getPatternByID(patternTag.getString("Pattern")); if (pattern != null) { Map<String, String> entry = Maps.newHashMap(); entry.put("id", pattern.getPatternID()); entry.put("name", pattern.getPatternName()); entry.put("colour", color.toString()); entry.put("color", color.toString()); out.put(++idx, entry); } } } return out; } }
Fix using client only methods
src/main/java/org/squiddev/plethora/integration/vanilla/meta/MetaItemBanner.java
Fix using client only methods
<ide><path>rc/main/java/org/squiddev/plethora/integration/vanilla/meta/MetaItemBanner.java <ide> import net.minecraft.nbt.NBTTagCompound; <ide> import net.minecraft.nbt.NBTTagList; <ide> import net.minecraft.tileentity.TileEntityBanner; <add>import net.minecraftforge.fml.common.ObfuscationReflectionHelper; <ide> import org.squiddev.plethora.api.meta.BasicMetaProvider; <ide> import org.squiddev.plethora.api.meta.IMetaProvider; <ide> <ide> NBTTagCompound patternTag = nbttaglist.getCompoundTagAt(i); <ide> <ide> EnumDyeColor color = EnumDyeColor.byDyeDamage(patternTag.getInteger("Color")); <del> TileEntityBanner.EnumBannerPattern pattern = TileEntityBanner.EnumBannerPattern.getPatternByID(patternTag.getString("Pattern")); <add> TileEntityBanner.EnumBannerPattern pattern = getPatternByID(patternTag.getString("Pattern")); <ide> <ide> if (pattern != null) { <ide> Map<String, String> entry = Maps.newHashMap(); <ide> entry.put("id", pattern.getPatternID()); <del> entry.put("name", pattern.getPatternName()); <add> <add> // patternName <add> String name = ObfuscationReflectionHelper.getPrivateValue(TileEntityBanner.EnumBannerPattern.class, pattern, "field_177284_N"); <add> entry.put("name", name); <add> <ide> entry.put("colour", color.toString()); <ide> entry.put("color", color.toString()); <ide> <ide> <ide> return out; <ide> } <add> <add> private static TileEntityBanner.EnumBannerPattern getPatternByID(String id) { <add> for (TileEntityBanner.EnumBannerPattern pattern : TileEntityBanner.EnumBannerPattern.values()) { <add> if (pattern.getPatternID().equals(id)) return pattern; <add> } <add> <add> return null; <add> } <ide> }
JavaScript
mit
bcbda97f750d34e960b91cb1073d2c2085f92321
0
nowsecure/r2frida,nowsecure/r2frida,nowsecure/r2frida
/* eslint-disable comma-dangle */ 'use strict'; // TODO : implement tracelog eval var and dump trace info into this file // this cant be done from the agent-side const { stalkFunction, stalkEverything } = require('./stalker'); const fs = require('./fs'); const path = require('path'); const config = require('./config'); const io = require('./io'); const isObjC = require('./isobjc'); const strings = require('./strings'); const utils = require('./utils'); // registered as a plugin require('../../ext/swift-frida/examples/r2swida/index.js'); let Gcwd = '/'; /* ObjC.available is buggy on non-objc apps, so override this */ const ObjCAvailable = (Process.platform === 'darwin') && ObjC && ObjC.available && ObjC.classes && typeof ObjC.classes.NSString !== 'undefined'; const NeedsSafeIo = (Process.platform === 'linux' && Process.arch === 'arm' && Process.pointerSize === 4); const JavaAvailable = Java && Java.available; /* globals */ const pointerSize = Process.pointerSize; let suspended = false; const tracehooks = {}; let logs = []; let traces = {}; let breakpoints = {}; const allocPool = {}; const pendingCmds = {}; const pendingCmdSends = []; let sendingCommand = false; const specialChars = '`${}~|;#@&<> ()'; function numEval (expr) { return new Promise((resolve, reject) => { const symbol = DebugSymbol.fromName(expr); if (symbol && symbol.name) { return resolve(symbol.address); } hostCmd('?v ' + expr).then(_ => resolve(_.trim())).catch(reject); }); } function javaUse (name) { const initialLoader = Java.classFactory.loader; let res = null; javaPerform(function () { for (const kl of Java.enumerateClassLoadersSync()) { try { Java.classFactory.loader = kl; res = Java.use(name); break; } catch (e) { // do nothing } } }); Java.classFactory.loader = initialLoader; return res; } function evalNum (args) { return new Promise((resolve, reject) => { numEval(args.join(' ')).then(res => { resolve(res); }); }); } function javaTraceExample () { javaPerform(function () { const System = Java.use('java.lang.System'); System.loadLibrary.implementation = function (library) { try { traceEmit('System.loadLibrary ' + library); const loaded = Runtime.getRuntime().loadLibrary0(VMStack.getCallingClassLoader(), library); return loaded; } catch (e) { console.error(e); } }; }); } const commandHandlers = { E: evalNum, '?e': echo, '/': search, '/i': searchInstances, '/ij': searchInstancesJson, '/j': searchJson, '/x': searchHex, '/xj': searchHexJson, '/w': searchWide, '/wj': searchWideJson, '/v1': searchValueImpl(1), '/v2': searchValueImpl(2), '/v4': searchValueImpl(4), '/v8': searchValueImpl(8), '/v1j': searchValueImplJson(1), '/v2j': searchValueImplJson(2), '/v4j': searchValueImplJson(4), '/v8j': searchValueImplJson(8), '?V': fridaVersion, // '.': // this is implemented in C i: dumpInfo, 'i*': dumpInfoR2, ij: dumpInfoJson, e: evalConfig, 'e*': evalConfigR2, 'e/': evalConfigSearch, db: breakpoint, dbj: breakpointJson, 'db-': breakpointUnset, dc: breakpointContinue, dcu: breakpointContinueUntil, dk: sendSignal, s: radareSeek, r: radareCommand, ie: listEntrypoint, ieq: listEntrypointQuiet, 'ie*': listEntrypointR2, iej: listEntrypointJson, ii: listImports, 'ii*': listImportsR2, iij: listImportsJson, il: listModules, 'il.': listModulesHere, 'il*': listModulesR2, ilq: listModulesQuiet, ilj: listModulesJson, ia: listAllHelp, iAs: listAllSymbols, // SLOW iAsj: listAllSymbolsJson, 'iAs*': listAllSymbolsR2, iAn: listAllClassesNatives, is: listSymbols, 'is.': lookupSymbolHere, isj: listSymbolsJson, 'is*': listSymbolsR2, ias: lookupSymbol, 'ias*': lookupSymbolR2, iasj: lookupSymbolJson, isa: lookupSymbol, 'isa*': lookupSymbolR2, isaj: lookupSymbolJson, // many symbols isam: lookupSymbolMany, isamj: lookupSymbolManyJson, 'isam*': lookupSymbolManyR2, iE: listExports, 'iE.': lookupSymbolHere, iEj: listExportsJson, 'iE*': listExportsR2, iaE: lookupExport, iaEj: lookupExportJson, 'iaE*': lookupExportR2, iEa: lookupExport, 'iEa*': lookupExportR2, iEaj: lookupExportJson, // maybe dupped iAE: listAllExports, iAEj: listAllExportsJson, 'iAE*': listAllExportsR2, init: initBasicInfoFromTarget, fD: lookupDebugInfo, fd: lookupAddress, 'fd.': lookupAddress, 'fd*': lookupAddressR2, fdj: lookupAddressJson, ic: listClasses, icw: listClassesWhere, icv: listClassVariables, ics: listClassSuperMethods, ica: listClassesAllMethods, icn: listClassesNatives, icL: listClassesLoaders, icl: listClassesLoaded, iclj: listClassesLoadedJson, 'ic*': listClassesR2, icj: listClassesJson, icm: listClassMethods, icmj: listClassMethodsJson, ip: listProtocols, ipj: listProtocolsJson, iz: listStrings, izj: listStringsJson, dd: listFileDescriptors, ddj: listFileDescriptorsJson, 'dd-': closeFileDescriptors, dm: listMemoryRanges, 'dm*': listMemoryRangesR2, dmj: listMemoryRangesJson, dmp: changeMemoryProtection, 'dm.': listMemoryRangesHere, dmm: listMemoryMaps, 'dmm*': listMemoryMapsR2, 'dmm.': listMemoryMapsHere, // alias for 'dm.' dmh: listMallocRanges, 'dmh*': listMallocRangesR2, dmhj: listMallocRangesJson, dmhm: listMallocMaps, dma: allocSize, dmas: allocString, dmad: allocDup, dmal: listAllocs, 'dma-': removeAlloc, dp: getPid, dxc: dxCall, dxo: dxObjc, dxs: dxSyscall, dpj: getPidJson, dpt: listThreads, dptj: listThreadsJson, dr: dumpRegisters, 'dr*': dumpRegistersR2, drr: dumpRegistersRecursively, drp: dumpRegisterProfile, dr8: dumpRegisterArena, drj: dumpRegistersJson, env: getOrSetEnv, envj: getOrSetEnvJson, dl: dlopen, dlf: loadFrameworkBundle, 'dlf-': unloadFrameworkBundle, dtf: traceFormat, dth: traceHook, dt: trace, dtj: traceJson, dtq: traceQuiet, 'dt*': traceR2, 'dt.': traceHere, 'dt-': clearTrace, 'dt-*': clearAllTrace, dtr: traceRegs, dtl: traceLogDump, 'dtl*': traceLogDumpR2, dtlq: traceLogDumpQuiet, dtlj: traceLogDumpJson, 'dtl-': traceLogClear, 'dtl-*': traceLogClearAll, dts: stalkTraceEverything, 'dts?': stalkTraceEverythingHelp, dtsj: stalkTraceEverythingJson, 'dts*': stalkTraceEverythingR2, dtsf: stalkTraceFunction, dtsfj: stalkTraceFunctionJson, 'dtsf*': stalkTraceFunctionR2, di: interceptHelp, dif: interceptHelp, // intercept ret after calling function dis: interceptRetString, di0: interceptRet0, di1: interceptRet1, dii: interceptRetInt, 'di-1': interceptRet_1, // intercept ret and dont call the function difs: interceptFunRetString, dif0: interceptFunRet0, dif1: interceptFunRet1, difi: interceptFunRetInt, 'dif-1': interceptFunRet_1, // unix compat pwd: getCwd, cd: chDir, cat: fsCat, ls: fsList, // required for m-io md: fsList, mg: fsGet, m: fsOpen, pd: disasmCode, px: printHexdump, x: printHexdump, eval: evalCode, chcon: changeSelinuxContext, }; async function initBasicInfoFromTarget (args) { const str = ` e dbg.backend = io e anal.autoname=true e cmd.fcn.new=aan .=!ie* .=!dmm* .=!il* m /r2f io 0 s entry0 `; return str; } function nameFromAddress (address) { const at = DebugSymbol.fromAddress(ptr(address)); if (at) { return at.name; } const module = Process.findModuleByAddress(address); if (module === null) { return null; } const imports = Module.enumerateImports(module.name); for (const imp of imports) { if (imp.address.equals(address)) { return imp.name; } } const exports = Module.enumerateExports(module.name); for (const exp of exports) { if (exp.address.equals(address)) { return exp.name; } } return address.toString(); } function allocSize (args) { const size = +args[0]; if (size > 0) { const a = Memory.alloc(size); return _addAlloc(a); } return 0; } function allocString (args) { const theString = args.join(' '); if (theString.length > 0) { const a = Memory.allocUtf8String(theString); return _addAlloc(a); } throw new Error('Usage: dmas [string]'); } function allocDup (args) { if (args.length < 2) { throw new Error('Missing argument'); } const addr = +args[0]; const size = +args[1]; if (addr > 0 && size > 0) { const a = Memory.dup(ptr(addr), size); return _addAlloc(a); } return 0; } function removeAlloc (args) { if (args.length === 0) { _clearAllocs(); } else { for (const addr of args) { _delAlloc(addr); } } return ''; } function listAllocs (args) { return Object.values(allocPool) .sort() .map((x) => { const bytes = Memory.readByteArray(x, 60); const printables = _filterPrintable(bytes); return `${x}\t"${printables}"`; }) .join('\n') + '\n'; } function _delAlloc (addr) { delete allocPool[addr]; } function _clearAllocs () { Object.keys(allocPool) .forEach(addr => delete allocPool[addr]); } function _addAlloc (allocPtr) { const key = allocPtr.toString(); if (!allocPtr.isNull()) { allocPool[key] = allocPtr; } return key; } function resolveSyscallNumber (name) { const ios = Process.arch === 'arm64'; switch (name) { case 'read': return ios ? 3 : 0x2000003; case 'write': return ios ? 4 : 0x2000004; case 'exit': return ios ? 1 : 0x2000001; } return '' + name; } function dxSyscall (args) { if (args.length === 0) { return 'Usage dxs [syscallname] [args ...]'; } const syscallNumber = '' + resolveSyscallNumber(args[0]); return dxCall(['syscall', syscallNumber, ...args.slice(1)]); } function autoType (args) { const nfArgs = []; const nfArgsData = []; // push arguments for (let i = 0; i < args.length; i++) { if (args[i].substring(0, 2) === '0x') { nfArgs.push('pointer'); nfArgsData.push(ptr(args[i])); } else if (args[i][0] === '"') { // string.. join args nfArgs.push('pointer'); const str = args[i].substring(1, args[i].length - 1); const buf = Memory.allocUtf8String(str.replace(/\\n/g, '\n')); nfArgsData.push(buf); } else if (args[i].endsWith('f')) { nfArgs.push('float'); nfArgsData.push(0.0 + args[i]); } else if (args[i].endsWith('F')) { nfArgs.push('double'); nfArgsData.push(0.0 + args[i]); } else if (+args[i] > 0 || args[i] === '0') { nfArgs.push('int'); nfArgsData.push(+args[i]); } else { nfArgs.push('pointer'); const address = Module.getExportByName(null, args[i]); nfArgsData.push(address); } } return [nfArgs, nfArgsData]; } function dxObjc (args) { if (!ObjCAvailable) { return 'dxo requires the objc runtime to be available to work.'; } // Usage: "dxo instance-pointer [arg0 arg1]" const instancePointer = args[0]; const methodName = args[1]; const [v, t] = autoType(args.slice(2)); try { ObjC.schedule(ObjC.mainQueue, function () { const instance = new ObjC.Object(ptr(instancePointer)); const method = instance[methodName]; if (method) { method(...t); } else { console.error('unknown method ' + methodName + ' for objc instance at ' + padPointer(ptr(instancePointer))); } }); } catch (e) { console.error(e); } return ''; } function dxCall (args) { if (args.length === 0) { return ` Usage: dxc [funcptr] [arg0 arg1..] For example: =!dxc write 1 "hello\\n" 6 =!dxc read 0 \`?v rsp\` 10 `; } const address = (args[0].substring(0, 2) === '0x') ? ptr(args[0]) : Module.getExportByName(null, args[0]); const [nfArgs, nfArgsData] = autoType(args.slice(1)); const fun = new NativeFunction(address, 'pointer', nfArgs); if (nfArgs.length === 0) { return fun(); } return fun(...nfArgsData); } function evalCode (args) { const code = args.join(' '); const result = eval(code); // eslint-disable-line return (result !== undefined) ? result : ''; } function printHexdump (lenstr) { const len = +lenstr || 32; try { return hexdump(ptr(r2frida.offset), len) || ''; } catch (e) { return 'Cannot read memory.'; } } function disasmCode (lenstr) { const len = +lenstr || 32; return disasm(r2frida.offset, len); } function disasm (addr, len, initialOldName) { len = len || 32; if (typeof addr === 'string') { try { addr = Module.findExportByName(null, addr); if (!addr) { throw new Error(); } } catch (e) { addr = ptr(r2frida.offset); } } let oldName = initialOldName !== undefined ? initialOldName : null; let lastAt = null; let disco = ''; for (let i = 0; i < len; i++) { const [op, next] = _tolerantInstructionParse(addr); const vaddr = padPointer(addr); if (op === null) { disco += `${vaddr}\tinvalid\n`; addr = next; continue; } const ds = DebugSymbol.fromAddress(addr); let dsName = (ds.name === null || ds.name.indexOf('0x') === 0) ? '' : ds.name; let moduleName = ds.moduleName; if (!ds.moduleName) { moduleName = ''; } if (!dsName) { dsName = ''; } if ((moduleName || dsName) && dsName !== oldName) { disco += ';;; ' + (moduleName || dsName) + '\n'; oldName = dsName; } let comment = ''; const id = op.opStr.indexOf('#0x'); if (id !== -1) { try { const at = op.opStr.substring(id + 1).split(' ')[0].split(',')[0].split(']')[0]; if (op.opStr.indexOf(']') !== -1) { try { const p = Memory.readPointer(ptr(lastAt).add(at)); const str = Memory.readCString(p); // console.log('; str:', str); disco += '; str:' + str + '\n'; } catch (e) { const p2 = Memory.readPointer(ptr(at)); const str2 = Memory.readCString(p2); // console.log('; str2:', str2); disco += '; str2:' + str2 + '\n'; console.log(e); } } lastAt = at; const di = DebugSymbol.fromAddress(ptr(at)); if (di.name !== null) { comment = '\t; ' + (di.moduleName || '') + ' ' + di.name; } else { const op2 = Instruction.parse(ptr(at)); const id2 = op2.opStr.indexOf('#0x'); const at2 = op2.opStr.substring(id2 + 1).split(' ')[0].split(',')[0].split(']')[0]; const di2 = DebugSymbol.fromAddress(ptr(at2)); if (di2.name !== null) { comment = '\t; -> ' + (di2.moduleName || '') + ' ' + di2.name; } } } catch (e) { // console.log(e); } } // console.log([op.address, op.mnemonic, op.opStr, comment].join('\t')); disco += [padPointer(op.address), op.mnemonic, op.opStr, comment].join('\t') + '\n'; if (op.size < 1) { // break; // continue after invalid op.size = 1; } addr = addr.add(op.size); } return disco; } function sym (name, ret, arg) { try { return new NativeFunction(Module.getExportByName(null, name), ret, arg); } catch (e) { console.error(name, ':', e); } } function symf (name, ret, arg) { try { return new SystemFunction(Module.getExportByName(null, name), ret, arg); } catch (e) { // console.error('Warning', name, ':', e); } } let _getenv = 0; let _setenv = 0; let _getpid = 0; let _getuid = 0; let _dup2 = 0; let _readlink = 0; let _fstat = 0; let _close = 0; let _kill = 0; if (Process.platform === 'windows') { _getenv = sym('getenv', 'pointer', ['pointer']); _setenv = sym('SetEnvironmentVariableA', 'int', ['pointer', 'pointer']); _getpid = sym('_getpid', 'int', []); _getuid = getWindowsUserNameA; _dup2 = sym('_dup2', 'int', ['int', 'int']); _fstat = sym('_fstat', 'int', ['int', 'pointer']); _close = sym('_close', 'int', ['int']); _kill = sym('TerminateProcess', 'int', ['int', 'int']); } else { _getenv = sym('getenv', 'pointer', ['pointer']); _setenv = sym('setenv', 'int', ['pointer', 'pointer', 'int']); _getpid = sym('getpid', 'int', []); _getuid = sym('getuid', 'int', []); _dup2 = sym('dup2', 'int', ['int', 'int']); _readlink = sym('readlink', 'int', ['pointer', 'pointer', 'int']); _fstat = Module.findExportByName(null, 'fstat') ? sym('fstat', 'int', ['int', 'pointer']) : sym('__fxstat', 'int', ['int', 'pointer']); _close = sym('close', 'int', ['int']); _kill = sym('kill', 'int', ['int', 'int']); } /* This is only available on Android/Linux */ const _setfilecon = symf('setfilecon', 'int', ['pointer', 'pointer']); if (Process.platform === 'darwin') { // required for early instrumentation try { Module.load('/System/Library/Frameworks/Foundation.framework/Foundation'); } catch (e) { // ignored } } const traceListeners = []; async function dumpInfo () { const padding = (x) => ''.padStart(20 - x, ' '); const properties = await dumpInfoJson(); return Object.keys(properties) .map(k => k + padding(k.length) + properties[k]) .join('\n'); } async function dumpInfoR2 () { const properties = await dumpInfoJson(); const jnienv = properties.jniEnv !== undefined ? properties.jniEnv : ''; return [ 'e asm.arch=' + properties.arch, 'e asm.bits=' + properties.bits, 'e asm.os=' + properties.os, ].join('\n') + jnienv; } function getR2Arch (arch) { switch (arch) { case 'ia32': case 'x64': return 'x86'; case 'arm64': return 'arm'; } return arch; } function breakpointUnset (args) { if (args.length === 1) { /* if (args[0] === '*') { for (let k of Object.keys(breakpoints)) { const bp = breakpoints[k]; Interceptor.revert(ptr(bp.address)); } breakpoints = {}; return 'All breakpoints removed'; } */ const symbol = Module.findExportByName(null, args[0]); const arg0 = args[0]; const addr = arg0 == '*' ? ptr(0) : (symbol !== null) ? symbol : ptr(arg0); const newbps = []; let found = false; for (const k of Object.keys(breakpoints)) { const bp = breakpoints[k]; console.log(bp.address, addr, JSON.stringify(bp)); if (arg0 === '*' || '' + bp.address === '' + addr) { found = true; console.log('Breakpoint reverted', JSON.stringify(bp)); breakpoints[k].continue = true; // continue execution // send continue action here bp.handler.detach(); } else { newbps.push(bp); } } if (!found) { console.error('Cannot found any breakpoint matching'); } // // NOPE // if (arg0 === '*') { // Interceptor.detachAll(); // } breakpoints = {}; for (const bp of newbps) { breakpoints[bp.address] = bp; } Interceptor.flush(); return ''; } return 'Usage: db- [addr|*]'; } function breakpointExist (addr) { const bp = breakpoints['' + addr]; return bp && !bp.continue; } let _r2 = null; let _r_core_new = null; let _r_core_cmd_str = null; let _r_core_free = null; let _free = null; function radareCommandInit () { if (_r2) { return true; } if (!_r_core_new) { _r_core_new = sym('r_core_new', 'pointer', []); if (!_r_core_new) { console.error('ERROR: Cannot find r_core_new. Do =!dl /tmp/libr.dylib'); return false; } _r_core_cmd_str = sym('r_core_cmd_str', 'pointer', ['pointer', 'pointer']); _r_core_free = sym('r_core_free', 'void', ['pointer']); _free = sym('free', 'void', ['pointer']); _r2 = _r_core_new(); } return true; } function radareCommandString (cmd) { if (_r2) { const aCmd = Memory.allocUtf8String(cmd); const ptr = _r_core_cmd_str(_r2, aCmd); const str = Memory.readCString(ptr); _free(ptr); return str; } console.error('Warning: not calling back r2'); return ''; } function radareSeek (args) { const addr = getPtr('' + args); const cmdstr = 's ' + (addr || '' + args); return cmdstr; // XXX hangs // return hostCmd(cmdstr); } function radareCommand (args) { const cmd = args.join(' '); if (cmd.length === 0) { return 'Usage: =!r [cmd]'; } if (radareCommandInit()) { return radareCommandString(cmd); } return '=!dl /tmp/libr.dylib'; } function sendSignal (args) { const argsLength = args.length; console.error('WARNING: Frida hangs when signal is sent. But at least the process doesnt continue'); if (argsLength === 1) { const sig = +args[0]; _kill(_getpid(), sig); } else if (argsLength === 2) { const [pid, sig] = args; _kill(+pid, +sig); } else { return 'Usage: =!dk ([pid]) [sig]'; } return ''; } function breakpointContinueUntil (args) { return new Promise((resolve, reject) => { numEval(args[0]).then(num => { setBreakpoint(num); const shouldPromise = breakpointContinue(); if (typeof shouldPromise === 'object') { shouldPromise.then(resolve).catch(reject); } else { resolve(shouldPromise); } }).catch(reject); }); } function breakpointContinue (args) { if (suspended) { suspended = false; return hostCmd('=!dc'); } let count = 0; for (const k of Object.keys(breakpoints)) { const bp = breakpoints[k]; if (bp && bp.stopped) { count++; bp.continue = true; } } for (const thread of Process.enumerateThreads()) { // console.error('send ', thread.id); send(wrapStanza('action-' + thread.id, { action: 'continue' })); } return 'Continue ' + count + ' thread(s).'; } function breakpointJson (args) { if (args.length === 0) { return JSON.stringify(breakpoints, null, ' '); } return new Promise((resolve, reject) => { numEval(args[0]).then(num => { setBreakpoint(num); resolve(JSON.stringify(breakpoints, null, ' ')); }).catch(e => { console.error(e); reject(e); }); }); } function breakpoint (args) { if (args.length === 0) { return Object.keys(breakpoints).map((bpat) => { const bp = breakpoints[bpat]; const stop = bp.stopped ? 'stop' : 'nostop'; const cont = bp.continue ? 'cont' : 'nocont'; return [bp.address, bp.moduleName, bp.name, stop, cont].join('\t'); }).join('\n'); } return new Promise((resolve, reject) => { numEval(args[0]).then(num => { resolve(setBreakpoint(args[0], num)); }).catch(e => { console.error(e); reject(e); }); }); } function setBreakpoint (name, address) { const symbol = Module.findExportByName(null, name); const addr = (symbol !== null) ? symbol : ptr(address); if (breakpointExist(addr)) { return 'Cant set a breakpoint twice'; } const addrString = '' + addr; const currentModule = Process.findModuleByAddress(address); const bp = { name: name, moduleName: currentModule ? currentModule.name : '', stopped: false, address: address, continue: false, handler: Interceptor.attach(addr, function () { if (breakpoints[addrString]) { breakpoints[addrString].stopped = true; if (config.getBoolean('hook.backtrace')) { console.log(addr); const bt = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); console.log(bt.join('\n\t')); } } /* while (breakpointExist(addr)) { Thread.sleep(1); } */ const tid = this.threadId; send({ type: 'breakpoint-hit', name: addrString, tid: tid }); let state = 'stopped'; do { const op = recv((stanza, data) => { if (stanza.payload.command === 'dc') { state = 'hit'; for (const bp in breakpoints) { breakpoints[bp].continue = true; } } else { onceStanza = true; onStanza(stanza, data); } }); op.wait(); } while (state === 'stopped'); if (breakpoints[addrString]) { breakpoints[addrString].stopped = false; breakpoints[addrString].continue = false; } }) }; breakpoints[addrString] = bp; } function getCwd () { let _getcwd = 0; if (Process.platform === 'windows') { _getcwd = sym('_getcwd', 'pointer', ['pointer', 'int']); } else { _getcwd = sym('getcwd', 'pointer', ['pointer', 'int']); } if (_getcwd) { const PATH_MAX = 4096; const buf = Memory.alloc(PATH_MAX); if (!buf.isNull()) { const ptr = _getcwd(buf, PATH_MAX); const str = Memory.readCString(ptr); Gcwd = str; return str; } } return ''; } function chDir (args) { const _chdir = sym('chdir', 'int', ['pointer']); if (_chdir && args) { const arg = Memory.allocUtf8String(args[0]); _chdir(arg); getCwd(); // update Gcwd } return ''; } function waitForJava () { javaPerform(function () { const ActivityThread = Java.use('android.app.ActivityThread'); const app = ActivityThread.currentApplication(); const ctx = app.getApplicationContext(); console.log('Done: ' + ctx); }); } async function dumpInfoJson () { const res = { arch: getR2Arch(Process.arch), bits: pointerSize * 8, os: Process.platform, pid: getPid(), uid: _getuid(), objc: ObjCAvailable, runtime: Script.runtime, java: JavaAvailable, mainLoop: hasMainLoop(), pageSize: Process.pageSize, pointerSize: Process.pointerSize, codeSigningPolicy: Process.codeSigningPolicy, isDebuggerAttached: Process.isDebuggerAttached(), cwd: getCwd(), }; if (ObjCAvailable) { try { const id = ObjC.classes.NSBundle.mainBundle().infoDictionary(); function get (k) { const v = id.objectForKey_(k); return v ? v.toString() : ''; } const NSHomeDirectory = new NativeFunction( Module.getExportByName(null, 'NSHomeDirectory'), 'pointer', []); const NSTemporaryDirectory = new NativeFunction( Module.getExportByName(null, 'NSTemporaryDirectory'), 'pointer', []); res.bundle = get('CFBundleIdentifier'); res.exename = get('CFBundleExecutable'); res.appname = get('CFBundleDisplayName'); res.appversion = get('CFBundleShortVersionString'); res.appnumversion = get('CFBundleNumericVersion'); res.homedir = (new ObjC.Object(NSHomeDirectory()).toString()); res.tmpdir = (new ObjC.Object(NSTemporaryDirectory()).toString()); res.bundledir = ObjC.classes.NSBundle.mainBundle().bundleURL().path(); // res.appdata = ObjC.classes.NSBundle.mainBundle().bundleURL().path(); res.minOS = get('MinimumOSVersion'); } catch (e) { console.error(e); } } if (JavaAvailable) { await performOnJavaVM(() => { const ActivityThread = Java.use('android.app.ActivityThread'); const app = ActivityThread.currentApplication(); if (app !== null) { const ctx = app.getApplicationContext(); if (ctx !== null) { try { res.dataDir = ctx.getDataDir().getAbsolutePath(); } catch (e) { // not available below API 24 (<Android7) } res.codeCacheDir = ctx.getCodeCacheDir().getAbsolutePath(); res.extCacheDir = ctx.getExternalCacheDir().getAbsolutePath(); res.obbDir = ctx.getObbDir().getAbsolutePath(); res.filesDir = ctx.getFilesDir().getAbsolutePath(); res.noBackupDir = ctx.getNoBackupFilesDir().getAbsolutePath(); res.codePath = ctx.getPackageCodePath(); res.packageName = ctx.getPackageName(); } try { function getContext () { return Java.use('android.app.ActivityThread').currentApplication().getApplicationContext().getContentResolver(); } res.androidId = Java.use('android.provider.Settings$Secure').getString(getContext(), 'android_id'); } catch (ignoredError) { } } res.cacheDir = Java.classFactory.cacheDir; const jniEnv = ptr(Java.vm.getEnv()); if (jniEnv) { res.jniEnv = jniEnv.toString(); } }); } return res; } function listModules () { return Process.enumerateModules() .map(m => padPointer(m.base) + ' ' + m.name) .join('\n'); } function listModulesQuiet () { return Process.enumerateModules().map(m => m.name).join('\n'); } function listModulesR2 () { return Process.enumerateModules() .map(m => 'f lib.' + utils.flagify(m.name) + ' = ' + padPointer(m.base)) .join('\n'); } function listModulesJson () { return Process.enumerateModules(); } function listModulesHere () { const here = ptr(r2frida.offset); return Process.enumerateModules() .filter(m => here.compare(m.base) >= 0 && here.compare(m.base.add(m.size)) < 0) .map(m => padPointer(m.base) + ' ' + m.name) .join('\n'); } function listExports (args) { return listExportsJson(args) .map(({ type, name, address }) => { return [address, type[0], name].join(' '); }) .join('\n'); } function listExportsR2 (args) { return listExportsJson(args) .map(({ type, name, address }) => { return ['f', 'sym.' + type.substring(0, 3) + '.' + name, '=', address].join(' '); }) .join('\n'); } function listAllExportsJson (args) { const modules = (args.length === 0) ? Process.enumerateModules().map(m => m.path) : [args.join(' ')]; return modules.reduce((result, moduleName) => { return result.concat(Module.enumerateExports(moduleName)); }, []); } function listAllExports (args) { return listAllExportsJson(args) .map(({ type, name, address }) => { return [address, type[0], name].join(' '); }) .join('\n'); } function listAllExportsR2 (args) { return listAllExportsJson(args) .map(({ type, name, address }) => { return ['f', 'sym.' + type.substring(0, 3) + '.' + name, '=', address].join(' '); }) .join('\n'); } function listAllSymbolsJson (args) { const argName = args[0]; const modules = Process.enumerateModules().map(m => m.path); let res = []; for (const module of modules) { const symbols = Module.enumerateSymbols(module) .filter((r) => r.address.compare(ptr('0')) > 0 && r.name); if (argName) { res.push(...symbols.filter((s) => s.name.indexOf(argName) !== -1)); } else { res.push(...symbols); } if (res.length > 100000) { res.forEach((r) => { console.error([r.address, r.moduleName, r.name].join(' ')); }); res = []; } } return res; } function listAllHelp (args) { return 'See =!ia? for more information. Those commands may take a while to run.'; } function listAllSymbols (args) { return listAllSymbolsJson(args) .map(({ type, name, address }) => { return [address, type[0], name].join(' '); }) .join('\n'); } function listAllSymbolsR2 (args) { return listAllSymbolsJson(args) .map(({ type, name, address }) => { return ['f', 'sym.' + type.substring(0, 3) + '.' + name, '=', address].join(' '); }) .join('\n'); } function listExportsJson (args) { const currentModule = (args.length > 0) ? Process.getModuleByName(args[0]) : getModuleByAddress(ptr(r2frida.offset)); return Module.enumerateExports(currentModule.name); } function getModuleByAddress (addr) { const m = config.getString('symbols.module'); if (m !== '') { return Process.getModuleByName(m); } try { return Process.getModuleByAddress(addr); } catch (e) { return Process.getModuleByAddress(ptr(r2frida.offset)); } } function listSymbols (args) { return listSymbolsJson(args) .map(({ type, name, address }) => { return [address, type[0], name].join(' '); }) .join('\n'); } function listSymbolsR2 (args) { return listSymbolsJson(args) .filter(({ address }) => !address.isNull()) .map(({ type, name, address }) => { return ['f', 'sym.' + type.substring(0, 3) + '.' + sanitizeString(name), '=', address].join(' '); }) .join('\n'); } function sanitizeString (str) { return str.split('').map(c => specialChars.indexOf(c) === -1 ? c : '_').join(''); } function listSymbolsJson (args) { const currentModule = (args.length > 0) ? Process.getModuleByName(args[0]) : getModuleByAddress(r2frida.offset); const symbols = Module.enumerateSymbols(currentModule.name); return symbols.map(sym => { if (config.getBoolean('symbols.unredact') && sym.name.indexOf('redacted') !== -1) { const dbgSym = DebugSymbol.fromAddress(sym.address); if (dbgSym !== null) { sym.name = dbgSym.name; } } return sym; }); } function lookupDebugInfo (args) { const o = DebugSymbol.fromAddress(ptr('' + args)); console.log(o); } function lookupAddress (args) { if (args.length === 0) { args = [ptr(r2frida.offset)]; } return lookupAddressJson(args) .map(({ type, name, address }) => [type, name, address].join(' ')) .join('\n'); } function lookupAddressR2 (args) { return lookupAddressJson(args) .map(({ type, name, address }) => ['f', 'sym.' + name, '=', address].join(' ')) .join('\n'); } function lookupAddressJson (args) { const exportAddress = ptr(args[0]); const result = []; const modules = Process.enumerateModules().map(m => m.path); return modules.reduce((result, moduleName) => { return result.concat(Module.enumerateExports(moduleName)); }, []) .reduce((type, obj) => { if (ptr(obj.address).compare(exportAddress) === 0) { result.push({ type: obj.type, name: obj.name, address: obj.address }); } return result; }, []); } function lookupSymbolHere (args) { return lookupAddress([ptr(r2frida.offset)]); } function lookupExport (args) { return lookupExportJson(args) // .map(({library, name, address}) => [library, name, address].join(' ')) .map(({ address }) => '' + address) .join('\n'); } function lookupExportR2 (args) { return lookupExportJson(args) .map(({ name, address }) => ['f', 'sym.' + name, '=', address].join(' ')) .join('\n'); } function lookupExportJson (args) { if (args.length === 2) { const [moduleName, exportName] = args; const address = Module.findExportByName(moduleName, exportName); if (address === null) { return []; } const m = getModuleByAddress(address); return [{ library: m.name, name: exportName, address: address }]; } else { const exportName = args[0]; let prevAddress = null; return Process.enumerateModules() .reduce((result, m) => { const address = Module.findExportByName(m.path, exportName); if (address !== null && (prevAddress === null || address.compare(prevAddress))) { result.push({ library: m.name, name: exportName, address: address }); prevAddress = address; } return result; }, []); } } // lookup symbols function lookupSymbol (args) { return lookupSymbolJson(args) // .map(({library, name, address}) => [library, name, address].join(' ')) .map(({ address }) => '' + address) .join('\n'); } function lookupSymbolR2 (args) { return lookupSymbolJson(args) .map(({ name, address }) => ['f', 'sym.' + name, '=', address].join(' ')) .join('\n'); } function lookupSymbolManyJson (args) { const res = []; for (const arg of args) { res.push({ name: arg, address: lookupSymbol([arg]) }); } return res; } function lookupSymbolMany (args) { return lookupSymbolManyJson(args).map(({ address }) => address).join('\n'); } function lookupSymbolManyR2 (args) { return lookupSymbolManyJson(args) .map(({ name, address }) => ['f', 'sym.' + name, '=', address].join(' ')) .join('\n'); } function lookupSymbolJson (args) { if (args.length === 0) { return []; } if (args.length === 2) { let [moduleName, symbolName] = args; try { const m = Process.getModuleByName(moduleName); // unused, this needs to be rewritten } catch (e) { const res = Process.enumerateModules().filter(function (x) { return x.name.indexOf(moduleName) !== -1; }); if (res.length !== 1) { return []; } moduleName = res[0].name; } let address = 0; Module.enumerateSymbols(moduleName).filter(function (s) { if (s.name === symbolName) { address = s.address; } }); return [{ library: moduleName, name: symbolName, address: address }]; } else { const [symbolName] = args; const res = getPtr(symbolName); const mod = getModuleAt(res); if (res) { return [{ library: mod ? mod.name : 'unknown', name: symbolName, address: res }]; } const fcns = DebugSymbol.findFunctionsNamed(symbolName); if (fcns) { return fcns.map((f) => { return { name: symbolName, address: f }; }); } return []; /* var at = DebugSymbol.fromName(symbolName); if (at.name) { return [{ library: at.moduleName, name: symbolName, address: at.address }]; } */ } } function listEntrypointJson (args) { function isEntrypoint (s) { if (s.type === 'section') { switch (s.name) { case '_start': case 'start': case 'main': return true; } } return false; } if (Process.platform === 'linux') { const at = DebugSymbol.fromName('main'); if (at) { return [at]; } } const firstModule = Process.enumerateModules()[0]; return Module.enumerateSymbols(firstModule.name) .filter((symbol) => { return isEntrypoint(symbol); }).map((symbol) => { symbol.moduleName = getModuleByAddress(symbol.address).name; return symbol; }); } function listEntrypointR2 (args) { let n = 0; return listEntrypointJson() .map((entry) => { return 'f entry' + (n++) + ' = ' + entry.address; }).join('\n'); } function listEntrypointQuiet (args) { return listEntrypointJson() .map((entry) => { return entry.address; }).join('\n'); } function listEntrypoint (args) { const n = 0; return listEntrypointJson() .map((entry) => { return entry.address + ' ' + entry.name + ' # ' + entry.moduleName; }).join('\n'); } function listImports (args) { return listImportsJson(args) .map(({ type, name, module, address }) => [address, type ? type[0] : ' ', name, module].join(' ')) .join('\n'); } function listImportsR2 (args) { const seen = new Set(); return listImportsJson(args).map((x) => { const flags = []; if (!seen.has(x.address)) { seen.add(x.address); flags.push('f sym.imp.' + utils.flagify(x.name) + ` = ${x.address}`); } if (x.slot !== undefined) { const fn = utils.flagify(`f reloc.${x.targetModuleName}.${x.name}_${x.index}`); flags.push(`f ${fn} = ${x.slot}`); } return flags.join('\n'); }).join('\n'); } function listImportsJson (args) { const alen = args.length; let result = []; let moduleName = null; if (alen === 2) { moduleName = args[0]; const importName = args[1]; const imports = Module.enumerateImports(moduleName); if (imports !== null) { result = imports.filter((x, i) => { x.index = i; return x.name === importName; }); } } else if (alen === 1) { moduleName = args[0]; result = Module.enumerateImports(moduleName) || []; } else { const currentModule = getModuleByAddress(r2frida.offset); if (currentModule) { result = Module.enumerateImports(currentModule.name) || []; } } result.forEach((x, i) => { if (x.index === undefined) { x.index = i; } x.targetModuleName = moduleName; }); return result; } function listClassesLoadedJson (args) { if (JavaAvailable) { return listClasses(args); } if (ObjCAvailable) { return JSON.stringify(ObjC.enumerateLoadedClassesSync()); } } function listClassesLoaders (args) { if (!JavaAvailable) { return 'Error: icL is only available on Android targets.'; } let res = ''; javaPerform(function () { function s2o (s) { let indent = 0; let res = ''; for (const ch of s.toString()) { switch (ch) { case '[': indent++; res += '[\n' + Array(indent + 1).join(' '); break; case ']': indent--; res += ']\n' + Array(indent + 1).join(' '); break; case ',': res += ',\n' + Array(indent + 1).join(' '); break; default: res += ch; break; } } return res; } const c = Java.enumerateClassLoadersSync(); for (const cl in c) { const cs = s2o(c[cl].toString()); res += cs; } }); return res; } function listClassesLoaded (args) { if (JavaAvailable) { return listClasses(args); } if (ObjCAvailable) { const results = ObjC.enumerateLoadedClassesSync(); const loadedClasses = []; for (const module of Object.keys(results)) { loadedClasses.push(...results[module]); } return loadedClasses.join('\n'); } return []; } // only for java function listAllClassesNatives (args) { return listClassesNatives(['.']); } function listClassesNatives (args) { const natives = []; const vkn = args[0] || 'com'; javaPerform(function () { const klasses = listClassesJson([]); for (let kn of klasses) { kn = kn.toString(); // if (kn.indexOf('android') !== -1) { continue; } if (kn.indexOf(vkn) === -1) { continue; } try { const handle = javaUse(kn); const klass = handle.class; const klassNatives = klass.getMethods().map(_ => _.toString()).filter(_ => _.indexOf('static native') !== -1); if (klassNatives.length > 0) { const kns = klassNatives.map((n) => { const p = n.indexOf('('); let sn = ''; if (p !== -1) { const s = n.substring(0, p); const w = s.split(' '); sn = w[w.length - 1]; return sn; } return n; // { name: sn, fullname: n }; }); console.error(kns.join('\n')); for (const tkn of kns) { if (natives.indexOf(tkn) === -1) { natives.push(tkn); } } } } catch (ignoreError) { } } }); return natives; } function listClassesAllMethods (args) { return listClassesJson(args, 'all').join('\n'); } function listClassSuperMethods (args) { return listClassesJson(args, 'super').join('\n'); } function listClassVariables (args) { return listClassesJson(args, 'ivars').join('\n'); } function listClassesWhere (args, mode) { let out = ''; if (args.length === 0) { const moduleNames = {}; const result = listClassesJson([]); if (ObjCAvailable) { const klasses = ObjC.classes; for (const k of result) { moduleNames[k] = klasses[k].$moduleName; } } for (const klass of result) { const modName = moduleNames[klass]; out += [modName, klass].join(' ') + '\n'; } return out; } else { const moduleNames = {}; const result = listClassesJson([]); if (ObjCAvailable) { const klasses = ObjC.classes; for (const k of result) { moduleNames[k] = ObjC.classes[k].$moduleName; } } for (const k of result) { const modName = moduleNames[k]; if (modName && modName.indexOf(args[0]) != -1) { const ins = searchInstancesJson([k]); const inss = ins.map((x) => { return x.address; }).join(' '); out += k + ' # ' + inss + '\n'; if (mode === 'ivars') { for (const a of ins) { out += 'instance ' + padPointer(a.address) + '\n'; const i = new ObjC.Object(ptr(a.address)); out += (JSON.stringify(i.$ivars)) + '\n'; } } } } return out; } } function listClasses (args) { const result = listClassesJson(args); if (result instanceof Array) { return result.join('\n'); } return Object.keys(result) .map(methodName => { const address = result[methodName]; return [padPointer(address), methodName].join(' '); }) .join('\n'); } function classGlob (k, v) { if (!k || !v) { return true; } return k.indexOf(v.replace(/\*/g, '')) !== -1; } function listClassesR2 (args) { const className = args[0]; if (args.length === 0 || args[0].indexOf('*') !== -1) { let methods = ''; if (ObjCAvailable) { for (const cn of Object.keys(ObjC.classes)) { if (classGlob(cn, args[0])) { methods += listClassesR2([cn]); } } } return methods; } const result = listClassesJson(args); return Object.keys(result) .map(methodName => { const address = result[methodName]; return ['f', flagName(methodName), '=', padPointer(address)].join(' '); }) .join('\n') + '\n'; function flagName (m) { return 'sym.objc.' + (className + '.' + m) .replace(':', '') .replace(' ', '') .replace('-', '') .replace('+', ''); } } /* this ugly sync mehtod with while+settimeout is needed because returning a promise is not properly handled yet and makes r2 lose track of the output of the command so you cant grep on it */ function listJavaClassesJsonSync (args) { if (args.length === 1) { let methods; /* list methods */ javaPerform(function () { const obj = javaUse(args[0]); methods = Object.getOwnPropertyNames(Object.getPrototypeOf(obj)); // methods = Object.keys(obj).map(x => x + ':' + obj[x] ); }); // eslint-disable-next-line while (methods === undefined) { /* wait here */ setTimeout(null, 0); } return methods; } let classes; javaPerform(function () { try { classes = Java.enumerateLoadedClassesSync(); } catch (e) { classes = null; } }); return classes; } // eslint-disable-next-line function listJavaClassesJson (args, classMethodsOnly) { let res = []; if (args.length === 1) { javaPerform(function () { try { const arg = args[0]; const handle = javaUse(arg); if (handle === null || !handle.class) { throw new Error('Cannot find a classloader for this class'); } const klass = handle.class; try { if (classMethodsOnly) { klass.getMethods().filter(x => x.toString().indexOf(arg) !== -1).map(_ => res.push(_.toString())); } else { klass.getMethods().map(_ => res.push(_.toString())); } klass.getFields().map(_ => res.push(_.toString())); try { klass.getConstructors().map(_ => res.push(_.toString())); } catch (ignore) { } } catch (e) { console.error(e.message); console.error(Object.keys(klass), JSON.stringify(klass), klass); } } catch (e) { console.error(e.message); } }); } else { javaPerform(function () { try { res = Java.enumerateLoadedClassesSync(); } catch (e) { console.error(e); } }); } return res; } function listClassMethods (args) { return listClassesJson(args, 'methods').join('\n'); } function listClassMethodsJson (args) { return listClassesJson(args, 'methods'); } function listClassesJson (args, mode) { if (JavaAvailable) { return listJavaClassesJson(args, mode === 'methods'); } if (!ObjCAvailable) { return []; } if (args.length === 0) { return Object.keys(ObjC.classes); } const klassName = args[0]; const klass = ObjC.classes[klassName]; if (klass === undefined) { throw new Error('Class ' + klassName + ' not found'); } let out = ''; if (mode === 'ivars') { const ins = searchInstancesJson([klassName]); out += klassName + ': '; for (const i of ins) { out += 'instance ' + padPointer(ptr(i.address)) + ': '; const ii = new ObjC.Object(ptr(i.address)); out += JSON.stringify(ii.$ivars, null, ' '); } return [out]; } const methods = (mode == 'methods') ? klass.$ownMethods : (mode == 'super') ? klass.$super.$ownMethods : (mode == 'all') ? klass.$methods : klass.$ownMethods; const getImpl = ObjC.api.method_getImplementation; try { return methods .reduce((result, methodName) => { try { result[methodName] = getImpl(klass[methodName].handle); } catch (_) { console.error('warning: unsupported method \'' + methodName + '\' in ' + klassName); } return result; }, {}); } catch (e) { return methods; } } function listProtocols (args) { return listProtocolsJson(args) .join('\n'); } function closeFileDescriptors (args) { if (args.length === 0) { return 'Please, provide a file descriptor'; } return _close(+args[0]); } function listFileDescriptors (args) { return listFileDescriptorsJson(args).map(([fd, name]) => { return fd + ' ' + name; }).join('\n'); } function listFileDescriptorsJson (args) { const PATH_MAX = 4096; function getFdName (fd) { if (_readlink && Process.platform === 'linux') { const fdPath = path.join('proc', '' + getPid(), 'fd', '' + fd); const buffer = Memory.alloc(PATH_MAX); const source = Memory.alloc(PATH_MAX); source.writeUtf8String(fdPath); buffer.writeUtf8String(''); if (_readlink(source, buffer, PATH_MAX) !== -1) { return buffer.readUtf8String(); } return undefined; } try { // TODO: port this to iOS const F_GETPATH = 50; // on macOS const buffer = Memory.alloc(PATH_MAX); const addr = Module.getExportByName(null, 'fcntl'); const fcntl = new NativeFunction(addr, 'int', ['int', 'int', 'pointer']); fcntl(fd, F_GETPATH, buffer); return buffer.readCString(); } catch (e) { return ''; } } if (args.length === 0) { const statBuf = Memory.alloc(128); const fds = []; for (let i = 0; i < 1024; i++) { if (_fstat(i, statBuf) === 0) { fds.push(i); } } return fds.map((fd) => { return [fd, getFdName(fd)]; }); } else { const rc = _dup2(+args[0], +args[1]); return rc; } } function listStringsJson (args) { if (!args || args.length !== 1) { args = [r2frida.offset]; } const base = ptr(args[0]); const currentRange = Process.findRangeByAddress(base); if (currentRange) { const options = { base: base }; // filter for urls? const length = Math.min(currentRange.size, 1024 * 1024 * 128); const block = 1024 * 1024; // 512KB if (length !== currentRange.size) { const curSize = currentRange.size / (1024 * 1024); console.error('Warning: this range is too big (' + curSize + 'MB), truncated to ' + length / (1024 * 1024) + 'MB'); } try { const res = []; console.log('Reading ' + (length / (1024 * 1024)) + 'MB ...'); for (let i = 0; i < length; i += block) { const addr = currentRange.base.add(i); const bytes = addr.readCString(block); const blockResults = strings(bytes.split('').map(_ => _.charCodeAt(0)), options); res.push(...blockResults); } return res; } catch (e) { console.log(e.message); } } throw new Error('Memory not mapped here'); } function listStrings (args) { if (!args || args.length !== 1) { args = [ptr(r2frida.offset)]; } const base = ptr(args[0]); return listStringsJson(args).map(({ base, text }) => padPointer(base) + ` "${text}"`).join('\n'); } function listProtocolsJson (args) { if (!ObjCAvailable) { return []; } if (args.length === 0) { return Object.keys(ObjC.protocols); } else { const protocol = ObjC.protocols[args[0]]; if (protocol === undefined) { throw new Error('Protocol not found'); } return Object.keys(protocol.methods); } } function listMallocMaps (args) { const heaps = squashRanges(listMallocRangesJson(args)); function inRange (x) { for (const heap of heaps) { if (x.base.compare(heap.base) >= 0 && x.base.add(x.size).compare(heap.base.add(heap.size))) { return true; } } return false; } return squashRanges(listMemoryRangesJson()) .filter(inRange) .map(({ base, size, protection, file }) => [ padPointer(base), '-', padPointer(base.add(size)), protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function listMallocRangesJson (args) { return Process.enumerateMallocRanges(); } function listMallocRangesR2 (args) { const chunks = listMallocRangesJson(args) .map(_ => 'f chunk.' + _.base + ' ' + _.size + ' ' + _.base).join('\n'); return chunks + squashRanges(listMallocRangesJson(args)) .map(_ => 'f heap.' + _.base + ' ' + _.size + ' ' + _.base).join('\n'); } function listMallocRanges (args) { return squashRanges(listMallocRangesJson(args)) .map(_ => '' + _.base + ' - ' + _.base.add(_.size) + ' (' + _.size + ')').join('\n') + '\n'; } function listMemoryMapsHere (args) { if (args.length !== 1) { args = [ptr(r2frida.offset)]; } const addr = ptr(args[0]); return squashRanges(listMemoryRangesJson()) .filter(({ base, size }) => addr.compare(base) >= 0 && addr.compare(base.add(size)) < 0) .map(({ base, size, protection, file }) => { return [ padPointer(base), '-', padPointer(base.add(size)), protection, file.path ].join(' '); }) .join('\n') + '\n'; } function listMemoryRangesHere (args) { if (args.length !== 1) { args = [ptr(r2frida.offset)]; } const addr = ptr(args[0]); return listMemoryRangesJson() .filter(({ base, size }) => addr.compare(base) >= 0 && addr.compare(base.add(size)) < 0) .map(({ base, size, protection, file }) => [ padPointer(base), '-', padPointer(base.add(size)), protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function rwxstr (x) { let str = ''; str += (x & 1) ? 'r' : '-'; str += (x & 2) ? 'w' : '-'; str += (x & 4) ? 'x' : '-'; return str; } function rwxint (x) { const ops = ['---', '--x', '-w-', '-wx', 'r--', 'r-x', 'rw-', 'rwx']; return ops.indexOf([x]); } function squashRanges (ranges) { const res = []; let begin = ptr(0); let end = ptr(0); let lastPerm = 0; let lastFile = ''; for (const r of ranges) { lastPerm |= rwxint(r.protection); // console.log("-", r.base, range.base.add(range.size)); if (r.base.equals(end)) { // enlarge segment end = end.add(r.size); // console.log("enlarge", begin, end); } else { if (begin.equals(ptr(0))) { begin = r.base; end = begin.add(r.size); // console.log(" set", begin, end); } else { // console.log(" append", begin, end); res.push({ base: begin, size: end.sub(begin), protection: rwxstr(lastPerm), file: lastFile }); end = ptr(0); begin = ptr(0); lastPerm = 0; lastFile = ''; } } if (r.file) { lastFile = r.file; } } if (!begin.equals(ptr(0))) { res.push({ base: begin, size: end.sub(begin), protection: rwxstr(lastPerm), file: lastFile }); } return res; } function listMemoryMapsR2 () { function filterFile (file) { return file.replace(/\//g, '_').replace(/-/g, '_'); } return squashRanges(listMemoryRangesJson()) .filter(_ => _.file) .map(({ base, size, protection, file }) => [ 'f', 'dmm.' + filterFile(file.path), '=', padPointer(base), ] .join(' ') ) .join('\n') + '\n'; } function listMemoryMaps () { return squashRanges(listMemoryRangesJson()) .filter(_ => _.file) .map(({ base, size, protection, file }) => [ padPointer(base), '-', padPointer(base.add(size)), protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function listMemoryRangesR2 () { return listMemoryRangesJson() .map(({ base, size, protection, file }) => [ 'f', 'map.' + padPointer(base), '=', base, // padPointer(base.add(size)), '#', protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function listMemoryRanges () { return listMemoryRangesJson() .map(({ base, size, protection, file }) => [ padPointer(base), '-', padPointer(base.add(size)), protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function listMemoryRangesJson () { return _getMemoryRanges('---'); } function _getMemoryRanges (protection) { if (r2frida.hookedRanges !== null) { return r2frida.hookedRanges(protection); } return Process.enumerateRangesSync({ protection, coalesce: false }); } async function changeMemoryProtection (args) { const [addr, size, protection] = args; if (args.length !== 3 || protection.length > 3) { return 'Usage: =!dmp [address] [size] [rwx]'; } const address = getPtr(addr); const mapsize = await numEval(size); Memory.protect(address, ptr(mapsize).toInt32(), protection); return ''; } function getPidJson () { return JSON.stringify({ pid: getPid() }); } function getPid () { return _getpid(); } function listThreads () { let canGetThreadName = false; try { const addr = Module.getExportByName(null, 'pthread_getname_np'); var pthreadGetnameNp = new NativeFunction(addr, 'int', ['pointer', 'pointer', 'int']); const addr2 = Module.getExportByName(null, 'pthread_from_mach_thread_np'); var pthreadFromMachThreadNp = new NativeFunction(addr2, 'pointer', ['uint']); canGetThreadName = true; } catch (e) { // do nothing } function getThreadName (tid) { if (!canGetThreadName) { return ''; } const buffer = Memory.alloc(4096); const p = pthreadFromMachThreadNp(tid); pthreadGetnameNp(p, buffer, 4096); return buffer.readCString(); } return Process.enumerateThreads().map((thread) => { const threadName = getThreadName(thread.id); return [thread.id, threadName].join(' '); }).join('\n') + '\n'; } function listThreadsJson () { return Process.enumerateThreads() .map(thread => thread.id); } function regProfileAliasFor (arch) { switch (arch) { case 'arm64': return `=PC pc =SP sp =BP x29 =A0 x0 =A1 x1 =A2 x2 =A3 x3 =ZF zf =SF nf =OF vf =CF cf =SN x8 `; case 'arm': return `=PC r15 =LR r14 =SP sp =BP fp =A0 r0 =A1 r1 =A2 r2 =A3 r3 =ZF zf =SF nf =OF vf =CF cf =SN r7 `; case 'ia64': case 'x64': return `=PC rip =SP rsp =BP rbp =A0 rdi =A1 rsi =A2 rdx =A3 rcx =A4 r8 =A5 r9 =SN rax `; case 'ia32': case 'x86': return `=PC eip =SP esp =BP ebp =A0 eax =A1 ebx =A2 ecx =A3 edx =A4 esi =A5 edi =SN eax `; } return ''; } function dumpRegisterProfile (args) { const threads = Process.enumerateThreads(); const context = threads[0].context; const names = Object.keys(JSON.parse(JSON.stringify(context))) .filter(_ => _ !== 'pc' && _ !== 'sp'); names.sort(compareRegisterNames); let off = 0; const inc = Process.pointerSize; let profile = regProfileAliasFor(Process.arch); for (const reg of names) { profile += `gpr\t${reg}\t${inc}\t${off}\t0\n`; off += inc; } return profile; } function dumpRegisterArena (args) { const threads = Process.enumerateThreads(); let [tidx] = args; if (!tidx) { tidx = 0; } if (tidx < 0 || tidx >= threads.length) { return ''; } const context = threads[tidx].context; const names = Object.keys(JSON.parse(JSON.stringify(context))) .filter(_ => _ !== 'pc' && _ !== 'sp'); names.sort(compareRegisterNames); let off = 0; const inc = Process.pointerSize; const buf = Buffer.alloc(inc * names.length); for (const reg of names) { const r = context[reg]; const b = [r.and(0xff), r.shr(8).and(0xff), r.shr(16).and(0xff), r.shr(24).and(0xff), r.shr(32).and(0xff), r.shr(40).and(0xff), r.shr(48).and(0xff), r.shr(56).and(0xff)]; for (let i = 0; i < inc; i++) { buf.writeUInt8(b[i], off + i); } off += inc; } return buf.toString('hex'); } function regcursive (regname, regvalue) { const data = [regvalue]; try { const str = Memory.readCString(regvalue, 32); if (str && str.length > 3) { const printableString = str.replace(/[^\x20-\x7E]/g, ''); data.push('\'' + printableString + '\''); } const ptr = regvalue.readPointer(); data.push('=>'); data.push(regcursive(regname, ptr)); } catch (e) { } if (regvalue === 0) { data.push('NULL'); } else if (regvalue === 0xffffffff) { data.push(-1); } else if (regvalue > ' ' && regvalue < 127) { data.push('\'' + String.fromCharCode(regvalue) + '\''); } try { const module = Process.findModuleByAddress(regvalue); if (module) { data.push(module.name); } } catch (e) { } try { const name = nameFromAddress(regvalue); if (name) { data.push(name); } } catch (e) { } return data.join(' '); } function dumpRegistersRecursively (args) { const [tid] = args; Process.enumerateThreads() .filter(thread => !tid || tid === thread.id) .map(thread => { const { id, state, context } = thread; const res = ['# thread ' + id + ' ' + state]; for (const reg of Object.keys(context)) { try { const data = regcursive(reg, context[reg]); res.push(reg + ': ' + data); } catch (e) { res.push(reg); } } console.log(res.join('\n')); }); return ''; // nothing to see here } function dumpRegistersR2 (args) { const threads = Process.enumerateThreads(); const [tid] = args; const context = tid ? threads.filter(th => th.id === tid) : threads[0].context; if (!context) { return ''; } const names = Object.keys(JSON.parse(JSON.stringify(context))); names.sort(compareRegisterNames); const values = names .map((name, index) => { if (name === 'pc' || name === 'sp') return ''; const value = context[name] || 0; return `ar ${name} = ${value}\n`; }); return values.join(''); } function dumpRegisters (args) { const [tid] = args; return Process.enumerateThreads() .filter(thread => !tid || thread.id === tid) .map(thread => { const { id, state, context } = thread; const heading = `tid ${id} ${state}`; const names = Object.keys(JSON.parse(JSON.stringify(context))); names.sort(compareRegisterNames); const values = names .map((name, index) => alignRight(name, 3) + ' : ' + padPointer(context[name])) .map(indent); return heading + '\n' + values.join(''); }) .join('\n\n') + '\n'; } function dumpRegistersJson () { return Process.enumerateThreads(); } function getOrSetEnv (args) { if (args.length === 0) { return getEnv().join('\n') + '\n'; } const { key, value } = getOrSetEnvJson(args); return key + '=' + value; } function getOrSetEnvJson (args) { if (args.length === 0) { return getEnvJson(); } const kv = args.join(''); const eq = kv.indexOf('='); if (eq !== -1) { const k = kv.substring(0, eq); const v = kv.substring(eq + 1); setenv(k, v, true); return { key: k, value: v }; } else { return { key: kv, value: getenv(kv) }; } } function getEnv () { const result = []; let envp = Memory.readPointer(Module.findExportByName(null, 'environ')); let env; while (!envp.isNull() && !(env = envp.readPointer()).isNull()) { result.push(env.readCString()); envp = envp.add(Process.pointerSize); } return result; } function getEnvJson () { return getEnv().map(kv => { const eq = kv.indexOf('='); return { key: kv.substring(0, eq), value: kv.substring(eq + 1) }; }); } function dlopen (args) { const path = fs.transformVirtualPath(args[0]); if (fs.exist(path)) { return Module.load(path); } return Module.load(args[0]); } function loadFrameworkBundle (args) { if (!ObjCAvailable) { console.log('dlf: This command requires the objc runtime'); return false; } const path = args[0]; const app_path = ObjC.classes.NSBundle.mainBundle().bundlePath(); const full_path = app_path.stringByAppendingPathComponent_(path); const bundle = ObjC.classes.NSBundle.bundleWithPath_(full_path); if (bundle.isLoaded()) { console.log('Bundle already loaded'); return false; } return bundle.load(); } function unloadFrameworkBundle (args) { if (!ObjCAvailable) { console.log('dlf: This command requires the objc runtime'); return false; } const path = args[0]; const app_path = ObjC.classes.NSBundle.mainBundle().bundlePath(); const full_path = app_path.stringByAppendingPathComponent_(path); const bundle = ObjC.classes.NSBundle.bundleWithPath_(full_path); if (!bundle.isLoaded()) { console.log('Bundle already unloaded'); return false; } return bundle.unload(); } function changeSelinuxContext (args) { if (_setfilecon === null) { return 'Error: cannot find setfilecon symbol'; } // TODO This doesnt run yet because permissions // TODO If it runs as root, then file might be checked const file = args[0]; const con = Memory.allocUtf8String('u:object_r:frida_file:s0'); const path = Memory.allocUtf8String(file); const rv = _setfilecon(path, con); return JSON.stringify({ ret: rv.value, errno: rv.errno }); } function formatArgs (args, fmt) { const a = []; const dumps = []; let arg; let j = 0; for (let i = 0; i < fmt.length; i++, j++) { try { arg = args[j]; } catch (err) { console.error('invalid format', i); } switch (fmt[i]) { case '+': case '^': j--; break; case 'h': { // hexdump pointer target, default length 128 // customize length with h<length>, f.e. h16 to dump 16 bytes let dumpLen = 128; const optionalNumStr = fmt.slice(i + 1).match(/^[0-9]*/)[0]; if (optionalNumStr.length > 0) { i += optionalNumStr.length; dumpLen = +optionalNumStr; } dumps.push(_hexdumpUntrusted(arg, dumpLen)); a.push(`dump:${dumps.length} (len=${dumpLen})`); } break; case 'H': { // hexdump pointer target, default length 128 // use length from other funtion arg with H<arg number>, f.e. H0 to dump '+args[0]' bytes let dumpLen = 128; const optionalNumStr = fmt.slice(i + 1).match(/^[0-9]*/)[0]; if (optionalNumStr.length > 0) { i += optionalNumStr.length; const posLenArg = +optionalNumStr; if (posLenArg !== j) { // only adjust dump length, if the length param isn't the dump address itself dumpLen = +args[posLenArg]; } } // limit dumpLen, to avoid oversized dumps, caused by accidentally parsing pointer agrs as length // set length limit to 64K for now const lenLimit = 0x10000; dumpLen = dumpLen > lenLimit ? lenLimit : dumpLen; dumps.push(_hexdumpUntrusted(arg, dumpLen)); a.push(`dump:${dumps.length} (len=${dumpLen})`); } break; case 'x': a.push('' + ptr(arg)); break; case 'c': a.push("'" + arg + "'"); break; case 'i': a.push(+arg); break; case 'z': // *s const s = _readUntrustedUtf8(arg); a.push(JSON.stringify(s)); break; case 'Z': // *s[i] const len = +args[j + 1]; const str = _readUntrustedUtf8(arg, len); a.push(JSON.stringify(str)); break; case 'S': // **s const sss = _readUntrustedUtf8(Memory.readPointer(arg)); a.push(JSON.stringify(sss)); break; case 'o': case 'O': if (ObjC.available) { if (!arg.isNull()) { if (isObjC(arg)) { const o = new ObjC.Object(arg); a.push(`${o.$className}: "${o.toString()}"`); } else { const str = Memory.readCString(arg); if (str.length > 2) { a.push(str); } else { a.push('' + arg); } } } else { a.push('nil'); } } else { a.push(arg); } break; default: a.push(arg); break; } } return { args: a, dumps: dumps }; } function cloneArgs (args, fmt) { const a = []; let j = 0; for (let i = 0; i < fmt.length; i++, j++) { const arg = args[j]; switch (fmt[i]) { case '+': case '^': j--; break; default: a.push(arg); break; } } return a; } function _hexdumpUntrusted (addr, len) { try { if (typeof len === 'number') return hexdump(addr, { length: len }); else return hexdump(addr); } catch (e) { return `hexdump at ${addr} failed: ${e}`; } } function _readUntrustedUtf8 (address, length) { try { if (typeof length === 'number') { return Memory.readUtf8String(ptr(address), length); } return Memory.readUtf8String(ptr(address)); } catch (e) { if (e.message !== 'invalid UTF-8') { // TODO: just use this, doo not mess with utf8 imho return Memory.readCString(ptr(address)); } return '(invalid utf8)'; } } function traceList () { let count = 0; return traceListeners.map((t) => { return [count++, t.hits, t.at, t.source, t.moduleName, t.name, t.args].join('\t'); }).join('\n') + '\n'; } function traceListJson () { return traceListeners.map(_ => JSON.stringify(_)).join('\n') + '\n'; } function getPtr (p) { if (typeof p === 'string') { p = p.trim(); } if (!p || p === '$$') { return ptr(global.r2frida.offset); } if (p.startsWith('java:')) { return p; } if (p.startsWith('objc:')) { const hatSign = p.indexOf('^') !== -1; if (hatSign !== -1) { p = p.replace('^', ''); } const endsWith = p.endsWith('$'); if (endsWith) { p = p.substring(0, p.length - 1); } p = p.substring(5); let dot = p.indexOf('.'); if (dot === -1) { dot = p.indexOf(':'); if (dot === -1) { throw new Error('r2frida\'s ObjC class syntax is: objc:CLASSNAME.METHOD'); } } const kv0 = p.substring(0, dot); const kv1 = p.substring(dot + 1); const klass = ObjC.classes[kv0]; if (klass === undefined) { throw new Error('Class ' + kv0 + ' not found'); } let found = null; let firstFail = false; let oldMethodName = null; for (const methodName of klass.$ownMethods) { const method = klass[methodName]; if (methodName.indexOf(kv1) !== -1) { if (hatSign && !methodName.substring(2).startsWith(kv1)) { continue; } if (endsWith && !methodName.endsWith(kv1)) { continue; } if (found) { if (!firstFail) { console.error(found.implementation, oldMethodName); firstFail = true; } console.error(method.implementation, methodName); } found = method; oldMethodName = methodName; } } if (firstFail) { return ptr(0); } return found ? found.implementation : ptr(0); } try { if (p.substring(0, 2) === '0x') { return ptr(p); } } catch (e) { // console.error(e); } // return DebugSymbol.fromAddress(ptr_p) || '' + ptr_p; return Module.findExportByName(null, p); } function traceHook (args) { if (args.length === 0) { return JSON.stringify(tracehooks, null, 2); } const arg = args[0]; if (arg !== undefined) { tracehookSet(arg, args.slice(1).join(' ')); } return ''; } function traceFormat (args) { if (args.length === 0) { return traceList(); } let address, format; const name = args[0]; if (args.length === 2) { address = '' + getPtr(name); format = args[1]; } else if (args.length === 1) { address = '' + getPtr(name); format = ''; } else { address = global.r2frida.offset; format = args[0]; } if (haveTraceAt(address)) { return 'There\'s already a trace in here'; } const traceOnEnter = format.indexOf('^') !== -1; const traceBacktrace = format.indexOf('+') !== -1; const currentModule = getModuleByAddress(address); const listener = Interceptor.attach(ptr(address), { myArgs: [], myBacktrace: [], keepArgs: [], onEnter: function (args) { traceListener.hits++; if (!traceOnEnter) { this.keepArgs = cloneArgs(args, format); } else { const fa = formatArgs(args, format); this.myArgs = fa.args; this.myDumps = fa.dumps; } if (traceBacktrace) { this.myBacktrace = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); } if (traceOnEnter) { const traceMessage = { source: 'dtf', name: name, address: address, timestamp: new Date(), values: this.myArgs, }; if (config.getBoolean('hook.backtrace')) { traceMessage.backtrace = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); } if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { let msg = `[dtf onEnter][${traceMessage.timestamp}] ${name}@${address} - args: ${this.myArgs.join(', ')}`; if (config.getBoolean('hook.backtrace')) { msg += ` backtrace: ${traceMessage.backtrace.toString()}`; } for (let i = 0; i < this.myDumps.length; i++) msg += `\ndump:${i + 1}\n${this.myDumps[i]}`; traceEmit(msg); } } }, onLeave: function (retval) { if (!traceOnEnter) { const fa = formatArgs(this.keepArgs, format); this.myArgs = fa.args; this.myDumps = fa.dumps; const traceMessage = { source: 'dtf', name: name, address: address, timestamp: new Date(), values: this.myArgs, retval }; if (config.getBoolean('hook.backtrace')) { traceMessage.backtrace = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); } if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { let msg = `[dtf onLeave][${traceMessage.timestamp}] ${name}@${address} - args: ${this.myArgs.join(', ')}. Retval: ${retval.toString()}`; if (config.getBoolean('hook.backtrace')) { msg += ` backtrace: ${traceMessage.backtrace.toString()}`; } for (let i = 0; i < this.myDumps.length; i++) msg += `\ndump:${i + 1}\n${this.myDumps[i]}`; traceEmit(msg); } } } }); const traceListener = { source: 'dtf', hits: 0, at: ptr(address), name: name, moduleName: currentModule ? currentModule.name : '', format: format, listener: listener }; traceListeners.push(traceListener); return true; } function traceListenerFromAddress (address) { const results = traceListeners.filter((tl) => '' + address === '' + tl.at); return (results.length > 0) ? results[0] : undefined; } function traceCountFromAddress (address) { const tl = traceListenerFromAddress(address); return tl ? tl.hits : 0; } function traceNameFromAddress (address) { const tl = traceListenerFromAddress(address); return tl ? tl.moduleName + ':' + tl.name : ''; } function traceLogDumpQuiet () { return logs.map(({ address, timestamp }) => [address, timestamp, traceCountFromAddress(address), traceNameFromAddress(address)].join(' ')) .join('\n') + '\n'; } function traceLogDumpJson () { return JSON.stringify(logs); } function traceLogDumpR2 () { let res = ''; for (const l of logs) { if (l.script) { res += l.script; } } return res; } function objectToString (o) { // console.error(JSON.stringify(o)); const r = Object.keys(o).map((k) => { try { const p = ptr(o[k]); if (isObjC(p)) { const o = new ObjC.Object(p); return k + ': ' + o.toString(); } const str = Memory.readCString(p); if (str.length > 2) { return k + ': "' + str + '"'; } } catch (e) { } return k + ': ' + o[k]; }).join(' '); return '(' + r + ')'; } function tracelogToString (l) { const line = [l.source, l.name || l.address, objectToString(l.values)].join('\t'); const bt = (!l.backtrace) ? '' : l.backtrace.map((b) => { return ['', b.address, b.moduleName, b.name].join('\t'); }).join('\n') + '\n'; return line + bt; } function traceLogDump () { return logs.map(tracelogToString).join('\n') + '\n'; } function traceLogClear (args) { // TODO: clear one trace instead of all console.error('ARGS', JSON.stringify(args)); return traceLogClearAll(); } function traceLogClearAll () { logs = []; traces = {}; return ''; } function traceEmit (msg) { const fileLog = config.getString('file.log'); if (fileLog.length > 0) { send(wrapStanza('log-file', { filename: fileLog, message: msg })); } else { traceLog(msg); } if (config.getBoolean('hook.logs')) { logs.push(msg); } global.r2frida.logs = logs; } function traceLog (msg) { if (config.getBoolean('hook.verbose')) { send(wrapStanza('log', { message: msg })); } } function haveTraceAt (address) { try { for (const trace of traceListeners) { if (trace.at.compare(address) === 0) { return true; } } } catch (e) { console.error(e); } return false; } function traceRegs (args) { if (args.length < 1) { return 'Usage: dtr [name|address] [reg ...]'; } const address = getPtr(args[0]); if (haveTraceAt(address)) { return 'There\'s already a trace in here'; } const rest = args.slice(1); const currentModule = getModuleByAddress(address); const listener = Interceptor.attach(address, traceFunction); function traceFunction (_) { traceListener.hits++; const regState = {}; rest.map((r) => { let regName = r; let regValue; if (r.indexOf('=') !== -1) { const kv = r.split('='); this.context[kv[0]] = ptr(kv[1]); // set register value regName = kv[0]; regValue = kv[1]; } else { try { const rv = ptr(this.context[r]); regValue = rv; let tail = Memory.readCString(rv); if (tail) { tail = ' (' + tail + ')'; regValue += tail; } } catch (e) { // do nothing } } regState[regName] = regValue; }); const traceMessage = { source: 'dtr', address: address, timestamp: new Date(), values: regState, }; if (config.getBoolean('hook.backtrace')) { traceMessage.backtrace = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); } if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { let msg = `[dtr][${traceMessage.timestamp}] ${address} - registers: ${JSON.stringify(regState)}`; if (config.getBoolean('hook.backtrace')) { msg += ` backtrace: ${traceMessage.backtrace.toString()}`; } traceEmit(msg); } } const traceListener = { source: 'dtr', hits: 0, at: address, moduleName: currentModule ? currentModule.name : 'unknown', name: args[0], listener: listener, args: rest }; traceListeners.push(traceListener); return ''; } function traceHere () { const args = [r2frida.offset]; args.forEach(address => { const at = DebugSymbol.fromAddress(ptr(address)) || '' + ptr(address); const listener = Interceptor.attach(ptr(address), function () { const bt = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); const at = nameFromAddress(address); console.log('Trace here probe hit at ' + address + '::' + at + '\n\t' + bt.join('\n\t')); }); traceListeners.push({ at: at, listener: listener }); }); return true; } function traceR2 (args) { return traceListeners.map(_ => `dt+ ${_.at} ${_.hits}`).join('\n') + '\n'; } function dumpJavaArguments (args) { let res = ''; try { for (const a of args) { try { res += a.toString() + ' '; } catch (ee) { } } } catch (e) { } return res; } function traceJavaConstructors (className) { javaPerform(function () { const foo = Java.use(className).$init.overloads; foo.forEach((over) => { over.implementation = function () { console.log('dt', className, '(', dumpJavaArguments(arguments), ')'); if (config.getBoolean('hook.backtrace')) { const Throwable = Java.use('java.lang.Throwable'); const bt = Throwable.$new().getStackTrace().map(_ => _.toString()).join('\n- ') + '\n'; console.log('-', bt); } return over.apply(this, arguments); }; }); }); } function traceJava (klass, method) { javaPerform(function () { const Throwable = Java.use('java.lang.Throwable'); const k = javaUse(klass); k[method].implementation = function (args) { const res = this[method](); const bt = config.getBoolean('hook.backtrace') ? Throwable.$new().getStackTrace().map(_ => _.toString()) : []; const traceMessage = { source: 'dt', klass: klass, method: method, backtrace: bt, timestamp: new Date(), result: res, values: args }; if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { let msg = `[JAVA TRACE][${traceMessage.timestamp}] ${klass}:${method} - args: ${JSON.stringify(args)}. Return value: ${res.toString()}`; if (config.getBoolean('hook.backtrace')) { msg += ` backtrace: \n${traceMessage.backtrace.toString().split(',').join('\nat ')}\n`; } traceEmit(msg); } return res; }; }); } function traceQuiet (args) { return traceListeners.map(({ address, hits, moduleName, name }) => [address, hits, moduleName + ':' + name].join(' ')).join('\n') + '\n'; } function traceJson (args) { if (args.length === 0) { return traceListJson(); } if (args[0].startsWith('java:')) { traceReal(args[0]); return; } return new Promise(function (resolve, reject) { (function pull () { const arg = args.pop(); if (arg === undefined) { return resolve(''); } const narg = getPtr(arg); if (narg) { traceReal(arg, narg); pull(); } else { numEval(arg).then(function (at) { console.error(traceReal(arg, at)); pull(); }).catch(reject); } })(); }); } function trace (args) { if (args.length === 0) { return traceList(); } return traceJson(args); } function tracehookSet (name, format, callback) { if (name === null) { console.error('Name was not resolved'); return false; } tracehooks[name] = { format: format, callback: callback }; return true; } function arrayBufferToHex (arrayBuffer) { if (typeof arrayBuffer !== 'object' || arrayBuffer === null || typeof arrayBuffer.byteLength !== 'number') { throw new TypeError('Expected input to be an ArrayBuffer'); } const view = new Uint8Array(arrayBuffer); let result = ''; let value; for (let i = 0; i < view.length; i++) { value = view[i].toString(16); result += (value.length === 1 ? '0' + value : value); } return result; } // \dth printf 0,1 .. kind of dtf function tracehook (address, args) { const at = nameFromAddress(address); const th = tracehooks[at]; const fmtarg = []; if (th && th.format) { for (const fmt of th.format.split(' ')) { const [k, v] = fmt.split(':'); switch (k) { case 'i': // console.log('int', args[v]); fmtarg.push(+args[v]); break; case 's': { const [a, l] = v.split(','); const addr = ptr(args[a]); const size = +args[l]; // const buf = Memory.readByteArray(addr, size); // console.log('buf', arrayBufferToHex(buf)); // console.log('string', Memory.readCString(addr, size)); fmtarg.push(Memory.readCString(addr, size)); } break; case 'z': // console.log('string', Memory.readCString(args[+v])); fmtarg.push(Memory.readCString(ptr(args[+v]))); break; case 'v': { const [a, l] = v.split(','); const addr = ptr(args[a]); const buf = Memory.readByteArray(addr, +args[l]); fmtarg.push(arrayBufferToHex(buf)); } break; } } } return fmtarg; } function traceReal (name, addressString) { if (arguments.length === 0) { return traceList(); } if (name.startsWith('java:')) { const javaName = name.substring(5); if (javaUse(javaName)) { console.error('Tracing class constructors'); traceJavaConstructors(javaName); } else { const dot = javaName.lastIndexOf('.'); if (dot !== -1) { const klass = javaName.substring(0, dot); const methd = javaName.substring(dot + 1); traceJava(klass, methd); } else { console.log('Invalid java method name. Use =!dt java:package.class.method'); } } return; } const address = ptr(addressString); if (haveTraceAt(address)) { return 'There\'s already a trace in here'; } const currentModule = getModuleByAddress(address); const listener = Interceptor.attach(address, function (args) { const values = tracehook(address, args); const traceMessage = { source: 'dt', address: address, timestamp: new Date(), values: values, }; traceListener.hits++; if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { traceEmit(`[dt][${traceMessage.timestamp}] ${address} - args: ${JSON.stringify(values)}`); } }); const traceListener = { source: 'dt', at: address, hits: 0, name: name, moduleName: currentModule ? currentModule.name : 'unknown', args: '', listener: listener }; traceListeners.push(traceListener); return ''; } function clearAllTrace (args) { traceListeners.splice(0).forEach(lo => lo.listener ? lo.listener.detach() : null); return ''; } function clearTrace (args) { if (args.length > 0 && +args[0] > 0) { const res = []; const nth = +args[0]; for (let i = 0; i < traceListeners.length; i++) { const tl = traceListeners[i]; if (i === nth) { tl.listener.detach(); } else { res.push(tl); } } } return ''; } function interceptHelp (args) { return 'Usage: di[f][0,1,-1,s] [addr] : intercept function before/after calling and replace return value\n'; 'dif0 0x808080 # when program calls this address, dont run the function and return 0\n'; } /* Intercept function calls *after* calling the original function code */ function interceptRetJava (klass, method, value) { javaPerform(function () { const System = javaUse(klass); System[method].implementation = function (library) { const timestamp = new Date(); if (config.getString('hook.output') === 'json') { traceEmit({ source: 'java', class: klass, method, returnValue: value, timestamp }); } else { traceEmit(`[JAVA TRACE][${timestamp}] Intercept return for ${klass}:${method} with ${value}`); } switch (value) { case 0: return false; case 1: return true; case -1: return -1; // TODO should throw an error? } return value; }; }); } function interceptRetJavaExpression (target, value) { let klass = target.substring('java:'.length); const lastDot = klass.lastIndexOf('.'); if (lastDot !== -1) { const method = klass.substring(lastDot + 1); klass = klass.substring(0, lastDot); return interceptRetJava(klass, method, value); } return 'Error: Wrong java method syntax'; } function interceptRet (target, value) { if (target.startsWith('java:')) { return interceptRetJavaExpression(target, value); } const p = getPtr(target); Interceptor.attach(p, { onLeave (retval) { retval.replace(ptr(value)); } }); } function interceptRet0 (args) { const target = args[0]; return interceptRet(target, 0); } function interceptRetString (args) { const target = args[0]; return interceptRet(target, args[1]); } function interceptRetInt (args) { const target = args[0]; return interceptRet(target, args[1]); } function interceptRet1 (args) { const target = args[0]; return interceptRet(target, 1); } function interceptRet_1 (args) { // eslint-disable-line const target = args[0]; return interceptRet(target, -1); } /* Intercept function calls *before* calling the original function code */ function interceptFunRet (target, value) { if (target.startsWith('java:')) { return 'TODO: not yet implemented'; } const p = getPtr(target); Interceptor.replace(p, new NativeCallback(function () { return ptr(value); }, 'pointer', ['pointer'])); } function interceptFunRet0 (args) { const target = args[0]; return interceptFunRet(target, 0); } function interceptFunRetString (args) { const target = args[0]; return interceptFunRet(target, args[1]); } function interceptFunRetInt (args) { const target = args[0]; return interceptFunRet(target, args[1]); } function interceptFunRet1 (args) { const target = args[0]; return interceptFunRet(target, 1); } function interceptFunRet_1 (args) { // eslint-disable-line const target = args[0]; return interceptFunRet(target, -1); } function getenv (name) { return Memory.readUtf8String(_getenv(Memory.allocUtf8String(name))); } function setenv (name, value, overwrite) { return _setenv(Memory.allocUtf8String(name), Memory.allocUtf8String(value), overwrite ? 1 : 0); } function getWindowsUserNameA () { const _GetUserNameA = sym('GetUserNameA', 'int', ['pointer', 'pointer']); const PATH_MAX = 4096; const buf = Memory.allocUtf8String('A'.repeat(PATH_MAX)); const char_out = Memory.allocUtf8String('A'.repeat(PATH_MAX)); const res = _GetUserNameA(buf, char_out); const user = Memory.readCString(buf); return user; } function stalkTraceFunction (args) { return _stalkTraceSomething(_stalkFunctionAndGetEvents, args); } function stalkTraceFunctionR2 (args) { return _stalkTraceSomethingR2(_stalkFunctionAndGetEvents, args); } function stalkTraceFunctionJson (args) { return _stalkTraceSomethingJson(_stalkFunctionAndGetEvents, args); } function stalkTraceEverything (args) { if (args.length === 0) { return 'Warnnig: dts is experimental and slow\nUsage: dts [symbol]'; } return _stalkTraceSomething(_stalkEverythingAndGetEvents, args); } function stalkTraceEverythingR2 (args) { if (args.length === 0) { return 'Warnnig: dts is experimental and slow\nUsage: dts* [symbol]'; } return _stalkTraceSomethingR2(_stalkEverythingAndGetEvents, args); } function stalkTraceEverythingJson (args) { if (args.length === 0) { return 'Warnnig: dts is experimental and slow\nUsage: dtsj [symbol]'; } return _stalkTraceSomethingJson(_stalkEverythingAndGetEvents, args); } function _stalkTraceSomething (getEvents, args) { return getEvents(args, (isBlock, events) => { let previousSymbolName; const result = []; const threads = Object.keys(events); for (const threadId of threads) { result.push(`; --- thread ${threadId} --- ;`); if (isBlock) { result.push(..._mapBlockEvents(events[threadId], (address) => { const pd = disasmOne(address, previousSymbolName); previousSymbolName = getSymbolName(address); return pd; }, (begin, end) => { previousSymbolName = null; return ''; })); } else { result.push(...events[threadId].map((event) => { const address = event[0]; const target = event[1]; const pd = disasmOne(address, previousSymbolName, target); previousSymbolName = getSymbolName(address); return pd; })); } } return result.join('\n') + '\n'; }); function disasmOne (address, previousSymbolName, target) { let pd = disasm(address, 1, previousSymbolName); if (pd.endsWith('\n')) { pd = pd.slice(0, -1); } if (target) { pd += ` ; ${target} ${getSymbolName(target)}`; } return pd; } } function _stalkTraceSomethingR2 (getEvents, args) { return getEvents(args, (isBlock, events) => { const result = []; const threads = Object.keys(events); for (const threadId of threads) { if (isBlock) { result.push(..._mapBlockEvents(events[threadId], (address) => { return `dt+ ${address} 1`; })); } else { result.push(...events[threadId].map((event) => { const commands = []; const location = event[0]; commands.push(`dt+ ${location} 1`); const target = event[1]; if (target) { commands.push(`CC ${target} ${getSymbolName(target)} @ ${location}`); } return commands.join('\n') + '\n'; })); } } return result.join('\n') + '\n'; }); } function _stalkTraceSomethingJson (getEvents, args) { return getEvents(args, (isBlock, events) => { const result = { event: config.get('stalker.event'), threads: events }; return result; }); } function _stalkFunctionAndGetEvents (args, eventsHandler) { _requireFridaVersion(10, 3, 13); const at = getPtr(args[0]); const conf = { event: config.get('stalker.event'), timeout: config.get('stalker.timeout'), stalkin: config.get('stalker.in') }; const isBlock = conf.event === 'block' || conf.event === 'compile'; const operation = stalkFunction(conf, at) .then((events) => { return eventsHandler(isBlock, events); }); breakpointContinue([]); return operation; } function _stalkEverythingAndGetEvents (args, eventsHandler) { _requireFridaVersion(10, 3, 13); const timeout = (args.length > 0) ? +args[0] : null; const conf = { event: config.get('stalker.event'), timeout: config.get('stalker.timeout'), stalkin: config.get('stalker.in') }; const isBlock = conf.event === 'block' || conf.event === 'compile'; const operation = stalkEverything(conf, timeout) .then((events) => { return eventsHandler(isBlock, events); }); breakpointContinue([]); return operation; } function getSymbolName (address) { const ds = DebugSymbol.fromAddress(address); return (ds.name === null || ds.name.indexOf('0x') === 0) ? '' : ds.name; } function _requireFridaVersion (major, minor, patch) { const required = [major, minor, patch]; const actual = Frida.version.split('.'); for (let i = 0; i < actual.length; i++) { if (actual[i] > required[i]) { return; } if (actual[i] < required[i]) { throw new Error(`Frida v${major}.${minor}.${patch} or higher required for this (you have v${Frida.version}).`); } } } function _mapBlockEvents (events, onInstruction, onBlock) { const result = []; events.forEach(([begin, end]) => { if (typeof onBlock === 'function') { result.push(onBlock(begin, end)); } let cursor = begin; while (cursor < end) { const [instr, next] = _tolerantInstructionParse(cursor); if (instr !== null) { result.push(onInstruction(cursor)); } cursor = next; } }); return result; } function _tolerantInstructionParse (address) { let instr = null; let cursor = address; try { instr = Instruction.parse(cursor); cursor = instr.next; } catch (e) { if (e.message !== 'invalid instruction' && e.message !== `access violation accessing ${cursor}`) { throw e; } if (e.message.indexOf('access violation') !== -1) { // cannot access the memory } else { // console.log(`warning: error parsing instruction at ${cursor}`); } // skip invalid instructions switch (Process.arch) { case 'arm64': cursor = cursor.add(4); break; case 'arm': cursor = cursor.add(2); break; default: cursor = cursor.add(1); break; } } return [instr, cursor]; } function compareRegisterNames (lhs, rhs) { const lhsIndex = parseRegisterIndex(lhs); const rhsIndex = parseRegisterIndex(rhs); const lhsHasIndex = lhsIndex !== null; const rhsHasIndex = rhsIndex !== null; if (lhsHasIndex && rhsHasIndex) { return lhsIndex - rhsIndex; } if (lhsHasIndex === rhsHasIndex) { const lhsLength = lhs.length; const rhsLength = rhs.length; if (lhsLength === rhsLength) { return lhs.localeCompare(rhs); } if (lhsLength > rhsLength) { return 1; } return -1; } if (lhsHasIndex) { return 1; } return -1; } function parseRegisterIndex (name) { const length = name.length; for (let index = 1; index < length; index++) { const value = parseInt(name.substr(index)); if (!isNaN(value)) { return value; } } return null; } function indent (message, index) { if (index === 0) { return message; } if ((index % 3) === 0) { return '\n' + message; } return '\t' + message; } function alignRight (text, width) { let result = text; while (result.length < width) { result = ' ' + result; } return result; } function padPointer (value) { let result = value.toString(16); const paddedLength = 2 * pointerSize; while (result.length < paddedLength) { result = '0' + result; } return '0x' + result; } const requestHandlers = { safeio: () => { r2frida.safeio = true; }, read: io.read, write: io.write, state: state, perform: perform, evaluate: evaluate, }; function state (params, data) { r2frida.offset = params.offset; suspended = params.suspended; return [{}, null]; } function isPromise (value) { return value !== null && typeof value === 'object' && typeof value.then === 'function'; } function stalkTraceEverythingHelp () { return `Usage: dts[j*] [symbol|address] - Trace given symbol using the Frida Stalker dtsf[*j] [sym|addr] Trace address or symbol using the stalker dts[*j] seconds Trace all threads for given seconds using the stalker `; } function getHelpMessage (prefix) { return Object.keys(commandHandlers).sort() .filter((k) => { return !prefix || k.startsWith(prefix); }) .map((k) => { const desc = commandHandlers[k].name .replace(/(?:^|\.?)([A-Z])/g, function (x, y) { return ' ' + y.toLowerCase(); }).replace(/^_/, ''); return ' ' + k + '\t' + desc; }).join('\n') + '\n'; } function perform (params) { const { command } = params; const tokens = command.split(/ /).map((c) => c.trim()).filter((x) => x); const [name, ...args] = tokens; if (typeof name === 'undefined') { const value = getHelpMessage(''); return [{ value: normalizeValue(value) }, null]; } if (name.length > 0 && name.endsWith('?') && !commandHandlers[name]) { const prefix = name.substring(0, name.length - 1); const value = getHelpMessage(prefix); return [{ value: normalizeValue(value) }, null]; } const userHandler = global.r2frida.commandHandler(name); const handler = userHandler !== undefined ? userHandler : commandHandlers[name]; if (handler === undefined) { throw new Error('Unhandled command: ' + name); } if (isPromise(handler)) { throw new Error("The handler can't be a promise"); } const value = handler(args); if (isPromise(value)) { return new Promise((resolve, reject) => { return value.then(output => { resolve([{ value: normalizeValue(output) }, null]); }).catch(reject); }); } const nv = normalizeValue(value); if (nv === '' || nv === 'null' || nv === undefined || nv === null) { return [{}, null]; } return [{ value: nv }, null]; } function normalizeValue (value) { if (typeof value === null || typeof value === undefined) { return null; } if (typeof value === 'undefined') { return 'undefined'; } if (typeof value === 'string') { return value; } return JSON.stringify(value); } function evaluate (params) { return new Promise(resolve => { let { code, ccode } = params; const isObjcMainLoopRunning = ObjCAvailable && hasMainLoop(); if (ObjCAvailable && isObjcMainLoopRunning && !suspended) { ObjC.schedule(ObjC.mainQueue, performEval); } else { performEval(); } function performEval () { let result; try { if (ccode) { code = ` var m = new CModule(` + '`' + ccode + '`' + `); const main = new NativeFunction(m.main, 'int', []); main(); `; } const rawResult = (1, eval)(code); // eslint-disable-line global._ = rawResult; result = rawResult; // 'undefined'; } catch (e) { result = 'throw new ' + e.name + '("' + e.message + '")'; } resolve([{ value: result }, null]); } }); } function hasMainLoop () { const getMainPtr = Module.findExportByName(null, 'CFRunLoopGetMain'); if (getMainPtr === null) { return false; } const copyCurrentModePtr = Module.findExportByName(null, 'CFRunLoopCopyCurrentMode'); if (copyCurrentModePtr === null) { return false; } const getMain = new NativeFunction(getMainPtr, 'pointer', []); const copyCurrentMode = new NativeFunction(copyCurrentModePtr, 'pointer', ['pointer']); const main = getMain(); if (main.isNull()) { return false; } const mode = copyCurrentMode(main); const hasLoop = !mode.isNull(); if (hasLoop) { new ObjC.Object(mode).release(); } return hasLoop; } Script.setGlobalAccessHandler({ enumerate () { return []; }, get (property) { return undefined; } }); function fridaVersion () { return { version: Frida.version }; } function search (args) { return searchJson(args).then(hits => { return _readableHits(hits); }); } function echo (args) { console.log(args.join(' ')); return null; } function searchJson (args) { const pattern = _toHexPairs(args.join(' ')); return _searchPatternJson(pattern).then(hits => { hits.forEach(hit => { try { const bytes = io.read({ offset: hit.address, count: 60 })[1]; hit.content = _filterPrintable(bytes); } catch (e) { } }); return hits.filter(hit => hit.content !== undefined); }); } function searchInstancesJson (args) { const className = args.join(''); if (ObjCAvailable) { const results = JSON.parse(JSON.stringify(ObjC.chooseSync(ObjC.classes[className]))); return results.map(function (res) { return { address: res.handle, content: className }; }); } else { Java.performNow(function () { const results = Java.choose(Java.classes[className]); return results.map(function (res) { return { address: res, content: className }; }); }); } } function searchInstances (args) { return _readableHits(searchInstancesJson(args)); } function searchHex (args) { return searchHexJson(args).then(hits => { return _readableHits(hits); }); } function searchHexJson (args) { const pattern = _normHexPairs(args.join('')); return _searchPatternJson(pattern).then(hits => { hits.forEach(hit => { const bytes = Memory.readByteArray(hit.address, hit.size); hit.content = _byteArrayToHex(bytes); }); return hits; }); } function searchWide (args) { return searchWideJson(args).then(hits => { return _readableHits(hits); }); } function searchWideJson (args) { const pattern = _toWidePairs(args.join(' ')); return searchHexJson([pattern]); } function searchValueImpl (width) { return function (args) { return searchValueJson(args, width).then(hits => { return _readableHits(hits); }); }; } function searchValueImplJson (width) { return function (args) { return searchValueJson(args, width); }; } function searchValueJson (args, width) { let value; try { value = uint64(args.join('')); } catch (e) { return new Promise((resolve, reject) => reject(e)); } return hostCmdj('ej') .then((r2cfg) => { const bigEndian = r2cfg['cfg.bigendian']; const bytes = _renderEndian(value, bigEndian, width); return searchHexJson([_toHexPairs(bytes)]); }); } function evalConfigSearch (args) { const currentRange = Process.getRangeByAddress(ptr(r2frida.offset)); const from = currentRange.base; const to = from.add(currentRange.size); return `e search.in=raw e search.from=${from} e search.to=${to} e anal.in=raw e anal.from=${from} e anal.to=${to}`; } function evalConfigR2 (args) { return config.asR2Script(); } function evalConfig (args) { // list if (args.length === 0) { return config.asR2Script(); } const kv = args[0].split(/=/); const [k, v] = kv; if (kv.length === 2) { if (config.get(k) !== undefined) { // help if (v === '?') { return config.helpFor(kv[0]); } // set (and flatten case for variables except file.log) if (kv[0] !== 'file.log' && typeof kv[1] === 'string') { config.set(kv[0], kv[1].toLowerCase()); } else { config.set(kv[0], kv[1]); } } else { console.error('unknown variable'); } return ''; } // get return config.getString(args[0]); } function _renderEndian (value, bigEndian, width) { const bytes = []; for (let i = 0; i !== width; i++) { if (bigEndian) { bytes.push(value.shr((width - i - 1) * 8).and(0xff).toNumber()); } else { bytes.push(value.shr(i * 8).and(0xff).toNumber()); } } return bytes; } function _byteArrayToHex (arr) { const u8arr = new Uint8Array(arr); const hexs = []; for (let i = 0; i !== u8arr.length; i += 1) { const h = u8arr[i].toString(16); hexs.push((h.length === 2) ? h : `0${h}`); } return hexs.join(''); } const minPrintable = ' '.charCodeAt(0); const maxPrintable = '~'.charCodeAt(0); function _filterPrintable (arr) { const u8arr = new Uint8Array(arr); const printable = []; for (let i = 0; i !== u8arr.length; i += 1) { const c = u8arr[i]; if (c === 0) { break; } if (c >= minPrintable && c <= maxPrintable) { printable.push(String.fromCharCode(c)); } } return printable.join(''); } function _readableHits (hits) { const output = hits.map(hit => { if (typeof hit.flag === 'string') { return `${hexPtr(hit.address)} ${hit.flag} ${hit.content}`; } return `${hexPtr(hit.address)} ${hit.content}`; }); return output.join('\n') + '\n'; } function hexPtr (p) { if (p instanceof UInt64) { return `0x${p.toString(16)}`; } return p.toString(); } function _searchPatternJson (pattern) { return hostCmdj('ej') .then(r2cfg => { const flags = r2cfg['search.flags']; const prefix = r2cfg['search.prefix'] || 'hit'; const count = r2cfg['search.count'] || 0; const kwidx = r2cfg['search.kwidx'] || 0; const ranges = _getRanges(r2cfg['search.from'], r2cfg['search.to']); const nBytes = pattern.split(' ').length; qlog(`Searching ${nBytes} bytes: ${pattern}`); let results = []; const commands = []; let idx = 0; for (const range of ranges) { if (range.size === 0) { continue; } const rangeStr = `[${padPointer(range.address)}-${padPointer(range.address.add(range.size))}]`; qlog(`Searching ${nBytes} bytes in ${rangeStr}`); try { const partial = _scanForPattern(range.address, range.size, pattern); partial.forEach((hit) => { if (flags) { hit.flag = `${prefix}${kwidx}_${idx + count}`; commands.push('fs+searches'); commands.push(`f ${hit.flag} ${hit.size} ${hexPtr(hit.address)}`); commands.push('fs-'); } idx += 1; }); results = results.concat(partial); } catch (e) { console.error('Oops', e); } } qlog(`hits: ${results.length}`); commands.push(`e search.kwidx=${kwidx + 1}`); return hostCmds(commands).then(() => { return results; }); }); function qlog (message) { if (!config.getBoolean('search.quiet')) { console.log(message); } } } function _scanForPattern (address, size, pattern) { if (r2frida.hookedScan !== null) { return r2frida.hookedScan(address, size, pattern); } return Memory.scanSync(address, size, pattern); } function _configParseSearchIn () { const res = { current: false, perm: 'r--', path: null, heap: false }; const c = config.getString('search.in'); const cSplit = c.split(':'); const [scope, param] = cSplit; if (scope === 'current') { res.current = true; } if (scope === 'heap') { res.heap = true; } if (scope === 'perm') { res.perm = param; } if (scope === 'path') { cSplit.shift(); res.path = cSplit.join(''); } return res; } function _getRanges (fromNum, toNum) { const searchIn = _configParseSearchIn(); if (searchIn.heap) { return Process.enumerateMallocRanges() .map(_ => { return { address: _.base, size: _.size }; }); } const ranges = _getMemoryRanges(searchIn.perm).filter(range => { const start = range.base; const end = start.add(range.size); const offPtr = ptr(r2frida.offset); if (searchIn.current) { return offPtr.compare(start) >= 0 && offPtr.compare(end) < 0; } if (searchIn.path !== null) { if (range.file !== undefined) { return range.file.path.indexOf(searchIn.path) >= 0; } return false; } return true; }); if (ranges.length === 0) { return []; } const first = ranges[0]; const last = ranges[ranges.length - 1]; const from = (fromNum === -1) ? first.base : ptr(fromNum); const to = (toNum === -1) ? last.base.add(last.size) : ptr(toNum); return ranges.filter(range => { return range.base.compare(to) <= 0 && range.base.add(range.size).compare(from) >= 0; }).map(range => { const start = _ptrMax(range.base, from); const end = _ptrMin(range.base.add(range.size), to); return { address: start, size: uint64(end.sub(start).toString()).toNumber() }; }); } function _ptrMax (a, b) { return a.compare(b) > 0 ? a : b; } function _ptrMin (a, b) { return a.compare(b) < 0 ? a : b; } function _toHexPairs (raw) { const isString = typeof raw === 'string'; const pairs = []; for (let i = 0; i !== raw.length; i += 1) { const code = (isString ? raw.charCodeAt(i) : raw[i]) & 0xff; const h = code.toString(16); pairs.push((h.length === 2) ? h : `0${h}`); } return pairs.join(' '); } function _toWidePairs (raw) { const pairs = []; for (let i = 0; i !== raw.length; i += 1) { const code = raw.charCodeAt(i) & 0xff; const h = code.toString(16); pairs.push((h.length === 2) ? h : `0${h}`); pairs.push('00'); } return pairs.join(' '); } function _normHexPairs (raw) { const norm = raw.replace(/ /g, ''); if (_isHex(norm)) { return _toPairs(norm.replace(/\./g, '?')); } throw new Error('Invalid hex string'); } function _toPairs (hex) { if ((hex.length % 2) !== 0) { throw new Error('Odd-length string'); } const pairs = []; for (let i = 0; i !== hex.length; i += 2) { pairs.push(hex.substr(i, 2)); } return pairs.join(' ').toLowerCase(); } function _isHex (raw) { const hexSet = new Set(Array.from('abcdefABCDEF0123456789?.')); const inSet = new Set(Array.from(raw)); for (const h of hexSet) { inSet.delete(h); } return inSet.size === 0; } function fsList (args) { return fs.ls(args[0] || Gcwd); } function fsGet (args) { return fs.cat(args[0] || '', '*', args[1] || 0, args[2] || null); } function fsCat (args) { return fs.cat(args[0] || ''); } function fsOpen (args) { return fs.open(args[0] || Gcwd); } function javaPerform (fn) { if (config.getBoolean('java.wait')) { return Java.perform(fn); } return Java.performNow(fn); } function performOnJavaVM (fn) { return new Promise((resolve, reject) => { javaPerform(function () { try { const result = fn(); resolve(result); } catch (e) { reject(e); } }); }); } function getModuleAt (addr) { if (addr === null) { return null; } const modules = Process.enumerateModules() .filter((m) => { const a = m.base; const b = m.base.add(m.size); return addr.compare(a) >= 0 && addr.compare(b) < 0; }); return modules.length > 0 ? modules[0] : null; } let onceStanza = false; function onStanza (stanza, data) { const handler = requestHandlers[stanza.type]; if (handler !== undefined) { try { const value = handler(stanza.payload, data); if (value instanceof Promise) { // handle async stuff in here value .then(([replyStanza, replyBytes]) => { send(wrapStanza('reply', replyStanza), replyBytes); }) .catch(e => { send(wrapStanza('reply', { error: e.message })); }); } else { const [replyStanza, replyBytes] = value; send(wrapStanza('reply', replyStanza), replyBytes); } } catch (e) { send(wrapStanza('reply', { error: e.message })); } } else if (stanza.type === 'bp') { console.error('Breakpoint handler'); } else if (stanza.type === 'cmd') { onCmdResp(stanza.payload); } else { console.error('Unhandled stanza: ' + stanza.type); } if (!onceStanza) { recv(onStanza); } } let cmdSerial = 0; function hostCmds (commands) { let i = 0; function sendOne () { if (i < commands.length) { return hostCmd(commands[i]).then(() => { i += 1; return sendOne(); }); } else { return Promise.resolve(); } } return sendOne(); } function hostCmdj (cmd) { return hostCmd(cmd) .then(output => { return JSON.parse(output); }); } function hostCmd (cmd) { return new Promise((resolve) => { const serial = cmdSerial; cmdSerial++; pendingCmds[serial] = resolve; sendCommand(cmd, serial); }); } global.r2frida.hostCmd = hostCmd; global.r2frida.hostCmdj = hostCmdj; global.r2frida.logs = logs; global.r2frida.log = traceLog; global.r2frida.emit = traceEmit; global.r2frida.safeio = NeedsSafeIo; global.r2frida.module = ''; function sendCommand (cmd, serial) { function sendIt () { sendingCommand = true; send(wrapStanza('cmd', { cmd: cmd, serial: serial })); } if (sendingCommand) { pendingCmdSends.push(sendIt); } else { sendIt(); } } function onCmdResp (params) { const { serial, output } = params; sendingCommand = false; if (serial in pendingCmds) { const onFinish = pendingCmds[serial]; delete pendingCmds[serial]; process.nextTick(() => onFinish(output)); } else { throw new Error('Command response out of sync'); } process.nextTick(() => { if (!sendingCommand) { const nextSend = pendingCmdSends.shift(); if (nextSend !== undefined) { nextSend(); } } }); return [{}, null]; } function wrapStanza (name, stanza) { return { name: name, stanza: stanza }; } recv(onStanza);
src/agent/index.js
/* eslint-disable comma-dangle */ 'use strict'; // TODO : implement tracelog eval var and dump trace info into this file // this cant be done from the agent-side const { stalkFunction, stalkEverything } = require('./stalker'); const fs = require('./fs'); const path = require('path'); const config = require('./config'); const io = require('./io'); const isObjC = require('./isobjc'); const strings = require('./strings'); const utils = require('./utils'); // registered as a plugin require('../../ext/swift-frida/examples/r2swida/index.js'); let Gcwd = '/'; /* ObjC.available is buggy on non-objc apps, so override this */ const ObjCAvailable = (Process.platform === 'darwin') && ObjC && ObjC.available && ObjC.classes && typeof ObjC.classes.NSString !== 'undefined'; const NeedsSafeIo = (Process.platform === 'linux' && Process.arch === 'arm' && Process.pointerSize === 4); const JavaAvailable = Java && Java.available; /* globals */ const pointerSize = Process.pointerSize; let suspended = false; const tracehooks = {}; let logs = []; let traces = {}; let breakpoints = {}; const allocPool = {}; const pendingCmds = {}; const pendingCmdSends = []; let sendingCommand = false; const specialChars = '`${}~|;#@&<> ()'; function numEval (expr) { return new Promise((resolve, reject) => { const symbol = DebugSymbol.fromName(expr); if (symbol && symbol.name) { return resolve(symbol.address); } hostCmd('?v ' + expr).then(_ => resolve(_.trim())).catch(reject); }); } function javaUse (name) { const initialLoader = Java.classFactory.loader; let res = null; javaPerform(function () { for (const kl of Java.enumerateClassLoadersSync()) { try { Java.classFactory.loader = kl; res = Java.use(name); break; } catch (e) { // do nothing } } }); Java.classFactory.loader = initialLoader; return res; } function evalNum (args) { return new Promise((resolve, reject) => { numEval(args.join(' ')).then(res => { resolve(res); }); }); } function javaTraceExample () { javaPerform(function () { const System = Java.use('java.lang.System'); System.loadLibrary.implementation = function (library) { try { traceEmit('System.loadLibrary ' + library); const loaded = Runtime.getRuntime().loadLibrary0(VMStack.getCallingClassLoader(), library); return loaded; } catch (e) { console.error(e); } }; }); } const commandHandlers = { E: evalNum, '?e': echo, '/': search, '/i': searchInstances, '/ij': searchInstancesJson, '/j': searchJson, '/x': searchHex, '/xj': searchHexJson, '/w': searchWide, '/wj': searchWideJson, '/v1': searchValueImpl(1), '/v2': searchValueImpl(2), '/v4': searchValueImpl(4), '/v8': searchValueImpl(8), '/v1j': searchValueImplJson(1), '/v2j': searchValueImplJson(2), '/v4j': searchValueImplJson(4), '/v8j': searchValueImplJson(8), '?V': fridaVersion, // '.': // this is implemented in C i: dumpInfo, 'i*': dumpInfoR2, ij: dumpInfoJson, e: evalConfig, 'e*': evalConfigR2, 'e/': evalConfigSearch, db: breakpoint, dbj: breakpointJson, 'db-': breakpointUnset, dc: breakpointContinue, dcu: breakpointContinueUntil, dk: sendSignal, s: radareSeek, r: radareCommand, ie: listEntrypoint, ieq: listEntrypointQuiet, 'ie*': listEntrypointR2, iej: listEntrypointJson, ii: listImports, 'ii*': listImportsR2, iij: listImportsJson, il: listModules, 'il.': listModulesHere, 'il*': listModulesR2, ilq: listModulesQuiet, ilj: listModulesJson, ia: listAllHelp, iAs: listAllSymbols, // SLOW iAsj: listAllSymbolsJson, 'iAs*': listAllSymbolsR2, iAn: listAllClassesNatives, is: listSymbols, 'is.': lookupSymbolHere, isj: listSymbolsJson, 'is*': listSymbolsR2, ias: lookupSymbol, 'ias*': lookupSymbolR2, iasj: lookupSymbolJson, isa: lookupSymbol, 'isa*': lookupSymbolR2, isaj: lookupSymbolJson, // many symbols isam: lookupSymbolMany, isamj: lookupSymbolManyJson, 'isam*': lookupSymbolManyR2, iE: listExports, 'iE.': lookupSymbolHere, iEj: listExportsJson, 'iE*': listExportsR2, iaE: lookupExport, iaEj: lookupExportJson, 'iaE*': lookupExportR2, iEa: lookupExport, 'iEa*': lookupExportR2, iEaj: lookupExportJson, // maybe dupped iAE: listAllExports, iAEj: listAllExportsJson, 'iAE*': listAllExportsR2, init: initBasicInfoFromTarget, fD: lookupDebugInfo, fd: lookupAddress, 'fd.': lookupAddress, 'fd*': lookupAddressR2, fdj: lookupAddressJson, ic: listClasses, icw: listClassesWhere, icv: listClassVariables, ics: listClassSuperMethods, ica: listClassesAllMethods, icn: listClassesNatives, icL: listClassesLoaders, icl: listClassesLoaded, iclj: listClassesLoadedJson, 'ic*': listClassesR2, icj: listClassesJson, icm: listClassMethods, icmj: listClassMethodsJson, ip: listProtocols, ipj: listProtocolsJson, iz: listStrings, izj: listStringsJson, dd: listFileDescriptors, ddj: listFileDescriptorsJson, 'dd-': closeFileDescriptors, dm: listMemoryRanges, 'dm*': listMemoryRangesR2, dmj: listMemoryRangesJson, dmp: changeMemoryProtection, 'dm.': listMemoryRangesHere, dmm: listMemoryMaps, 'dmm*': listMemoryMapsR2, 'dmm.': listMemoryMapsHere, // alias for 'dm.' dmh: listMallocRanges, 'dmh*': listMallocRangesR2, dmhj: listMallocRangesJson, dmhm: listMallocMaps, dma: allocSize, dmas: allocString, dmad: allocDup, dmal: listAllocs, 'dma-': removeAlloc, dp: getPid, dxc: dxCall, dxo: dxObjc, dxs: dxSyscall, dpj: getPidJson, dpt: listThreads, dptj: listThreadsJson, dr: dumpRegisters, 'dr*': dumpRegistersR2, drr: dumpRegistersRecursively, drp: dumpRegisterProfile, dr8: dumpRegisterArena, drj: dumpRegistersJson, env: getOrSetEnv, envj: getOrSetEnvJson, dl: dlopen, dlf: loadFrameworkBundle, 'dlf-': unloadFrameworkBundle, dtf: traceFormat, dth: traceHook, dt: trace, dtj: traceJson, dtq: traceQuiet, 'dt*': traceR2, 'dt.': traceHere, 'dt-': clearTrace, 'dt-*': clearAllTrace, dtr: traceRegs, dtl: traceLogDump, 'dtl*': traceLogDumpR2, dtlq: traceLogDumpQuiet, dtlj: traceLogDumpJson, 'dtl-': traceLogClear, 'dtl-*': traceLogClearAll, dts: stalkTraceEverything, 'dts?': stalkTraceEverythingHelp, dtsj: stalkTraceEverythingJson, 'dts*': stalkTraceEverythingR2, dtsf: stalkTraceFunction, dtsfj: stalkTraceFunctionJson, 'dtsf*': stalkTraceFunctionR2, di: interceptHelp, dif: interceptHelp, // intercept ret after calling function dis: interceptRetString, di0: interceptRet0, di1: interceptRet1, dii: interceptRetInt, 'di-1': interceptRet_1, // intercept ret and dont call the function difs: interceptFunRetString, dif0: interceptFunRet0, dif1: interceptFunRet1, difi: interceptFunRetInt, 'dif-1': interceptFunRet_1, // unix compat pwd: getCwd, cd: chDir, cat: fsCat, ls: fsList, // required for m-io md: fsList, mg: fsGet, m: fsOpen, pd: disasmCode, px: printHexdump, x: printHexdump, eval: evalCode, chcon: changeSelinuxContext, }; async function initBasicInfoFromTarget (args) { const str = ` e dbg.backend = io e anal.autoname=true e cmd.fcn.new=aan .=!ie* .=!dmm* .=!il* m /r2f io 0 s entry0 `; return str; } function nameFromAddress (address) { const at = DebugSymbol.fromAddress(ptr(address)); if (at) { return at.name; } const module = Process.findModuleByAddress(address); if (module === null) { return null; } const imports = Module.enumerateImports(module.name); for (const imp of imports) { if (imp.address.equals(address)) { return imp.name; } } const exports = Module.enumerateExports(module.name); for (const exp of exports) { if (exp.address.equals(address)) { return exp.name; } } return address.toString(); } function allocSize (args) { const size = +args[0]; if (size > 0) { const a = Memory.alloc(size); return _addAlloc(a); } return 0; } function allocString (args) { const theString = args.join(' '); if (theString.length > 0) { const a = Memory.allocUtf8String(theString); return _addAlloc(a); } throw new Error('Usage: dmas [string]'); } function allocDup (args) { if (args.length < 2) { throw new Error('Missing argument'); } const addr = +args[0]; const size = +args[1]; if (addr > 0 && size > 0) { const a = Memory.dup(ptr(addr), size); return _addAlloc(a); } return 0; } function removeAlloc (args) { if (args.length === 0) { _clearAllocs(); } else { for (const addr of args) { _delAlloc(addr); } } return ''; } function listAllocs (args) { return Object.values(allocPool) .sort() .map((x) => { const bytes = Memory.readByteArray(x, 60); const printables = _filterPrintable(bytes); return `${x}\t"${printables}"`; }) .join('\n') + '\n'; } function _delAlloc (addr) { delete allocPool[addr]; } function _clearAllocs () { Object.keys(allocPool) .forEach(addr => delete allocPool[addr]); } function _addAlloc (allocPtr) { const key = allocPtr.toString(); if (!allocPtr.isNull()) { allocPool[key] = allocPtr; } return key; } function resolveSyscallNumber (name) { const ios = Process.arch === 'arm64'; switch (name) { case 'read': return ios ? 3 : 0x2000003; case 'write': return ios ? 4 : 0x2000004; case 'exit': return ios ? 1 : 0x2000001; } return '' + name; } function dxSyscall (args) { if (args.length === 0) { return 'Usage dxs [syscallname] [args ...]'; } const syscallNumber = '' + resolveSyscallNumber(args[0]); return dxCall(['syscall', syscallNumber, ...args.slice(1)]); } function autoType (args) { const nfArgs = []; const nfArgsData = []; // push arguments for (let i = 0; i < args.length; i++) { if (args[i].substring(0, 2) === '0x') { nfArgs.push('pointer'); nfArgsData.push(ptr(args[i])); } else if (args[i][0] === '"') { // string.. join args nfArgs.push('pointer'); const str = args[i].substring(1, args[i].length - 1); const buf = Memory.allocUtf8String(str.replace(/\\n/g, '\n')); nfArgsData.push(buf); } else if (args[i].endsWith('f')) { nfArgs.push('float'); nfArgsData.push(0.0 + args[i]); } else if (args[i].endsWith('F')) { nfArgs.push('double'); nfArgsData.push(0.0 + args[i]); } else if (+args[i] > 0 || args[i] === '0') { nfArgs.push('int'); nfArgsData.push(+args[i]); } else { nfArgs.push('pointer'); const address = Module.getExportByName(null, args[i]); nfArgsData.push(address); } } return [nfArgs, nfArgsData]; } function dxObjc (args) { if (!ObjCAvailable) { return 'dxo requires the objc runtime to be available to work.'; } // Usage: "dxo instance-pointer [arg0 arg1]" const instancePointer = args[0]; const methodName = args[1]; const [v, t] = autoType(args.slice(2)); try { ObjC.schedule(ObjC.mainQueue, function () { const instance = new ObjC.Object(ptr(instancePointer)); const method = instance[methodName]; if (method) { method(...t); } else { console.error('unknown method ' + methodName + ' for objc instance at ' + padPointer(ptr(instancePointer))); } }); } catch (e) { console.error(e); } return ''; } function dxCall (args) { if (args.length === 0) { return ` Usage: dxc [funcptr] [arg0 arg1..] For example: =!dxc write 1 "hello\\n" 6 =!dxc read 0 \`?v rsp\` 10 `; } const address = (args[0].substring(0, 2) === '0x') ? ptr(args[0]) : Module.getExportByName(null, args[0]); const [nfArgs, nfArgsData] = autoType(args.slice(1)); const fun = new NativeFunction(address, 'pointer', nfArgs); if (nfArgs.length === 0) { return fun(); } return fun(...nfArgsData); } function evalCode (args) { const code = args.join(' '); const result = eval(code); // eslint-disable-line return (result !== undefined) ? result : ''; } function printHexdump (lenstr) { const len = +lenstr || 32; try { return hexdump(ptr(r2frida.offset), len) || ''; } catch (e) { return 'Cannot read memory.'; } } function disasmCode (lenstr) { const len = +lenstr || 32; return disasm(r2frida.offset, len); } function disasm (addr, len, initialOldName) { len = len || 32; if (typeof addr === 'string') { try { addr = Module.findExportByName(null, addr); if (!addr) { throw new Error(); } } catch (e) { addr = ptr(r2frida.offset); } } let oldName = initialOldName !== undefined ? initialOldName : null; let lastAt = null; let disco = ''; for (let i = 0; i < len; i++) { const [op, next] = _tolerantInstructionParse(addr); const vaddr = padPointer(addr); if (op === null) { disco += `${vaddr}\tinvalid\n`; addr = next; continue; } const ds = DebugSymbol.fromAddress(addr); let dsName = (ds.name === null || ds.name.indexOf('0x') === 0) ? '' : ds.name; let moduleName = ds.moduleName; if (!ds.moduleName) { moduleName = ''; } if (!dsName) { dsName = ''; } if ((moduleName || dsName) && dsName !== oldName) { disco += ';;; ' + (moduleName || dsName) + '\n'; oldName = dsName; } let comment = ''; const id = op.opStr.indexOf('#0x'); if (id !== -1) { try { const at = op.opStr.substring(id + 1).split(' ')[0].split(',')[0].split(']')[0]; if (op.opStr.indexOf(']') !== -1) { try { const p = Memory.readPointer(ptr(lastAt).add(at)); const str = Memory.readCString(p); // console.log('; str:', str); disco += '; str:' + str + '\n'; } catch (e) { const p2 = Memory.readPointer(ptr(at)); const str2 = Memory.readCString(p2); // console.log('; str2:', str2); disco += '; str2:' + str2 + '\n'; console.log(e); } } lastAt = at; const di = DebugSymbol.fromAddress(ptr(at)); if (di.name !== null) { comment = '\t; ' + (di.moduleName || '') + ' ' + di.name; } else { const op2 = Instruction.parse(ptr(at)); const id2 = op2.opStr.indexOf('#0x'); const at2 = op2.opStr.substring(id2 + 1).split(' ')[0].split(',')[0].split(']')[0]; const di2 = DebugSymbol.fromAddress(ptr(at2)); if (di2.name !== null) { comment = '\t; -> ' + (di2.moduleName || '') + ' ' + di2.name; } } } catch (e) { // console.log(e); } } // console.log([op.address, op.mnemonic, op.opStr, comment].join('\t')); disco += [padPointer(op.address), op.mnemonic, op.opStr, comment].join('\t') + '\n'; if (op.size < 1) { // break; // continue after invalid op.size = 1; } addr = addr.add(op.size); } return disco; } function sym (name, ret, arg) { try { return new NativeFunction(Module.getExportByName(null, name), ret, arg); } catch (e) { console.error(name, ':', e); } } function symf (name, ret, arg) { try { return new SystemFunction(Module.getExportByName(null, name), ret, arg); } catch (e) { // console.error('Warning', name, ':', e); } } let _getenv = 0; let _setenv = 0; let _getpid = 0; let _getuid = 0; let _dup2 = 0; let _readlink = 0; let _fstat = 0; let _close = 0; let _kill = 0; if (Process.platform === 'windows') { _getenv = sym('getenv', 'pointer', ['pointer']); _setenv = sym('SetEnvironmentVariableA', 'int', ['pointer', 'pointer']); _getpid = sym('_getpid', 'int', []); _getuid = getWindowsUserNameA; _dup2 = sym('_dup2', 'int', ['int', 'int']); _fstat = sym('_fstat', 'int', ['int', 'pointer']); _close = sym('_close', 'int', ['int']); _kill = sym('TerminateProcess', 'int', ['int', 'int']); } else { _getenv = sym('getenv', 'pointer', ['pointer']); _setenv = sym('setenv', 'int', ['pointer', 'pointer', 'int']); _getpid = sym('getpid', 'int', []); _getuid = sym('getuid', 'int', []); _dup2 = sym('dup2', 'int', ['int', 'int']); _readlink = sym('readlink', 'int', ['pointer', 'pointer', 'int']); _fstat = Module.findExportByName(null, 'fstat') ? sym('fstat', 'int', ['int', 'pointer']) : sym('__fxstat', 'int', ['int', 'pointer']); _close = sym('close', 'int', ['int']); _kill = sym('kill', 'int', ['int', 'int']); } /* This is only available on Android/Linux */ const _setfilecon = symf('setfilecon', 'int', ['pointer', 'pointer']); if (Process.platform === 'darwin') { // required for early instrumentation try { Module.load('/System/Library/Frameworks/Foundation.framework/Foundation'); } catch (e) { // ignored } } const traceListeners = []; async function dumpInfo () { const padding = (x) => ''.padStart(20 - x, ' '); const properties = await dumpInfoJson(); return Object.keys(properties) .map(k => k + padding(k.length) + properties[k]) .join('\n'); } async function dumpInfoR2 () { const properties = await dumpInfoJson(); const jnienv = properties.jniEnv !== undefined ? properties.jniEnv : ''; return [ 'e asm.arch=' + properties.arch, 'e asm.bits=' + properties.bits, 'e asm.os=' + properties.os, ].join('\n') + jnienv; } function getR2Arch (arch) { switch (arch) { case 'ia32': case 'x64': return 'x86'; case 'arm64': return 'arm'; } return arch; } function breakpointUnset (args) { if (args.length === 1) { /* if (args[0] === '*') { for (let k of Object.keys(breakpoints)) { const bp = breakpoints[k]; Interceptor.revert(ptr(bp.address)); } breakpoints = {}; return 'All breakpoints removed'; } */ const symbol = Module.findExportByName(null, args[0]); const arg0 = args[0]; const addr = arg0 == '*' ? ptr(0) : (symbol !== null) ? symbol : ptr(arg0); const newbps = []; let found = false; for (const k of Object.keys(breakpoints)) { const bp = breakpoints[k]; console.log(bp.address, addr, JSON.stringify(bp)); if (arg0 === '*' || '' + bp.address === '' + addr) { found = true; console.log('Breakpoint reverted', JSON.stringify(bp)); breakpoints[k].continue = true; // continue execution // send continue action here bp.handler.detach(); } else { newbps.push(bp); } } if (!found) { console.error('Cannot found any breakpoint matching'); } // // NOPE // if (arg0 === '*') { // Interceptor.detachAll(); // } breakpoints = {}; for (const bp of newbps) { breakpoints[bp.address] = bp; } Interceptor.flush(); return ''; } return 'Usage: db- [addr|*]'; } function breakpointExist (addr) { const bp = breakpoints['' + addr]; return bp && !bp.continue; } let _r2 = null; let _r_core_new = null; let _r_core_cmd_str = null; let _r_core_free = null; let _free = null; function radareCommandInit () { if (_r2) { return true; } if (!_r_core_new) { _r_core_new = sym('r_core_new', 'pointer', []); if (!_r_core_new) { console.error('ERROR: Cannot find r_core_new. Do =!dl /tmp/libr.dylib'); return false; } _r_core_cmd_str = sym('r_core_cmd_str', 'pointer', ['pointer', 'pointer']); _r_core_free = sym('r_core_free', 'void', ['pointer']); _free = sym('free', 'void', ['pointer']); _r2 = _r_core_new(); } return true; } function radareCommandString (cmd) { if (_r2) { const aCmd = Memory.allocUtf8String(cmd); const ptr = _r_core_cmd_str(_r2, aCmd); const str = Memory.readCString(ptr); _free(ptr); return str; } console.error('Warning: not calling back r2'); return ''; } function radareSeek (args) { const addr = getPtr('' + args); const cmdstr = 's ' + (addr || '' + args); return cmdstr; // XXX hangs // return hostCmd(cmdstr); } function radareCommand (args) { const cmd = args.join(' '); if (cmd.length === 0) { return 'Usage: =!r [cmd]'; } if (radareCommandInit()) { return radareCommandString(cmd); } return '=!dl /tmp/libr.dylib'; } function sendSignal (args) { const argsLength = args.length; console.error('WARNING: Frida hangs when signal is sent. But at least the process doesnt continue'); if (argsLength === 1) { const sig = +args[0]; _kill(_getpid(), sig); } else if (argsLength === 2) { const [pid, sig] = args; _kill(+pid, +sig); } else { return 'Usage: =!dk ([pid]) [sig]'; } return ''; } function breakpointContinueUntil (args) { return new Promise((resolve, reject) => { numEval(args[0]).then(num => { setBreakpoint(num); const shouldPromise = breakpointContinue(); if (typeof shouldPromise === 'object') { shouldPromise.then(resolve).catch(reject); } else { resolve(shouldPromise); } }).catch(reject); }); } function breakpointContinue (args) { if (suspended) { suspended = false; return hostCmd('=!dc'); } let count = 0; for (const k of Object.keys(breakpoints)) { const bp = breakpoints[k]; if (bp && bp.stopped) { count++; bp.continue = true; } } for (const thread of Process.enumerateThreads()) { // console.error('send ', thread.id); send(wrapStanza('action-' + thread.id, { action: 'continue' })); } return 'Continue ' + count + ' thread(s).'; } function breakpointJson (args) { if (args.length === 0) { return JSON.stringify(breakpoints, null, ' '); } return new Promise((resolve, reject) => { numEval(args[0]).then(num => { setBreakpoint(num); resolve(JSON.stringify(breakpoints, null, ' ')); }).catch(e => { console.error(e); reject(e); }); }); } function breakpoint (args) { if (args.length === 0) { return Object.keys(breakpoints).map((bpat) => { const bp = breakpoints[bpat]; const stop = bp.stopped ? 'stop' : 'nostop'; const cont = bp.continue ? 'cont' : 'nocont'; return [bp.address, bp.moduleName, bp.name, stop, cont].join('\t'); }).join('\n'); } return new Promise((resolve, reject) => { numEval(args[0]).then(num => { resolve(setBreakpoint(args[0], num)); }).catch(e => { console.error(e); reject(e); }); }); } function setBreakpoint (name, address) { const symbol = Module.findExportByName(null, name); const addr = (symbol !== null) ? symbol : ptr(address); if (breakpointExist(addr)) { return 'Cant set a breakpoint twice'; } const addrString = '' + addr; const currentModule = Process.findModuleByAddress(address); const bp = { name: name, moduleName: currentModule ? currentModule.name : '', stopped: false, address: address, continue: false, handler: Interceptor.attach(addr, function () { if (breakpoints[addrString]) { breakpoints[addrString].stopped = true; if (config.getBoolean('hook.backtrace')) { console.log(addr); const bt = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); console.log(bt.join('\n\t')); } } /* while (breakpointExist(addr)) { Thread.sleep(1); } */ const tid = this.threadId; send({ type: 'breakpoint-hit', name: addrString, tid: tid }); let state = 'stopped'; do { const op = recv((stanza, data) => { if (stanza.payload.command === 'dc') { state = 'hit'; for (const bp in breakpoints) { breakpoints[bp].continue = true; } } else { onceStanza = true; onStanza(stanza, data); } }); op.wait(); } while (state === 'stopped'); if (breakpoints[addrString]) { breakpoints[addrString].stopped = false; breakpoints[addrString].continue = false; } }) }; breakpoints[addrString] = bp; } function getCwd () { let _getcwd = 0; if (Process.platform === 'windows') { _getcwd = sym('_getcwd', 'pointer', ['pointer', 'int']); } else { _getcwd = sym('getcwd', 'pointer', ['pointer', 'int']); } if (_getcwd) { const PATH_MAX = 4096; const buf = Memory.alloc(PATH_MAX); if (!buf.isNull()) { const ptr = _getcwd(buf, PATH_MAX); const str = Memory.readCString(ptr); Gcwd = str; return str; } } return ''; } function chDir (args) { const _chdir = sym('chdir', 'int', ['pointer']); if (_chdir && args) { const arg = Memory.allocUtf8String(args[0]); _chdir(arg); getCwd(); // update Gcwd } return ''; } function waitForJava () { javaPerform(function () { const ActivityThread = Java.use('android.app.ActivityThread'); const app = ActivityThread.currentApplication(); const ctx = app.getApplicationContext(); console.log('Done: ' + ctx); }); } async function dumpInfoJson () { const res = { arch: getR2Arch(Process.arch), bits: pointerSize * 8, os: Process.platform, pid: getPid(), uid: _getuid(), objc: ObjCAvailable, runtime: Script.runtime, java: JavaAvailable, mainLoop: hasMainLoop(), pageSize: Process.pageSize, pointerSize: Process.pointerSize, codeSigningPolicy: Process.codeSigningPolicy, isDebuggerAttached: Process.isDebuggerAttached(), cwd: getCwd(), }; if (ObjCAvailable) { try { const id = ObjC.classes.NSBundle.mainBundle().infoDictionary(); function get (k) { const v = id.objectForKey_(k); return v ? v.toString() : ''; } res.bundle = get('CFBundleIdentifier'); res.exename = get('CFBundleExecutable'); res.appname = get('CFBundleDisplayName'); res.appversion = get('CFBundleShortVersionString'); res.appnumversion = get('CFBundleNumericVersion'); res.apphome = ObjC.classes.NSBundle.mainBundle().bundleURL().path(); res.minOS = get('MinimumOSVersion'); } catch (e) { console.error(e); } } if (JavaAvailable) { await performOnJavaVM(() => { const ActivityThread = Java.use('android.app.ActivityThread'); const app = ActivityThread.currentApplication(); if (app !== null) { const ctx = app.getApplicationContext(); if (ctx !== null) { try { res.dataDir = ctx.getDataDir().getAbsolutePath(); } catch (e) { // not available below API 24 (<Android7) } res.codeCacheDir = ctx.getCodeCacheDir().getAbsolutePath(); res.extCacheDir = ctx.getExternalCacheDir().getAbsolutePath(); res.obbDir = ctx.getObbDir().getAbsolutePath(); res.filesDir = ctx.getFilesDir().getAbsolutePath(); res.noBackupDir = ctx.getNoBackupFilesDir().getAbsolutePath(); res.codePath = ctx.getPackageCodePath(); res.packageName = ctx.getPackageName(); } try { function getContext () { return Java.use('android.app.ActivityThread').currentApplication().getApplicationContext().getContentResolver(); } res.androidId = Java.use('android.provider.Settings$Secure').getString(getContext(), 'android_id'); } catch (ignoredError) { } } res.cacheDir = Java.classFactory.cacheDir; const jniEnv = ptr(Java.vm.getEnv()); if (jniEnv) { res.jniEnv = jniEnv.toString(); } }); } return res; } function listModules () { return Process.enumerateModules() .map(m => padPointer(m.base) + ' ' + m.name) .join('\n'); } function listModulesQuiet () { return Process.enumerateModules().map(m => m.name).join('\n'); } function listModulesR2 () { return Process.enumerateModules() .map(m => 'f lib.' + utils.flagify(m.name) + ' = ' + padPointer(m.base)) .join('\n'); } function listModulesJson () { return Process.enumerateModules(); } function listModulesHere () { const here = ptr(r2frida.offset); return Process.enumerateModules() .filter(m => here.compare(m.base) >= 0 && here.compare(m.base.add(m.size)) < 0) .map(m => padPointer(m.base) + ' ' + m.name) .join('\n'); } function listExports (args) { return listExportsJson(args) .map(({ type, name, address }) => { return [address, type[0], name].join(' '); }) .join('\n'); } function listExportsR2 (args) { return listExportsJson(args) .map(({ type, name, address }) => { return ['f', 'sym.' + type.substring(0, 3) + '.' + name, '=', address].join(' '); }) .join('\n'); } function listAllExportsJson (args) { const modules = (args.length === 0) ? Process.enumerateModules().map(m => m.path) : [args.join(' ')]; return modules.reduce((result, moduleName) => { return result.concat(Module.enumerateExports(moduleName)); }, []); } function listAllExports (args) { return listAllExportsJson(args) .map(({ type, name, address }) => { return [address, type[0], name].join(' '); }) .join('\n'); } function listAllExportsR2 (args) { return listAllExportsJson(args) .map(({ type, name, address }) => { return ['f', 'sym.' + type.substring(0, 3) + '.' + name, '=', address].join(' '); }) .join('\n'); } function listAllSymbolsJson (args) { const argName = args[0]; const modules = Process.enumerateModules().map(m => m.path); let res = []; for (const module of modules) { const symbols = Module.enumerateSymbols(module) .filter((r) => r.address.compare(ptr('0')) > 0 && r.name); if (argName) { res.push(...symbols.filter((s) => s.name.indexOf(argName) !== -1)); } else { res.push(...symbols); } if (res.length > 100000) { res.forEach((r) => { console.error([r.address, r.moduleName, r.name].join(' ')); }); res = []; } } return res; } function listAllHelp (args) { return 'See =!ia? for more information. Those commands may take a while to run.'; } function listAllSymbols (args) { return listAllSymbolsJson(args) .map(({ type, name, address }) => { return [address, type[0], name].join(' '); }) .join('\n'); } function listAllSymbolsR2 (args) { return listAllSymbolsJson(args) .map(({ type, name, address }) => { return ['f', 'sym.' + type.substring(0, 3) + '.' + name, '=', address].join(' '); }) .join('\n'); } function listExportsJson (args) { const currentModule = (args.length > 0) ? Process.getModuleByName(args[0]) : getModuleByAddress(ptr(r2frida.offset)); return Module.enumerateExports(currentModule.name); } function getModuleByAddress (addr) { const m = config.getString('symbols.module'); if (m !== '') { return Process.getModuleByName(m); } try { return Process.getModuleByAddress(addr); } catch (e) { return Process.getModuleByAddress(ptr(r2frida.offset)); } } function listSymbols (args) { return listSymbolsJson(args) .map(({ type, name, address }) => { return [address, type[0], name].join(' '); }) .join('\n'); } function listSymbolsR2 (args) { return listSymbolsJson(args) .filter(({ address }) => !address.isNull()) .map(({ type, name, address }) => { return ['f', 'sym.' + type.substring(0, 3) + '.' + sanitizeString(name), '=', address].join(' '); }) .join('\n'); } function sanitizeString (str) { return str.split('').map(c => specialChars.indexOf(c) === -1 ? c : '_').join(''); } function listSymbolsJson (args) { const currentModule = (args.length > 0) ? Process.getModuleByName(args[0]) : getModuleByAddress(r2frida.offset); const symbols = Module.enumerateSymbols(currentModule.name); return symbols.map(sym => { if (config.getBoolean('symbols.unredact') && sym.name.indexOf('redacted') !== -1) { const dbgSym = DebugSymbol.fromAddress(sym.address); if (dbgSym !== null) { sym.name = dbgSym.name; } } return sym; }); } function lookupDebugInfo (args) { const o = DebugSymbol.fromAddress(ptr('' + args)); console.log(o); } function lookupAddress (args) { if (args.length === 0) { args = [ptr(r2frida.offset)]; } return lookupAddressJson(args) .map(({ type, name, address }) => [type, name, address].join(' ')) .join('\n'); } function lookupAddressR2 (args) { return lookupAddressJson(args) .map(({ type, name, address }) => ['f', 'sym.' + name, '=', address].join(' ')) .join('\n'); } function lookupAddressJson (args) { const exportAddress = ptr(args[0]); const result = []; const modules = Process.enumerateModules().map(m => m.path); return modules.reduce((result, moduleName) => { return result.concat(Module.enumerateExports(moduleName)); }, []) .reduce((type, obj) => { if (ptr(obj.address).compare(exportAddress) === 0) { result.push({ type: obj.type, name: obj.name, address: obj.address }); } return result; }, []); } function lookupSymbolHere (args) { return lookupAddress([ptr(r2frida.offset)]); } function lookupExport (args) { return lookupExportJson(args) // .map(({library, name, address}) => [library, name, address].join(' ')) .map(({ address }) => '' + address) .join('\n'); } function lookupExportR2 (args) { return lookupExportJson(args) .map(({ name, address }) => ['f', 'sym.' + name, '=', address].join(' ')) .join('\n'); } function lookupExportJson (args) { if (args.length === 2) { const [moduleName, exportName] = args; const address = Module.findExportByName(moduleName, exportName); if (address === null) { return []; } const m = getModuleByAddress(address); return [{ library: m.name, name: exportName, address: address }]; } else { const exportName = args[0]; let prevAddress = null; return Process.enumerateModules() .reduce((result, m) => { const address = Module.findExportByName(m.path, exportName); if (address !== null && (prevAddress === null || address.compare(prevAddress))) { result.push({ library: m.name, name: exportName, address: address }); prevAddress = address; } return result; }, []); } } // lookup symbols function lookupSymbol (args) { return lookupSymbolJson(args) // .map(({library, name, address}) => [library, name, address].join(' ')) .map(({ address }) => '' + address) .join('\n'); } function lookupSymbolR2 (args) { return lookupSymbolJson(args) .map(({ name, address }) => ['f', 'sym.' + name, '=', address].join(' ')) .join('\n'); } function lookupSymbolManyJson (args) { const res = []; for (const arg of args) { res.push({ name: arg, address: lookupSymbol([arg]) }); } return res; } function lookupSymbolMany (args) { return lookupSymbolManyJson(args).map(({ address }) => address).join('\n'); } function lookupSymbolManyR2 (args) { return lookupSymbolManyJson(args) .map(({ name, address }) => ['f', 'sym.' + name, '=', address].join(' ')) .join('\n'); } function lookupSymbolJson (args) { if (args.length === 0) { return []; } if (args.length === 2) { let [moduleName, symbolName] = args; try { const m = Process.getModuleByName(moduleName); // unused, this needs to be rewritten } catch (e) { const res = Process.enumerateModules().filter(function (x) { return x.name.indexOf(moduleName) !== -1; }); if (res.length !== 1) { return []; } moduleName = res[0].name; } let address = 0; Module.enumerateSymbols(moduleName).filter(function (s) { if (s.name === symbolName) { address = s.address; } }); return [{ library: moduleName, name: symbolName, address: address }]; } else { const [symbolName] = args; const res = getPtr(symbolName); const mod = getModuleAt(res); if (res) { return [{ library: mod ? mod.name : 'unknown', name: symbolName, address: res }]; } const fcns = DebugSymbol.findFunctionsNamed(symbolName); if (fcns) { return fcns.map((f) => { return { name: symbolName, address: f }; }); } return []; /* var at = DebugSymbol.fromName(symbolName); if (at.name) { return [{ library: at.moduleName, name: symbolName, address: at.address }]; } */ } } function listEntrypointJson (args) { function isEntrypoint (s) { if (s.type === 'section') { switch (s.name) { case '_start': case 'start': case 'main': return true; } } return false; } if (Process.platform === 'linux') { const at = DebugSymbol.fromName('main'); if (at) { return [at]; } } const firstModule = Process.enumerateModules()[0]; return Module.enumerateSymbols(firstModule.name) .filter((symbol) => { return isEntrypoint(symbol); }).map((symbol) => { symbol.moduleName = getModuleByAddress(symbol.address).name; return symbol; }); } function listEntrypointR2 (args) { let n = 0; return listEntrypointJson() .map((entry) => { return 'f entry' + (n++) + ' = ' + entry.address; }).join('\n'); } function listEntrypointQuiet (args) { return listEntrypointJson() .map((entry) => { return entry.address; }).join('\n'); } function listEntrypoint (args) { const n = 0; return listEntrypointJson() .map((entry) => { return entry.address + ' ' + entry.name + ' # ' + entry.moduleName; }).join('\n'); } function listImports (args) { return listImportsJson(args) .map(({ type, name, module, address }) => [address, type ? type[0] : ' ', name, module].join(' ')) .join('\n'); } function listImportsR2 (args) { const seen = new Set(); return listImportsJson(args).map((x) => { const flags = []; if (!seen.has(x.address)) { seen.add(x.address); flags.push('f sym.imp.' + utils.flagify(x.name) + ` = ${x.address}`); } if (x.slot !== undefined) { const fn = utils.flagify(`f reloc.${x.targetModuleName}.${x.name}_${x.index}`); flags.push(`f ${fn} = ${x.slot}`); } return flags.join('\n'); }).join('\n'); } function listImportsJson (args) { const alen = args.length; let result = []; let moduleName = null; if (alen === 2) { moduleName = args[0]; const importName = args[1]; const imports = Module.enumerateImports(moduleName); if (imports !== null) { result = imports.filter((x, i) => { x.index = i; return x.name === importName; }); } } else if (alen === 1) { moduleName = args[0]; result = Module.enumerateImports(moduleName) || []; } else { const currentModule = getModuleByAddress(r2frida.offset); if (currentModule) { result = Module.enumerateImports(currentModule.name) || []; } } result.forEach((x, i) => { if (x.index === undefined) { x.index = i; } x.targetModuleName = moduleName; }); return result; } function listClassesLoadedJson (args) { if (JavaAvailable) { return listClasses(args); } if (ObjCAvailable) { return JSON.stringify(ObjC.enumerateLoadedClassesSync()); } } function listClassesLoaders (args) { if (!JavaAvailable) { return 'Error: icL is only available on Android targets.'; } let res = ''; javaPerform(function () { function s2o (s) { let indent = 0; let res = ''; for (const ch of s.toString()) { switch (ch) { case '[': indent++; res += '[\n' + Array(indent + 1).join(' '); break; case ']': indent--; res += ']\n' + Array(indent + 1).join(' '); break; case ',': res += ',\n' + Array(indent + 1).join(' '); break; default: res += ch; break; } } return res; } const c = Java.enumerateClassLoadersSync(); for (const cl in c) { const cs = s2o(c[cl].toString()); res += cs; } }); return res; } function listClassesLoaded (args) { if (JavaAvailable) { return listClasses(args); } if (ObjCAvailable) { const results = ObjC.enumerateLoadedClassesSync(); const loadedClasses = []; for (const module of Object.keys(results)) { loadedClasses.push(...results[module]); } return loadedClasses.join('\n'); } return []; } // only for java function listAllClassesNatives (args) { return listClassesNatives(['.']); } function listClassesNatives (args) { const natives = []; const vkn = args[0] || 'com'; javaPerform(function () { const klasses = listClassesJson([]); for (let kn of klasses) { kn = kn.toString(); // if (kn.indexOf('android') !== -1) { continue; } if (kn.indexOf(vkn) === -1) { continue; } try { const handle = javaUse(kn); const klass = handle.class; const klassNatives = klass.getMethods().map(_ => _.toString()).filter(_ => _.indexOf('static native') !== -1); if (klassNatives.length > 0) { const kns = klassNatives.map((n) => { const p = n.indexOf('('); let sn = ''; if (p !== -1) { const s = n.substring(0, p); const w = s.split(' '); sn = w[w.length - 1]; return sn; } return n; // { name: sn, fullname: n }; }); console.error(kns.join('\n')); for (const tkn of kns) { if (natives.indexOf(tkn) === -1) { natives.push(tkn); } } } } catch (ignoreError) { } } }); return natives; } function listClassesAllMethods (args) { return listClassesJson(args, 'all').join('\n'); } function listClassSuperMethods (args) { return listClassesJson(args, 'super').join('\n'); } function listClassVariables (args) { return listClassesJson(args, 'ivars').join('\n'); } function listClassesWhere (args, mode) { let out = ''; if (args.length === 0) { const moduleNames = {}; const result = listClassesJson([]); if (ObjCAvailable) { const klasses = ObjC.classes; for (const k of result) { moduleNames[k] = klasses[k].$moduleName; } } for (const klass of result) { const modName = moduleNames[klass]; out += [modName, klass].join(' ') + '\n'; } return out; } else { const moduleNames = {}; const result = listClassesJson([]); if (ObjCAvailable) { const klasses = ObjC.classes; for (const k of result) { moduleNames[k] = ObjC.classes[k].$moduleName; } } for (const k of result) { const modName = moduleNames[k]; if (modName && modName.indexOf(args[0]) != -1) { const ins = searchInstancesJson([k]); const inss = ins.map((x) => { return x.address; }).join(' '); out += k + ' # ' + inss + '\n'; if (mode === 'ivars') { for (const a of ins) { out += 'instance ' + padPointer(a.address) + '\n'; const i = new ObjC.Object(ptr(a.address)); out += (JSON.stringify(i.$ivars)) + '\n'; } } } } return out; } } function listClasses (args) { const result = listClassesJson(args); if (result instanceof Array) { return result.join('\n'); } return Object.keys(result) .map(methodName => { const address = result[methodName]; return [padPointer(address), methodName].join(' '); }) .join('\n'); } function classGlob (k, v) { if (!k || !v) { return true; } return k.indexOf(v.replace(/\*/g, '')) !== -1; } function listClassesR2 (args) { const className = args[0]; if (args.length === 0 || args[0].indexOf('*') !== -1) { let methods = ''; if (ObjCAvailable) { for (const cn of Object.keys(ObjC.classes)) { if (classGlob(cn, args[0])) { methods += listClassesR2([cn]); } } } return methods; } const result = listClassesJson(args); return Object.keys(result) .map(methodName => { const address = result[methodName]; return ['f', flagName(methodName), '=', padPointer(address)].join(' '); }) .join('\n') + '\n'; function flagName (m) { return 'sym.objc.' + (className + '.' + m) .replace(':', '') .replace(' ', '') .replace('-', '') .replace('+', ''); } } /* this ugly sync mehtod with while+settimeout is needed because returning a promise is not properly handled yet and makes r2 lose track of the output of the command so you cant grep on it */ function listJavaClassesJsonSync (args) { if (args.length === 1) { let methods; /* list methods */ javaPerform(function () { const obj = javaUse(args[0]); methods = Object.getOwnPropertyNames(Object.getPrototypeOf(obj)); // methods = Object.keys(obj).map(x => x + ':' + obj[x] ); }); // eslint-disable-next-line while (methods === undefined) { /* wait here */ setTimeout(null, 0); } return methods; } let classes; javaPerform(function () { try { classes = Java.enumerateLoadedClassesSync(); } catch (e) { classes = null; } }); return classes; } // eslint-disable-next-line function listJavaClassesJson (args, classMethodsOnly) { let res = []; if (args.length === 1) { javaPerform(function () { try { const arg = args[0]; const handle = javaUse(arg); if (handle === null || !handle.class) { throw new Error('Cannot find a classloader for this class'); } const klass = handle.class; try { if (classMethodsOnly) { klass.getMethods().filter(x => x.toString().indexOf(arg) !== -1).map(_ => res.push(_.toString())); } else { klass.getMethods().map(_ => res.push(_.toString())); } klass.getFields().map(_ => res.push(_.toString())); try { klass.getConstructors().map(_ => res.push(_.toString())); } catch (ignore) { } } catch (e) { console.error(e.message); console.error(Object.keys(klass), JSON.stringify(klass), klass); } } catch (e) { console.error(e.message); } }); } else { javaPerform(function () { try { res = Java.enumerateLoadedClassesSync(); } catch (e) { console.error(e); } }); } return res; } function listClassMethods (args) { return listClassesJson(args, 'methods').join('\n'); } function listClassMethodsJson (args) { return listClassesJson(args, 'methods'); } function listClassesJson (args, mode) { if (JavaAvailable) { return listJavaClassesJson(args, mode === 'methods'); } if (!ObjCAvailable) { return []; } if (args.length === 0) { return Object.keys(ObjC.classes); } const klassName = args[0]; const klass = ObjC.classes[klassName]; if (klass === undefined) { throw new Error('Class ' + klassName + ' not found'); } let out = ''; if (mode === 'ivars') { const ins = searchInstancesJson([klassName]); out += klassName + ': '; for (const i of ins) { out += 'instance ' + padPointer(ptr(i.address)) + ': '; const ii = new ObjC.Object(ptr(i.address)); out += JSON.stringify(ii.$ivars, null, ' '); } return [out]; } const methods = (mode == 'methods') ? klass.$ownMethods : (mode == 'super') ? klass.$super.$ownMethods : (mode == 'all') ? klass.$methods : klass.$ownMethods; const getImpl = ObjC.api.method_getImplementation; try { return methods .reduce((result, methodName) => { try { result[methodName] = getImpl(klass[methodName].handle); } catch (_) { console.error('warning: unsupported method \'' + methodName + '\' in ' + klassName); } return result; }, {}); } catch (e) { return methods; } } function listProtocols (args) { return listProtocolsJson(args) .join('\n'); } function closeFileDescriptors (args) { if (args.length === 0) { return 'Please, provide a file descriptor'; } return _close(+args[0]); } function listFileDescriptors (args) { return listFileDescriptorsJson(args).map(([fd, name]) => { return fd + ' ' + name; }).join('\n'); } function listFileDescriptorsJson (args) { const PATH_MAX = 4096; function getFdName (fd) { if (_readlink && Process.platform === 'linux') { const fdPath = path.join('proc', '' + getPid(), 'fd', '' + fd); const buffer = Memory.alloc(PATH_MAX); const source = Memory.alloc(PATH_MAX); source.writeUtf8String(fdPath); buffer.writeUtf8String(''); if (_readlink(source, buffer, PATH_MAX) !== -1) { return buffer.readUtf8String(); } return undefined; } try { // TODO: port this to iOS const F_GETPATH = 50; // on macOS const buffer = Memory.alloc(PATH_MAX); const addr = Module.getExportByName(null, 'fcntl'); const fcntl = new NativeFunction(addr, 'int', ['int', 'int', 'pointer']); fcntl(fd, F_GETPATH, buffer); return buffer.readCString(); } catch (e) { return ''; } } if (args.length === 0) { const statBuf = Memory.alloc(128); const fds = []; for (let i = 0; i < 1024; i++) { if (_fstat(i, statBuf) === 0) { fds.push(i); } } return fds.map((fd) => { return [fd, getFdName(fd)]; }); } else { const rc = _dup2(+args[0], +args[1]); return rc; } } function listStringsJson (args) { if (!args || args.length !== 1) { args = [r2frida.offset]; } const base = ptr(args[0]); const currentRange = Process.findRangeByAddress(base); if (currentRange) { const options = { base: base }; // filter for urls? const length = Math.min(currentRange.size, 1024 * 1024 * 128); const block = 1024 * 1024; // 512KB if (length !== currentRange.size) { const curSize = currentRange.size / (1024 * 1024); console.error('Warning: this range is too big (' + curSize + 'MB), truncated to ' + length / (1024 * 1024) + 'MB'); } try { const res = []; console.log('Reading ' + (length / (1024 * 1024)) + 'MB ...'); for (let i = 0; i < length; i += block) { const addr = currentRange.base.add(i); const bytes = addr.readCString(block); const blockResults = strings(bytes.split('').map(_ => _.charCodeAt(0)), options); res.push(...blockResults); } return res; } catch (e) { console.log(e.message); } } throw new Error('Memory not mapped here'); } function listStrings (args) { if (!args || args.length !== 1) { args = [ptr(r2frida.offset)]; } const base = ptr(args[0]); return listStringsJson(args).map(({ base, text }) => padPointer(base) + ` "${text}"`).join('\n'); } function listProtocolsJson (args) { if (!ObjCAvailable) { return []; } if (args.length === 0) { return Object.keys(ObjC.protocols); } else { const protocol = ObjC.protocols[args[0]]; if (protocol === undefined) { throw new Error('Protocol not found'); } return Object.keys(protocol.methods); } } function listMallocMaps (args) { const heaps = squashRanges(listMallocRangesJson(args)); function inRange (x) { for (const heap of heaps) { if (x.base.compare(heap.base) >= 0 && x.base.add(x.size).compare(heap.base.add(heap.size))) { return true; } } return false; } return squashRanges(listMemoryRangesJson()) .filter(inRange) .map(({ base, size, protection, file }) => [ padPointer(base), '-', padPointer(base.add(size)), protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function listMallocRangesJson (args) { return Process.enumerateMallocRanges(); } function listMallocRangesR2 (args) { const chunks = listMallocRangesJson(args) .map(_ => 'f chunk.' + _.base + ' ' + _.size + ' ' + _.base).join('\n'); return chunks + squashRanges(listMallocRangesJson(args)) .map(_ => 'f heap.' + _.base + ' ' + _.size + ' ' + _.base).join('\n'); } function listMallocRanges (args) { return squashRanges(listMallocRangesJson(args)) .map(_ => '' + _.base + ' - ' + _.base.add(_.size) + ' (' + _.size + ')').join('\n') + '\n'; } function listMemoryMapsHere (args) { if (args.length !== 1) { args = [ptr(r2frida.offset)]; } const addr = ptr(args[0]); return squashRanges(listMemoryRangesJson()) .filter(({ base, size }) => addr.compare(base) >= 0 && addr.compare(base.add(size)) < 0) .map(({ base, size, protection, file }) => { return [ padPointer(base), '-', padPointer(base.add(size)), protection, file.path ].join(' '); }) .join('\n') + '\n'; } function listMemoryRangesHere (args) { if (args.length !== 1) { args = [ptr(r2frida.offset)]; } const addr = ptr(args[0]); return listMemoryRangesJson() .filter(({ base, size }) => addr.compare(base) >= 0 && addr.compare(base.add(size)) < 0) .map(({ base, size, protection, file }) => [ padPointer(base), '-', padPointer(base.add(size)), protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function rwxstr (x) { let str = ''; str += (x & 1) ? 'r' : '-'; str += (x & 2) ? 'w' : '-'; str += (x & 4) ? 'x' : '-'; return str; } function rwxint (x) { const ops = ['---', '--x', '-w-', '-wx', 'r--', 'r-x', 'rw-', 'rwx']; return ops.indexOf([x]); } function squashRanges (ranges) { const res = []; let begin = ptr(0); let end = ptr(0); let lastPerm = 0; let lastFile = ''; for (const r of ranges) { lastPerm |= rwxint(r.protection); // console.log("-", r.base, range.base.add(range.size)); if (r.base.equals(end)) { // enlarge segment end = end.add(r.size); // console.log("enlarge", begin, end); } else { if (begin.equals(ptr(0))) { begin = r.base; end = begin.add(r.size); // console.log(" set", begin, end); } else { // console.log(" append", begin, end); res.push({ base: begin, size: end.sub(begin), protection: rwxstr(lastPerm), file: lastFile }); end = ptr(0); begin = ptr(0); lastPerm = 0; lastFile = ''; } } if (r.file) { lastFile = r.file; } } if (!begin.equals(ptr(0))) { res.push({ base: begin, size: end.sub(begin), protection: rwxstr(lastPerm), file: lastFile }); } return res; } function listMemoryMapsR2 () { function filterFile (file) { return file.replace(/\//g, '_').replace(/-/g, '_'); } return squashRanges(listMemoryRangesJson()) .filter(_ => _.file) .map(({ base, size, protection, file }) => [ 'f', 'dmm.' + filterFile(file.path), '=', padPointer(base), ] .join(' ') ) .join('\n') + '\n'; } function listMemoryMaps () { return squashRanges(listMemoryRangesJson()) .filter(_ => _.file) .map(({ base, size, protection, file }) => [ padPointer(base), '-', padPointer(base.add(size)), protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function listMemoryRangesR2 () { return listMemoryRangesJson() .map(({ base, size, protection, file }) => [ 'f', 'map.' + padPointer(base), '=', base, // padPointer(base.add(size)), '#', protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function listMemoryRanges () { return listMemoryRangesJson() .map(({ base, size, protection, file }) => [ padPointer(base), '-', padPointer(base.add(size)), protection, ] .concat((file !== undefined) ? [file.path] : []) .join(' ') ) .join('\n') + '\n'; } function listMemoryRangesJson () { return _getMemoryRanges('---'); } function _getMemoryRanges (protection) { if (r2frida.hookedRanges !== null) { return r2frida.hookedRanges(protection); } return Process.enumerateRangesSync({ protection, coalesce: false }); } async function changeMemoryProtection (args) { const [addr, size, protection] = args; if (args.length !== 3 || protection.length > 3) { return 'Usage: =!dmp [address] [size] [rwx]'; } const address = getPtr(addr); const mapsize = await numEval(size); Memory.protect(address, ptr(mapsize).toInt32(), protection); return ''; } function getPidJson () { return JSON.stringify({ pid: getPid() }); } function getPid () { return _getpid(); } function listThreads () { let canGetThreadName = false; try { const addr = Module.getExportByName(null, 'pthread_getname_np'); var pthreadGetnameNp = new NativeFunction(addr, 'int', ['pointer', 'pointer', 'int']); const addr2 = Module.getExportByName(null, 'pthread_from_mach_thread_np'); var pthreadFromMachThreadNp = new NativeFunction(addr2, 'pointer', ['uint']); canGetThreadName = true; } catch (e) { // do nothing } function getThreadName (tid) { if (!canGetThreadName) { return ''; } const buffer = Memory.alloc(4096); const p = pthreadFromMachThreadNp(tid); pthreadGetnameNp(p, buffer, 4096); return buffer.readCString(); } return Process.enumerateThreads().map((thread) => { const threadName = getThreadName(thread.id); return [thread.id, threadName].join(' '); }).join('\n') + '\n'; } function listThreadsJson () { return Process.enumerateThreads() .map(thread => thread.id); } function regProfileAliasFor (arch) { switch (arch) { case 'arm64': return `=PC pc =SP sp =BP x29 =A0 x0 =A1 x1 =A2 x2 =A3 x3 =ZF zf =SF nf =OF vf =CF cf =SN x8 `; case 'arm': return `=PC r15 =LR r14 =SP sp =BP fp =A0 r0 =A1 r1 =A2 r2 =A3 r3 =ZF zf =SF nf =OF vf =CF cf =SN r7 `; case 'ia64': case 'x64': return `=PC rip =SP rsp =BP rbp =A0 rdi =A1 rsi =A2 rdx =A3 rcx =A4 r8 =A5 r9 =SN rax `; case 'ia32': case 'x86': return `=PC eip =SP esp =BP ebp =A0 eax =A1 ebx =A2 ecx =A3 edx =A4 esi =A5 edi =SN eax `; } return ''; } function dumpRegisterProfile (args) { const threads = Process.enumerateThreads(); const context = threads[0].context; const names = Object.keys(JSON.parse(JSON.stringify(context))) .filter(_ => _ !== 'pc' && _ !== 'sp'); names.sort(compareRegisterNames); let off = 0; const inc = Process.pointerSize; let profile = regProfileAliasFor(Process.arch); for (const reg of names) { profile += `gpr\t${reg}\t${inc}\t${off}\t0\n`; off += inc; } return profile; } function dumpRegisterArena (args) { const threads = Process.enumerateThreads(); let [tidx] = args; if (!tidx) { tidx = 0; } if (tidx < 0 || tidx >= threads.length) { return ''; } const context = threads[tidx].context; const names = Object.keys(JSON.parse(JSON.stringify(context))) .filter(_ => _ !== 'pc' && _ !== 'sp'); names.sort(compareRegisterNames); let off = 0; const inc = Process.pointerSize; const buf = Buffer.alloc(inc * names.length); for (const reg of names) { const r = context[reg]; const b = [r.and(0xff), r.shr(8).and(0xff), r.shr(16).and(0xff), r.shr(24).and(0xff), r.shr(32).and(0xff), r.shr(40).and(0xff), r.shr(48).and(0xff), r.shr(56).and(0xff)]; for (let i = 0; i < inc; i++) { buf.writeUInt8(b[i], off + i); } off += inc; } return buf.toString('hex'); } function regcursive (regname, regvalue) { const data = [regvalue]; try { const str = Memory.readCString(regvalue, 32); if (str && str.length > 3) { const printableString = str.replace(/[^\x20-\x7E]/g, ''); data.push('\'' + printableString + '\''); } const ptr = regvalue.readPointer(); data.push('=>'); data.push(regcursive(regname, ptr)); } catch (e) { } if (regvalue === 0) { data.push('NULL'); } else if (regvalue === 0xffffffff) { data.push(-1); } else if (regvalue > ' ' && regvalue < 127) { data.push('\'' + String.fromCharCode(regvalue) + '\''); } try { const module = Process.findModuleByAddress(regvalue); if (module) { data.push(module.name); } } catch (e) { } try { const name = nameFromAddress(regvalue); if (name) { data.push(name); } } catch (e) { } return data.join(' '); } function dumpRegistersRecursively (args) { const [tid] = args; Process.enumerateThreads() .filter(thread => !tid || tid === thread.id) .map(thread => { const { id, state, context } = thread; const res = ['# thread ' + id + ' ' + state]; for (const reg of Object.keys(context)) { try { const data = regcursive(reg, context[reg]); res.push(reg + ': ' + data); } catch (e) { res.push(reg); } } console.log(res.join('\n')); }); return ''; // nothing to see here } function dumpRegistersR2 (args) { const threads = Process.enumerateThreads(); const [tid] = args; const context = tid ? threads.filter(th => th.id === tid) : threads[0].context; if (!context) { return ''; } const names = Object.keys(JSON.parse(JSON.stringify(context))); names.sort(compareRegisterNames); const values = names .map((name, index) => { if (name === 'pc' || name === 'sp') return ''; const value = context[name] || 0; return `ar ${name} = ${value}\n`; }); return values.join(''); } function dumpRegisters (args) { const [tid] = args; return Process.enumerateThreads() .filter(thread => !tid || thread.id === tid) .map(thread => { const { id, state, context } = thread; const heading = `tid ${id} ${state}`; const names = Object.keys(JSON.parse(JSON.stringify(context))); names.sort(compareRegisterNames); const values = names .map((name, index) => alignRight(name, 3) + ' : ' + padPointer(context[name])) .map(indent); return heading + '\n' + values.join(''); }) .join('\n\n') + '\n'; } function dumpRegistersJson () { return Process.enumerateThreads(); } function getOrSetEnv (args) { if (args.length === 0) { return getEnv().join('\n') + '\n'; } const { key, value } = getOrSetEnvJson(args); return key + '=' + value; } function getOrSetEnvJson (args) { if (args.length === 0) { return getEnvJson(); } const kv = args.join(''); const eq = kv.indexOf('='); if (eq !== -1) { const k = kv.substring(0, eq); const v = kv.substring(eq + 1); setenv(k, v, true); return { key: k, value: v }; } else { return { key: kv, value: getenv(kv) }; } } function getEnv () { const result = []; let envp = Memory.readPointer(Module.findExportByName(null, 'environ')); let env; while (!envp.isNull() && !(env = envp.readPointer()).isNull()) { result.push(env.readCString()); envp = envp.add(Process.pointerSize); } return result; } function getEnvJson () { return getEnv().map(kv => { const eq = kv.indexOf('='); return { key: kv.substring(0, eq), value: kv.substring(eq + 1) }; }); } function dlopen (args) { const path = fs.transformVirtualPath(args[0]); if (fs.exist(path)) { return Module.load(path); } return Module.load(args[0]); } function loadFrameworkBundle (args) { if (!ObjCAvailable) { console.log('dlf: This command requires the objc runtime'); return false; } const path = args[0]; const app_path = ObjC.classes.NSBundle.mainBundle().bundlePath(); const full_path = app_path.stringByAppendingPathComponent_(path); const bundle = ObjC.classes.NSBundle.bundleWithPath_(full_path); if (bundle.isLoaded()) { console.log('Bundle already loaded'); return false; } return bundle.load(); } function unloadFrameworkBundle (args) { if (!ObjCAvailable) { console.log('dlf: This command requires the objc runtime'); return false; } const path = args[0]; const app_path = ObjC.classes.NSBundle.mainBundle().bundlePath(); const full_path = app_path.stringByAppendingPathComponent_(path); const bundle = ObjC.classes.NSBundle.bundleWithPath_(full_path); if (!bundle.isLoaded()) { console.log('Bundle already unloaded'); return false; } return bundle.unload(); } function changeSelinuxContext (args) { if (_setfilecon === null) { return 'Error: cannot find setfilecon symbol'; } // TODO This doesnt run yet because permissions // TODO If it runs as root, then file might be checked const file = args[0]; const con = Memory.allocUtf8String('u:object_r:frida_file:s0'); const path = Memory.allocUtf8String(file); const rv = _setfilecon(path, con); return JSON.stringify({ ret: rv.value, errno: rv.errno }); } function formatArgs (args, fmt) { const a = []; const dumps = []; let arg; let j = 0; for (let i = 0; i < fmt.length; i++, j++) { try { arg = args[j]; } catch (err) { console.error('invalid format', i); } switch (fmt[i]) { case '+': case '^': j--; break; case 'h': { // hexdump pointer target, default length 128 // customize length with h<length>, f.e. h16 to dump 16 bytes let dumpLen = 128; const optionalNumStr = fmt.slice(i + 1).match(/^[0-9]*/)[0]; if (optionalNumStr.length > 0) { i += optionalNumStr.length; dumpLen = +optionalNumStr; } dumps.push(_hexdumpUntrusted(arg, dumpLen)); a.push(`dump:${dumps.length} (len=${dumpLen})`); } break; case 'H': { // hexdump pointer target, default length 128 // use length from other funtion arg with H<arg number>, f.e. H0 to dump '+args[0]' bytes let dumpLen = 128; const optionalNumStr = fmt.slice(i + 1).match(/^[0-9]*/)[0]; if (optionalNumStr.length > 0) { i += optionalNumStr.length; const posLenArg = +optionalNumStr; if (posLenArg !== j) { // only adjust dump length, if the length param isn't the dump address itself dumpLen = +args[posLenArg]; } } // limit dumpLen, to avoid oversized dumps, caused by accidentally parsing pointer agrs as length // set length limit to 64K for now const lenLimit = 0x10000; dumpLen = dumpLen > lenLimit ? lenLimit : dumpLen; dumps.push(_hexdumpUntrusted(arg, dumpLen)); a.push(`dump:${dumps.length} (len=${dumpLen})`); } break; case 'x': a.push('' + ptr(arg)); break; case 'c': a.push("'" + arg + "'"); break; case 'i': a.push(+arg); break; case 'z': // *s const s = _readUntrustedUtf8(arg); a.push(JSON.stringify(s)); break; case 'Z': // *s[i] const len = +args[j + 1]; const str = _readUntrustedUtf8(arg, len); a.push(JSON.stringify(str)); break; case 'S': // **s const sss = _readUntrustedUtf8(Memory.readPointer(arg)); a.push(JSON.stringify(sss)); break; case 'o': case 'O': if (ObjC.available) { if (!arg.isNull()) { if (isObjC(arg)) { const o = new ObjC.Object(arg); a.push(`${o.$className}: "${o.toString()}"`); } else { const str = Memory.readCString(arg); if (str.length > 2) { a.push(str); } else { a.push('' + arg); } } } else { a.push('nil'); } } else { a.push(arg); } break; default: a.push(arg); break; } } return { args: a, dumps: dumps }; } function cloneArgs (args, fmt) { const a = []; let j = 0; for (let i = 0; i < fmt.length; i++, j++) { const arg = args[j]; switch (fmt[i]) { case '+': case '^': j--; break; default: a.push(arg); break; } } return a; } function _hexdumpUntrusted (addr, len) { try { if (typeof len === 'number') return hexdump(addr, { length: len }); else return hexdump(addr); } catch (e) { return `hexdump at ${addr} failed: ${e}`; } } function _readUntrustedUtf8 (address, length) { try { if (typeof length === 'number') { return Memory.readUtf8String(ptr(address), length); } return Memory.readUtf8String(ptr(address)); } catch (e) { if (e.message !== 'invalid UTF-8') { // TODO: just use this, doo not mess with utf8 imho return Memory.readCString(ptr(address)); } return '(invalid utf8)'; } } function traceList () { let count = 0; return traceListeners.map((t) => { return [count++, t.hits, t.at, t.source, t.moduleName, t.name, t.args].join('\t'); }).join('\n') + '\n'; } function traceListJson () { return traceListeners.map(_ => JSON.stringify(_)).join('\n') + '\n'; } function getPtr (p) { if (typeof p === 'string') { p = p.trim(); } if (!p || p === '$$') { return ptr(global.r2frida.offset); } if (p.startsWith('java:')) { return p; } if (p.startsWith('objc:')) { const hatSign = p.indexOf('^') !== -1; if (hatSign !== -1) { p = p.replace('^', ''); } const endsWith = p.endsWith('$'); if (endsWith) { p = p.substring(0, p.length - 1); } p = p.substring(5); let dot = p.indexOf('.'); if (dot === -1) { dot = p.indexOf(':'); if (dot === -1) { throw new Error('r2frida\'s ObjC class syntax is: objc:CLASSNAME.METHOD'); } } const kv0 = p.substring(0, dot); const kv1 = p.substring(dot + 1); const klass = ObjC.classes[kv0]; if (klass === undefined) { throw new Error('Class ' + kv0 + ' not found'); } let found = null; let firstFail = false; let oldMethodName = null; for (const methodName of klass.$ownMethods) { const method = klass[methodName]; if (methodName.indexOf(kv1) !== -1) { if (hatSign && !methodName.substring(2).startsWith(kv1)) { continue; } if (endsWith && !methodName.endsWith(kv1)) { continue; } if (found) { if (!firstFail) { console.error(found.implementation, oldMethodName); firstFail = true; } console.error(method.implementation, methodName); } found = method; oldMethodName = methodName; } } if (firstFail) { return ptr(0); } return found ? found.implementation : ptr(0); } try { if (p.substring(0, 2) === '0x') { return ptr(p); } } catch (e) { // console.error(e); } // return DebugSymbol.fromAddress(ptr_p) || '' + ptr_p; return Module.findExportByName(null, p); } function traceHook (args) { if (args.length === 0) { return JSON.stringify(tracehooks, null, 2); } const arg = args[0]; if (arg !== undefined) { tracehookSet(arg, args.slice(1).join(' ')); } return ''; } function traceFormat (args) { if (args.length === 0) { return traceList(); } let address, format; const name = args[0]; if (args.length === 2) { address = '' + getPtr(name); format = args[1]; } else if (args.length === 1) { address = '' + getPtr(name); format = ''; } else { address = global.r2frida.offset; format = args[0]; } if (haveTraceAt(address)) { return 'There\'s already a trace in here'; } const traceOnEnter = format.indexOf('^') !== -1; const traceBacktrace = format.indexOf('+') !== -1; const currentModule = getModuleByAddress(address); const listener = Interceptor.attach(ptr(address), { myArgs: [], myBacktrace: [], keepArgs: [], onEnter: function (args) { traceListener.hits++; if (!traceOnEnter) { this.keepArgs = cloneArgs(args, format); } else { const fa = formatArgs(args, format); this.myArgs = fa.args; this.myDumps = fa.dumps; } if (traceBacktrace) { this.myBacktrace = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); } if (traceOnEnter) { const traceMessage = { source: 'dtf', name: name, address: address, timestamp: new Date(), values: this.myArgs, }; if (config.getBoolean('hook.backtrace')) { traceMessage.backtrace = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); } if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { let msg = `[dtf onEnter][${traceMessage.timestamp}] ${name}@${address} - args: ${this.myArgs.join(', ')}`; if (config.getBoolean('hook.backtrace')) { msg += ` backtrace: ${traceMessage.backtrace.toString()}`; } for (let i = 0; i < this.myDumps.length; i++) msg += `\ndump:${i + 1}\n${this.myDumps[i]}`; traceEmit(msg); } } }, onLeave: function (retval) { if (!traceOnEnter) { const fa = formatArgs(this.keepArgs, format); this.myArgs = fa.args; this.myDumps = fa.dumps; const traceMessage = { source: 'dtf', name: name, address: address, timestamp: new Date(), values: this.myArgs, retval }; if (config.getBoolean('hook.backtrace')) { traceMessage.backtrace = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); } if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { let msg = `[dtf onLeave][${traceMessage.timestamp}] ${name}@${address} - args: ${this.myArgs.join(', ')}. Retval: ${retval.toString()}`; if (config.getBoolean('hook.backtrace')) { msg += ` backtrace: ${traceMessage.backtrace.toString()}`; } for (let i = 0; i < this.myDumps.length; i++) msg += `\ndump:${i + 1}\n${this.myDumps[i]}`; traceEmit(msg); } } } }); const traceListener = { source: 'dtf', hits: 0, at: ptr(address), name: name, moduleName: currentModule ? currentModule.name : '', format: format, listener: listener }; traceListeners.push(traceListener); return true; } function traceListenerFromAddress (address) { const results = traceListeners.filter((tl) => '' + address === '' + tl.at); return (results.length > 0) ? results[0] : undefined; } function traceCountFromAddress (address) { const tl = traceListenerFromAddress(address); return tl ? tl.hits : 0; } function traceNameFromAddress (address) { const tl = traceListenerFromAddress(address); return tl ? tl.moduleName + ':' + tl.name : ''; } function traceLogDumpQuiet () { return logs.map(({ address, timestamp }) => [address, timestamp, traceCountFromAddress(address), traceNameFromAddress(address)].join(' ')) .join('\n') + '\n'; } function traceLogDumpJson () { return JSON.stringify(logs); } function traceLogDumpR2 () { let res = ''; for (const l of logs) { if (l.script) { res += l.script; } } return res; } function objectToString (o) { // console.error(JSON.stringify(o)); const r = Object.keys(o).map((k) => { try { const p = ptr(o[k]); if (isObjC(p)) { const o = new ObjC.Object(p); return k + ': ' + o.toString(); } const str = Memory.readCString(p); if (str.length > 2) { return k + ': "' + str + '"'; } } catch (e) { } return k + ': ' + o[k]; }).join(' '); return '(' + r + ')'; } function tracelogToString (l) { const line = [l.source, l.name || l.address, objectToString(l.values)].join('\t'); const bt = (!l.backtrace) ? '' : l.backtrace.map((b) => { return ['', b.address, b.moduleName, b.name].join('\t'); }).join('\n') + '\n'; return line + bt; } function traceLogDump () { return logs.map(tracelogToString).join('\n') + '\n'; } function traceLogClear (args) { // TODO: clear one trace instead of all console.error('ARGS', JSON.stringify(args)); return traceLogClearAll(); } function traceLogClearAll () { logs = []; traces = {}; return ''; } function traceEmit (msg) { const fileLog = config.getString('file.log'); if (fileLog.length > 0) { send(wrapStanza('log-file', { filename: fileLog, message: msg })); } else { traceLog(msg); } if (config.getBoolean('hook.logs')) { logs.push(msg); } global.r2frida.logs = logs; } function traceLog (msg) { if (config.getBoolean('hook.verbose')) { send(wrapStanza('log', { message: msg })); } } function haveTraceAt (address) { try { for (const trace of traceListeners) { if (trace.at.compare(address) === 0) { return true; } } } catch (e) { console.error(e); } return false; } function traceRegs (args) { if (args.length < 1) { return 'Usage: dtr [name|address] [reg ...]'; } const address = getPtr(args[0]); if (haveTraceAt(address)) { return 'There\'s already a trace in here'; } const rest = args.slice(1); const currentModule = getModuleByAddress(address); const listener = Interceptor.attach(address, traceFunction); function traceFunction (_) { traceListener.hits++; const regState = {}; rest.map((r) => { let regName = r; let regValue; if (r.indexOf('=') !== -1) { const kv = r.split('='); this.context[kv[0]] = ptr(kv[1]); // set register value regName = kv[0]; regValue = kv[1]; } else { try { const rv = ptr(this.context[r]); regValue = rv; let tail = Memory.readCString(rv); if (tail) { tail = ' (' + tail + ')'; regValue += tail; } } catch (e) { // do nothing } } regState[regName] = regValue; }); const traceMessage = { source: 'dtr', address: address, timestamp: new Date(), values: regState, }; if (config.getBoolean('hook.backtrace')) { traceMessage.backtrace = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); } if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { let msg = `[dtr][${traceMessage.timestamp}] ${address} - registers: ${JSON.stringify(regState)}`; if (config.getBoolean('hook.backtrace')) { msg += ` backtrace: ${traceMessage.backtrace.toString()}`; } traceEmit(msg); } } const traceListener = { source: 'dtr', hits: 0, at: address, moduleName: currentModule ? currentModule.name : 'unknown', name: args[0], listener: listener, args: rest }; traceListeners.push(traceListener); return ''; } function traceHere () { const args = [r2frida.offset]; args.forEach(address => { const at = DebugSymbol.fromAddress(ptr(address)) || '' + ptr(address); const listener = Interceptor.attach(ptr(address), function () { const bt = Thread.backtrace(this.context).map(DebugSymbol.fromAddress); const at = nameFromAddress(address); console.log('Trace here probe hit at ' + address + '::' + at + '\n\t' + bt.join('\n\t')); }); traceListeners.push({ at: at, listener: listener }); }); return true; } function traceR2 (args) { return traceListeners.map(_ => `dt+ ${_.at} ${_.hits}`).join('\n') + '\n'; } function dumpJavaArguments (args) { let res = ''; try { for (const a of args) { try { res += a.toString() + ' '; } catch (ee) { } } } catch (e) { } return res; } function traceJavaConstructors (className) { javaPerform(function () { const foo = Java.use(className).$init.overloads; foo.forEach((over) => { over.implementation = function () { console.log('dt', className, '(', dumpJavaArguments(arguments), ')'); if (config.getBoolean('hook.backtrace')) { const Throwable = Java.use('java.lang.Throwable'); const bt = Throwable.$new().getStackTrace().map(_ => _.toString()).join('\n- ') + '\n'; console.log('-', bt); } return over.apply(this, arguments); }; }); }); } function traceJava (klass, method) { javaPerform(function () { const Throwable = Java.use('java.lang.Throwable'); const k = javaUse(klass); k[method].implementation = function (args) { const res = this[method](); const bt = config.getBoolean('hook.backtrace') ? Throwable.$new().getStackTrace().map(_ => _.toString()) : []; const traceMessage = { source: 'dt', klass: klass, method: method, backtrace: bt, timestamp: new Date(), result: res, values: args }; if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { let msg = `[JAVA TRACE][${traceMessage.timestamp}] ${klass}:${method} - args: ${JSON.stringify(args)}. Return value: ${res.toString()}`; if (config.getBoolean('hook.backtrace')) { msg += ` backtrace: \n${traceMessage.backtrace.toString().split(',').join('\nat ')}\n`; } traceEmit(msg); } return res; }; }); } function traceQuiet (args) { return traceListeners.map(({ address, hits, moduleName, name }) => [address, hits, moduleName + ':' + name].join(' ')).join('\n') + '\n'; } function traceJson (args) { if (args.length === 0) { return traceListJson(); } if (args[0].startsWith('java:')) { traceReal(args[0]); return; } return new Promise(function (resolve, reject) { (function pull () { const arg = args.pop(); if (arg === undefined) { return resolve(''); } const narg = getPtr(arg); if (narg) { traceReal(arg, narg); pull(); } else { numEval(arg).then(function (at) { console.error(traceReal(arg, at)); pull(); }).catch(reject); } })(); }); } function trace (args) { if (args.length === 0) { return traceList(); } return traceJson(args); } function tracehookSet (name, format, callback) { if (name === null) { console.error('Name was not resolved'); return false; } tracehooks[name] = { format: format, callback: callback }; return true; } function arrayBufferToHex (arrayBuffer) { if (typeof arrayBuffer !== 'object' || arrayBuffer === null || typeof arrayBuffer.byteLength !== 'number') { throw new TypeError('Expected input to be an ArrayBuffer'); } const view = new Uint8Array(arrayBuffer); let result = ''; let value; for (let i = 0; i < view.length; i++) { value = view[i].toString(16); result += (value.length === 1 ? '0' + value : value); } return result; } // \dth printf 0,1 .. kind of dtf function tracehook (address, args) { const at = nameFromAddress(address); const th = tracehooks[at]; const fmtarg = []; if (th && th.format) { for (const fmt of th.format.split(' ')) { const [k, v] = fmt.split(':'); switch (k) { case 'i': // console.log('int', args[v]); fmtarg.push(+args[v]); break; case 's': { const [a, l] = v.split(','); const addr = ptr(args[a]); const size = +args[l]; // const buf = Memory.readByteArray(addr, size); // console.log('buf', arrayBufferToHex(buf)); // console.log('string', Memory.readCString(addr, size)); fmtarg.push(Memory.readCString(addr, size)); } break; case 'z': // console.log('string', Memory.readCString(args[+v])); fmtarg.push(Memory.readCString(ptr(args[+v]))); break; case 'v': { const [a, l] = v.split(','); const addr = ptr(args[a]); const buf = Memory.readByteArray(addr, +args[l]); fmtarg.push(arrayBufferToHex(buf)); } break; } } } return fmtarg; } function traceReal (name, addressString) { if (arguments.length === 0) { return traceList(); } if (name.startsWith('java:')) { const javaName = name.substring(5); if (javaUse(javaName)) { console.error('Tracing class constructors'); traceJavaConstructors(javaName); } else { const dot = javaName.lastIndexOf('.'); if (dot !== -1) { const klass = javaName.substring(0, dot); const methd = javaName.substring(dot + 1); traceJava(klass, methd); } else { console.log('Invalid java method name. Use =!dt java:package.class.method'); } } return; } const address = ptr(addressString); if (haveTraceAt(address)) { return 'There\'s already a trace in here'; } const currentModule = getModuleByAddress(address); const listener = Interceptor.attach(address, function (args) { const values = tracehook(address, args); const traceMessage = { source: 'dt', address: address, timestamp: new Date(), values: values, }; traceListener.hits++; if (config.getString('hook.output') === 'json') { traceEmit(traceMessage); } else { traceEmit(`[dt][${traceMessage.timestamp}] ${address} - args: ${JSON.stringify(values)}`); } }); const traceListener = { source: 'dt', at: address, hits: 0, name: name, moduleName: currentModule ? currentModule.name : 'unknown', args: '', listener: listener }; traceListeners.push(traceListener); return ''; } function clearAllTrace (args) { traceListeners.splice(0).forEach(lo => lo.listener ? lo.listener.detach() : null); return ''; } function clearTrace (args) { if (args.length > 0 && +args[0] > 0) { const res = []; const nth = +args[0]; for (let i = 0; i < traceListeners.length; i++) { const tl = traceListeners[i]; if (i === nth) { tl.listener.detach(); } else { res.push(tl); } } } return ''; } function interceptHelp (args) { return 'Usage: di[f][0,1,-1,s] [addr] : intercept function before/after calling and replace return value\n'; 'dif0 0x808080 # when program calls this address, dont run the function and return 0\n'; } /* Intercept function calls *after* calling the original function code */ function interceptRetJava (klass, method, value) { javaPerform(function () { const System = javaUse(klass); System[method].implementation = function (library) { const timestamp = new Date(); if (config.getString('hook.output') === 'json') { traceEmit({ source: 'java', class: klass, method, returnValue: value, timestamp }); } else { traceEmit(`[JAVA TRACE][${timestamp}] Intercept return for ${klass}:${method} with ${value}`); } switch (value) { case 0: return false; case 1: return true; case -1: return -1; // TODO should throw an error? } return value; }; }); } function interceptRetJavaExpression (target, value) { let klass = target.substring('java:'.length); const lastDot = klass.lastIndexOf('.'); if (lastDot !== -1) { const method = klass.substring(lastDot + 1); klass = klass.substring(0, lastDot); return interceptRetJava(klass, method, value); } return 'Error: Wrong java method syntax'; } function interceptRet (target, value) { if (target.startsWith('java:')) { return interceptRetJavaExpression(target, value); } const p = getPtr(target); Interceptor.attach(p, { onLeave (retval) { retval.replace(ptr(value)); } }); } function interceptRet0 (args) { const target = args[0]; return interceptRet(target, 0); } function interceptRetString (args) { const target = args[0]; return interceptRet(target, args[1]); } function interceptRetInt (args) { const target = args[0]; return interceptRet(target, args[1]); } function interceptRet1 (args) { const target = args[0]; return interceptRet(target, 1); } function interceptRet_1 (args) { // eslint-disable-line const target = args[0]; return interceptRet(target, -1); } /* Intercept function calls *before* calling the original function code */ function interceptFunRet (target, value) { if (target.startsWith('java:')) { return 'TODO: not yet implemented'; } const p = getPtr(target); Interceptor.replace(p, new NativeCallback(function () { return ptr(value); }, 'pointer', ['pointer'])); } function interceptFunRet0 (args) { const target = args[0]; return interceptFunRet(target, 0); } function interceptFunRetString (args) { const target = args[0]; return interceptFunRet(target, args[1]); } function interceptFunRetInt (args) { const target = args[0]; return interceptFunRet(target, args[1]); } function interceptFunRet1 (args) { const target = args[0]; return interceptFunRet(target, 1); } function interceptFunRet_1 (args) { // eslint-disable-line const target = args[0]; return interceptFunRet(target, -1); } function getenv (name) { return Memory.readUtf8String(_getenv(Memory.allocUtf8String(name))); } function setenv (name, value, overwrite) { return _setenv(Memory.allocUtf8String(name), Memory.allocUtf8String(value), overwrite ? 1 : 0); } function getWindowsUserNameA () { const _GetUserNameA = sym('GetUserNameA', 'int', ['pointer', 'pointer']); const PATH_MAX = 4096; const buf = Memory.allocUtf8String('A'.repeat(PATH_MAX)); const char_out = Memory.allocUtf8String('A'.repeat(PATH_MAX)); const res = _GetUserNameA(buf, char_out); const user = Memory.readCString(buf); return user; } function stalkTraceFunction (args) { return _stalkTraceSomething(_stalkFunctionAndGetEvents, args); } function stalkTraceFunctionR2 (args) { return _stalkTraceSomethingR2(_stalkFunctionAndGetEvents, args); } function stalkTraceFunctionJson (args) { return _stalkTraceSomethingJson(_stalkFunctionAndGetEvents, args); } function stalkTraceEverything (args) { if (args.length === 0) { return 'Warnnig: dts is experimental and slow\nUsage: dts [symbol]'; } return _stalkTraceSomething(_stalkEverythingAndGetEvents, args); } function stalkTraceEverythingR2 (args) { if (args.length === 0) { return 'Warnnig: dts is experimental and slow\nUsage: dts* [symbol]'; } return _stalkTraceSomethingR2(_stalkEverythingAndGetEvents, args); } function stalkTraceEverythingJson (args) { if (args.length === 0) { return 'Warnnig: dts is experimental and slow\nUsage: dtsj [symbol]'; } return _stalkTraceSomethingJson(_stalkEverythingAndGetEvents, args); } function _stalkTraceSomething (getEvents, args) { return getEvents(args, (isBlock, events) => { let previousSymbolName; const result = []; const threads = Object.keys(events); for (const threadId of threads) { result.push(`; --- thread ${threadId} --- ;`); if (isBlock) { result.push(..._mapBlockEvents(events[threadId], (address) => { const pd = disasmOne(address, previousSymbolName); previousSymbolName = getSymbolName(address); return pd; }, (begin, end) => { previousSymbolName = null; return ''; })); } else { result.push(...events[threadId].map((event) => { const address = event[0]; const target = event[1]; const pd = disasmOne(address, previousSymbolName, target); previousSymbolName = getSymbolName(address); return pd; })); } } return result.join('\n') + '\n'; }); function disasmOne (address, previousSymbolName, target) { let pd = disasm(address, 1, previousSymbolName); if (pd.endsWith('\n')) { pd = pd.slice(0, -1); } if (target) { pd += ` ; ${target} ${getSymbolName(target)}`; } return pd; } } function _stalkTraceSomethingR2 (getEvents, args) { return getEvents(args, (isBlock, events) => { const result = []; const threads = Object.keys(events); for (const threadId of threads) { if (isBlock) { result.push(..._mapBlockEvents(events[threadId], (address) => { return `dt+ ${address} 1`; })); } else { result.push(...events[threadId].map((event) => { const commands = []; const location = event[0]; commands.push(`dt+ ${location} 1`); const target = event[1]; if (target) { commands.push(`CC ${target} ${getSymbolName(target)} @ ${location}`); } return commands.join('\n') + '\n'; })); } } return result.join('\n') + '\n'; }); } function _stalkTraceSomethingJson (getEvents, args) { return getEvents(args, (isBlock, events) => { const result = { event: config.get('stalker.event'), threads: events }; return result; }); } function _stalkFunctionAndGetEvents (args, eventsHandler) { _requireFridaVersion(10, 3, 13); const at = getPtr(args[0]); const conf = { event: config.get('stalker.event'), timeout: config.get('stalker.timeout'), stalkin: config.get('stalker.in') }; const isBlock = conf.event === 'block' || conf.event === 'compile'; const operation = stalkFunction(conf, at) .then((events) => { return eventsHandler(isBlock, events); }); breakpointContinue([]); return operation; } function _stalkEverythingAndGetEvents (args, eventsHandler) { _requireFridaVersion(10, 3, 13); const timeout = (args.length > 0) ? +args[0] : null; const conf = { event: config.get('stalker.event'), timeout: config.get('stalker.timeout'), stalkin: config.get('stalker.in') }; const isBlock = conf.event === 'block' || conf.event === 'compile'; const operation = stalkEverything(conf, timeout) .then((events) => { return eventsHandler(isBlock, events); }); breakpointContinue([]); return operation; } function getSymbolName (address) { const ds = DebugSymbol.fromAddress(address); return (ds.name === null || ds.name.indexOf('0x') === 0) ? '' : ds.name; } function _requireFridaVersion (major, minor, patch) { const required = [major, minor, patch]; const actual = Frida.version.split('.'); for (let i = 0; i < actual.length; i++) { if (actual[i] > required[i]) { return; } if (actual[i] < required[i]) { throw new Error(`Frida v${major}.${minor}.${patch} or higher required for this (you have v${Frida.version}).`); } } } function _mapBlockEvents (events, onInstruction, onBlock) { const result = []; events.forEach(([begin, end]) => { if (typeof onBlock === 'function') { result.push(onBlock(begin, end)); } let cursor = begin; while (cursor < end) { const [instr, next] = _tolerantInstructionParse(cursor); if (instr !== null) { result.push(onInstruction(cursor)); } cursor = next; } }); return result; } function _tolerantInstructionParse (address) { let instr = null; let cursor = address; try { instr = Instruction.parse(cursor); cursor = instr.next; } catch (e) { if (e.message !== 'invalid instruction' && e.message !== `access violation accessing ${cursor}`) { throw e; } if (e.message.indexOf('access violation') !== -1) { // cannot access the memory } else { // console.log(`warning: error parsing instruction at ${cursor}`); } // skip invalid instructions switch (Process.arch) { case 'arm64': cursor = cursor.add(4); break; case 'arm': cursor = cursor.add(2); break; default: cursor = cursor.add(1); break; } } return [instr, cursor]; } function compareRegisterNames (lhs, rhs) { const lhsIndex = parseRegisterIndex(lhs); const rhsIndex = parseRegisterIndex(rhs); const lhsHasIndex = lhsIndex !== null; const rhsHasIndex = rhsIndex !== null; if (lhsHasIndex && rhsHasIndex) { return lhsIndex - rhsIndex; } if (lhsHasIndex === rhsHasIndex) { const lhsLength = lhs.length; const rhsLength = rhs.length; if (lhsLength === rhsLength) { return lhs.localeCompare(rhs); } if (lhsLength > rhsLength) { return 1; } return -1; } if (lhsHasIndex) { return 1; } return -1; } function parseRegisterIndex (name) { const length = name.length; for (let index = 1; index < length; index++) { const value = parseInt(name.substr(index)); if (!isNaN(value)) { return value; } } return null; } function indent (message, index) { if (index === 0) { return message; } if ((index % 3) === 0) { return '\n' + message; } return '\t' + message; } function alignRight (text, width) { let result = text; while (result.length < width) { result = ' ' + result; } return result; } function padPointer (value) { let result = value.toString(16); const paddedLength = 2 * pointerSize; while (result.length < paddedLength) { result = '0' + result; } return '0x' + result; } const requestHandlers = { safeio: () => { r2frida.safeio = true; }, read: io.read, write: io.write, state: state, perform: perform, evaluate: evaluate, }; function state (params, data) { r2frida.offset = params.offset; suspended = params.suspended; return [{}, null]; } function isPromise (value) { return value !== null && typeof value === 'object' && typeof value.then === 'function'; } function stalkTraceEverythingHelp () { return `Usage: dts[j*] [symbol|address] - Trace given symbol using the Frida Stalker dtsf[*j] [sym|addr] Trace address or symbol using the stalker dts[*j] seconds Trace all threads for given seconds using the stalker `; } function getHelpMessage (prefix) { return Object.keys(commandHandlers).sort() .filter((k) => { return !prefix || k.startsWith(prefix); }) .map((k) => { const desc = commandHandlers[k].name .replace(/(?:^|\.?)([A-Z])/g, function (x, y) { return ' ' + y.toLowerCase(); }).replace(/^_/, ''); return ' ' + k + '\t' + desc; }).join('\n') + '\n'; } function perform (params) { const { command } = params; const tokens = command.split(/ /).map((c) => c.trim()).filter((x) => x); const [name, ...args] = tokens; if (typeof name === 'undefined') { const value = getHelpMessage(''); return [{ value: normalizeValue(value) }, null]; } if (name.length > 0 && name.endsWith('?') && !commandHandlers[name]) { const prefix = name.substring(0, name.length - 1); const value = getHelpMessage(prefix); return [{ value: normalizeValue(value) }, null]; } const userHandler = global.r2frida.commandHandler(name); const handler = userHandler !== undefined ? userHandler : commandHandlers[name]; if (handler === undefined) { throw new Error('Unhandled command: ' + name); } if (isPromise(handler)) { throw new Error("The handler can't be a promise"); } const value = handler(args); if (isPromise(value)) { return new Promise((resolve, reject) => { return value.then(output => { resolve([{ value: normalizeValue(output) }, null]); }).catch(reject); }); } const nv = normalizeValue(value); if (nv === '' || nv === 'null' || nv === undefined || nv === null) { return [{}, null]; } return [{ value: nv }, null]; } function normalizeValue (value) { if (typeof value === null || typeof value === undefined) { return null; } if (typeof value === 'undefined') { return 'undefined'; } if (typeof value === 'string') { return value; } return JSON.stringify(value); } function evaluate (params) { return new Promise(resolve => { let { code, ccode } = params; const isObjcMainLoopRunning = ObjCAvailable && hasMainLoop(); if (ObjCAvailable && isObjcMainLoopRunning && !suspended) { ObjC.schedule(ObjC.mainQueue, performEval); } else { performEval(); } function performEval () { let result; try { if (ccode) { code = ` var m = new CModule(` + '`' + ccode + '`' + `); const main = new NativeFunction(m.main, 'int', []); main(); `; } const rawResult = (1, eval)(code); // eslint-disable-line global._ = rawResult; result = rawResult; // 'undefined'; } catch (e) { result = 'throw new ' + e.name + '("' + e.message + '")'; } resolve([{ value: result }, null]); } }); } function hasMainLoop () { const getMainPtr = Module.findExportByName(null, 'CFRunLoopGetMain'); if (getMainPtr === null) { return false; } const copyCurrentModePtr = Module.findExportByName(null, 'CFRunLoopCopyCurrentMode'); if (copyCurrentModePtr === null) { return false; } const getMain = new NativeFunction(getMainPtr, 'pointer', []); const copyCurrentMode = new NativeFunction(copyCurrentModePtr, 'pointer', ['pointer']); const main = getMain(); if (main.isNull()) { return false; } const mode = copyCurrentMode(main); const hasLoop = !mode.isNull(); if (hasLoop) { new ObjC.Object(mode).release(); } return hasLoop; } Script.setGlobalAccessHandler({ enumerate () { return []; }, get (property) { return undefined; } }); function fridaVersion () { return { version: Frida.version }; } function search (args) { return searchJson(args).then(hits => { return _readableHits(hits); }); } function echo (args) { console.log(args.join(' ')); return null; } function searchJson (args) { const pattern = _toHexPairs(args.join(' ')); return _searchPatternJson(pattern).then(hits => { hits.forEach(hit => { try { const bytes = io.read({ offset: hit.address, count: 60 })[1]; hit.content = _filterPrintable(bytes); } catch (e) { } }); return hits.filter(hit => hit.content !== undefined); }); } function searchInstancesJson (args) { const className = args.join(''); if (ObjCAvailable) { const results = JSON.parse(JSON.stringify(ObjC.chooseSync(ObjC.classes[className]))); return results.map(function (res) { return { address: res.handle, content: className }; }); } else { Java.performNow(function () { const results = Java.choose(Java.classes[className]); return results.map(function (res) { return { address: res, content: className }; }); }); } } function searchInstances (args) { return _readableHits(searchInstancesJson(args)); } function searchHex (args) { return searchHexJson(args).then(hits => { return _readableHits(hits); }); } function searchHexJson (args) { const pattern = _normHexPairs(args.join('')); return _searchPatternJson(pattern).then(hits => { hits.forEach(hit => { const bytes = Memory.readByteArray(hit.address, hit.size); hit.content = _byteArrayToHex(bytes); }); return hits; }); } function searchWide (args) { return searchWideJson(args).then(hits => { return _readableHits(hits); }); } function searchWideJson (args) { const pattern = _toWidePairs(args.join(' ')); return searchHexJson([pattern]); } function searchValueImpl (width) { return function (args) { return searchValueJson(args, width).then(hits => { return _readableHits(hits); }); }; } function searchValueImplJson (width) { return function (args) { return searchValueJson(args, width); }; } function searchValueJson (args, width) { let value; try { value = uint64(args.join('')); } catch (e) { return new Promise((resolve, reject) => reject(e)); } return hostCmdj('ej') .then((r2cfg) => { const bigEndian = r2cfg['cfg.bigendian']; const bytes = _renderEndian(value, bigEndian, width); return searchHexJson([_toHexPairs(bytes)]); }); } function evalConfigSearch (args) { const currentRange = Process.getRangeByAddress(ptr(r2frida.offset)); const from = currentRange.base; const to = from.add(currentRange.size); return `e search.in=raw e search.from=${from} e search.to=${to} e anal.in=raw e anal.from=${from} e anal.to=${to}`; } function evalConfigR2 (args) { return config.asR2Script(); } function evalConfig (args) { // list if (args.length === 0) { return config.asR2Script(); } const kv = args[0].split(/=/); const [k, v] = kv; if (kv.length === 2) { if (config.get(k) !== undefined) { // help if (v === '?') { return config.helpFor(kv[0]); } // set (and flatten case for variables except file.log) if (kv[0] !== 'file.log' && typeof kv[1] === 'string') { config.set(kv[0], kv[1].toLowerCase()); } else { config.set(kv[0], kv[1]); } } else { console.error('unknown variable'); } return ''; } // get return config.getString(args[0]); } function _renderEndian (value, bigEndian, width) { const bytes = []; for (let i = 0; i !== width; i++) { if (bigEndian) { bytes.push(value.shr((width - i - 1) * 8).and(0xff).toNumber()); } else { bytes.push(value.shr(i * 8).and(0xff).toNumber()); } } return bytes; } function _byteArrayToHex (arr) { const u8arr = new Uint8Array(arr); const hexs = []; for (let i = 0; i !== u8arr.length; i += 1) { const h = u8arr[i].toString(16); hexs.push((h.length === 2) ? h : `0${h}`); } return hexs.join(''); } const minPrintable = ' '.charCodeAt(0); const maxPrintable = '~'.charCodeAt(0); function _filterPrintable (arr) { const u8arr = new Uint8Array(arr); const printable = []; for (let i = 0; i !== u8arr.length; i += 1) { const c = u8arr[i]; if (c === 0) { break; } if (c >= minPrintable && c <= maxPrintable) { printable.push(String.fromCharCode(c)); } } return printable.join(''); } function _readableHits (hits) { const output = hits.map(hit => { if (typeof hit.flag === 'string') { return `${hexPtr(hit.address)} ${hit.flag} ${hit.content}`; } return `${hexPtr(hit.address)} ${hit.content}`; }); return output.join('\n') + '\n'; } function hexPtr (p) { if (p instanceof UInt64) { return `0x${p.toString(16)}`; } return p.toString(); } function _searchPatternJson (pattern) { return hostCmdj('ej') .then(r2cfg => { const flags = r2cfg['search.flags']; const prefix = r2cfg['search.prefix'] || 'hit'; const count = r2cfg['search.count'] || 0; const kwidx = r2cfg['search.kwidx'] || 0; const ranges = _getRanges(r2cfg['search.from'], r2cfg['search.to']); const nBytes = pattern.split(' ').length; qlog(`Searching ${nBytes} bytes: ${pattern}`); let results = []; const commands = []; let idx = 0; for (const range of ranges) { if (range.size === 0) { continue; } const rangeStr = `[${padPointer(range.address)}-${padPointer(range.address.add(range.size))}]`; qlog(`Searching ${nBytes} bytes in ${rangeStr}`); try { const partial = _scanForPattern(range.address, range.size, pattern); partial.forEach((hit) => { if (flags) { hit.flag = `${prefix}${kwidx}_${idx + count}`; commands.push('fs+searches'); commands.push(`f ${hit.flag} ${hit.size} ${hexPtr(hit.address)}`); commands.push('fs-'); } idx += 1; }); results = results.concat(partial); } catch (e) { console.error('Oops', e); } } qlog(`hits: ${results.length}`); commands.push(`e search.kwidx=${kwidx + 1}`); return hostCmds(commands).then(() => { return results; }); }); function qlog (message) { if (!config.getBoolean('search.quiet')) { console.log(message); } } } function _scanForPattern (address, size, pattern) { if (r2frida.hookedScan !== null) { return r2frida.hookedScan(address, size, pattern); } return Memory.scanSync(address, size, pattern); } function _configParseSearchIn () { const res = { current: false, perm: 'r--', path: null, heap: false }; const c = config.getString('search.in'); const cSplit = c.split(':'); const [scope, param] = cSplit; if (scope === 'current') { res.current = true; } if (scope === 'heap') { res.heap = true; } if (scope === 'perm') { res.perm = param; } if (scope === 'path') { cSplit.shift(); res.path = cSplit.join(''); } return res; } function _getRanges (fromNum, toNum) { const searchIn = _configParseSearchIn(); if (searchIn.heap) { return Process.enumerateMallocRanges() .map(_ => { return { address: _.base, size: _.size }; }); } const ranges = _getMemoryRanges(searchIn.perm).filter(range => { const start = range.base; const end = start.add(range.size); const offPtr = ptr(r2frida.offset); if (searchIn.current) { return offPtr.compare(start) >= 0 && offPtr.compare(end) < 0; } if (searchIn.path !== null) { if (range.file !== undefined) { return range.file.path.indexOf(searchIn.path) >= 0; } return false; } return true; }); if (ranges.length === 0) { return []; } const first = ranges[0]; const last = ranges[ranges.length - 1]; const from = (fromNum === -1) ? first.base : ptr(fromNum); const to = (toNum === -1) ? last.base.add(last.size) : ptr(toNum); return ranges.filter(range => { return range.base.compare(to) <= 0 && range.base.add(range.size).compare(from) >= 0; }).map(range => { const start = _ptrMax(range.base, from); const end = _ptrMin(range.base.add(range.size), to); return { address: start, size: uint64(end.sub(start).toString()).toNumber() }; }); } function _ptrMax (a, b) { return a.compare(b) > 0 ? a : b; } function _ptrMin (a, b) { return a.compare(b) < 0 ? a : b; } function _toHexPairs (raw) { const isString = typeof raw === 'string'; const pairs = []; for (let i = 0; i !== raw.length; i += 1) { const code = (isString ? raw.charCodeAt(i) : raw[i]) & 0xff; const h = code.toString(16); pairs.push((h.length === 2) ? h : `0${h}`); } return pairs.join(' '); } function _toWidePairs (raw) { const pairs = []; for (let i = 0; i !== raw.length; i += 1) { const code = raw.charCodeAt(i) & 0xff; const h = code.toString(16); pairs.push((h.length === 2) ? h : `0${h}`); pairs.push('00'); } return pairs.join(' '); } function _normHexPairs (raw) { const norm = raw.replace(/ /g, ''); if (_isHex(norm)) { return _toPairs(norm.replace(/\./g, '?')); } throw new Error('Invalid hex string'); } function _toPairs (hex) { if ((hex.length % 2) !== 0) { throw new Error('Odd-length string'); } const pairs = []; for (let i = 0; i !== hex.length; i += 2) { pairs.push(hex.substr(i, 2)); } return pairs.join(' ').toLowerCase(); } function _isHex (raw) { const hexSet = new Set(Array.from('abcdefABCDEF0123456789?.')); const inSet = new Set(Array.from(raw)); for (const h of hexSet) { inSet.delete(h); } return inSet.size === 0; } function fsList (args) { return fs.ls(args[0] || Gcwd); } function fsGet (args) { return fs.cat(args[0] || '', '*', args[1] || 0, args[2] || null); } function fsCat (args) { return fs.cat(args[0] || ''); } function fsOpen (args) { return fs.open(args[0] || Gcwd); } function javaPerform (fn) { if (config.getBoolean('java.wait')) { return Java.perform(fn); } return Java.performNow(fn); } function performOnJavaVM (fn) { return new Promise((resolve, reject) => { javaPerform(function () { try { const result = fn(); resolve(result); } catch (e) { reject(e); } }); }); } function getModuleAt (addr) { if (addr === null) { return null; } const modules = Process.enumerateModules() .filter((m) => { const a = m.base; const b = m.base.add(m.size); return addr.compare(a) >= 0 && addr.compare(b) < 0; }); return modules.length > 0 ? modules[0] : null; } let onceStanza = false; function onStanza (stanza, data) { const handler = requestHandlers[stanza.type]; if (handler !== undefined) { try { const value = handler(stanza.payload, data); if (value instanceof Promise) { // handle async stuff in here value .then(([replyStanza, replyBytes]) => { send(wrapStanza('reply', replyStanza), replyBytes); }) .catch(e => { send(wrapStanza('reply', { error: e.message })); }); } else { const [replyStanza, replyBytes] = value; send(wrapStanza('reply', replyStanza), replyBytes); } } catch (e) { send(wrapStanza('reply', { error: e.message })); } } else if (stanza.type === 'bp') { console.error('Breakpoint handler'); } else if (stanza.type === 'cmd') { onCmdResp(stanza.payload); } else { console.error('Unhandled stanza: ' + stanza.type); } if (!onceStanza) { recv(onStanza); } } let cmdSerial = 0; function hostCmds (commands) { let i = 0; function sendOne () { if (i < commands.length) { return hostCmd(commands[i]).then(() => { i += 1; return sendOne(); }); } else { return Promise.resolve(); } } return sendOne(); } function hostCmdj (cmd) { return hostCmd(cmd) .then(output => { return JSON.parse(output); }); } function hostCmd (cmd) { return new Promise((resolve) => { const serial = cmdSerial; cmdSerial++; pendingCmds[serial] = resolve; sendCommand(cmd, serial); }); } global.r2frida.hostCmd = hostCmd; global.r2frida.hostCmdj = hostCmdj; global.r2frida.logs = logs; global.r2frida.log = traceLog; global.r2frida.emit = traceEmit; global.r2frida.safeio = NeedsSafeIo; global.r2frida.module = ''; function sendCommand (cmd, serial) { function sendIt () { sendingCommand = true; send(wrapStanza('cmd', { cmd: cmd, serial: serial })); } if (sendingCommand) { pendingCmdSends.push(sendIt); } else { sendIt(); } } function onCmdResp (params) { const { serial, output } = params; sendingCommand = false; if (serial in pendingCmds) { const onFinish = pendingCmds[serial]; delete pendingCmds[serial]; process.nextTick(() => onFinish(output)); } else { throw new Error('Command response out of sync'); } process.nextTick(() => { if (!sendingCommand) { const nextSend = pendingCmdSends.shift(); if (nextSend !== undefined) { nextSend(); } } }); return [{}, null]; } function wrapStanza (name, stanza) { return { name: name, stanza: stanza }; } recv(onStanza);
Add tmpdir and homedir in addition to bundledir to :i for iOS
src/agent/index.js
Add tmpdir and homedir in addition to bundledir to :i for iOS
<ide><path>rc/agent/index.js <ide> <ide> function radareSeek (args) { <ide> const addr = getPtr('' + args); <del> const cmdstr = 's ' + (addr || '' + args); <add> const cmdstr = 's ' + (addr || '' + args); <ide> return cmdstr; <ide> // XXX hangs <ide> // return hostCmd(cmdstr); <ide> const v = id.objectForKey_(k); <ide> return v ? v.toString() : ''; <ide> } <add> const NSHomeDirectory = new NativeFunction( <add> Module.getExportByName(null, 'NSHomeDirectory'), <add> 'pointer', []); <add> const NSTemporaryDirectory = new NativeFunction( <add> Module.getExportByName(null, 'NSTemporaryDirectory'), <add> 'pointer', []); <ide> res.bundle = get('CFBundleIdentifier'); <ide> res.exename = get('CFBundleExecutable'); <ide> res.appname = get('CFBundleDisplayName'); <ide> res.appversion = get('CFBundleShortVersionString'); <ide> res.appnumversion = get('CFBundleNumericVersion'); <del> res.apphome = ObjC.classes.NSBundle.mainBundle().bundleURL().path(); <add> res.homedir = (new ObjC.Object(NSHomeDirectory()).toString()); <add> res.tmpdir = (new ObjC.Object(NSTemporaryDirectory()).toString()); <add> res.bundledir = ObjC.classes.NSBundle.mainBundle().bundleURL().path(); <add> // res.appdata = ObjC.classes.NSBundle.mainBundle().bundleURL().path(); <ide> res.minOS = get('MinimumOSVersion'); <ide> } catch (e) { <ide> console.error(e);
JavaScript
mit
58ffe14f9f6d0bcdd7e7f77d7490aa130f7a152f
0
cetic/sitcom,cetic/sitcom,aurels/sitcom,cetic/sitcom,aurels/sitcom,aurels/sitcom
class SocialShow extends React.Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div className="social"> <div className="row"> { this.renderEdit() } { this.renderFacebook() } { this.renderLinkedin() } { this.renderTwitter() } </div> </div> ); } renderEdit() { return( <button className="btn btn-secondary btn-edit" onClick={this.props.toggleEditMode}> Modifier </button> ) } renderSocialInside(url) { if(url == '') { return <em>non-renseigné</em>; } else { return ( <a href={ url } target="_blank"> { url } </a> ) } } renderFacebook() { return ( <div className="col-md-12 facebook"> <i className="fa fa-facebook-square"></i> { this.renderSocialInside(this.props.contact.facebookUrl) } </div> ) } renderLinkedin() { return ( <div className="col-md-12 linkedin"> <i className="fa fa-linkedin-square"></i> { this.renderSocialInside(this.props.contact.linkedinUrl) } </div> ) } renderTwitter() { return ( <div className="col-md-12 twitter"> <i className="fa fa-twitter-square"></i> { this.renderSocialInside(this.props.contact.twitterUrl) } </div> ) } } module.exports = SocialShow
app/assets/javascripts/contacts/show/social_show.es6
class SocialShow extends React.Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div className="social"> <div className="row"> { this.renderEdit() } { this.renderFacebook() } { this.renderLinkedin() } { this.renderTwitter() } </div> </div> ); } renderEdit() { return( <button className="btn btn-secondary btn-edit" onClick={this.props.toggleEditMode}> Modifier </button> ) } renderFacebook() { return ( <div className="col-md-12 facebook"> <i className="fa fa-facebook-square"></i> <a href={ this.props.contact.facebookUrl } target="_blank"> { this.props.contact.facebookUrl } </a> </div> ) } renderLinkedin() { return ( <div className="col-md-12 linkedin"> <i className="fa fa-linkedin-square"></i> <a href={ this.props.contact.linkedinUrl } target="_blank"> { this.props.contact.linkedinUrl } </a> </div> ) } renderTwitter() { return ( <div className="col-md-12 twitter"> <i className="fa fa-twitter-square"></i> <a href={ this.props.contact.twitterUrl } target="_blank"> { this.props.contact.twitterUrl } </a> </div> ) } } module.exports = SocialShow
empty slate social links
app/assets/javascripts/contacts/show/social_show.es6
empty slate social links
<ide><path>pp/assets/javascripts/contacts/show/social_show.es6 <ide> ) <ide> } <ide> <add> renderSocialInside(url) { <add> if(url == '') { <add> return <em>non-renseigné</em>; <add> } <add> else { <add> return ( <add> <a href={ url } target="_blank"> <add> { url } <add> </a> <add> ) <add> } <add> } <add> <ide> renderFacebook() { <ide> return ( <ide> <div className="col-md-12 facebook"> <ide> <i className="fa fa-facebook-square"></i> <del> <a href={ this.props.contact.facebookUrl } target="_blank"> <del> { this.props.contact.facebookUrl } <del> </a> <add> { this.renderSocialInside(this.props.contact.facebookUrl) } <ide> </div> <ide> ) <ide> } <ide> return ( <ide> <div className="col-md-12 linkedin"> <ide> <i className="fa fa-linkedin-square"></i> <del> <a href={ this.props.contact.linkedinUrl } target="_blank"> <del> { this.props.contact.linkedinUrl } <del> </a> <add> { this.renderSocialInside(this.props.contact.linkedinUrl) } <ide> </div> <ide> ) <ide> } <ide> return ( <ide> <div className="col-md-12 twitter"> <ide> <i className="fa fa-twitter-square"></i> <del> <a href={ this.props.contact.twitterUrl } target="_blank"> <del> { this.props.contact.twitterUrl } <del> </a> <add> { this.renderSocialInside(this.props.contact.twitterUrl) } <ide> </div> <ide> ) <ide> }
Java
apache-2.0
79d406a6e924e5257230f5442e30df75642140aa
0
scala/scala,jvican/scala,scala/scala,lrytz/scala,scala/scala,jvican/scala,lrytz/scala,slothspot/scala,scala/scala,slothspot/scala,slothspot/scala,scala/scala,shimib/scala,martijnhoekstra/scala,felixmulder/scala,martijnhoekstra/scala,shimib/scala,jvican/scala,shimib/scala,martijnhoekstra/scala,felixmulder/scala,martijnhoekstra/scala,felixmulder/scala,slothspot/scala,martijnhoekstra/scala,shimib/scala,martijnhoekstra/scala,jvican/scala,slothspot/scala,felixmulder/scala,jvican/scala,lrytz/scala,shimib/scala,jvican/scala,lrytz/scala,lrytz/scala,lrytz/scala,slothspot/scala,felixmulder/scala,jvican/scala,slothspot/scala,felixmulder/scala,shimib/scala,scala/scala,felixmulder/scala
/* ____ ____ ____ ____ ______ *\ ** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** ** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** ** /_____/\____/\___/\____/____/ ** \* */ // $OldId: Erasure.java,v 1.48 2003/01/16 14:21:19 schinz Exp $ // $Id$ package scalac.transformer; import java.util.HashMap; import scalac.Global; import scalac.Unit; import scalac.ast.Tree; import scalac.ast.Tree.Template; import scalac.ast.Tree.AbsTypeDef; import scalac.ast.Tree.AliasTypeDef; import scalac.ast.Tree.ValDef; import scalac.ast.TreeList; import scalac.ast.Transformer; import scalac.symtab.Definitions; import scalac.symtab.Kinds; import scalac.symtab.Type; import scalac.symtab.TypeTags; import scalac.symtab.Modifiers; import scalac.symtab.Scope; import scalac.symtab.SymSet; import scalac.symtab.Symbol; import scalac.backend.Primitives; import scalac.util.Name; import scalac.util.Names; import scalac.util.Debug; /** A transformer for type erasure and bridge building * * @author Martin Odersky * @version 1.0 * * What it does: * (1) Map every type to its erasure. * (2) If method A overrides a method B, and the erased type ETA of A is * different from the erased type ETB of B seen as a member of A's class, * add a bridge method with the same name as A,B, with signature ETB * which calls A after casting parameters. */ public class Erasure extends Transformer implements Modifiers { private final Definitions definitions; private final Primitives primitives; private Unit unit; public Erasure(Global global) { super(global); this.definitions = global.definitions; this.primitives = global.primitives; } public void apply(Unit unit) { this.unit = unit; unit.body = transform(unit.body); } ////////////////////////////////////////////////////////////////////////////////// // Box/Unbox and Coercions ///////////////////////////////////////////////////////////////////////////////// boolean isUnboxed(Type type) { switch (type) { case UnboxedType(_): case UnboxedArrayType(_): return true; default: return false; } } boolean isUnboxedArray(Type type) { switch (type) { case UnboxedArrayType(_): return true; default: return false; } } boolean isBoxed(Type type) { return type.unbox() != type || type.symbol().fullName() == Names.scala_Array; } Type boxedType(Type tp) { switch (tp) { case UnboxedType(int kind): return definitions.getType(Type.boxedFullName(kind)); case UnboxedArrayType(Type elemtp): return definitions.arrayType(boxedType(elemtp)); default: return tp; } } Symbol boxSym(Type unboxedtp) { return primitives.getBoxValueSymbol(unboxedtp); } /** Emit `scala.RunTime.box(tree)' or * `{ tree ; scala.RunTime.box() }' if type of `tree' is `void'. */ Tree box(Tree tree) { Tree boxtree = gen.mkRef(tree.pos, primitives.RUNTIME_TYPE, boxSym(tree.type)); switch (tree.type) { case UnboxedType(int kind): if (kind == TypeTags.UNIT) return gen.Block( tree.pos, new Tree[]{tree, gen.Apply(boxtree, new Tree[0])}); } return gen.Apply(boxtree, new Tree[]{tree}); } /** The symbol of the unbox method corresponding to unboxed type`unboxedtp' */ Symbol unboxSym(Type unboxedtp) { return primitives.getUnboxValueSymbol(unboxedtp); } /** Emit tree.asType() or tree.asTypeArray(), where pt = Type or pt = Type[]. */ Tree unbox(Tree tree, Type pt) { Tree sel = gen.Select(tree, unboxSym(pt)); return gen.Apply(sel, new Tree[0]); } /** Generate a select from an unboxed type. */ public Tree unboxedSelect(Tree qual, Symbol sym) { return make.Select(qual.pos, qual, sym.name) .setSymbol(sym) .setType(Type.singleType(boxedType(qual.type).symbol().thisType(),sym).erasure()); } /** Subclass relation for class types; empty for other types. */ boolean isSubClass(Type tp1, Type tp2) { Symbol sym1 = tp1.symbol(); Symbol sym2 = tp2.symbol(); return sym1 != null && sym2 != null && sym1.isSubClass(sym2); } /** Subtyping relation on erased types. */ boolean isSubType(Type tp1, Type tp2) { if (isSameAs(tp1, tp2)) return true; switch (tp2) { case UnboxedType(_): return tp1.isSubType(tp2); case UnboxedArrayType(Type elemtp2): switch (tp1) { case UnboxedArrayType(Type elemtp1): return !(elemtp1 instanceof Type.UnboxedType) && isSubType(elemtp1, elemtp2); default: return tp1.isSubType(tp2); } } switch (tp1) { case UnboxedArrayType(Type elemtp1): if (tp2.symbol() == definitions.ANY_CLASS) return true; } return isSubClass(tp1, tp2); } /** Equality relation on erased types. */ boolean isSameAs(Type tp1, Type tp2) { global.nextPhase(); boolean result = tp1.isSameAs(tp2); global.prevPhase(); return result; } Tree coerce(Tree tree, Type pt) { return isSubType(tree.type, pt) ? tree : cast(tree, pt); } Tree cast(Tree tree, Type pt) { if (global.debug) global.log("cast " + tree + ":" + tree.type + " to " + pt);//debug if (isSameAs(tree.type, pt)) { return tree; } else if (isSubType(tree.type, pt)) { return tree; } else if (isUnboxed(tree.type) && !isUnboxed(pt)) { return cast(box(tree), pt); } else if ((isUnboxedArray(tree.type) || (tree.type.symbol() == definitions.ANY_CLASS)) && isUnboxedArray(pt)) { return make.Apply(tree.pos, make.TypeApply(tree.pos, unboxedSelect(tree, definitions.AS), new Tree[]{gen.mkType(tree.pos, pt)}) .setType(new Type.MethodType(Symbol.EMPTY_ARRAY, pt)), new Tree[0]) .setType(pt); } else if (!isUnboxed(tree.type) && isUnboxed(pt)) { if (isBoxed(tree.type)) { return coerce(unbox(tree, pt), pt); } else { Type bt = boxedType(pt); while (isBoxed(bt.parents()[0])) { bt = bt.parents()[0]; } return cast(coerce(tree, bt), pt); } } else if (isUnboxed(tree.type) && isUnboxed(pt)) { return gen.Apply( unboxedSelect(box(tree), unboxSym(pt)), new Tree[0]); } else if (!isUnboxed(tree.type) && !isUnboxed(pt) || isUnboxedArray(tree.type) && isUnboxedArray(pt)) { return gen.Apply( gen.TypeApply( gen.Select(tree, definitions.AS), new Tree[]{gen.mkType(tree.pos, pt)}), new Tree[0]); } else { throw Debug.abort("cannot cast " + tree.type + " to " + pt); } } ////////////////////////////////////////////////////////////////////////////////// // Bridge Building ///////////////////////////////////////////////////////////////////////////////// private TreeList bridges; private HashMap bridgeSyms; /** Add bridge which Java-overrides `sym1' and which forwards to `sym' */ public void addBridge(Symbol owner, Symbol sym, Symbol sym1) { Type bridgeType = sym1.type().erasure(); // create bridge symbol and add to bridgeSyms(sym) // or return if bridge with required type already exists for sym. SymSet bridgesOfSym = (SymSet) bridgeSyms.get(sym); if (bridgesOfSym == null) bridgesOfSym = SymSet.EMPTY; Symbol[] brs = bridgesOfSym.toArray(); for (int i = 0; i < brs.length; i++) { if (isSameAs(brs[i].type(), bridgeType)) return; } Symbol bridgeSym = sym.cloneSymbol(); bridgeSym.flags |= (SYNTHETIC | BRIDGE); bridgeSym.flags &= ~(JAVA | DEFERRED); bridgesOfSym = bridgesOfSym.incl(bridgeSym); bridgeSyms.put(sym, bridgesOfSym); bridgeSym.setOwner(owner); // check that there is no overloaded symbol with same erasure as bridge // todo: why only check for overloaded? Symbol overSym = owner.members().lookup(sym.name); switch (overSym.type()) { case OverloadedType(Symbol[] alts, Type[] alttypes): for (int i = 0; i < alts.length; i++) { if (sym != alts[i] && isSameAs(bridgeType, alttypes[i].erasure())) { unit.error(sym.pos, "overlapping overloaded alternatives; " + "overridden " + sym1 + sym1.locationString() + " has same erasure as " + alts[i] + alttypes[i] + alts[i].locationString()); } } } switch (bridgeType) { case MethodType(Symbol[] params, Type restp): // assign to bridge symbol its bridge type // where owner of all parameters is bridge symbol itself. Symbol[] params1 = new Symbol[params.length]; for (int i = 0; i < params.length; i++) { params1[i] = params[i].cloneSymbol(bridgeSym); } bridgeSym.setType(Type.MethodType(params1, restp)); // create bridge definition Type symtype = sym.type().erasure(); switch (symtype) { case MethodType(Symbol[] symparams, Type symrestp): assert params1.length == symparams.length; Tree[] args = new Tree[params1.length]; for (int i = 0; i < args.length; i++) { args[i] = cast(gen.Ident(sym.pos, params1[i]), symparams[i].type().erasure()); } Tree fwd = make.Apply(sym.pos, gen.Ident(sym.pos, sym).setType(symtype), args) .setType(symrestp); bridges.append(gen.DefDef(bridgeSym, coerce(fwd, restp))); return; } } throw Debug.abort("bad bridge types " + bridgeType + "," + sym.type().erasure()); } public void addBridges(Symbol sym) { Symbol c = sym.owner(); if (c.isClass() && !c.isInterface()) { //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " : " + sym.type().erasure() + " @ " + Debug.show(c)); global.prevPhase(); Type[] basetypes = c.parents(); for (int i = 0; i < basetypes.length; i++) { addBridges(basetypes[i], sym); } } } public void addBridges(Type basetype, Symbol sym) { Symbol sym1 = sym.overriddenSymbol(basetype); //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " @ " + basetype + " -> " + Debug.show(sym1) + (sym1.kind == Kinds.NONE ? "" : " : " + sym1.type().erasure() + " => " + (isSameAs(sym1.type().erasure(), sym.type().erasure()) ? "ok" : "ADD BRIDGE"))); global.prevPhase(); if (sym1.kind != Kinds.NONE && !isSameAs(sym1.type().erasure(), sym.type().erasure())) { //System.out.println("!!! " + Debug.show(sym) + " adding bridge for " + Debug.show(sym1)); addBridge(sym.owner(), sym, sym1); } } public void addInterfaceBridges(Symbol c, Symbol sym) { assert c.isClass() && !c.isInterface(): Debug.show(c); //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " : " + sym.type().erasure() + " @ " + Debug.show(c)); global.prevPhase(); Symbol member = sym; // !!! create a clone to make overriddenSymbol return the right symbol Symbol clone = sym.cloneSymbol(); clone.setOwner(c); clone.setType(c.thisType().memberType(sym)); sym = clone; //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " : " + sym.type().erasure() + " @ " + Debug.show(c)); global.prevPhase(); Type basetype = c.thisType(); Symbol sym1 = sym.overriddenSymbol(basetype); sym = member; //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " @ " + basetype + " -> " + Debug.show(sym1) + (sym1.kind == Kinds.NONE ? "" : " : " + sym1.type().erasure() + " => " + (isSameAs(sym1.type().erasure(), sym.type().erasure()) ? "ok" : "ADD BRIDGE"))); global.prevPhase(); if (sym1.kind != Kinds.NONE && !isSameAs(sym1.type().erasure(), sym.type().erasure())) { //System.out.println("!!! " + Debug.show(sym) + " adding bridge for " + Debug.show(sym1)); addBridge(c, sym1, member); } } ////////////////////////////////////////////////////////////////////////////////// // Transformer ///////////////////////////////////////////////////////////////////////////////// /** Contract: every node needs to be transformed so that it's type is the * erasure of the node's original type. The only exception are functions; * these are mapped to the erasure of the function symbol's type. */ Symbol currentClass = null; public Tree transform(Tree tree, boolean eraseFully) { assert tree.type != null : tree; Type owntype = eraseFully ? tree.type.fullErasure() : tree.type.erasure(); switch (tree) { case ClassDef(_, _, _, _, _, Template(_, Tree[] body)): Symbol oldCurrentClass = currentClass; TreeList savedBridges = bridges; HashMap savedBridgeSyms = bridgeSyms; Symbol clazz = currentClass = tree.symbol(); bridges = new TreeList(); bridgeSyms = new HashMap(); TreeList body1 = new TreeList(transform(body)); if (!clazz.isInterface()) addInterfaceBridges(clazz); body1.append(bridges); if (bridges.length() > 0) { Type info = clazz.nextInfo(); switch (info) { case CompoundType(Type[] parts, Scope members): members = new Scope(members); for (int i = 0; i < bridges.length(); i++) { Tree bridge = (Tree)bridges.get(i); members.enterOrOverload(bridge.symbol()); } clazz.updateInfo(Type.compoundType(parts, members, info.symbol())); break; default: throw Debug.abort("class = " + Debug.show(clazz) + ", " + "info = " + Debug.show(info)); } } Tree newTree = gen.ClassDef(clazz, body1.toArray()); bridgeSyms = savedBridgeSyms; bridges = savedBridges; currentClass = oldCurrentClass; return newTree; case DefDef(_, _, _, _, _, Tree rhs): Symbol method = tree.symbol(); addBridges(method); if (rhs != Tree.Empty) rhs = transform(rhs, method.nextType().resultType()); return gen.DefDef(method, rhs); case ValDef(_, _, _, Tree rhs): Symbol field = tree.symbol(); if (rhs != Tree.Empty) rhs = transform(rhs, field.nextType()); return gen.ValDef(field, rhs); case AbsTypeDef(_, _, _, _): case AliasTypeDef(_, _, _, _): // eliminate return Tree.Empty; case Block(Tree[] stats): Tree[] newStats = new Tree[stats.length]; for (int i = 0; i < stats.length; ++i) newStats[i] = transform(stats[i], true); return gen.Block(tree.pos, newStats); case Assign(Tree lhs, Tree rhs): Tree lhs1 = transformLhs(lhs); Tree rhs1 = transform(rhs, lhs1.type); return copy.Assign(tree, lhs1, rhs1).setType(owntype.fullErasure()); case If(Tree cond, Tree thenp, Tree elsep): Tree cond1 = transform(cond, Type.unboxedType(TypeTags.BOOLEAN)); Tree thenp1 = transform(thenp, owntype); Tree elsep1 = (elsep == Tree.Empty) ? elsep : transform(elsep, owntype); return copy.If(tree, cond1, thenp1, elsep1).setType(owntype); case Switch(Tree test, int[] tags, Tree[] bodies, Tree otherwise): Tree test1 = transform(test, Type.unboxedType(TypeTags.INT)); Tree[] bodies1 = transform(bodies, owntype); Tree otherwise1 = transform(otherwise, owntype); return copy.Switch(tree, test1, tags, bodies1, otherwise1).setType(owntype); case Return(Tree expr): Tree expr1 = transform(expr, tree.symbol().type().resultType().fullErasure()); Tree zero = gen.Ident(tree.pos, definitions.NULL); return make.Block(tree.pos, new Tree[] { copy.Return(tree, expr1).setType(owntype), zero}).setType(zero.type()); case New(Template templ): if (tree.type.symbol() == definitions.UNIT_CLASS) // !!! return Tree.Literal(UNIT, null).setType(owntype); throw Debug.abort("found unit literal in " + currentClass); if (tree.type.symbol() == definitions.ARRAY_CLASS) { switch (templ.parents[0]) { case Apply(_, Tree[] args): args = transform(args); switch (owntype) { case UnboxedArrayType(Type elemtp): switch (elemtp) { case UnboxedType(int kind): return genNewArray(tree.pos,args[0],kind); default: return genNewArray(tree.pos,args[0],elemtp); } default: throw Debug.abort("illegal case", owntype); } default: throw Debug.abort("illegal case", templ.parents[0]); } } return super.transform(tree).setType(owntype); case Typed(Tree expr, Tree tpe): // coerce expr to tpe Tree tpe1 = gen.mkType(tpe.pos, tpe.type().erasure()); // !!! was transform(tpe); // !!! More generally, we should never transform a tree // that represents a type. We should always transform // types and then reconstruct the corresponding tree. return transform(expr, tpe1.type); case TypeApply(Tree fun, Tree[] args): Symbol sym = fun.symbol(); if (sym == definitions.AS || sym == definitions.IS) { Type tp = args[0].type.erasure(); if (isUnboxed(tp) && (sym != definitions.IS || (!isUnboxedArray(tp) && !tp.isSameAs(Type.UnboxedType(TypeTags.BOOLEAN))))) { Tree qual1 = transform(getQualifier(currentClass, fun)); if (isUnboxed(qual1.type)) qual1 = box(qual1); Symbol primSym = (sym == definitions.AS) ? primitives.getUnboxValueSymbol(tp) : primitives.getInstanceTestSymbol(tp); qual1 = coerce(qual1, primSym.owner().type()); return gen.Select(qual1, primSym); } else return copy.TypeApply(tree, transform(fun), tp.isSameAs(Type.UnboxedType(TypeTags.BOOLEAN)) ? args : transform(args)).setType(owntype); } else return transform(fun); case Apply(Tree fun, Tree[] args): Type isSelectorType = Type.NoType; Tree isQualTree = Tree.Empty; switch (fun) { case Select(Tree array, _): if (isUnboxedArray(array.type().erasure())) { switch (primitives.getPrimitive(fun.symbol())) { case LENGTH: return transformLength(tree); case APPLY: return transformApply(tree); case UPDATE: return transformUpdate(tree); } } break; case TypeApply(Tree poly, Tree[] targs): if (poly.symbol() == definitions.IS) { isSelectorType = targs[0].type.erasure(); if (isSelectorType.isSameAs(Type.UnboxedType(TypeTags.BOOLEAN))) isSelectorType = targs[0].type; isQualTree = poly; } } Tree fun1 = transform(fun); if (fun1.symbol() == definitions.NULL) return fun1.setType(owntype); if (global.debug) global.log("fn: " + fun1.symbol() + ":" + fun1.type);//debug switch (fun1.type) { case MethodType(Symbol[] params, Type restpe): assert params.length == args.length: "\nclass : " + Debug.show(currentClass) + "\ntree : " + tree + "\nfun1 : " + fun1 + "\nfun1.type: " + fun1.type; Tree[] args1 = args; for (int i = 0; i < args.length; i++) { Tree arg = args[i]; Type pt1 = params[i].type().erasure(); Tree arg1 = cast(transform(arg, pt1), pt1); if (arg1 != arg && args1 == args) { args1 = new Tree[args.length]; System.arraycopy(args, 0, args1, 0, i); } args1[i] = arg1; } Tree result = coerce(copy.Apply(tree, fun1, args1).setType(restpe), owntype); if (isUnboxed(isSelectorType) && !isUnboxedArray(isSelectorType)) { Symbol primSym = primitives.getInstanceTestSymbol(isSelectorType); Symbol ampAmpSym = definitions.BOOLEAN_AND(); result = make.Apply( result.pos, make.Select( result.pos, box( make.Apply( fun.pos, make.TypeApply( fun.pos, transform(isQualTree), new Tree[]{ gen.mkType(tree.pos, primSym.owner().type())} ).setType(Type.MethodType(Symbol.EMPTY_ARRAY, result.type)), Tree.EMPTY_ARRAY ).setType(result.type)), ampAmpSym.name ).setSymbol(ampAmpSym) .setType(ampAmpSym.type().erasure()), new Tree[]{result} ).setType(result.type); //new scalac.ast.printer.TextTreePrinter().print("IS: ").print(result).println().end();//debug } return result; default: global.debugPrinter.print(fun1); throw Debug.abort("bad method type: " + Debug.show(fun1.type) + " " + Debug.show(fun1.symbol())); } case Select(_, _): case Ident(_): Tree tree1 = transformLhs(tree); //global.log("id: " + tree1+": "+tree1.type+" -> "+owntype);//DEBUG return (tree1.type instanceof Type.MethodType) ? tree1 : coerce(tree1, owntype); case LabelDef(Name name, Tree.Ident[] params,Tree body): Tree.Ident[] new_params = new Tree.Ident[params.length]; for (int i = 0; i < params.length; i++) { new_params[i] = (Tree.Ident)gen.Ident(params[i].pos, params[i].symbol()); } return copy.LabelDef(tree, new_params, transform(body)).setType(owntype); case Empty: case PackageDef(_,_): case Template(_,_): case Sequence(_): // !!! ? [BE:was Tuple before] case Super(_, _): case This(_): case Literal(_): case TypeTerm(): return super.transform(tree).setType(owntype); case Bad(): case ModuleDef(_,_,_,_): case PatDef(_,_,_): case Import(_,_): case CaseDef(_,_,_): case Visitor(_): case Function(_,_): case SingletonType(_): case SelectFromType(_,_): case FunType(_,_): case CompoundType(_,_): case AppliedType(_, _): throw Debug.abort("illegal case", tree); default: throw Debug.abort("unknown case", tree); } } public Tree transform(Tree tree) { return transform(tree, false); } // !!! This is just rapid fix. Needs to be reviewed. private void addInterfaceBridges(Symbol owner) { Type[] parents = owner.info().parents(); for (int i = 1; i < parents.length; i++) addInterfaceBridgesRec(owner, parents[i].symbol()); } private void addInterfaceBridgesRec(Symbol owner, Symbol interfase) { addInterfaceBridgesAux(owner, interfase.nextInfo().members()); Type[] parents = interfase.parents(); for (int i = 0; i < parents.length; i++) { Symbol clasz = parents[i].symbol(); if (clasz.isInterface()) addInterfaceBridgesRec(owner, clasz); } } private void addInterfaceBridgesAux(Symbol owner, Scope symbols) { for (Scope.SymbolIterator i = symbols.iterator(true); i.hasNext();) { Symbol member = i.next(); if (!member.isTerm() || !member.isDeferred()) continue; addInterfaceBridges(owner, member); } } /** Transform without keeping the previous transform's contract. */ Tree transformLhs(Tree tree) { Tree tree1; switch (tree) { case Ident(Name name): if (name == Names.ZERO) tree1 = gen.mkNullLit(tree.pos); else tree1 = tree; break; case Select(Tree qual, _): Symbol sym = tree.symbol(); Tree qual1 = transform(qual); if (isUnboxed(qual1.type)) if (!isUnboxedArray(qual1.type) || sym == definitions.ARRAY_CLASS) qual1 = box(qual1); tree1 = copy.Select(tree, sym, qual1); break; default: throw Debug.abort("illegal case", tree); } if (global.debug) global.log("id: " + tree1.symbol() + ":" + tree1.symbol().type().erasure());//debug return tree1.setType(tree1.symbol().type().erasure()); } /** Transform with prototype */ Tree transform(Tree expr, Type pt) { return coerce(transform(expr), pt); } Tree[] transform(Tree[] exprs, Type pt) { for (int i = 0; i < exprs.length; i++) { Tree tree = transform(exprs[i], pt); if (tree == exprs[i]) continue; Tree[] trees = new Tree[exprs.length]; for (int j = 0; j < i ; j++) trees[j] = exprs[j]; trees[i] = tree; while (++i < exprs.length) trees[i] = transform(exprs[i], pt); return trees; } return exprs; } /** Transform an array length */ Tree transformLength(Tree tree) { switch (tree) { case Apply(Select(Tree array, _), Tree[] args): assert args.length == 0 : Debug.show(args); Type finalType = tree.type().erasure(); array = transform(array); Symbol symbol = primitives.getArrayLengthSymbol(array.type()); Tree method = gen.mkRef(tree.pos,primitives.RUNTIME_TYPE,symbol); args = new Tree[] { array }; return coerce(gen.Apply(tree.pos, method, args), finalType); default: throw Debug.abort("illegal case", tree); } } /** Transform an array apply */ Tree transformApply(Tree tree) { switch (tree) { case Apply(Select(Tree array, _), Tree[] args): assert args.length == 1 : Debug.show(args); Type finalType = tree.type().erasure(); array = transform(array); Symbol symbol = primitives.getArrayGetSymbol(array.type()); Tree method = gen.mkRef(tree.pos,primitives.RUNTIME_TYPE,symbol); args = new Tree[] { array, transform(args[0]) }; return coerce(gen.Apply(tree.pos, method, args), finalType); default: throw Debug.abort("illegal case", tree); } } /** Transform an array update */ Tree transformUpdate(Tree tree) { switch (tree) { case Apply(Select(Tree array, _), Tree[] args): assert args.length == 2 : Debug.show(args); array = transform(array); Symbol symbol = primitives.getArraySetSymbol(array.type()); Tree method = gen.mkRef(tree.pos,primitives.RUNTIME_TYPE,symbol); args = new Tree[] { array, transform(args[0]),transform(args[1]) }; return gen.Apply(tree.pos, method, args); default: throw Debug.abort("illegal case", tree); } } private Tree getQualifier(Symbol currentClass, Tree tree) { switch (tree) { case Select(Tree qual, _): return qual; case Ident(_): assert currentClass != null; if (currentClass.isSubClass(tree.symbol().owner())) return gen.This(tree.pos, currentClass); else throw Debug.abort("no qualifier for tree", tree); default: throw Debug.abort("no qualifier for tree", tree); } } private Tree genNewArray(int pos, Tree size, Type elemtp) { if (global.target == global.TARGET_INT) { global.nextPhase(); while (!elemtp.symbol().isJava()) elemtp = elemtp.parents()[0]; global.prevPhase(); } Tree classname = make.Literal(pos, primitives.getNameForClassForName(elemtp)) .setType(definitions.JAVA_STRING_TYPE); Tree array = gen.Apply(pos, gen.mkRef(pos, primitives.RUNTIME_TYPE, primitives.NEW_OARRAY), new Tree[] {size, classname}); Tree cast = gen.TypeApply(pos, gen.Select(pos, array, definitions.AS), new Tree[] {gen.mkType(pos, Type.UnboxedArrayType(elemtp))}); return gen.Apply(cast, new Tree[0]); } private Tree genNewArray(int pos, Tree size, int kind) { return gen.Apply(pos, gen.mkRef(pos, primitives.RUNTIME_TYPE, primitives.getNewArraySymbol(kind)), new Tree[] {size}); } }
sources/scalac/transformer/Erasure.java
/* ____ ____ ____ ____ ______ *\ ** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** ** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** ** /_____/\____/\___/\____/____/ ** \* */ // $OldId: Erasure.java,v 1.48 2003/01/16 14:21:19 schinz Exp $ // $Id$ package scalac.transformer; import java.util.HashMap; import scalac.Global; import scalac.Unit; import scalac.ast.Tree; import scalac.ast.Tree.Template; import scalac.ast.Tree.AbsTypeDef; import scalac.ast.Tree.AliasTypeDef; import scalac.ast.Tree.ValDef; import scalac.ast.TreeList; import scalac.ast.Transformer; import scalac.symtab.Definitions; import scalac.symtab.Kinds; import scalac.symtab.Type; import scalac.symtab.TypeTags; import scalac.symtab.Modifiers; import scalac.symtab.Scope; import scalac.symtab.SymSet; import scalac.symtab.Symbol; import scalac.backend.Primitives; import scalac.util.Name; import scalac.util.Names; import scalac.util.Debug; /** A transformer for type erasure and bridge building * * @author Martin Odersky * @version 1.0 * * What it does: * (1) Map every type to its erasure. * (2) If method A overrides a method B, and the erased type ETA of A is * different from the erased type ETB of B seen as a member of A's class, * add a bridge method with the same name as A,B, with signature ETB * which calls A after casting parameters. */ public class Erasure extends Transformer implements Modifiers { private final Definitions definitions; private final Primitives primitives; private Unit unit; public Erasure(Global global) { super(global); this.definitions = global.definitions; this.primitives = global.primitives; } public void apply(Unit unit) { this.unit = unit; unit.body = transform(unit.body); } ////////////////////////////////////////////////////////////////////////////////// // Box/Unbox and Coercions ///////////////////////////////////////////////////////////////////////////////// boolean isUnboxed(Type type) { switch (type) { case UnboxedType(_): case UnboxedArrayType(_): return true; default: return false; } } boolean isUnboxedArray(Type type) { switch (type) { case UnboxedArrayType(_): return true; default: return false; } } boolean isBoxed(Type type) { return type.unbox() != type || type.symbol().fullName() == Names.scala_Array; } Type boxedType(Type tp) { switch (tp) { case UnboxedType(int kind): return definitions.getType(Type.boxedFullName(kind)); case UnboxedArrayType(Type elemtp): return definitions.arrayType(boxedType(elemtp)); default: return tp; } } Symbol boxSym(Type unboxedtp) { return primitives.getBoxValueSymbol(unboxedtp); } /** Emit `scala.RunTime.box(tree)' or * `{ tree ; scala.RunTime.box() }' if type of `tree' is `void'. */ Tree box(Tree tree) { Tree boxtree = gen.mkRef(tree.pos, primitives.RUNTIME_TYPE, boxSym(tree.type)); switch (tree.type) { case UnboxedType(int kind): if (kind == TypeTags.UNIT) return gen.Block( tree.pos, new Tree[]{tree, gen.Apply(boxtree, new Tree[0])}); } return gen.Apply(boxtree, new Tree[]{tree}); } /** The symbol of the unbox method corresponding to unboxed type`unboxedtp' */ Symbol unboxSym(Type unboxedtp) { return primitives.getUnboxValueSymbol(unboxedtp); } /** Emit tree.asType() or tree.asTypeArray(), where pt = Type or pt = Type[]. */ Tree unbox(Tree tree, Type pt) { Tree sel = gen.Select(tree, unboxSym(pt)); return gen.Apply(sel, new Tree[0]); } /** Generate a select from an unboxed type. */ public Tree unboxedSelect(Tree qual, Symbol sym) { return make.Select(qual.pos, qual, sym.name) .setSymbol(sym) .setType(Type.singleType(boxedType(qual.type).symbol().thisType(),sym).erasure()); } /** Subclass relation for class types; empty for other types. */ boolean isSubClass(Type tp1, Type tp2) { Symbol sym1 = tp1.symbol(); Symbol sym2 = tp2.symbol(); return sym1 != null && sym2 != null && sym1.isSubClass(sym2); } /** Subtyping relation on erased types. */ boolean isSubType(Type tp1, Type tp2) { if (isSameAs(tp1, tp2)) return true; switch (tp2) { case UnboxedType(_): return tp1.isSubType(tp2); case UnboxedArrayType(Type elemtp2): switch (tp1) { case UnboxedArrayType(Type elemtp1): return !(elemtp1 instanceof Type.UnboxedType) && isSubType(elemtp1, elemtp2); default: return tp1.isSubType(tp2); } } switch (tp1) { case UnboxedArrayType(Type elemtp1): if (tp2.symbol() == definitions.ANY_CLASS) return true; } return isSubClass(tp1, tp2); } /** Equality relation on erased types. */ boolean isSameAs(Type tp1, Type tp2) { global.nextPhase(); boolean result = tp1.isSameAs(tp2); global.prevPhase(); return result; } Tree coerce(Tree tree, Type pt) { return isSubType(tree.type, pt) ? tree : cast(tree, pt); } Tree cast(Tree tree, Type pt) { if (global.debug) global.log("cast " + tree + ":" + tree.type + " to " + pt);//debug if (isSameAs(tree.type, pt)) { return tree; } else if (isSubType(tree.type, pt)) { return tree; } else if (isUnboxed(tree.type) && !isUnboxed(pt)) { return cast(box(tree), pt); } else if ((isUnboxedArray(tree.type) || (tree.type.symbol() == definitions.ANY_CLASS)) && isUnboxedArray(pt)) { return make.Apply(tree.pos, make.TypeApply(tree.pos, unboxedSelect(tree, definitions.AS), new Tree[]{gen.mkType(tree.pos, pt)}) .setType(new Type.MethodType(Symbol.EMPTY_ARRAY, pt)), new Tree[0]) .setType(pt); } else if (!isUnboxed(tree.type) && isUnboxed(pt)) { if (isBoxed(tree.type)) { return coerce(unbox(tree, pt), pt); } else { Type bt = boxedType(pt); while (isBoxed(bt.parents()[0])) { bt = bt.parents()[0]; } return cast(coerce(tree, bt), pt); } } else if (isUnboxed(tree.type) && isUnboxed(pt)) { return gen.Apply( unboxedSelect(box(tree), unboxSym(pt)), new Tree[0]); } else if (!isUnboxed(tree.type) && !isUnboxed(pt) || isUnboxedArray(tree.type) && isUnboxedArray(pt)) { return gen.Apply( gen.TypeApply( gen.Select(tree, definitions.AS), new Tree[]{gen.mkType(tree.pos, pt)}), new Tree[0]); } else { throw Debug.abort("cannot cast " + tree.type + " to " + pt); } } ////////////////////////////////////////////////////////////////////////////////// // Bridge Building ///////////////////////////////////////////////////////////////////////////////// private TreeList bridges; private HashMap bridgeSyms; /** Add bridge which Java-overrides `sym1' and which forwards to `sym' */ public void addBridge(Symbol owner, Symbol sym, Symbol sym1) { Type bridgeType = sym1.type().erasure(); // create bridge symbol and add to bridgeSyms(sym) // or return if bridge with required type already exists for sym. SymSet bridgesOfSym = (SymSet) bridgeSyms.get(sym); if (bridgesOfSym == null) bridgesOfSym = SymSet.EMPTY; Symbol[] brs = bridgesOfSym.toArray(); for (int i = 0; i < brs.length; i++) { if (isSameAs(brs[i].type(), bridgeType)) return; } Symbol bridgeSym = sym.cloneSymbol(); bridgeSym.flags |= (SYNTHETIC | BRIDGE); bridgeSym.flags &= ~(JAVA | DEFERRED); bridgesOfSym = bridgesOfSym.incl(bridgeSym); bridgeSyms.put(sym, bridgesOfSym); bridgeSym.setOwner(owner); // check that there is no overloaded symbol with same erasure as bridge // todo: why only check for overloaded? Symbol overSym = owner.members().lookup(sym.name); switch (overSym.type()) { case OverloadedType(Symbol[] alts, Type[] alttypes): for (int i = 0; i < alts.length; i++) { if (sym != alts[i] && isSameAs(bridgeType, alttypes[i].erasure())) { unit.error(sym.pos, "overlapping overloaded alternatives; " + "overridden " + sym1 + sym1.locationString() + " has same erasure as " + alts[i] + alttypes[i] + alts[i].locationString()); } } } switch (bridgeType) { case MethodType(Symbol[] params, Type restp): // assign to bridge symbol its bridge type // where owner of all parameters is bridge symbol itself. Symbol[] params1 = new Symbol[params.length]; for (int i = 0; i < params.length; i++) { params1[i] = params[i].cloneSymbol(bridgeSym); } bridgeSym.setType(Type.MethodType(params1, restp)); // create bridge definition Type symtype = sym.type().erasure(); switch (symtype) { case MethodType(Symbol[] symparams, Type symrestp): assert params1.length == symparams.length; Tree[] args = new Tree[params1.length]; for (int i = 0; i < args.length; i++) { args[i] = cast(gen.Ident(sym.pos, params1[i]), symparams[i].type().erasure()); } Tree fwd = make.Apply(sym.pos, gen.Ident(sym.pos, sym).setType(symtype), args) .setType(symrestp); bridges.append(gen.DefDef(bridgeSym, coerce(fwd, restp))); return; } } throw Debug.abort("bad bridge types " + bridgeType + "," + sym.type().erasure()); } public void addBridges(Symbol sym) { Symbol c = sym.owner(); if (c.isClass() && !c.isInterface()) { //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " : " + sym.type().erasure() + " @ " + Debug.show(c)); global.prevPhase(); Type[] basetypes = c.parents(); for (int i = 0; i < basetypes.length; i++) { addBridges(basetypes[i], sym); } } } public void addBridges(Type basetype, Symbol sym) { Symbol sym1 = sym.overriddenSymbol(basetype); //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " @ " + basetype + " -> " + Debug.show(sym1) + (sym1.kind == Kinds.NONE ? "" : " : " + sym1.type().erasure() + " => " + (isSameAs(sym1.type().erasure(), sym.type().erasure()) ? "ok" : "ADD BRIDGE"))); global.prevPhase(); if (sym1.kind != Kinds.NONE && !isSameAs(sym1.type().erasure(), sym.type().erasure())) { //System.out.println("!!! " + Debug.show(sym) + " adding bridge for " + Debug.show(sym1)); addBridge(sym.owner(), sym, sym1); } } public void addInterfaceBridges(Symbol c, Symbol sym) { assert c.isClass() && !c.isInterface(): Debug.show(c); //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " : " + sym.type().erasure() + " @ " + Debug.show(c)); global.prevPhase(); Symbol member = sym; // !!! create a clone to make overriddenSymbol return the right symbol Symbol clone = sym.cloneSymbol(); clone.setOwner(c); clone.setType(c.thisType().memberType(sym)); sym = clone; //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " : " + sym.type().erasure() + " @ " + Debug.show(c)); global.prevPhase(); Type basetype = c.thisType(); Symbol sym1 = sym.overriddenSymbol(basetype); sym = member; //global.nextPhase(); System.out.println("!!! " + Debug.show(sym) + " @ " + basetype + " -> " + Debug.show(sym1) + (sym1.kind == Kinds.NONE ? "" : " : " + sym1.type().erasure() + " => " + (isSameAs(sym1.type().erasure(), sym.type().erasure()) ? "ok" : "ADD BRIDGE"))); global.prevPhase(); if (sym1.kind != Kinds.NONE && !isSameAs(sym1.type().erasure(), sym.type().erasure())) { //System.out.println("!!! " + Debug.show(sym) + " adding bridge for " + Debug.show(sym1)); addBridge(c, sym1, member); } } ////////////////////////////////////////////////////////////////////////////////// // Transformer ///////////////////////////////////////////////////////////////////////////////// /** Contract: every node needs to be transformed so that it's type is the * erasure of the node's original type. The only exception are functions; * these are mapped to the erasure of the function symbol's type. */ Symbol currentClass = null; public Tree transform(Tree tree, boolean eraseFully) { assert tree.type != null : tree; Type owntype = eraseFully ? tree.type.fullErasure() : tree.type.erasure(); switch (tree) { case ClassDef(_, _, AbsTypeDef[] tparams, ValDef[][] vparams, Tree tpe, Template impl): Symbol oldCurrentClass = currentClass; currentClass = tree.symbol(); Tree newTree = copy.ClassDef(tree, new AbsTypeDef[0], transform(vparams), tpe, transform(impl, tree.symbol())) .setType(owntype); currentClass = oldCurrentClass; return newTree; case DefDef(_, _, AbsTypeDef[] tparams, ValDef[][] vparams, Tree tpe, Tree rhs): addBridges(tree.symbol()); Tree tpe1 = gen.mkType(tpe.pos, tpe.type.fullErasure()); Tree rhs1 = (rhs == Tree.Empty) ? rhs : transform(rhs, tpe1.type); return copy.DefDef( tree, new AbsTypeDef[0], transform(vparams), tpe1, rhs1) .setType(owntype); case ValDef(_, _, Tree tpe, Tree rhs): Tree tpe1 = transform(tpe); Tree rhs1 = (rhs == Tree.Empty) ? rhs : transform(rhs, tpe1.type); return copy.ValDef(tree, tpe1, rhs1).setType(owntype); case AbsTypeDef(_, _, _, _): case AliasTypeDef(_, _, _, _): // eliminate return Tree.Empty; case Block(Tree[] stats): Tree[] newStats = new Tree[stats.length]; for (int i = 0; i < stats.length; ++i) newStats[i] = transform(stats[i], true); return copy.Block(tree, newStats).setType(owntype.fullErasure()); case Assign(Tree lhs, Tree rhs): Tree lhs1 = transformLhs(lhs); Tree rhs1 = transform(rhs, lhs1.type); return copy.Assign(tree, lhs1, rhs1).setType(owntype.fullErasure()); case If(Tree cond, Tree thenp, Tree elsep): Tree cond1 = transform(cond, Type.unboxedType(TypeTags.BOOLEAN)); Tree thenp1 = transform(thenp, owntype); Tree elsep1 = (elsep == Tree.Empty) ? elsep : transform(elsep, owntype); return copy.If(tree, cond1, thenp1, elsep1).setType(owntype); case Switch(Tree test, int[] tags, Tree[] bodies, Tree otherwise): Tree test1 = transform(test, Type.unboxedType(TypeTags.INT)); Tree[] bodies1 = transform(bodies, owntype); Tree otherwise1 = transform(otherwise, owntype); return copy.Switch(tree, test1, tags, bodies1, otherwise1).setType(owntype); case Return(Tree expr): Tree expr1 = transform(expr, tree.symbol().type().resultType().fullErasure()); Tree zero = gen.Ident(tree.pos, definitions.NULL); return make.Block(tree.pos, new Tree[] { copy.Return(tree, expr1).setType(owntype), zero}).setType(zero.type()); case New(Template templ): if (tree.type.symbol() == definitions.UNIT_CLASS) // !!! return Tree.Literal(UNIT, null).setType(owntype); throw Debug.abort("found unit literal in " + currentClass); if (tree.type.symbol() == definitions.ARRAY_CLASS) { switch (templ.parents[0]) { case Apply(_, Tree[] args): args = transform(args); switch (owntype) { case UnboxedArrayType(Type elemtp): switch (elemtp) { case UnboxedType(int kind): return genNewArray(tree.pos,args[0],kind); default: return genNewArray(tree.pos,args[0],elemtp); } default: throw Debug.abort("illegal case", owntype); } default: throw Debug.abort("illegal case", templ.parents[0]); } } return super.transform(tree).setType(owntype); case Typed(Tree expr, Tree tpe): // coerce expr to tpe Tree tpe1 = gen.mkType(tpe.pos, tpe.type().erasure()); // !!! was transform(tpe); // !!! More generally, we should never transform a tree // that represents a type. We should always transform // types and then reconstruct the corresponding tree. return transform(expr, tpe1.type); case TypeApply(Tree fun, Tree[] args): Symbol sym = fun.symbol(); if (sym == definitions.AS || sym == definitions.IS) { Type tp = args[0].type.erasure(); if (isUnboxed(tp) && (sym != definitions.IS || (!isUnboxedArray(tp) && !tp.isSameAs(Type.UnboxedType(TypeTags.BOOLEAN))))) { Tree qual1 = transform(getQualifier(currentClass, fun)); if (isUnboxed(qual1.type)) qual1 = box(qual1); Symbol primSym = (sym == definitions.AS) ? primitives.getUnboxValueSymbol(tp) : primitives.getInstanceTestSymbol(tp); qual1 = coerce(qual1, primSym.owner().type()); return gen.Select(qual1, primSym); } else return copy.TypeApply(tree, transform(fun), tp.isSameAs(Type.UnboxedType(TypeTags.BOOLEAN)) ? args : transform(args)).setType(owntype); } else return transform(fun); case Apply(Tree fun, Tree[] args): Type isSelectorType = Type.NoType; Tree isQualTree = Tree.Empty; switch (fun) { case Select(Tree array, _): if (isUnboxedArray(array.type().erasure())) { switch (primitives.getPrimitive(fun.symbol())) { case LENGTH: return transformLength(tree); case APPLY: return transformApply(tree); case UPDATE: return transformUpdate(tree); } } break; case TypeApply(Tree poly, Tree[] targs): if (poly.symbol() == definitions.IS) { isSelectorType = targs[0].type.erasure(); if (isSelectorType.isSameAs(Type.UnboxedType(TypeTags.BOOLEAN))) isSelectorType = targs[0].type; isQualTree = poly; } } Tree fun1 = transform(fun); if (fun1.symbol() == definitions.NULL) return fun1.setType(owntype); if (global.debug) global.log("fn: " + fun1.symbol() + ":" + fun1.type);//debug switch (fun1.type) { case MethodType(Symbol[] params, Type restpe): assert params.length == args.length: "\nclass : " + Debug.show(currentClass) + "\ntree : " + tree + "\nfun1 : " + fun1 + "\nfun1.type: " + fun1.type; Tree[] args1 = args; for (int i = 0; i < args.length; i++) { Tree arg = args[i]; Type pt1 = params[i].type().erasure(); Tree arg1 = cast(transform(arg, pt1), pt1); if (arg1 != arg && args1 == args) { args1 = new Tree[args.length]; System.arraycopy(args, 0, args1, 0, i); } args1[i] = arg1; } Tree result = coerce(copy.Apply(tree, fun1, args1).setType(restpe), owntype); if (isUnboxed(isSelectorType) && !isUnboxedArray(isSelectorType)) { Symbol primSym = primitives.getInstanceTestSymbol(isSelectorType); Symbol ampAmpSym = definitions.BOOLEAN_AND(); result = make.Apply( result.pos, make.Select( result.pos, box( make.Apply( fun.pos, make.TypeApply( fun.pos, transform(isQualTree), new Tree[]{ gen.mkType(tree.pos, primSym.owner().type())} ).setType(Type.MethodType(Symbol.EMPTY_ARRAY, result.type)), Tree.EMPTY_ARRAY ).setType(result.type)), ampAmpSym.name ).setSymbol(ampAmpSym) .setType(ampAmpSym.type().erasure()), new Tree[]{result} ).setType(result.type); //new scalac.ast.printer.TextTreePrinter().print("IS: ").print(result).println().end();//debug } return result; default: global.debugPrinter.print(fun1); throw Debug.abort("bad method type: " + Debug.show(fun1.type) + " " + Debug.show(fun1.symbol())); } case Select(_, _): case Ident(_): Tree tree1 = transformLhs(tree); //global.log("id: " + tree1+": "+tree1.type+" -> "+owntype);//DEBUG return (tree1.type instanceof Type.MethodType) ? tree1 : coerce(tree1, owntype); case LabelDef(Name name, Tree.Ident[] params,Tree body): Tree.Ident[] new_params = new Tree.Ident[params.length]; for (int i = 0; i < params.length; i++) { new_params[i] = (Tree.Ident)gen.Ident(params[i].pos, params[i].symbol()); } return copy.LabelDef(tree, new_params, transform(body)).setType(owntype); case Empty: case PackageDef(_,_): case Template(_,_): case Sequence(_): // !!! ? [BE:was Tuple before] case Super(_, _): case This(_): case Literal(_): case TypeTerm(): return super.transform(tree).setType(owntype); case Bad(): case ModuleDef(_,_,_,_): case PatDef(_,_,_): case Import(_,_): case CaseDef(_,_,_): case Visitor(_): case Function(_,_): case SingletonType(_): case SelectFromType(_,_): case FunType(_,_): case CompoundType(_,_): case AppliedType(_, _): throw Debug.abort("illegal case", tree); default: throw Debug.abort("unknown case", tree); } } public Tree transform(Tree tree) { return transform(tree, false); } public Template transform(Template templ, Symbol clazz) { TreeList savedBridges = bridges; HashMap savedBridgeSyms = bridgeSyms; bridges = new TreeList(); bridgeSyms = new HashMap(); Tree[] bases1 = transform(templ.parents); TreeList body1 = new TreeList(transform(templ.body)); if (!clazz.isInterface()) addInterfaceBridges(clazz); body1.append(bridges); if (bridges.length() > 0) { Type info = clazz.nextInfo(); switch (info) { case CompoundType(Type[] parts, Scope members): members = new Scope(members); for (int i = 0; i < bridges.length(); i++) { Tree bridge = (Tree)bridges.get(i); members.enterOrOverload(bridge.symbol()); } clazz.updateInfo(Type.compoundType(parts, members, info.symbol())); break; default: throw Debug.abort("class = " + Debug.show(clazz) + ", " + "info = " + Debug.show(info)); } } bridges = savedBridges; bridgeSyms = savedBridgeSyms; return (Template) copy.Template(templ, bases1, body1.toArray()) .setType(templ.type.erasure()); } // !!! This is just rapid fix. Needs to be reviewed. private void addInterfaceBridges(Symbol owner) { Type[] parents = owner.info().parents(); for (int i = 1; i < parents.length; i++) addInterfaceBridgesRec(owner, parents[i].symbol()); } private void addInterfaceBridgesRec(Symbol owner, Symbol interfase) { addInterfaceBridgesAux(owner, interfase.nextInfo().members()); Type[] parents = interfase.parents(); for (int i = 0; i < parents.length; i++) { Symbol clasz = parents[i].symbol(); if (clasz.isInterface()) addInterfaceBridgesRec(owner, clasz); } } private void addInterfaceBridgesAux(Symbol owner, Scope symbols) { for (Scope.SymbolIterator i = symbols.iterator(true); i.hasNext();) { Symbol member = i.next(); if (!member.isTerm() || !member.isDeferred()) continue; addInterfaceBridges(owner, member); } } /** Transform without keeping the previous transform's contract. */ Tree transformLhs(Tree tree) { Tree tree1; switch (tree) { case Ident(Name name): if (name == Names.ZERO) tree1 = gen.mkNullLit(tree.pos); else tree1 = tree; break; case Select(Tree qual, _): Symbol sym = tree.symbol(); Tree qual1 = transform(qual); if (isUnboxed(qual1.type)) if (!isUnboxedArray(qual1.type) || sym == definitions.ARRAY_CLASS) qual1 = box(qual1); tree1 = copy.Select(tree, sym, qual1); break; default: throw Debug.abort("illegal case", tree); } if (global.debug) global.log("id: " + tree1.symbol() + ":" + tree1.symbol().type().erasure());//debug return tree1.setType(tree1.symbol().type().erasure()); } /** Transform with prototype */ Tree transform(Tree expr, Type pt) { return coerce(transform(expr), pt); } Tree[] transform(Tree[] exprs, Type pt) { for (int i = 0; i < exprs.length; i++) { Tree tree = transform(exprs[i], pt); if (tree == exprs[i]) continue; Tree[] trees = new Tree[exprs.length]; for (int j = 0; j < i ; j++) trees[j] = exprs[j]; trees[i] = tree; while (++i < exprs.length) trees[i] = transform(exprs[i], pt); return trees; } return exprs; } /** Transform an array length */ Tree transformLength(Tree tree) { switch (tree) { case Apply(Select(Tree array, _), Tree[] args): assert args.length == 0 : Debug.show(args); Type finalType = tree.type().erasure(); array = transform(array); Symbol symbol = primitives.getArrayLengthSymbol(array.type()); Tree method = gen.mkRef(tree.pos,primitives.RUNTIME_TYPE,symbol); args = new Tree[] { array }; return coerce(gen.Apply(tree.pos, method, args), finalType); default: throw Debug.abort("illegal case", tree); } } /** Transform an array apply */ Tree transformApply(Tree tree) { switch (tree) { case Apply(Select(Tree array, _), Tree[] args): assert args.length == 1 : Debug.show(args); Type finalType = tree.type().erasure(); array = transform(array); Symbol symbol = primitives.getArrayGetSymbol(array.type()); Tree method = gen.mkRef(tree.pos,primitives.RUNTIME_TYPE,symbol); args = new Tree[] { array, transform(args[0]) }; return coerce(gen.Apply(tree.pos, method, args), finalType); default: throw Debug.abort("illegal case", tree); } } /** Transform an array update */ Tree transformUpdate(Tree tree) { switch (tree) { case Apply(Select(Tree array, _), Tree[] args): assert args.length == 2 : Debug.show(args); array = transform(array); Symbol symbol = primitives.getArraySetSymbol(array.type()); Tree method = gen.mkRef(tree.pos,primitives.RUNTIME_TYPE,symbol); args = new Tree[] { array, transform(args[0]),transform(args[1]) }; return gen.Apply(tree.pos, method, args); default: throw Debug.abort("illegal case", tree); } } private Tree getQualifier(Symbol currentClass, Tree tree) { switch (tree) { case Select(Tree qual, _): return qual; case Ident(_): assert currentClass != null; if (currentClass.isSubClass(tree.symbol().owner())) return gen.This(tree.pos, currentClass); else throw Debug.abort("no qualifier for tree", tree); default: throw Debug.abort("no qualifier for tree", tree); } } private Tree genNewArray(int pos, Tree size, Type elemtp) { if (global.target == global.TARGET_INT) { global.nextPhase(); while (!elemtp.symbol().isJava()) elemtp = elemtp.parents()[0]; global.prevPhase(); } Tree classname = make.Literal(pos, primitives.getNameForClassForName(elemtp)) .setType(definitions.JAVA_STRING_TYPE); Tree array = gen.Apply(pos, gen.mkRef(pos, primitives.RUNTIME_TYPE, primitives.NEW_OARRAY), new Tree[] {size, classname}); Tree cast = gen.TypeApply(pos, gen.Select(pos, array, definitions.AS), new Tree[] {gen.mkType(pos, Type.UnboxedArrayType(elemtp))}); return gen.Apply(cast, new Tree[0]); } private Tree genNewArray(int pos, Tree size, int kind) { return gen.Apply(pos, gen.mkRef(pos, primitives.RUNTIME_TYPE, primitives.getNewArraySymbol(kind)), new Tree[] {size}); } }
- Cleaned
sources/scalac/transformer/Erasure.java
- Cleaned
<ide><path>ources/scalac/transformer/Erasure.java <ide> assert tree.type != null : tree; <ide> Type owntype = eraseFully ? tree.type.fullErasure() : tree.type.erasure(); <ide> switch (tree) { <del> case ClassDef(_, _, AbsTypeDef[] tparams, ValDef[][] vparams, Tree tpe, Template impl): <add> case ClassDef(_, _, _, _, _, Template(_, Tree[] body)): <ide> Symbol oldCurrentClass = currentClass; <del> currentClass = tree.symbol(); <del> Tree newTree = <del> copy.ClassDef(tree, new AbsTypeDef[0], <del> transform(vparams), tpe, transform(impl, tree.symbol())) <del> .setType(owntype); <add> TreeList savedBridges = bridges; <add> HashMap savedBridgeSyms = bridgeSyms; <add> Symbol clazz = currentClass = tree.symbol(); <add> bridges = new TreeList(); <add> bridgeSyms = new HashMap(); <add> <add> TreeList body1 = new TreeList(transform(body)); <add> if (!clazz.isInterface()) addInterfaceBridges(clazz); <add> body1.append(bridges); <add> if (bridges.length() > 0) { <add> Type info = clazz.nextInfo(); <add> switch (info) { <add> case CompoundType(Type[] parts, Scope members): <add> members = new Scope(members); <add> for (int i = 0; i < bridges.length(); i++) { <add> Tree bridge = (Tree)bridges.get(i); <add> members.enterOrOverload(bridge.symbol()); <add> } <add> clazz.updateInfo(Type.compoundType(parts, members, info.symbol())); <add> break; <add> default: <add> throw Debug.abort("class = " + Debug.show(clazz) + ", " + <add> "info = " + Debug.show(info)); <add> } <add> } <add> Tree newTree = gen.ClassDef(clazz, body1.toArray()); <add> <add> bridgeSyms = savedBridgeSyms; <add> bridges = savedBridges; <ide> currentClass = oldCurrentClass; <ide> return newTree; <ide> <del> case DefDef(_, _, AbsTypeDef[] tparams, ValDef[][] vparams, Tree tpe, Tree rhs): <del> addBridges(tree.symbol()); <del> Tree tpe1 = gen.mkType(tpe.pos, tpe.type.fullErasure()); <del> Tree rhs1 = (rhs == Tree.Empty) ? rhs : transform(rhs, tpe1.type); <del> return copy.DefDef( <del> tree, new AbsTypeDef[0], transform(vparams), tpe1, rhs1) <del> .setType(owntype); <del> <del> case ValDef(_, _, Tree tpe, Tree rhs): <del> Tree tpe1 = transform(tpe); <del> Tree rhs1 = (rhs == Tree.Empty) ? rhs : transform(rhs, tpe1.type); <del> return copy.ValDef(tree, tpe1, rhs1).setType(owntype); <add> case DefDef(_, _, _, _, _, Tree rhs): <add> Symbol method = tree.symbol(); <add> addBridges(method); <add> if (rhs != Tree.Empty) <add> rhs = transform(rhs, method.nextType().resultType()); <add> return gen.DefDef(method, rhs); <add> <add> case ValDef(_, _, _, Tree rhs): <add> Symbol field = tree.symbol(); <add> if (rhs != Tree.Empty) rhs = transform(rhs, field.nextType()); <add> return gen.ValDef(field, rhs); <ide> <ide> case AbsTypeDef(_, _, _, _): <ide> case AliasTypeDef(_, _, _, _): <ide> Tree[] newStats = new Tree[stats.length]; <ide> for (int i = 0; i < stats.length; ++i) <ide> newStats[i] = transform(stats[i], true); <del> return copy.Block(tree, newStats).setType(owntype.fullErasure()); <add> return gen.Block(tree.pos, newStats); <ide> <ide> case Assign(Tree lhs, Tree rhs): <ide> Tree lhs1 = transformLhs(lhs); <ide> return transform(tree, false); <ide> } <ide> <del> public Template transform(Template templ, Symbol clazz) { <del> TreeList savedBridges = bridges; <del> HashMap savedBridgeSyms = bridgeSyms; <del> bridges = new TreeList(); <del> bridgeSyms = new HashMap(); <del> Tree[] bases1 = transform(templ.parents); <del> TreeList body1 = new TreeList(transform(templ.body)); <del> if (!clazz.isInterface()) addInterfaceBridges(clazz); <del> body1.append(bridges); <del> if (bridges.length() > 0) { <del> Type info = clazz.nextInfo(); <del> switch (info) { <del> case CompoundType(Type[] parts, Scope members): <del> members = new Scope(members); <del> for (int i = 0; i < bridges.length(); i++) { <del> Tree bridge = (Tree)bridges.get(i); <del> members.enterOrOverload(bridge.symbol()); <del> } <del> clazz.updateInfo(Type.compoundType(parts, members, info.symbol())); <del> break; <del> default: <del> throw Debug.abort("class = " + Debug.show(clazz) + ", " + <del> "info = " + Debug.show(info)); <del> } <del> } <del> bridges = savedBridges; <del> bridgeSyms = savedBridgeSyms; <del> return (Template) copy.Template(templ, bases1, body1.toArray()) <del> .setType(templ.type.erasure()); <del> } <del> <ide> // !!! This is just rapid fix. Needs to be reviewed. <ide> private void addInterfaceBridges(Symbol owner) { <ide> Type[] parents = owner.info().parents();
JavaScript
mit
4a3a7357f22ef96abba37cb496a509b74e82922f
0
FormidableLabs/victory-chart,GreenGremlin/victory-chart,FormidableLabs/victory-chart,GreenGremlin/victory-chart
import React from "react"; import { VictoryContainer, Selection, PropTypes as CustomPropTypes, Domain } from "victory-core"; import Helpers from "./container-helper-methods"; import { isFunction, isEqual } from "lodash"; export default class VictoryRangeContainer extends VictoryContainer { static displayName = "VictoryRangeContainer"; static propTypes = { ...VictoryContainer.propTypes, selectionStyle: React.PropTypes.object, dimension: React.PropTypes.oneOf(["x", "y"]), selectedDomain: React.PropTypes.shape({ x: React.PropTypes.array, y: React.PropTypes.array }), onDomainChange: React.PropTypes.func, handleWidth: React.PropTypes.number }; static defaultProps = { ...VictoryContainer.defaultProps, selectionStyle: { stroke: "black", fill: "black", fillOpacity: 0.2 }, dimension: "x", handleWidth: 5 }; static defaultEvents = [{ target: "parent", eventHandlers: { onMouseDown: (evt, targetProps) => { evt.preventDefault(); const { dimension, scale, selectedDomain } = targetProps; const fullDomain = targetProps.fullDomain || Helpers.getOriginalDomain(scale); const fullDomainBox = targetProps.fullDomainBox || Helpers.getDomainBox(targetProps, fullDomain); const {x, y} = Selection.getSVGEventCoordinates(evt); if (!Helpers.withinBounds({x, y}, fullDomainBox)) { return {}; } const domainBox = Helpers.getDomainBox(targetProps, fullDomain, selectedDomain); const {x1, y1, x2, y2} = domainBox; if (!selectedDomain || isEqual(selectedDomain, fullDomain)) { return [{ target: "parent", mutation: () => { return { isSelecting: true, selectedDomain, domainBox, fullDomainBox, x1: dimension !== "y" ? x : x1, y1: dimension !== "x" ? y : y1, x2: dimension !== "y" ? x : x2, y2: dimension !== "x" ? y : y2 }; } }]; } const handles = Helpers.getHandles(targetProps, domainBox); if (Helpers.withinBounds({x, y}, handles.left)) { return [{ target: "parent", mutation: () => { return { isSelecting: true, selectedDomain, domainBox, fullDomainBox, x1: Math.max(x1, x2), x2: Math.min(x1, x2) }; } }]; } else if (Helpers.withinBounds({x, y}, handles.right)) { return [{ target: "parent", mutation: () => { return { isSelecting: true, selectedDomain, domainBox, fullDomainBox, x1: Math.min(x1, x2), x2: Math.max(x1, x2) }; } }]; } else if (Helpers.withinBounds({x, y}, domainBox)) { return [{ target: "parent", mutation: () => ({ isPanning: true, startX: x, startY: y, selectedDomain, domainBox, fullDomainBox }) }]; } else { return [{ target: "parent", mutation: () => { return { isSelecting: true, selectedDomain, domainBox, fullDomainBox, x1: dimension !== "y" ? x : x1, y1: dimension !== "x" ? y : y1, x2: dimension !== "y" ? x : x2, y2: dimension !== "x" ? y : y2 }; } }]; } }, onMouseMove: (evt, targetProps) => { if (!targetProps.isPanning && !targetProps.isSelecting) { return {}; } const { dimension, scale, isPanning, isSelecting, startX, startY, fullDomainBox } = targetProps; const {x, y} = Selection.getSVGEventCoordinates(evt); if (!Helpers.withinBounds({x, y}, fullDomainBox)) { return {}; } if (isPanning) { const delta = { x: startX ? startX - x : 0, y: startY ? startY - y : 0 }; const x1 = dimension !== "y" ? targetProps.x1 - delta.x : targetProps.x1; const x2 = dimension !== "y" ? targetProps.x2 - delta.x : targetProps.x2; const y1 = dimension !== "x" ? targetProps.y1 - delta.y : targetProps.y1; const y2 = dimension !== "x" ? targetProps.y2 - delta.y : targetProps.y2; const constrainedDimensions = { x1: x2 > fullDomainBox.x2 ? fullDomainBox.x2 - Math.abs(x2 - x1) : Math.max(x1, fullDomainBox.x1), y1: y2 > fullDomainBox.y2 ? fullDomainBox.y2 - Math.abs(y2 - y1) : Math.max(y1, fullDomainBox.y1), x2: x1 < fullDomainBox.x1 ? fullDomainBox.x1 + Math.abs(x2 - x1) : Math.min(x2, fullDomainBox.x2), y2: y1 < fullDomainBox.y1 ? fullDomainBox.y1 + Math.abs(y2 - y1) : Math.min(y2, fullDomainBox.y2) }; const selectedDomain = Selection.getBounds({...constrainedDimensions, scale}); return [{ target: "parent", mutation: () => { return { selectedDomain, startX: x2 >= fullDomainBox.x2 || x1 <= fullDomainBox.x1 ? startX : x, startY: y2 >= fullDomainBox.y2 || y1 <= fullDomainBox.y1 ? startY : y, ...constrainedDimensions }; } }]; } else if (isSelecting) { const x2 = dimension !== "y" ? x : targetProps.x2; const y2 = dimension !== "x" ? y : targetProps.y2; const selectedDomain = Selection.getBounds({x2, y2, x1: targetProps.x1, y1: targetProps.y1, scale}); return [{ target: "parent", mutation: () => { return { x2, y2, selectedDomain }; } }]; } }, onMouseUp: (evt, targetProps) => { const {x1, y1, x2, y2, fullDomainBox} = targetProps; if (x1 === x2 || y1 === y2) { return [{ target: "parent", mutation: () => { return { isPanning: false, isSelecting: false, ...fullDomainBox }; } }]; } return [{ target: "parent", mutation: () => ({ isPanning: false, isSelecting: false }) }]; }, onMouseLeave: () => { return [{ target: "parent", mutation: () => ({ isPanning: false, isSelecting: false }) }]; } } }]; getRect(props) { const {x1, x2, y1, y2, selectionStyle} = props; const width = Math.abs(x2 - x1) || 1; const height = Math.abs(y2 - y1) || 1; const x = Math.min(x1, x2); const y = Math.min(y1, y2); return y2 && x2 && x1 && y1 ? <rect x={x} y={y} width={width} height={height} style={selectionStyle}/> : null; } renderContainer(props, svgProps, style) { const { title, desc, children, portalComponent, className } = props; return ( <svg {...svgProps} style={style} className={className}> <title id="title">{title}</title> <desc id="desc">{desc}</desc> {this.getRect(props)} {children} {React.cloneElement(portalComponent, {ref: this.savePortalRef})} </svg> ); } }
src/components/containers/victory-range-container.js
import React from "react"; import { VictoryContainer, Selection, PropTypes as CustomPropTypes, Domain } from "victory-core"; import Helpers from "./container-helper-methods"; import { isFunction, isEqual } from "lodash"; export default class VictoryRangeContainer extends VictoryContainer { static displayName = "VictoryRangeContainer"; static propTypes = { ...VictoryContainer.propTypes, selectionStyle: React.PropTypes.object, dimension: React.PropTypes.oneOf(["x", "y"]), selectedDomain: React.PropTypes.shape({ x: React.PropTypes.array, y: React.PropTypes.array }), onDomainChange: React.PropTypes.func, handleWidth: React.PropTypes.number }; static defaultProps = { ...VictoryContainer.defaultProps, selectionStyle: { stroke: "black", fill: "black", fillOpacity: 0.2 }, handleWidth: 5 }; static defaultEvents = [{ target: "parent", eventHandlers: { onMouseDown: (evt, targetProps) => { evt.preventDefault(); const { dimension, scale, selectedDomain } = targetProps; const fullDomain = targetProps.fullDomain || Helpers.getOriginalDomain(scale); const fullDomainBox = targetProps.fullDomainBox || Helpers.getDomainBox(targetProps, fullDomain); const domainBox = Helpers.getDomainBox(targetProps, fullDomain, selectedDomain); const {x, y} = Selection.getSVGEventCoordinates(evt); const {x1, y1, x2, y2} = domainBox; if (!selectedDomain || isEqual(selectedDomain, fullDomain)) { return [{ target: "parent", mutation: () => { return { isSelecting: true, selectedDomain, domainBox, fullDomainBox, x1: dimension !== "y" ? x : x1, y1: dimension !== "x" ? y : y1, x2: dimension !== "y" ? x : x2, y2: dimension !== "x" ? y : y2 }; } }]; } const handles = Helpers.getHandles(targetProps, domainBox); if (Helpers.withinBounds({x, y}, handles.left)) { return [{ target: "parent", mutation: () => { return { isSelecting: true, selectedDomain, domainBox, fullDomainBox, x1: Math.max(x1, x2), x2: Math.min(x1, x2) }; } }]; } else if (Helpers.withinBounds({x, y}, handles.right)) { return [{ target: "parent", mutation: () => { return { isSelecting: true, selectedDomain, domainBox, fullDomainBox, x1: Math.min(x1, x2), x2: Math.max(x1, x2) }; } }]; } else if (Helpers.withinBounds({x, y}, domainBox)) { return [{ target: "parent", mutation: () => ({ isPanning: true, startX: x, startY: y, selectedDomain, domainBox, fullDomainBox }) }]; } else { return [{ target: "parent", mutation: () => { return { isSelecting: true, selectedDomain, domainBox, fullDomainBox, x1: dimension !== "y" ? x : x1, y1: dimension !== "x" ? y : y1, x2: dimension !== "y" ? x : x2, y2: dimension !== "x" ? y : y2 }; } }]; } }, onMouseMove: (evt, targetProps) => { if (!targetProps.isPanning && !targetProps.isSelecting) { return {}; } const { dimension, scale, isPanning, isSelecting, startX, startY, fullDomainBox } = targetProps; const {x, y} = Selection.getSVGEventCoordinates(evt); if (isPanning) { const delta = { x: startX ? startX - x : 0, y: startY ? startY - y : 0 }; const x1 = dimension !== "y" ? targetProps.x1 - delta.x : targetProps.x1; const x2 = dimension !== "y" ? targetProps.x2 - delta.x : targetProps.x2; const y1 = dimension !== "x" ? targetProps.y1 - delta.y : targetProps.y1; const y2 = dimension !== "x" ? targetProps.y2 - delta.y : targetProps.y2; const constrainedDimensions = { x1: x2 > fullDomainBox.x2 ? fullDomainBox.x2 - Math.abs(x2 - x1) : Math.max(x1, fullDomainBox.x1), y1: y2 > fullDomainBox.y2 ? fullDomainBox.y2 - Math.abs(y2 - y1) : Math.max(y1, fullDomainBox.y1), x2: x1 < fullDomainBox.x1 ? fullDomainBox.x1 + Math.abs(x2 - x1) : Math.min(x2, fullDomainBox.x2), y2: y1 < fullDomainBox.y1 ? fullDomainBox.y1 + Math.abs(y2 - y1) : Math.min(y2, fullDomainBox.y2) }; const selectedDomain = Selection.getBounds({...constrainedDimensions, scale}); return [{ target: "parent", mutation: () => { return { selectedDomain, startX: x2 >= fullDomainBox.x2 || x1 <= fullDomainBox.x1 ? startX : x, startY: y2 >= fullDomainBox.y2 || y1 <= fullDomainBox.y1 ? startY : y, ...constrainedDimensions }; } }]; } else if (isSelecting) { const x2 = dimension !== "y" ? x : targetProps.x2; const y2 = dimension !== "x" ? y : targetProps.y2; const x1 = dimension !== "y" ? x : targetProps.x1; const y1 = dimension !== "x" ? y : targetProps.y1; const { negativeSelection } = targetProps; const selectedDomain = negativeSelection ? Selection.getBounds({x1, y1, x2: targetProps.x2, y2: targetProps.y2, scale}) : Selection.getBounds({x2, y2, x1: targetProps.x1, y1: targetProps.y1, scale}); return [{ target: "parent", mutation: () => { return { x2, y2, selectedDomain }; } }]; } }, onMouseUp: (evt, targetProps) => { const {x1, y1, x2, y2, fullDomainBox} = targetProps; if (x1 === x2 || y1 === y2) { return [{ target: "parent", mutation: () => { return { isPanning: false, isSelecting: false, ...fullDomainBox }; } }]; } return [{ target: "parent", mutation: () => ({ isPanning: false, isSelecting: false }) }]; }, onMouseLeave: () => { return [{ target: "parent", mutation: () => ({ isPanning: false, isSelecting: false }) }]; } } }]; getRect(props) { const {x1, x2, y1, y2, selectionStyle, selectedDomain} = props; const width = Math.abs(x2 - x1) || 1; const height = Math.abs(y2 - y1) || 1; const x = Math.min(x1, x2); const y = Math.min(y1, y2); return y2 && x2 && x1 && y1 ? <rect x={x} y={y} width={width} height={height} style={selectionStyle}/> : null; } renderContainer(props, svgProps, style) { const { title, desc, children, portalComponent, className } = props; return ( <svg {...svgProps} style={style} className={className}> <title id="title">{title}</title> <desc id="desc">{desc}</desc> {this.getRect(props)} {children} {React.cloneElement(portalComponent, {ref: this.savePortalRef})} </svg> ); } }
constrain selection area
src/components/containers/victory-range-container.js
constrain selection area
<ide><path>rc/components/containers/victory-range-container.js <ide> fill: "black", <ide> fillOpacity: 0.2 <ide> }, <add> dimension: "x", <ide> handleWidth: 5 <ide> }; <ide> <ide> const { dimension, scale, selectedDomain } = targetProps; <ide> const fullDomain = targetProps.fullDomain || Helpers.getOriginalDomain(scale); <ide> const fullDomainBox = targetProps.fullDomainBox || Helpers.getDomainBox(targetProps, fullDomain); <add> const {x, y} = Selection.getSVGEventCoordinates(evt); <add> if (!Helpers.withinBounds({x, y}, fullDomainBox)) { <add> return {}; <add> } <ide> const domainBox = Helpers.getDomainBox(targetProps, fullDomain, selectedDomain); <del> const {x, y} = Selection.getSVGEventCoordinates(evt); <ide> const {x1, y1, x2, y2} = domainBox; <ide> if (!selectedDomain || isEqual(selectedDomain, fullDomain)) { <ide> return [{ <ide> dimension, scale, isPanning, isSelecting, startX, startY, fullDomainBox <ide> } = targetProps; <ide> const {x, y} = Selection.getSVGEventCoordinates(evt); <add> if (!Helpers.withinBounds({x, y}, fullDomainBox)) { <add> return {}; <add> } <ide> if (isPanning) { <ide> const delta = { <ide> x: startX ? startX - x : 0, <ide> } else if (isSelecting) { <ide> const x2 = dimension !== "y" ? x : targetProps.x2; <ide> const y2 = dimension !== "x" ? y : targetProps.y2; <del> const x1 = dimension !== "y" ? x : targetProps.x1; <del> const y1 = dimension !== "x" ? y : targetProps.y1; <del> const { negativeSelection } = targetProps; <del> const selectedDomain = negativeSelection ? <del> Selection.getBounds({x1, y1, x2: targetProps.x2, y2: targetProps.y2, scale}) : <add> const selectedDomain = <ide> Selection.getBounds({x2, y2, x1: targetProps.x1, y1: targetProps.y1, scale}); <ide> return [{ <ide> target: "parent", <ide> }]; <ide> <ide> getRect(props) { <del> const {x1, x2, y1, y2, selectionStyle, selectedDomain} = props; <add> const {x1, x2, y1, y2, selectionStyle} = props; <ide> <ide> const width = Math.abs(x2 - x1) || 1; <ide> const height = Math.abs(y2 - y1) || 1;
Java
mit
2e1067ecae388c9c4bd951e34a23325479759dc8
0
sake/bouncycastle-java
package org.bouncycastle.math.ec; import java.math.BigInteger; import java.util.Random; public abstract class ECFieldElement implements ECConstants { BigInteger x; protected ECFieldElement(BigInteger x) { this.x = x; } public BigInteger toBigInteger() { return x; } public abstract String getFieldName(); public abstract ECFieldElement add(ECFieldElement b); public abstract ECFieldElement subtract(ECFieldElement b); public abstract ECFieldElement multiply(ECFieldElement b); public abstract ECFieldElement divide(ECFieldElement b); public abstract ECFieldElement negate(); public abstract ECFieldElement square(); public abstract ECFieldElement invert(); public abstract ECFieldElement sqrt(); public static class Fp extends ECFieldElement { BigInteger q; public Fp(BigInteger q, BigInteger x) { super(x); if (x.compareTo(q) >= 0) { throw new IllegalArgumentException("x value too large in field element"); } this.q = q; } /** * return the field name for this field. * * @return the string "Fp". */ public String getFieldName() { return "Fp"; } public BigInteger getQ() { return q; } public ECFieldElement add(ECFieldElement b) { return new Fp(q, x.add(b.x).mod(q)); } public ECFieldElement subtract(ECFieldElement b) { return new Fp(q, x.subtract(b.x).mod(q)); } public ECFieldElement multiply(ECFieldElement b) { return new Fp(q, x.multiply(b.x).mod(q)); } public ECFieldElement divide(ECFieldElement b) { return new Fp(q, x.multiply(b.x.modInverse(q)).mod(q)); } public ECFieldElement negate() { return new Fp(q, x.negate().mod(q)); } public ECFieldElement square() { return new Fp(q, x.multiply(x).mod(q)); } public ECFieldElement invert() { return new Fp(q, x.modInverse(q)); } // D.1.4 91 /** * return a sqrt root - the routine verifies that the calculation * returns the right value - if none exists it returns null. */ public ECFieldElement sqrt() { if (!q.testBit(0)) { throw new RuntimeException("not done yet"); } // p mod 4 == 3 if (q.testBit(1)) { // z = g^(u+1) + p, p = 4u + 3 ECFieldElement z = new Fp(q, x.modPow(q.shiftRight(2).add(ONE), q)); return z.square().equals(this) ? z : null; } // p mod 4 == 1 BigInteger qMinusOne = q.subtract(ECConstants.ONE); BigInteger u = qMinusOne.shiftRight(2); BigInteger k = u.shiftLeft(1).add(ECConstants.ONE); BigInteger Q = this.x; BigInteger fourQ = Q.shiftLeft(2).mod(q); BigInteger U, V; do { Random rand = new Random(); BigInteger P; do { P = new BigInteger(q.bitLength(), rand); } while (P.compareTo(q) >= 0); BigInteger[] result = lucasSequence(q, P, Q, k); U = result[0]; V = result[1]; if (V.multiply(V).mod(q).equals(fourQ)) { // Integer division by 2, mod q if (V.testBit(0)) { V = V.add(q); } V = V.shiftRight(1); //assert V.multiply(V).mod(q).equals(x); return new ECFieldElement.Fp(q, V); } } while (U.equals(ECConstants.ONE) || U.equals(qMinusOne)); return null; // BigInteger qMinusOne = q.subtract(ECConstants.ONE); // BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO); // if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) // { // return null; // } // // Random rand = new Random(); // BigInteger fourX = x.shiftLeft(2); // // BigInteger r; // do // { // r = new BigInteger(q.bitLength(), rand); // } // while (r.compareTo(q) >= 0 // || !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne))); // // BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR); // BigInteger n2 = n1.add(ECConstants.ONE); //q.add(ECConstants.THREE).divide(ECConstants.FOUR); // // BigInteger wOne = WOne(r, x, q); // BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q); // BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r); // // BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q) // .multiply(x).mod(q) // .multiply(wSum).mod(q); // // return new Fp(q, root); } // private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p) // { // if (n.equals(ECConstants.ONE)) // { // return wOne; // } // boolean isEven = !n.testBit(0); // n = n.shiftRight(1);//divide(ECConstants.TWO); // if (isEven) // { // BigInteger w = W(n, wOne, p); // return w.multiply(w).subtract(ECConstants.TWO).mod(p); // } // BigInteger w1 = W(n.add(ECConstants.ONE), wOne, p); // BigInteger w2 = W(n, wOne, p); // return w1.multiply(w2).subtract(wOne).mod(p); // } // // private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p) // { // return r.multiply(r).multiply(x.modPow(q.subtract(ECConstants.TWO), q)).subtract(ECConstants.TWO).mod(p); // } private static BigInteger[] lucasSequence( BigInteger p, BigInteger P, BigInteger Q, BigInteger k) { int n = k.bitLength(); int s = k.getLowestSetBit(); BigInteger Uh = ECConstants.ONE; BigInteger Vl = ECConstants.TWO; BigInteger Vh = P; BigInteger Ql = ECConstants.ONE; BigInteger Qh = ECConstants.ONE; for (int j = n - 1; j >= s + 1; --j) { Ql = Ql.multiply(Qh).mod(p); if (k.testBit(j)) { Qh = Ql.multiply(Q).mod(p); Uh = Uh.multiply(Vh).mod(p); Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p); } else { Qh = Ql; Uh = Uh.multiply(Vl).subtract(Ql).mod(p); Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); } } Ql = Ql.multiply(Qh).mod(p); Qh = Ql.multiply(Q).mod(p); Uh = Uh.multiply(Vl).subtract(Ql).mod(p); Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); Ql = Ql.multiply(Qh).mod(p); for (int j = 1; j <= s; ++j) { Uh = Uh.multiply(Vl).mod(p); Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); Ql = Ql.multiply(Ql).mod(p); } return new BigInteger[]{ Uh, Vl }; } public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof ECFieldElement.Fp)) { return false; } ECFieldElement.Fp o = (ECFieldElement.Fp)other; return q.equals(o.q) && x.equals(o.x); } public int hashCode() { return q.hashCode() ^ x.hashCode(); } } /** * Class representing the Elements of the finite field * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) * representation. Both trinomial (TPB) and pentanomial (PPB) polynomial * basis representations are supported. Gaussian normal basis (GNB) * representation is not supported. */ public static class F2m extends ECFieldElement { /** * Indicates gaussian normal basis representation (GNB). Number chosen * according to X9.62. GNB is not implemented at present. */ public static final int GNB = 1; /** * Indicates trinomial basis representation (TPB). Number chosen * according to X9.62. */ public static final int TPB = 2; /** * Indicates pentanomial basis representation (PPB). Number chosen * according to X9.62. */ public static final int PPB = 3; /** * TPB or PPB. */ private int representation; /** * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. */ private int m; /** * TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k1; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k2; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k3; /** * Constructor for PPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2m( int m, int k1, int k2, int k3, BigInteger x) { super(x); if ((k2 == 0) && (k3 == 0)) { this.representation = TPB; } else { if (k2 >= k3) { throw new IllegalArgumentException( "k2 must be smaller than k3"); } if (k2 <= 0) { throw new IllegalArgumentException( "k2 must be larger than 0"); } this.representation = PPB; } if (x.signum() < 0) { throw new IllegalArgumentException("x value cannot be negative"); } this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; } /** * Constructor for TPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2m(int m, int k, BigInteger x) { // Set k1 to k, and set k2 and k3 to 0 this(m, k, 0, 0, x); } public String getFieldName() { return "F2m"; } /** * Checks, if the ECFieldElements <code>a</code> and <code>b</code> * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> * (having the same representation). * @param a * @param b * @throws IllegalArgumentException if <code>a</code> and <code>b</code> * are not elements of the same field * <code>F<sub>2<sup>m</sup></sub></code> (having the same * representation). */ public static void checkFieldElements( ECFieldElement a, ECFieldElement b) { if ((!(a instanceof F2m)) || (!(b instanceof F2m))) { throw new IllegalArgumentException("Field elements are not " + "both instances of ECFieldElement.F2m"); } if ((a.x.signum() < 0) || (b.x.signum() < 0)) { throw new IllegalArgumentException( "x value may not be negative"); } ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a; ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b; if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) { throw new IllegalArgumentException("Field elements are not " + "elements of the same field F2m"); } if (aF2m.representation != bF2m.representation) { // Should never occur throw new IllegalArgumentException( "One of the field " + "elements are not elements has incorrect representation"); } } /** * Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is * the reduction polynomial of <code>this</code>. * @param a The polynomial <code>a(z)</code> to be multiplied by * <code>z mod f(z)</code>. * @return <code>z * a(z) mod f(z)</code> */ private BigInteger multZModF(final BigInteger a) { // Left-shift of a(z) BigInteger az = a.shiftLeft(1); if (az.testBit(this.m)) { // If the coefficient of z^m in a(z) equals 1, reduction // modulo f(z) is performed: Add f(z) to to a(z): // Step 1: Unset mth coeffient of a(z) az = az.clearBit(this.m); // Step 2: Add r(z) to a(z), where r(z) is defined as // f(z) = z^m + r(z), and k1, k2, k3 are the positions of // the non-zero coefficients in r(z) az = az.flipBit(0); az = az.flipBit(this.k1); if (this.representation == PPB) { az = az.flipBit(this.k2); az = az.flipBit(this.k3); } } return az; } public ECFieldElement add(final ECFieldElement b) { // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); return new F2m(this.m, this.k1, this.k2, this.k3, this.x.xor(b.x)); } public ECFieldElement subtract(final ECFieldElement b) { // Addition and subtraction are the same in F2m return add(b); } public ECFieldElement multiply(final ECFieldElement b) { // Left-to-right shift-and-add field multiplication in F2m // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // Output: c(z) = a(z) * b(z) mod f(z) // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); final BigInteger az = this.x; BigInteger bz = b.x; BigInteger cz; // Compute c(z) = a(z) * b(z) mod f(z) if (az.testBit(0)) { cz = bz; } else { cz = ECConstants.ZERO; } for (int i = 1; i < this.m; i++) { // b(z) := z * b(z) mod f(z) bz = multZModF(bz); if (az.testBit(i)) { // If the coefficient of x^i in a(z) equals 1, b(z) is added // to c(z) cz = cz.xor(bz); } } return new ECFieldElement.F2m(m, this.k1, this.k2, this.k3, cz); } public ECFieldElement divide(final ECFieldElement b) { // There may be more efficient implementations ECFieldElement bInv = b.invert(); return multiply(bInv); } public ECFieldElement negate() { // -x == x holds for all x in F2m, hence a copy of this is returned return new F2m(this.m, this.k1, this.k2, this.k3, this.x); } public ECFieldElement square() { // Naive implementation, can probably be speeded up using modular // reduction return multiply(this); } public ECFieldElement invert() { // Inversion in F2m using the extended Euclidean algorithm // Input: A nonzero polynomial a(z) of degree at most m-1 // Output: a(z)^(-1) mod f(z) // u(z) := a(z) BigInteger uz = this.x; if (uz.signum() <= 0) { throw new ArithmeticException("x is zero or negative, " + "inversion is impossible"); } // v(z) := f(z) BigInteger vz = ECConstants.ONE.shiftLeft(m); vz = vz.setBit(0); vz = vz.setBit(this.k1); if (this.representation == PPB) { vz = vz.setBit(this.k2); vz = vz.setBit(this.k3); } // g1(z) := 1, g2(z) := 0 BigInteger g1z = ECConstants.ONE; BigInteger g2z = ECConstants.ZERO; // while u != 1 while (!(uz.equals(ECConstants.ZERO))) { // j := deg(u(z)) - deg(v(z)) int j = uz.bitLength() - vz.bitLength(); // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j if (j < 0) { final BigInteger uzCopy = uz; uz = vz; vz = uzCopy; final BigInteger g1zCopy = g1z; g1z = g2z; g2z = g1zCopy; j = -j; } // u(z) := u(z) + z^j * v(z) // Note, that no reduction modulo f(z) is required, because // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // = deg(u(z)) uz = uz.xor(vz.shiftLeft(j)); // g1(z) := g1(z) + z^j * g2(z) g1z = g1z.xor(g2z.shiftLeft(j)); // if (g1z.bitLength() > this.m) { // throw new ArithmeticException( // "deg(g1z) >= m, g1z = " + g1z.toString(2)); // } } return new ECFieldElement.F2m( this.m, this.k1, this.k2, this.k3, g2z); } public ECFieldElement sqrt() { throw new RuntimeException("Not implemented"); } /** * @return the representation of the field * <code>F<sub>2<sup>m</sup></sub></code>, either of * TPB (trinomial * basis representation) or * PPB (pentanomial * basis representation). */ public int getRepresentation() { return this.representation; } /** * @return the degree <code>m</code> of the reduction polynomial * <code>f(z)</code>. */ public int getM() { return this.m; } /** * @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK1() { return this.k1; } /** * @return TPB: Always returns <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK2() { return this.k2; } /** * @return TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK3() { return this.k3; } public String toString() { return this.x.toString(2); } public boolean equals(Object anObject) { if (anObject == this) { return true; } if (!(anObject instanceof ECFieldElement.F2m)) { return false; } ECFieldElement.F2m b = (ECFieldElement.F2m)anObject; return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2) && (this.k3 == b.k3) && (this.representation == b.representation) && (this.x.equals(b.x))); } public int hashCode() { return x.hashCode() ^ m ^ k1 ^ k2 ^ k3; } } }
src/org/bouncycastle/math/ec/ECFieldElement.java
package org.bouncycastle.math.ec; import java.math.BigInteger; import java.util.Random; public abstract class ECFieldElement implements ECConstants { BigInteger x; protected ECFieldElement(BigInteger x) { this.x = x; } public BigInteger toBigInteger() { return x; } public abstract String getFieldName(); public abstract ECFieldElement add(ECFieldElement b); public abstract ECFieldElement subtract(ECFieldElement b); public abstract ECFieldElement multiply(ECFieldElement b); public abstract ECFieldElement divide(ECFieldElement b); public abstract ECFieldElement negate(); public abstract ECFieldElement square(); public abstract ECFieldElement invert(); public abstract ECFieldElement sqrt(); public static class Fp extends ECFieldElement { BigInteger q; public Fp(BigInteger q, BigInteger x) { super(x); if (x.compareTo(q) >= 0) { throw new IllegalArgumentException("x value too large in field element"); } this.q = q; } /** * return the field name for this field. * * @return the string "Fp". */ public String getFieldName() { return "Fp"; } public BigInteger getQ() { return q; } public ECFieldElement add(ECFieldElement b) { return new Fp(q, x.add(b.x).mod(q)); } public ECFieldElement subtract(ECFieldElement b) { return new Fp(q, x.subtract(b.x).mod(q)); } public ECFieldElement multiply(ECFieldElement b) { return new Fp(q, x.multiply(b.x).mod(q)); } public ECFieldElement divide(ECFieldElement b) { return new Fp(q, x.multiply(b.x.modInverse(q)).mod(q)); } public ECFieldElement negate() { return new Fp(q, x.negate().mod(q)); } public ECFieldElement square() { return new Fp(q, x.multiply(x).mod(q)); } public ECFieldElement invert() { return new Fp(q, x.modInverse(q)); } // D.1.4 91 /** * return a sqrt root - the routine verifies that the calculation * returns the right value - if none exists it returns null. */ public ECFieldElement sqrt() { if (!q.testBit(0)) throw new RuntimeException("not done yet"); // p mod 4 == 3 if (q.testBit(1)) { // z = g^(u+1) + p, p = 4u + 3 ECFieldElement z = new Fp(q, x.modPow(q.shiftRight(2).add(ONE), q)); return z.square().equals(this) ? z : null; } // p mod 4 == 1 BigInteger qMinusOne = q.subtract(ECConstants.ONE); BigInteger legendreExponent = qMinusOne.shiftRight(1); if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) return null; BigInteger u = qMinusOne.shiftRight(2); BigInteger k = u.shiftLeft(1).add(ECConstants.ONE); BigInteger Q = this.x; BigInteger fourQ = Q.shiftLeft(2).mod(q); BigInteger U, V; do { Random rand = new Random(); BigInteger P; do { P = new BigInteger(q.bitLength(), rand); } while (P.compareTo(q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, q).equals(qMinusOne))); BigInteger[] result = lucasSequence(q, P, Q, k); U = result[0]; V = result[1]; if (V.multiply(V).mod(q).equals(fourQ)) { // Integer division by 2, mod q if (V.testBit(0)) { V = V.add(q); } V = V.shiftRight(1); //assert V.multiply(V).mod(q).equals(x); return new ECFieldElement.Fp(q, V); } } while (U.equals(ECConstants.ONE) || U.equals(qMinusOne)); return null; // BigInteger qMinusOne = q.subtract(ECConstants.ONE); // BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO); // if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) // { // return null; // } // // Random rand = new Random(); // BigInteger fourX = x.shiftLeft(2); // // BigInteger r; // do // { // r = new BigInteger(q.bitLength(), rand); // } // while (r.compareTo(q) >= 0 // || !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne))); // // BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR); // BigInteger n2 = n1.add(ECConstants.ONE); //q.add(ECConstants.THREE).divide(ECConstants.FOUR); // // BigInteger wOne = WOne(r, x, q); // BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q); // BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r); // // BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q) // .multiply(x).mod(q) // .multiply(wSum).mod(q); // // return new Fp(q, root); } // private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p) // { // if (n.equals(ECConstants.ONE)) // { // return wOne; // } // boolean isEven = !n.testBit(0); // n = n.shiftRight(1);//divide(ECConstants.TWO); // if (isEven) // { // BigInteger w = W(n, wOne, p); // return w.multiply(w).subtract(ECConstants.TWO).mod(p); // } // BigInteger w1 = W(n.add(ECConstants.ONE), wOne, p); // BigInteger w2 = W(n, wOne, p); // return w1.multiply(w2).subtract(wOne).mod(p); // } // // private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p) // { // return r.multiply(r).multiply(x.modPow(q.subtract(ECConstants.TWO), q)).subtract(ECConstants.TWO).mod(p); // } private static BigInteger[] lucasSequence( BigInteger p, BigInteger P, BigInteger Q, BigInteger k) { int n = k.bitLength(); int s = k.getLowestSetBit(); BigInteger Uh = ECConstants.ONE; BigInteger Vl = ECConstants.TWO; BigInteger Vh = P; BigInteger Ql = ECConstants.ONE; BigInteger Qh = ECConstants.ONE; for (int j = n - 1; j >= s + 1; --j) { Ql = Ql.multiply(Qh).mod(p); if (k.testBit(j)) { Qh = Ql.multiply(Q).mod(p); Uh = Uh.multiply(Vh).mod(p); Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p); } else { Qh = Ql; Uh = Uh.multiply(Vl).subtract(Ql).mod(p); Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); } } Ql = Ql.multiply(Qh).mod(p); Qh = Ql.multiply(Q).mod(p); Uh = Uh.multiply(Vl).subtract(Ql).mod(p); Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p); Ql = Ql.multiply(Qh).mod(p); for (int j = 1; j <= s; ++j) { Uh = Uh.multiply(Vl).mod(p); Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p); Ql = Ql.multiply(Ql).mod(p); } return new BigInteger[]{ Uh, Vl }; } public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof ECFieldElement.Fp)) { return false; } ECFieldElement.Fp o = (ECFieldElement.Fp)other; return q.equals(o.q) && x.equals(o.x); } public int hashCode() { return q.hashCode() ^ x.hashCode(); } } /** * Class representing the Elements of the finite field * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) * representation. Both trinomial (TPB) and pentanomial (PPB) polynomial * basis representations are supported. Gaussian normal basis (GNB) * representation is not supported. */ public static class F2m extends ECFieldElement { /** * Indicates gaussian normal basis representation (GNB). Number chosen * according to X9.62. GNB is not implemented at present. */ public static final int GNB = 1; /** * Indicates trinomial basis representation (TPB). Number chosen * according to X9.62. */ public static final int TPB = 2; /** * Indicates pentanomial basis representation (PPB). Number chosen * according to X9.62. */ public static final int PPB = 3; /** * TPB or PPB. */ private int representation; /** * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. */ private int m; /** * TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k1; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k2; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k3; /** * Constructor for PPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2m( int m, int k1, int k2, int k3, BigInteger x) { super(x); if ((k2 == 0) && (k3 == 0)) { this.representation = TPB; } else { if (k2 >= k3) { throw new IllegalArgumentException( "k2 must be smaller than k3"); } if (k2 <= 0) { throw new IllegalArgumentException( "k2 must be larger than 0"); } this.representation = PPB; } if (x.signum() < 0) { throw new IllegalArgumentException("x value cannot be negative"); } this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; } /** * Constructor for TPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. */ public F2m(int m, int k, BigInteger x) { // Set k1 to k, and set k2 and k3 to 0 this(m, k, 0, 0, x); } public String getFieldName() { return "F2m"; } /** * Checks, if the ECFieldElements <code>a</code> and <code>b</code> * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> * (having the same representation). * @param a * @param b * @throws IllegalArgumentException if <code>a</code> and <code>b</code> * are not elements of the same field * <code>F<sub>2<sup>m</sup></sub></code> (having the same * representation). */ public static void checkFieldElements( ECFieldElement a, ECFieldElement b) { if ((!(a instanceof F2m)) || (!(b instanceof F2m))) { throw new IllegalArgumentException("Field elements are not " + "both instances of ECFieldElement.F2m"); } if ((a.x.signum() < 0) || (b.x.signum() < 0)) { throw new IllegalArgumentException( "x value may not be negative"); } ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a; ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b; if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) { throw new IllegalArgumentException("Field elements are not " + "elements of the same field F2m"); } if (aF2m.representation != bF2m.representation) { // Should never occur throw new IllegalArgumentException( "One of the field " + "elements are not elements has incorrect representation"); } } /** * Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is * the reduction polynomial of <code>this</code>. * @param a The polynomial <code>a(z)</code> to be multiplied by * <code>z mod f(z)</code>. * @return <code>z * a(z) mod f(z)</code> */ private BigInteger multZModF(final BigInteger a) { // Left-shift of a(z) BigInteger az = a.shiftLeft(1); if (az.testBit(this.m)) { // If the coefficient of z^m in a(z) equals 1, reduction // modulo f(z) is performed: Add f(z) to to a(z): // Step 1: Unset mth coeffient of a(z) az = az.clearBit(this.m); // Step 2: Add r(z) to a(z), where r(z) is defined as // f(z) = z^m + r(z), and k1, k2, k3 are the positions of // the non-zero coefficients in r(z) az = az.flipBit(0); az = az.flipBit(this.k1); if (this.representation == PPB) { az = az.flipBit(this.k2); az = az.flipBit(this.k3); } } return az; } public ECFieldElement add(final ECFieldElement b) { // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); return new F2m(this.m, this.k1, this.k2, this.k3, this.x.xor(b.x)); } public ECFieldElement subtract(final ECFieldElement b) { // Addition and subtraction are the same in F2m return add(b); } public ECFieldElement multiply(final ECFieldElement b) { // Left-to-right shift-and-add field multiplication in F2m // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // Output: c(z) = a(z) * b(z) mod f(z) // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); final BigInteger az = this.x; BigInteger bz = b.x; BigInteger cz; // Compute c(z) = a(z) * b(z) mod f(z) if (az.testBit(0)) { cz = bz; } else { cz = ECConstants.ZERO; } for (int i = 1; i < this.m; i++) { // b(z) := z * b(z) mod f(z) bz = multZModF(bz); if (az.testBit(i)) { // If the coefficient of x^i in a(z) equals 1, b(z) is added // to c(z) cz = cz.xor(bz); } } return new ECFieldElement.F2m(m, this.k1, this.k2, this.k3, cz); } public ECFieldElement divide(final ECFieldElement b) { // There may be more efficient implementations ECFieldElement bInv = b.invert(); return multiply(bInv); } public ECFieldElement negate() { // -x == x holds for all x in F2m, hence a copy of this is returned return new F2m(this.m, this.k1, this.k2, this.k3, this.x); } public ECFieldElement square() { // Naive implementation, can probably be speeded up using modular // reduction return multiply(this); } public ECFieldElement invert() { // Inversion in F2m using the extended Euclidean algorithm // Input: A nonzero polynomial a(z) of degree at most m-1 // Output: a(z)^(-1) mod f(z) // u(z) := a(z) BigInteger uz = this.x; if (uz.signum() <= 0) { throw new ArithmeticException("x is zero or negative, " + "inversion is impossible"); } // v(z) := f(z) BigInteger vz = ECConstants.ONE.shiftLeft(m); vz = vz.setBit(0); vz = vz.setBit(this.k1); if (this.representation == PPB) { vz = vz.setBit(this.k2); vz = vz.setBit(this.k3); } // g1(z) := 1, g2(z) := 0 BigInteger g1z = ECConstants.ONE; BigInteger g2z = ECConstants.ZERO; // while u != 1 while (!(uz.equals(ECConstants.ZERO))) { // j := deg(u(z)) - deg(v(z)) int j = uz.bitLength() - vz.bitLength(); // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j if (j < 0) { final BigInteger uzCopy = uz; uz = vz; vz = uzCopy; final BigInteger g1zCopy = g1z; g1z = g2z; g2z = g1zCopy; j = -j; } // u(z) := u(z) + z^j * v(z) // Note, that no reduction modulo f(z) is required, because // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // = deg(u(z)) uz = uz.xor(vz.shiftLeft(j)); // g1(z) := g1(z) + z^j * g2(z) g1z = g1z.xor(g2z.shiftLeft(j)); // if (g1z.bitLength() > this.m) { // throw new ArithmeticException( // "deg(g1z) >= m, g1z = " + g1z.toString(2)); // } } return new ECFieldElement.F2m( this.m, this.k1, this.k2, this.k3, g2z); } public ECFieldElement sqrt() { throw new RuntimeException("Not implemented"); } /** * @return the representation of the field * <code>F<sub>2<sup>m</sup></sub></code>, either of * TPB (trinomial * basis representation) or * PPB (pentanomial * basis representation). */ public int getRepresentation() { return this.representation; } /** * @return the degree <code>m</code> of the reduction polynomial * <code>f(z)</code>. */ public int getM() { return this.m; } /** * @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK1() { return this.k1; } /** * @return TPB: Always returns <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK2() { return this.k2; } /** * @return TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK3() { return this.k3; } public String toString() { return this.x.toString(2); } public boolean equals(Object anObject) { if (anObject == this) { return true; } if (!(anObject instanceof ECFieldElement.F2m)) { return false; } ECFieldElement.F2m b = (ECFieldElement.F2m)anObject; return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2) && (this.k3 == b.k3) && (this.representation == b.representation) && (this.x.equals(b.x))); } public int hashCode() { return x.hashCode() ^ m ^ k1 ^ k2 ^ k3; } } }
checkstyle change
src/org/bouncycastle/math/ec/ECFieldElement.java
checkstyle change
<ide><path>rc/org/bouncycastle/math/ec/ECFieldElement.java <ide> public ECFieldElement sqrt() <ide> { <ide> if (!q.testBit(0)) <add> { <ide> throw new RuntimeException("not done yet"); <add> } <ide> <ide> // p mod 4 == 3 <ide> if (q.testBit(1)) <ide> <ide> // p mod 4 == 1 <ide> BigInteger qMinusOne = q.subtract(ECConstants.ONE); <del> <del> BigInteger legendreExponent = qMinusOne.shiftRight(1); <del> if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) <del> return null; <del> <ide> BigInteger u = qMinusOne.shiftRight(2); <ide> BigInteger k = u.shiftLeft(1).add(ECConstants.ONE); <ide> <ide> { <ide> P = new BigInteger(q.bitLength(), rand); <ide> } <del> while (P.compareTo(q) >= 0 <del> || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, q).equals(qMinusOne))); <add> while (P.compareTo(q) >= 0); <ide> <ide> BigInteger[] result = lucasSequence(q, P, Q, k); <ide> U = result[0];
JavaScript
mit
0963f3d7d1a8e6c7f45c7f44427d0b289c50585e
0
appelgriebsch/Invaders-Phaser,appelgriebsch/Invaders-Phaser
(function () { 'use strict'; Phaser.Device.whenReady(function () { var width = window.screen.width; var height = window.screen.height - 100; if (Phaser.Device.desktop) { width = 400; height = 600; } var game = new Phaser.Game(width, height, Phaser.CANVAS, 'game', { preload: preload, create: create, update: update, render: render }); function preload() { game.load.image('bullet', 'img/bullet.png'); game.load.image('enemyBullet', 'img/enemy-bullet.png'); game.load.spritesheet('invader', 'img/invader32x32x4.png', 32, 32); game.load.image('ship', 'img/player.png'); game.load.spritesheet('kaboom', 'img/explode.png', 128, 128); game.load.image('starfield', 'img/starfield.png'); game.load.image('background', 'img/background2.png'); } var player; var aliens; var bullets; var bulletTime = 0; var cursors; var fireButton; var explosions; var starfield; var score = 0; var scoreString = ''; var scoreText; var lives; var enemyBullet; var firingTimer = 0; var stateText; var livingEnemies = []; var enemyBullets = []; function create() { game.physics.startSystem(Phaser.Physics.ARCADE); // The scrolling starfield background starfield = game.add.tileSprite(0, 0, width, height, 'starfield'); // Our bullet group bullets = game.add.group(); bullets.enableBody = true; bullets.physicsBodyType = Phaser.Physics.ARCADE; bullets.createMultiple(30, 'bullet'); bullets.setAll('anchor.x', 0.5); bullets.setAll('anchor.y', 1); bullets.setAll('outOfBoundsKill', true); bullets.setAll('checkWorldBounds', true); // The enemy's bullets enemyBullets = game.add.group(); enemyBullets.enableBody = true; enemyBullets.physicsBodyType = Phaser.Physics.ARCADE; enemyBullets.createMultiple(30, 'enemyBullet'); enemyBullets.setAll('anchor.x', 0.5); enemyBullets.setAll('anchor.y', 1); enemyBullets.setAll('outOfBoundsKill', true); enemyBullets.setAll('checkWorldBounds', true); // The hero! player = game.add.sprite(width / 2, height - 100, 'ship'); player.anchor.setTo(0.5, 0.5); game.physics.enable(player, Phaser.Physics.ARCADE); // The baddies! aliens = game.add.group(); aliens.enableBody = true; aliens.physicsBodyType = Phaser.Physics.ARCADE; createAliens(); // The score scoreString = 'Score : '; scoreText = game.add.text(10, 10, scoreString + score, { font: '20px Arial', fill: '#fff' }); // Lives lives = game.add.group(); game.add.text(game.world.width - 100, 10, 'Lives : ', { font: '20px Arial', fill: '#fff' }); // Text stateText = game.add.text(game.world.centerX, game.world.centerY, ' ', { font: '48px Arial', fill: '#fff' }); stateText.anchor.setTo(0.5, 0.5); stateText.visible = false; for (var i = 0; i < 3; i++) { var ship = lives.create(game.world.width - 100 + (30 * i), 60, 'ship'); ship.anchor.setTo(0.5, 0.5); ship.angle = 90; ship.alpha = 0.4; } // An explosion pool explosions = game.add.group(); explosions.createMultiple(30, 'kaboom'); explosions.forEach(setupInvader, this); // And some controls to play the game with cursors = game.input.keyboard.createCursorKeys(); fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); game.input.touch.onTouchEnd(fireBullet); // add the gyro for mobile gyro.frequency = 10; var origX = 0; gyro.startTracking(function (o) { if (player.alive) { // Reset the player, then check for movement keys var delta = o.x - origX; player.body.velocity.x += delta * 100; origX = o.x; } }); } function createAliens() { for (var y = 0; y < 4; y++) { for (var x = 0; x < 5; x++) { var alien = aliens.create(x * 48, y * 50, 'invader'); alien.anchor.setTo(0.5, 0.5); alien.animations.add('fly', [0, 1, 2, 3], 20, true); alien.play('fly'); alien.body.moves = false; } } aliens.x = 20; aliens.y = 50; // All this does is basically start the invaders moving. Notice we're moving the Group they belong to, rather than the invaders directly. var tween = game.add.tween(aliens).to({ x: 150 }, 2000, Phaser.Easing.Linear.None, true, 0, 1000, true); // When the tween loops it calls descend tween.onLoop.add(descend, this); } function setupInvader(invader) { invader.anchor.x = 0.5; invader.anchor.y = 0.5; invader.animations.add('kaboom'); } function descend() { aliens.y += 10; } function update() { // Scroll the background starfield.tilePosition.y += 2; if (player.alive) { // Reset the player, then check for movement keys //player.body.velocity.setTo(0, 0); if (cursors.left.isDown) { player.body.velocity.x = -200; } else if (cursors.right.isDown) { player.body.velocity.x = 200; } // Firing? if (fireButton.isDown) { fireBullet(); } if (game.time.now > firingTimer) { enemyFires(); } // Run collision game.physics.arcade.overlap(bullets, aliens, collisionHandler, null, this); game.physics.arcade.overlap(enemyBullets, player, enemyHitsPlayer, null, this); } } function render() { // for (var i = 0; i < aliens.length; i++) // { // game.debug.body(aliens.children[i]); // } } function collisionHandler(bullet, alien) { // When a bullet hits an alien we kill them both bullet.kill(); alien.kill(); // Increase the score score += 20; scoreText.text = scoreString + score; // And create an explosion :) var explosion = explosions.getFirstExists(false); explosion.reset(alien.body.x, alien.body.y); explosion.play('kaboom', 30, false, true); if (aliens.countLiving() == 0) { score += 1000; scoreText.text = scoreString + score; enemyBullets.callAll('kill', this); stateText.text = " You Won, \n Click to restart"; stateText.visible = true; //the "click to restart" handler game.input.onTap.addOnce(restart, this); } } function enemyHitsPlayer(player, bullet) { bullet.kill(); var live = lives.getFirstAlive(); if (live) { live.kill(); } // And create an explosion :) var explosion = explosions.getFirstExists(false); explosion.reset(player.body.x, player.body.y); explosion.play('kaboom', 30, false, true); // When the player dies if (lives.countLiving() < 1) { player.kill(); enemyBullets.callAll('kill'); stateText.text = " GAME OVER \n Click to restart"; stateText.visible = true; //the "click to restart" handler game.input.onTap.addOnce(restart, this); } } function enemyFires() { // Grab the first bullet we can from the pool enemyBullet = enemyBullets.getFirstExists(false); livingEnemies.length = 0; aliens.forEachAlive(function (alien) { // put every living enemy in an array livingEnemies.push(alien); }); if (enemyBullet && livingEnemies.length > 0) { var random = game.rnd.integerInRange(0, livingEnemies.length - 1); // randomly select one of them var shooter = livingEnemies[random]; // And fire the bullet from this enemy enemyBullet.reset(shooter.body.x, shooter.body.y); game.physics.arcade.moveToObject(enemyBullet, player, 120); firingTimer = game.time.now + 2000; } } function fireBullet() { // To avoid them being allowed to fire too fast we set a time limit if (game.time.now > bulletTime) { // Grab the first bullet we can from the pool var bullet = bullets.getFirstExists(false); if (bullet) { // And fire it bullet.reset(player.x, player.y + 8); bullet.body.velocity.y = -400; bulletTime = game.time.now + 200; } } } function resetBullet(bullet) { // Called if the bullet goes out of the screen bullet.kill(); } function restart() { // A new level starts //resets the life count lives.callAll('revive'); // And brings the aliens back from the dead :) aliens.removeAll(); createAliens(); //revives the player player.revive(); //hides the text stateText.visible = false; } }) })();
js/game.js
(function () { 'use strict'; Phaser.Device.whenReady(function () { var width = window.screen.width; var height = window.screen.height - 100; if (Phaser.Device.desktop) { width = 400; height = 600; } var game = new Phaser.Game(width, height, Phaser.CANVAS, 'game', { preload: preload, create: create, update: update, render: render }); function preload() { game.load.image('bullet', 'img/bullet.png'); game.load.image('enemyBullet', 'img/enemy-bullet.png'); game.load.spritesheet('invader', 'img/invader32x32x4.png', 32, 32); game.load.image('ship', 'img/player.png'); game.load.spritesheet('kaboom', 'img/explode.png', 128, 128); game.load.image('starfield', 'img/starfield.png'); game.load.image('background', 'img/background2.png'); } var player; var aliens; var bullets; var bulletTime = 0; var cursors; var fireButton; var explosions; var starfield; var score = 0; var scoreString = ''; var scoreText; var lives; var enemyBullet; var firingTimer = 0; var stateText; var livingEnemies = []; var enemyBullets = []; function create() { game.physics.startSystem(Phaser.Physics.ARCADE); // The scrolling starfield background starfield = game.add.tileSprite(0, 0, width, height, 'starfield'); // Our bullet group bullets = game.add.group(); bullets.enableBody = true; bullets.physicsBodyType = Phaser.Physics.ARCADE; bullets.createMultiple(30, 'bullet'); bullets.setAll('anchor.x', 0.5); bullets.setAll('anchor.y', 1); bullets.setAll('outOfBoundsKill', true); bullets.setAll('checkWorldBounds', true); // The enemy's bullets enemyBullets = game.add.group(); enemyBullets.enableBody = true; enemyBullets.physicsBodyType = Phaser.Physics.ARCADE; enemyBullets.createMultiple(30, 'enemyBullet'); enemyBullets.setAll('anchor.x', 0.5); enemyBullets.setAll('anchor.y', 1); enemyBullets.setAll('outOfBoundsKill', true); enemyBullets.setAll('checkWorldBounds', true); // The hero! player = game.add.sprite(width / 2, height - 100, 'ship'); player.anchor.setTo(0.5, 0.5); game.physics.enable(player, Phaser.Physics.ARCADE); // The baddies! aliens = game.add.group(); aliens.enableBody = true; aliens.physicsBodyType = Phaser.Physics.ARCADE; createAliens(); // The score scoreString = 'Score : '; scoreText = game.add.text(10, 10, scoreString + score, { font: '20px Arial', fill: '#fff' }); // Lives lives = game.add.group(); game.add.text(game.world.width - 100, 10, 'Lives : ', { font: '20px Arial', fill: '#fff' }); // Text stateText = game.add.text(game.world.centerX, game.world.centerY, ' ', { font: '48px Arial', fill: '#fff' }); stateText.anchor.setTo(0.5, 0.5); stateText.visible = false; for (var i = 0; i < 3; i++) { var ship = lives.create(game.world.width - 100 + (30 * i), 60, 'ship'); ship.anchor.setTo(0.5, 0.5); ship.angle = 90; ship.alpha = 0.4; } // An explosion pool explosions = game.add.group(); explosions.createMultiple(30, 'kaboom'); explosions.forEach(setupInvader, this); // And some controls to play the game with cursors = game.input.keyboard.createCursorKeys(); fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); } game.input.touch.onTouchEnd(fireBullet); // add the gyro for mobile gyro.frequency = 10; var origX = 0; gyro.startTracking(function (o) { if (player.alive) { // Reset the player, then check for movement keys var delta = o.x - origX; player.body.velocity.x += delta * 100; origX = o.x; } }); } function createAliens() { for (var y = 0; y < 4; y++) { for (var x = 0; x < 5; x++) { var alien = aliens.create(x * 48, y * 50, 'invader'); alien.anchor.setTo(0.5, 0.5); alien.animations.add('fly', [0, 1, 2, 3], 20, true); alien.play('fly'); alien.body.moves = false; } } aliens.x = 20; aliens.y = 50; // All this does is basically start the invaders moving. Notice we're moving the Group they belong to, rather than the invaders directly. var tween = game.add.tween(aliens).to({ x: 150 }, 2000, Phaser.Easing.Linear.None, true, 0, 1000, true); // When the tween loops it calls descend tween.onLoop.add(descend, this); } function setupInvader(invader) { invader.anchor.x = 0.5; invader.anchor.y = 0.5; invader.animations.add('kaboom'); } function descend() { aliens.y += 10; } function update() { // Scroll the background starfield.tilePosition.y += 2; if (player.alive) { // Reset the player, then check for movement keys //player.body.velocity.setTo(0, 0); if (cursors.left.isDown) { player.body.velocity.x = -200; } else if (cursors.right.isDown) { player.body.velocity.x = 200; } // Firing? if (fireButton.isDown) { fireBullet(); } if (game.time.now > firingTimer) { enemyFires(); } // Run collision game.physics.arcade.overlap(bullets, aliens, collisionHandler, null, this); game.physics.arcade.overlap(enemyBullets, player, enemyHitsPlayer, null, this); } } function render() { // for (var i = 0; i < aliens.length; i++) // { // game.debug.body(aliens.children[i]); // } } function collisionHandler(bullet, alien) { // When a bullet hits an alien we kill them both bullet.kill(); alien.kill(); // Increase the score score += 20; scoreText.text = scoreString + score; // And create an explosion :) var explosion = explosions.getFirstExists(false); explosion.reset(alien.body.x, alien.body.y); explosion.play('kaboom', 30, false, true); if (aliens.countLiving() == 0) { score += 1000; scoreText.text = scoreString + score; enemyBullets.callAll('kill', this); stateText.text = " You Won, \n Click to restart"; stateText.visible = true; //the "click to restart" handler game.input.onTap.addOnce(restart, this); } } function enemyHitsPlayer(player, bullet) { bullet.kill(); var live = lives.getFirstAlive(); if (live) { live.kill(); } // And create an explosion :) var explosion = explosions.getFirstExists(false); explosion.reset(player.body.x, player.body.y); explosion.play('kaboom', 30, false, true); // When the player dies if (lives.countLiving() < 1) { player.kill(); enemyBullets.callAll('kill'); stateText.text = " GAME OVER \n Click to restart"; stateText.visible = true; //the "click to restart" handler game.input.onTap.addOnce(restart, this); } } function enemyFires() { // Grab the first bullet we can from the pool enemyBullet = enemyBullets.getFirstExists(false); livingEnemies.length = 0; aliens.forEachAlive(function (alien) { // put every living enemy in an array livingEnemies.push(alien); }); if (enemyBullet && livingEnemies.length > 0) { var random = game.rnd.integerInRange(0, livingEnemies.length - 1); // randomly select one of them var shooter = livingEnemies[random]; // And fire the bullet from this enemy enemyBullet.reset(shooter.body.x, shooter.body.y); game.physics.arcade.moveToObject(enemyBullet, player, 120); firingTimer = game.time.now + 2000; } } function fireBullet() { // To avoid them being allowed to fire too fast we set a time limit if (game.time.now > bulletTime) { // Grab the first bullet we can from the pool var bullet = bullets.getFirstExists(false); if (bullet) { // And fire it bullet.reset(player.x, player.y + 8); bullet.body.velocity.y = -400; bulletTime = game.time.now + 200; } } } function resetBullet(bullet) { // Called if the bullet goes out of the screen bullet.kill(); } function restart() { // A new level starts //resets the life count lives.callAll('revive'); // And brings the aliens back from the dead :) aliens.removeAll(); createAliens(); //revives the player player.revive(); //hides the text stateText.visible = false; } }) })();
js bugfix
js/game.js
js bugfix
<ide><path>s/game.js <ide> // And some controls to play the game with <ide> cursors = game.input.keyboard.createCursorKeys(); <ide> fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); <del> } <del> <del> game.input.touch.onTouchEnd(fireBullet); <add> <add> game.input.touch.onTouchEnd(fireBullet); <add> <ide> // add the gyro for mobile <del> gyro.frequency = 10; <del> var origX = 0; <del> gyro.startTracking(function (o) { <del> if (player.alive) { <del> // Reset the player, then check for movement keys <del> var delta = o.x - origX; <del> player.body.velocity.x += delta * 100; <del> origX = o.x; <del> } <del> }); <add> gyro.frequency = 10; <add> var origX = 0; <add> gyro.startTracking(function (o) { <add> if (player.alive) { <add> // Reset the player, then check for movement keys <add> var delta = o.x - origX; <add> player.body.velocity.x += delta * 100; <add> origX = o.x; <add> } <add> }); <ide> } <ide> <ide> function createAliens() {
Java
apache-2.0
46726bfb9f5dd4ac1df67398c9c92a9d1eb2c82f
0
McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,McLeodMoores/starling
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.volatility.surface; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.time.InstantProvider; import javax.time.calendar.LocalDate; import javax.time.calendar.TimeZone; import javax.time.calendar.ZonedDateTime; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.core.config.ConfigSource; import com.opengamma.core.marketdatasnapshot.VolatilitySurfaceData; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.CompiledFunctionDefinition; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.OpenGammaCompilationContext; import com.opengamma.financial.analytics.model.InstrumentTypeProperties; import com.opengamma.id.ExternalId; import com.opengamma.util.tuple.Pair; /** * */ public abstract class RawVolatilitySurfaceDataFunction extends AbstractFunction { private static final Logger s_logger = LoggerFactory.getLogger(RawVolatilitySurfaceDataFunction.class); /** * Value specification property for the surface result. This allows surface to be distinguished by instrument type (e.g. an FX volatility * surface, swaption ATM volatility surface). */ private final String _instrumentType; public RawVolatilitySurfaceDataFunction(final String instrumentType) { Validate.notNull(instrumentType, "Instrument Type"); _instrumentType = instrumentType; } public abstract boolean isCorrectIdType(ComputationTarget target); protected String getInstrumentType() { return _instrumentType; } @SuppressWarnings("unchecked") public static <X, Y> Set<ValueRequirement> buildDataRequirements(final VolatilitySurfaceSpecification specification, final VolatilitySurfaceDefinition<X, Y> definition, final ZonedDateTime atInstant, final String surfaceName, final String instrumentType) { final Set<ValueRequirement> result = new HashSet<ValueRequirement>(); final SurfaceInstrumentProvider<X, Y> provider = (SurfaceInstrumentProvider<X, Y>) specification.getSurfaceInstrumentProvider(); for (final X x : definition.getXs()) { for (final Y y : definition.getYs()) { final ExternalId identifier = provider.getInstrument(x, y, atInstant.toLocalDate()); result.add(new ValueRequirement(provider.getDataFieldName(), identifier)); } } final ValueProperties specProperties = ValueProperties.builder() .with(ValuePropertyNames.SURFACE, surfaceName) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, instrumentType) .with(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, specification.getSurfaceQuoteType()) .with(SurfacePropertyNames.PROPERTY_SURFACE_UNITS, specification.getQuoteUnits()).get(); result.add(new ValueRequirement(ValueRequirementNames.VOLATILITY_SURFACE_SPEC, specification.getTarget(), specProperties)); return result; } @Override public CompiledFunctionDefinition compile(final FunctionCompilationContext myContext, final InstantProvider atInstantProvider) { final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(myContext); final ConfigDBVolatilitySurfaceDefinitionSource definitionSource = new ConfigDBVolatilitySurfaceDefinitionSource(configSource); final ConfigDBVolatilitySurfaceSpecificationSource specificationSource = new ConfigDBVolatilitySurfaceSpecificationSource(configSource); final ZonedDateTime atInstant = ZonedDateTime.ofInstant(atInstantProvider, TimeZone.UTC); return new AbstractInvokingCompiledFunction(atInstant.withTime(0, 0), atInstant.plusDays(1).withTime(0, 0).minusNanos(1000000)) { @Override public ComputationTargetType getTargetType() { return ComputationTargetType.PRIMITIVE; } @SuppressWarnings("synthetic-access") @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { return Collections.singleton(new ValueSpecification(ValueRequirementNames.VOLATILITY_SURFACE_DATA, target.toSpecification(), createValueProperties() .withAny(ValuePropertyNames.SURFACE) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, _instrumentType) .withAny(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE) .withAny(SurfacePropertyNames.PROPERTY_SURFACE_UNITS).get())); } @SuppressWarnings("synthetic-access") @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Set<String> surfaceNames = desiredValue.getConstraints().getValues(ValuePropertyNames.SURFACE); if (surfaceNames == null || surfaceNames.size() != 1) { s_logger.info("Can only get a single surface; asked for " + surfaceNames); return null; } final Set<String> instrumentTypes = desiredValue.getConstraints().getValues(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE); if (instrumentTypes == null || instrumentTypes.size() != 1) { s_logger.info("Did not specify a single instrument type; asked for " + instrumentTypes); return null; } final String surfaceName = surfaceNames.iterator().next(); if (surfaceName == null) { throw new OpenGammaRuntimeException("Surface name was null"); } final String instrumentType = instrumentTypes.iterator().next(); if (instrumentType == null) { throw new OpenGammaRuntimeException("Instrument type was null"); } final VolatilitySurfaceDefinition<Object, Object> definition = getSurfaceDefinition(definitionSource, target, surfaceName, instrumentType); //TODO should be calling something that provides volatility surface market data final VolatilitySurfaceSpecification specification = getSurfaceSpecification(specificationSource, target, surfaceName, instrumentType); return buildDataRequirements(specification, definition, atInstant, surfaceName, instrumentType); } @SuppressWarnings("synthetic-access") @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) { String surfaceName = null; String instrumentType = null; String surfaceQuoteType = null; String surfaceUnits = null; for (final Map.Entry<ValueSpecification, ValueRequirement> entry : inputs.entrySet()) { final ValueSpecification spec = entry.getKey(); if (spec.getValueName().equals(ValueRequirementNames.VOLATILITY_SURFACE_SPEC)) { surfaceName = spec.getProperty(ValuePropertyNames.SURFACE); instrumentType = spec.getProperty(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE); surfaceQuoteType = spec.getProperty(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE); surfaceUnits = spec.getProperty(SurfacePropertyNames.PROPERTY_SURFACE_UNITS); break; } } assert surfaceName != null; assert instrumentType != null; return Collections.singleton(new ValueSpecification(ValueRequirementNames.VOLATILITY_SURFACE_DATA, target.toSpecification(), createValueProperties() .with(ValuePropertyNames.SURFACE, surfaceName) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, instrumentType) .with(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, surfaceQuoteType) .with(SurfacePropertyNames.PROPERTY_SURFACE_UNITS, surfaceUnits).get())); } @Override public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) { if (target.getType() != ComputationTargetType.PRIMITIVE) { return false; } return isCorrectIdType(target); } @SuppressWarnings({"unchecked", "synthetic-access" }) @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final ValueRequirement desiredValue = desiredValues.iterator().next(); final String surfaceName = desiredValue.getConstraint(ValuePropertyNames.SURFACE); final String instrumentType = desiredValue.getConstraint(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE); final String surfaceQuoteType = desiredValue.getConstraint(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE); final String surfaceUnits = desiredValue.getConstraint(SurfacePropertyNames.PROPERTY_SURFACE_UNITS); final ValueRequirement specificationRequirement = new ValueRequirement(ValueRequirementNames.VOLATILITY_SURFACE_SPEC, target.toSpecification(), ValueProperties.builder() .with(ValuePropertyNames.SURFACE, surfaceName) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, instrumentType) .with(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, surfaceQuoteType) .with(SurfacePropertyNames.PROPERTY_SURFACE_UNITS, surfaceUnits).get()); final VolatilitySurfaceDefinition<Object, Object> definition = getSurfaceDefinition(definitionSource, target, surfaceName, instrumentType); final Object specificationObject = inputs.getValue(specificationRequirement); if (specificationObject == null) { throw new OpenGammaRuntimeException("Specification with requirement " + specificationRequirement + " was null"); } final VolatilitySurfaceSpecification specification = (VolatilitySurfaceSpecification) specificationObject; final LocalDate valuationDate = executionContext.getValuationClock().today(); final SurfaceInstrumentProvider<Object, Object> provider = (SurfaceInstrumentProvider<Object, Object>) specification.getSurfaceInstrumentProvider(); final Map<Pair<Object, Object>, Double> volatilityValues = new HashMap<Pair<Object, Object>, Double>(); final ObjectArrayList<Object> xList = new ObjectArrayList<Object>(); final ObjectArrayList<Object> yList = new ObjectArrayList<Object>(); for (final Object x : definition.getXs()) { for (final Object y : definition.getYs()) { final ExternalId identifier = provider.getInstrument(x, y, valuationDate); final ValueRequirement requirement = new ValueRequirement(provider.getDataFieldName(), identifier); final Double volatility = (Double) inputs.getValue(requirement); if (volatility != null) { xList.add(x); yList.add(y); volatilityValues.put(Pair.of(x, y), volatility); } else { // System.out.println(identifier.toString()); } } } final VolatilitySurfaceData<Object, Object> volSurfaceData = new VolatilitySurfaceData<Object, Object>(definition.getName(), specification.getName(), definition.getTarget(), definition.getXs(), definition.getYs(), volatilityValues); final ValueSpecification result = new ValueSpecification(ValueRequirementNames.VOLATILITY_SURFACE_DATA, new ComputationTargetSpecification(definition.getTarget()), createValueProperties() .with(ValuePropertyNames.SURFACE, surfaceName) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, instrumentType) .with(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, specification.getSurfaceQuoteType()) .with(SurfacePropertyNames.PROPERTY_SURFACE_UNITS, specification.getQuoteUnits()).get()); return Collections.singleton(new ComputedValue(result, volSurfaceData)); } @Override public boolean canHandleMissingInputs() { return true; } @Override public boolean canHandleMissingRequirements() { return true; } @SuppressWarnings({"unchecked" }) protected VolatilitySurfaceDefinition<Object, Object> getSurfaceDefinition(final ConfigDBVolatilitySurfaceDefinitionSource source, final ComputationTarget target, final String definitionName, final String instrumentType) { final String fullDefinitionName = definitionName + "_" + target.getUniqueId().getValue(); final VolatilitySurfaceDefinition<Object, Object> definition = (VolatilitySurfaceDefinition<Object, Object>) source.getDefinition(fullDefinitionName, instrumentType); if (definition == null) { throw new OpenGammaRuntimeException("Could not get volatility surface definition named " + fullDefinitionName + " for instrument type " + instrumentType); } return definition; } protected VolatilitySurfaceSpecification getSurfaceSpecification(final ConfigDBVolatilitySurfaceSpecificationSource source, final ComputationTarget target, final String specificationName, final String instrumentType) { final String fullSpecificationName = specificationName + "_" + target.getUniqueId().getValue(); final VolatilitySurfaceSpecification specification = source.getSpecification(fullSpecificationName, instrumentType); if (specification == null) { throw new OpenGammaRuntimeException("Could not get volatility surface specification named " + fullSpecificationName); } return specification; } }; } }
projects/OG-Financial/src/com/opengamma/financial/analytics/volatility/surface/RawVolatilitySurfaceDataFunction.java
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.volatility.surface; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.time.InstantProvider; import javax.time.calendar.Clock; import javax.time.calendar.TimeZone; import javax.time.calendar.ZonedDateTime; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.core.config.ConfigSource; import com.opengamma.core.marketdatasnapshot.VolatilitySurfaceData; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.CompiledFunctionDefinition; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.OpenGammaCompilationContext; import com.opengamma.financial.analytics.model.InstrumentTypeProperties; import com.opengamma.id.ExternalId; import com.opengamma.util.tuple.Pair; /** * */ public abstract class RawVolatilitySurfaceDataFunction extends AbstractFunction { private static final Logger s_logger = LoggerFactory.getLogger(RawVolatilitySurfaceDataFunction.class); /** * Value specification property for the surface result. This allows surface to be distinguished by instrument type (e.g. an FX volatility * surface, swaption ATM volatility surface). */ private final String _instrumentType; public RawVolatilitySurfaceDataFunction(final String instrumentType) { Validate.notNull(instrumentType, "Instrument Type"); _instrumentType = instrumentType; } public abstract boolean isCorrectIdType(ComputationTarget target); protected String getInstrumentType() { return _instrumentType; } @SuppressWarnings("unchecked") public static <X, Y> Set<ValueRequirement> buildDataRequirements(final VolatilitySurfaceSpecification specification, final VolatilitySurfaceDefinition<X, Y> definition, final ZonedDateTime atInstant, final String surfaceName, final String instrumentType) { final Set<ValueRequirement> result = new HashSet<ValueRequirement>(); final SurfaceInstrumentProvider<X, Y> provider = (SurfaceInstrumentProvider<X, Y>) specification.getSurfaceInstrumentProvider(); for (final X x : definition.getXs()) { for (final Y y : definition.getYs()) { final ExternalId identifier = provider.getInstrument(x, y, atInstant.toLocalDate()); result.add(new ValueRequirement(provider.getDataFieldName(), identifier)); } } final ValueProperties specProperties = ValueProperties.builder() .with(ValuePropertyNames.SURFACE, surfaceName) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, instrumentType) .with(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, specification.getSurfaceQuoteType()) .with(SurfacePropertyNames.PROPERTY_SURFACE_UNITS, specification.getQuoteUnits()).get(); result.add(new ValueRequirement(ValueRequirementNames.VOLATILITY_SURFACE_SPEC, specification.getTarget(), specProperties)); return result; } @Override public CompiledFunctionDefinition compile(final FunctionCompilationContext myContext, final InstantProvider atInstantProvider) { final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(myContext); final ConfigDBVolatilitySurfaceDefinitionSource definitionSource = new ConfigDBVolatilitySurfaceDefinitionSource(configSource); final ConfigDBVolatilitySurfaceSpecificationSource specificationSource = new ConfigDBVolatilitySurfaceSpecificationSource(configSource); final ZonedDateTime atInstant = ZonedDateTime.ofInstant(atInstantProvider, TimeZone.UTC); return new AbstractInvokingCompiledFunction(atInstant.withTime(0, 0), atInstant.plusDays(1).withTime(0, 0).minusNanos(1000000)) { @Override public ComputationTargetType getTargetType() { return ComputationTargetType.PRIMITIVE; } @SuppressWarnings("synthetic-access") @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { return Collections.singleton(new ValueSpecification(ValueRequirementNames.VOLATILITY_SURFACE_DATA, target.toSpecification(), createValueProperties() .withAny(ValuePropertyNames.SURFACE) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, _instrumentType) .withAny(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE) .withAny(SurfacePropertyNames.PROPERTY_SURFACE_UNITS).get())); } @SuppressWarnings("synthetic-access") @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Set<String> surfaceNames = desiredValue.getConstraints().getValues(ValuePropertyNames.SURFACE); if (surfaceNames == null || surfaceNames.size() != 1) { s_logger.info("Can only get a single surface; asked for " + surfaceNames); return null; } final Set<String> instrumentTypes = desiredValue.getConstraints().getValues(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE); if (instrumentTypes == null || instrumentTypes.size() != 1) { s_logger.info("Did not specify a single instrument type; asked for " + instrumentTypes); return null; } final String surfaceName = surfaceNames.iterator().next(); if (surfaceName == null) { throw new OpenGammaRuntimeException("Surface name was null"); } final String instrumentType = instrumentTypes.iterator().next(); if (instrumentType == null) { throw new OpenGammaRuntimeException("Instrument type was null"); } final VolatilitySurfaceDefinition<Object, Object> definition = getSurfaceDefinition(definitionSource, target, surfaceName, instrumentType); //TODO should be calling something that provides volatility surface market data final VolatilitySurfaceSpecification specification = getSurfaceSpecification(specificationSource, target, surfaceName, instrumentType); return buildDataRequirements(specification, definition, atInstant, surfaceName, instrumentType); } @SuppressWarnings("synthetic-access") @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) { String surfaceName = null; String instrumentType = null; String surfaceQuoteType = null; String surfaceUnits = null; for (final Map.Entry<ValueSpecification, ValueRequirement> entry : inputs.entrySet()) { final ValueSpecification spec = entry.getKey(); if (spec.getValueName().equals(ValueRequirementNames.VOLATILITY_SURFACE_SPEC)) { surfaceName = spec.getProperty(ValuePropertyNames.SURFACE); instrumentType = spec.getProperty(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE); surfaceQuoteType = spec.getProperty(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE); surfaceUnits = spec.getProperty(SurfacePropertyNames.PROPERTY_SURFACE_UNITS); break; } } assert surfaceName != null; assert instrumentType != null; return Collections.singleton(new ValueSpecification(ValueRequirementNames.VOLATILITY_SURFACE_DATA, target.toSpecification(), createValueProperties() .with(ValuePropertyNames.SURFACE, surfaceName) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, instrumentType) .with(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, surfaceQuoteType) .with(SurfacePropertyNames.PROPERTY_SURFACE_UNITS, surfaceUnits).get())); } @Override public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) { if (target.getType() != ComputationTargetType.PRIMITIVE) { return false; } return isCorrectIdType(target); } @SuppressWarnings({"unchecked", "synthetic-access" }) @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final ValueRequirement desiredValue = desiredValues.iterator().next(); final String surfaceName = desiredValue.getConstraint(ValuePropertyNames.SURFACE); final String instrumentType = desiredValue.getConstraint(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE); final String surfaceQuoteType = desiredValue.getConstraint(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE); final String surfaceUnits = desiredValue.getConstraint(SurfacePropertyNames.PROPERTY_SURFACE_UNITS); final ValueRequirement specificationRequirement = new ValueRequirement(ValueRequirementNames.VOLATILITY_SURFACE_SPEC, target.toSpecification(), ValueProperties.builder() .with(ValuePropertyNames.SURFACE, surfaceName) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, instrumentType) .with(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, surfaceQuoteType) .with(SurfacePropertyNames.PROPERTY_SURFACE_UNITS, surfaceUnits).get()); final VolatilitySurfaceDefinition<Object, Object> definition = getSurfaceDefinition(definitionSource, target, surfaceName, instrumentType); final Object specificationObject = inputs.getValue(specificationRequirement); if (specificationObject == null) { throw new OpenGammaRuntimeException("Specification with requirement " + specificationRequirement + " was null"); } final VolatilitySurfaceSpecification specification = (VolatilitySurfaceSpecification) specificationObject; final Clock snapshotClock = executionContext.getValuationClock(); final ZonedDateTime now = snapshotClock.zonedDateTime(); final SurfaceInstrumentProvider<Object, Object> provider = (SurfaceInstrumentProvider<Object, Object>) specification.getSurfaceInstrumentProvider(); final Map<Pair<Object, Object>, Double> volatilityValues = new HashMap<Pair<Object, Object>, Double>(); final ObjectArrayList<Object> xList = new ObjectArrayList<Object>(); final ObjectArrayList<Object> yList = new ObjectArrayList<Object>(); for (final Object x : definition.getXs()) { for (final Object y : definition.getYs()) { final ExternalId identifier = provider.getInstrument(x, y, now.toLocalDate()); final ValueRequirement requirement = new ValueRequirement(provider.getDataFieldName(), identifier); final Double volatility = (Double) inputs.getValue(requirement); if (volatility != null) { xList.add(x); yList.add(y); volatilityValues.put(Pair.of(x, y), volatility); } else { // System.out.println(identifier.toString()); } } } final VolatilitySurfaceData<Object, Object> volSurfaceData = new VolatilitySurfaceData<Object, Object>(definition.getName(), specification.getName(), definition.getTarget(), definition.getXs(), definition.getYs(), volatilityValues); final ValueSpecification result = new ValueSpecification(ValueRequirementNames.VOLATILITY_SURFACE_DATA, new ComputationTargetSpecification(definition.getTarget()), createValueProperties() .with(ValuePropertyNames.SURFACE, surfaceName) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, instrumentType) .with(SurfacePropertyNames.PROPERTY_SURFACE_QUOTE_TYPE, specification.getSurfaceQuoteType()) .with(SurfacePropertyNames.PROPERTY_SURFACE_UNITS, specification.getQuoteUnits()).get()); return Collections.singleton(new ComputedValue(result, volSurfaceData)); } @Override public boolean canHandleMissingInputs() { return true; } @Override public boolean canHandleMissingRequirements() { return true; } @SuppressWarnings({"unchecked" }) protected VolatilitySurfaceDefinition<Object, Object> getSurfaceDefinition(final ConfigDBVolatilitySurfaceDefinitionSource source, final ComputationTarget target, final String definitionName, final String instrumentType) { final String fullDefinitionName = definitionName + "_" + target.getUniqueId().getValue(); final VolatilitySurfaceDefinition<Object, Object> definition = (VolatilitySurfaceDefinition<Object, Object>) source.getDefinition(fullDefinitionName, instrumentType); if (definition == null) { throw new OpenGammaRuntimeException("Could not get volatility surface definition named " + fullDefinitionName + " for instrument type " + instrumentType); } return definition; } protected VolatilitySurfaceSpecification getSurfaceSpecification(final ConfigDBVolatilitySurfaceSpecificationSource source, final ComputationTarget target, final String specificationName, final String instrumentType) { final String fullSpecificationName = specificationName + "_" + target.getUniqueId().getValue(); final VolatilitySurfaceSpecification specification = source.getSpecification(fullSpecificationName, instrumentType); if (specification == null) { throw new OpenGammaRuntimeException("Could not get volatility surface specification named " + fullSpecificationName); } return specification; } }; } }
tiny local date cleanup
projects/OG-Financial/src/com/opengamma/financial/analytics/volatility/surface/RawVolatilitySurfaceDataFunction.java
tiny local date cleanup
<ide><path>rojects/OG-Financial/src/com/opengamma/financial/analytics/volatility/surface/RawVolatilitySurfaceDataFunction.java <ide> import java.util.Set; <ide> <ide> import javax.time.InstantProvider; <del>import javax.time.calendar.Clock; <add>import javax.time.calendar.LocalDate; <ide> import javax.time.calendar.TimeZone; <ide> import javax.time.calendar.ZonedDateTime; <ide> <ide> throw new OpenGammaRuntimeException("Specification with requirement " + specificationRequirement + " was null"); <ide> } <ide> final VolatilitySurfaceSpecification specification = (VolatilitySurfaceSpecification) specificationObject; <del> final Clock snapshotClock = executionContext.getValuationClock(); <del> final ZonedDateTime now = snapshotClock.zonedDateTime(); <add> final LocalDate valuationDate = executionContext.getValuationClock().today(); <ide> final SurfaceInstrumentProvider<Object, Object> provider = (SurfaceInstrumentProvider<Object, Object>) specification.getSurfaceInstrumentProvider(); <ide> final Map<Pair<Object, Object>, Double> volatilityValues = new HashMap<Pair<Object, Object>, Double>(); <ide> final ObjectArrayList<Object> xList = new ObjectArrayList<Object>(); <ide> final ObjectArrayList<Object> yList = new ObjectArrayList<Object>(); <ide> for (final Object x : definition.getXs()) { <ide> for (final Object y : definition.getYs()) { <del> final ExternalId identifier = provider.getInstrument(x, y, now.toLocalDate()); <add> final ExternalId identifier = provider.getInstrument(x, y, valuationDate); <ide> final ValueRequirement requirement = new ValueRequirement(provider.getDataFieldName(), identifier); <ide> final Double volatility = (Double) inputs.getValue(requirement); <ide> if (volatility != null) {
JavaScript
mit
f96f6c6dfa432886fc97f3c054a2a6c53e946f72
0
aspectron/iris-app,aspectron/iris-app
// // -- IRIS Toolkit - User Login // // Copyright (c) 2014 ASPECTRON Inc. // 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 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 fs = require('fs'); var _ = require('underscore'); var events = require('events'); var util = require('util'); var crypto = require('crypto'); var scrypt = require('./scrypt'); var base58 = require('iris-base58'); var path = require('path'); var notp = require('notp'); var base32 = require('thirty-two'); var UUID = require("node-uuid"); // http://stackoverflow.com/questions/14382725/how-to-get-the-correct-ip-address-of-a-client-into-a-node-socket-io-app-hosted-o function getClientIp(req) { var ipAddress; // Amazon EC2 / Heroku workaround to get real client IP var forwardedIpsStr = req.header('x-forwarded-for'); if (forwardedIpsStr) { // 'x-forwarded-for' header may return multiple IP addresses in // the format: "client IP, proxy 1 IP, proxy 2 IP" so take the // the first one var forwardedIps = forwardedIpsStr.split(','); ipAddress = forwardedIps[0]; } if (!ipAddress) { // Ensure getting client IP address still works in // development environment ipAddress = req.connection.remoteAddress; } return ipAddress; } function merge(dst, src) { _.each(src, function(v, k) { if(_.isArray(v)) { dst[k] = [ ]; merge(dst[k], v); } else if(_.isObject(v)) { if(!dst[k] || _.isString(dst[k]) || !_.isObject(dst[k])) dst[k] = { }; merge(dst[k], v); } else { if(_.isArray(src)) dst.push(v); else dst[k] = v; } }) } function EmailHelper(core, options){ var self = this; self.emailTpl = { recovery : { body: 'Please complete your password recovery by visiting the following link: <a href="{url}{token}">{url}{token}</a> .', subject: 'Please reset your password' }, passwordchanged:{ body: 'Your password have been changed.', subject: 'Password have been updated.' }, activation:{ body: 'Account is created but now you need to activate. Activate it by visiting following link: <a href="{url}{token}">{url}{token}</a> .', subject: 'Activate your account.' } } if ( _.isObject(options.emailTpl) ) merge(self.emailTpl, options.emailTpl); self.buildEmail = function(tpl, args){ html = tpl+''; _.each(args, function(v, k){ html = html.replace(new RegExp('{'+k+'}', 'g'), v); }); return html; } self.getMailer = function(){ return options.mailer || core.mailer; } self.sendEmail = function(tplKey, args, callback){ callback = callback || function(err){ err && console.log("SendEmail:error", err) }; var mailer = self.getMailer(); if (!mailer) return callback({error: 'No Mailer: Could not send email.'}); var tpl = self.emailTpl[tplKey]; if (!tpl) return callback({error: 'Email template missing for "'+tplKey+'".'}); var html = self.buildEmail(tpl.body, args); var text = tpl.textBody? self.buildEmail(tpl.textBody, args) : html; var mailOptions = { from: args.from || options.emailFrom || '[email protected]', to: args.to, subject: tpl.subject, html: html, text : text }; mailer[options.sendMailMethod || 'sendMail'](mailOptions, function (err, response) { console.log('mailer.sendMail', mailOptions, arguments); callback && callback(err, response); }); } } function Login(core, authenticator, options) { var self = this; events.EventEmitter.call(self); self.loginTracking = { } self.throttle = {attempts : 3, min : 3 }; self.passwordRecoveryTokens = {}; options.sessionKey = options.sessionKey || 'user'; if(_.isObject(options.throttle)) _.extend(self.throttle, options.throttle); self.authenticator = authenticator; if (!authenticator.mailer) authenticator.mailer = self; EmailHelper.call(self, core, options); function getLoginTracking(ip) { var o = self.loginTracking[ip]; if(!o) o = self.loginTracking[ip] = { unblock_ts : 0, attempts : 0, failures : 0 } return o; } self.authenticate = function(args, callback) { if(!self.authenticator) throw new Error("Login constructor requires authenticator argument"); return self.authenticator.authenticate(args, callback); } self._getLogin = function (viewPath, req, res) { res.setHeader('login-required', true); res.render(viewPath, { Client : self.getClientJavaScript(), req: req }, function(err, html) { if(err) { console.log(err); return res.end("Server Error"); } res.end(strip(html)); }); }; self.getLogin = function(req, res, next) { self._getLogin(options.view || path.join(__dirname, 'views/login.ejs'), req, res); } self._getPasswordRecovery = function(data, req, res, next) { var viewPath = options.passwordRecoveryView || path.join(__dirname, 'views/password-recovery.ejs'); if(!data.token) data.token = ''; data.req = req; res.render(viewPath, data, function(err, html) { if(err) return res.end("Server Error"); res.end(strip(html)); }); } self.getPasswordRecovery = function(req, res, next) { self._getPasswordRecovery( {Client : self.getClientJavaScript(), STAGE:'begin'}, req, res, next); } self.getPasswordRecoveryWithToken = function(req, res, next){ var token = req.params.token; var data = {Client : self.getClientJavaScript(), STAGE:'no-such-token'} self.authenticator.passwordRecovery({stage:'check', token: token}, function(err, success){ if (success){ data.STAGE = 'finish'; data.token = token; } self._getPasswordRecovery(data, req, res, next); }); } self.postPasswordRecovery = function(req, res, next) { var data = req.body; if (!data.email) return res.status(401).json({error: 'Email is required.'}); data.url = req.protocol + '://' + req.get('host') + (req.originalUrl.split('?')[0]+'/').replace(/\/\//g, "/"); data.stage = 'begin'; self.authenticator.passwordRecovery(data, function(err, data){ if (err) return res.status(401).json(err); res.status(200).json({success: true, data: data}); }); } self.postPasswordRecoveryWithToken = function(req, res, next){ var token = req.params.token; //var tokenData = self.passwordRecoveryTokens[token]; if(!token) return res.status(401).json({ error : "Password Recovery Error, <a href='"+(options.path || '')+"/password-recovery'>please restart password recovery process</a>. (Error Code: A7)"}) //if(!tokenData.email) //return res.status(401).json({ error : "Password Recovery Error, please restart password recovery process. (Error Code: A8)"}); var data = req.body; if (!data.password) return res.status(401).json({ error : "Password Recovery Error, password is required."}); self.authenticator.passwordRecovery({stage:'finish', token: token, password: data.password}, function(err, result){ delete req.session[options.sessionKey +'auth-passrecovery']; if (err) return res.status(401).json(err); res.json(result); }); } self.getActivationWithToken = function(req, res, next){ var token = req.params.token; if(!token) return req.redirectWithMsg('/', 'activation', {success: false, error:"Account activation Error, Token is required"}) self.authenticator.activateAccount({token: token, stage:'finish'}, function(err){ if (err) return req.redirectWithMsg('/', 'activation', {success: false, error:err}); req.redirectWithMsg(options.activationRedirectUrl || '/', 'activation', {success: true}) }) } self.getResendActivation = function(req, res, next) { var viewPath = options.resendActivationView || path.join(__dirname, 'views/resend-activation.ejs'); var data = {req: req, res: res, activePage: "resend-activation", Client : self.getClientJavaScript()}; res.render(viewPath, data, function(err, html) { if(err){ res.render("resend-activation", data, function(err, html) { if(err) return res.end("Server Error"); res.end(strip(html)); }); return } res.end(strip(html)); }); } self.postResendActivation = function(req, res, next) { var data = req.body; if(!data.username) return res.status(401).json({ error : "Username is required" }); data.url = req.protocol + '://' + req.get('host') + ((options.path || '')+'/activation/').replace(/\/\//g, "/"); self.resendActivation({ username : data.username, url: data.url }, function(err, result) { if (!result) return res.status(401).json(err || {error: 'Unable to send activation code. Please try again later.'}); res.json(result); }); } self.resendActivation = function(args, callback) { if(!self.authenticator) throw new Error("Login constructor requires authenticator argument"); args.stage = 'resend'; self.authenticator.activateAccount(args, callback); } self.postChallenge = function(req, res, next) { res.type('application/json'); if(req.body.isregistration || req.body.ispassrecovery){ self.authenticator.getClientAuth(function(err, auth) { req.session[options.sessionKey+ (req.body.ispassrecovery? 'auth-passrecovery' :'auth-reg')] = auth; res.status(200).json({ auth : auth }); }); return; } var ts = Date.now(); var ip = getClientIp(req); var o = getLoginTracking(ip); if(options.throttle && o.unblock_ts > ts) return res.status(401).json({ error : "Your access to the login system remains blocked for "+getDurationString(o.unblock_ts-ts), throttle : true, ts: parseInt( (o.unblock_ts-ts) / 1000 ) }); o.attempts++; if(options.throttle && o.attempts > self.throttle.attempts) { o.attempts = 0; o.failures++; o.unblock_ts = ts+(self.throttle.min*((o.failures+1)/2)*60*1000); return res.status(401).json({ error : "Your access to the login system has been blocked for "+getDurationString(o.unblock_ts-ts), throttle : true, ts: parseInt( (o.unblock_ts-ts) / 1000 ) }); } self.authenticator.getClientAuth(function(err, auth) { req.session[options.sessionKey+'auth'] = auth; res.status(200).json({ auth : auth }); }); } self.logout = function(req, res, next) { var user = req.session[options.sessionKey]; if(user){ delete req.session[options.sessionKey]; self.emit('user-logout', user, req, res, next); } } self.getLogout = function(req, res, next) { self.logout.apply(self, arguments); var redirect_uri = options.logoutRedirect || '/'; if(options.useRedirectUriAfterLogout && req.query && req.query.redirect_uri){ redirect_uri = req.query.redirect_uri; } res.redirect(redirect_uri); } self.postLogout = function(req, res, next) { self.logout.apply(self, arguments); res.send(200); } self.postLogin = function(req, res, next) { res.type('application/json'); if(!req.session[options.sessionKey+'auth']) return res.status(401).json({ error : "User name and password required" }); if(!req.body.username || !req.body.password || !req.body.sig) return res.status(401).json({ error : "User name and password required" }); var ts = Date.now(); var ip = getClientIp(req); var o = getLoginTracking(ip); if(options.throttle && o.unblock_ts > ts) return res.status(401).json({ error : "Your access to the login system remains blocked for another "+getDurationString(o.unblock_ts-ts), throttle : true, ts: parseInt( (o.unblock_ts-ts) / 1000 ) }); self.authenticate({ username : req.body.username, password : req.body.password, auth : req.session[options.sessionKey+'auth'], sig : req.body.sig, totpToken : req.body.totpToken }, function(err, user) { delete req.session[options.sessionKey+'auth']; if(!user) { if (err && err.activationRequired) return res.status(401).json({ error : "Waiting for account activation.", activationRequired: true}); if(options.throttle && o.attempts > self.throttle.attempts) { o.attempts = 0; o.failures++; o.unblock_ts = ts+(self.throttle.min*((o.failures+1)/2)*60*1000); res.status(401).json({ error : "Your access to the login system has been blocked for "+getDurationString(o.unblock_ts-ts), throttle : true, ts: parseInt( (o.unblock_ts-ts) / 1000 ) }); } else { if(err) res.status(401).json(err); else res.status(401).json({ error : "Wrong login credentials" }); } } else { if(user.blocked || user.blacklisted) { res.status(401).json({ error : "User access blocked by administration"}); } else { self.validateUser(user, function(err, userOk) { if(err) res.status(401).json(err); else { delete self.loginTracking[ip]; req.session[options.sessionKey] = user; delete req.session[options.sessionKey+'auth']; self.emit('user-login', user, req, res); (self.authenticator instanceof events.EventEmitter) && self.authenticator.emit('user-login', user); res.json({ success : true }); } }) } } }) } self.postRegister = function(req, res, next) { res.type('application/json'); var data = req.body; if(!req.session[options.sessionKey+'auth-reg']) return res.status(401).json({ error : "User name and password required" }); if(!data.username || !data.password || !data.sig) return res.status(401).json({ error : "User name and password required" }); data.url = req.protocol + '://' + req.get('host') + ((options.path || '')+'/activation/').replace(/\/\//g, "/"); self.register({ username : data.username, password : data.password, email : data.email, auth : req.session[options.sessionKey+'auth-reg'], sig : data.sig, totpToken : data.totpToken, url: data.url }, function(err, result) { delete req.session[options.sessionKey+'auth-reg']; if (!result) return res.status(401).json(err || {error: 'Unable to create account. Please try again later.'}); res.json(result); }); } self.register = function(args, callback) { if(!self.authenticator) throw new Error("Login constructor requires authenticator argument"); args.stage = 'begin'; self.authenticator.activateAccount(args, callback); } self.postConfigureTOTP = function(req, res, next){ self.authenticator.configureTOTP(req.body, function(err, result){ if (err) return res.status(401).json(err); res.json(err); }); } self.validateUser = function(user, callback) { /* if(!user.confirmed) { return callback({ error : "Waiting for user confirmation"}); } */ callback(null, true); } function strip(str) { return str; //return str.replace(/\s{2,}/g, ' ');//.replace(/ENTER/g,'\n'); //return str.replace(/[\n\r]/g, ' ').replace(/\s{2,}/g, ' ');//.replace(/ENTER/g,'\n'); //return str.replace(/[\n\r]/g, '\t').replace(/ {2,}/g, ' ');//.replace(/\/**\//g,'/*\n*/'); } function getDurationString(d) { var m = Math.floor(d / 1000 / 60); var s = Math.floor(d / 1000 % 60); if(s < 10) s = '0'+s; return m+' min '+s+' sec'; } self.init = function(app) { var _path = options.path || ''; app.get(_path+'/logout', self.getLogout); app.post(_path+'/logout', self.postLogout); app.get(_path+'/login', self.getLogin); app.get(_path+'/password-recovery', self.getPasswordRecovery); app.get(_path+'/password-recovery/:token', self.getPasswordRecoveryWithToken); app.post(_path+'/password-recovery', self.postPasswordRecovery); app.post(_path+'/password-recovery/:token', self.postPasswordRecoveryWithToken); app.post(_path+'/challenge', self.postChallenge); app.post(_path+'/login', self.postLogin); app.post(_path+'/register', self.postRegister); app.post(_path+'/configure-totp', self.postConfigureTOTP); app.get(_path+'/activation/:token', self.getActivationWithToken); app.get(_path+'/resend-activation/', self.getResendActivation); app.post(_path+'/resend-activation/', self.postResendActivation); app.use('/login/resources', core.express.static(path.join(__dirname, '../http'))); } self.redirectIfGuest = function(app, reqPath, redirectPath){ reqPath = reqPath || '*'; redirectPath = redirectPath || _path+'/login'; app.use(reqPath, function(req, res, next) { if(!req.session[options.sessionKey]) return res.redirect(redirectPath); next(); }); } self.getClientJavaScript = function() { var text = Client.toString(); text = text .replace("CLIENT_PATH", JSON.stringify(options.path || '')) .replace("CLIENT_ARGS", JSON.stringify(self.authenticator.client)); return "("+text+")()"; } } util.inherits(Login, events.EventEmitter); function Authenticator(core, options) { var self = this; events.EventEmitter.call(self); self.client = options.client; self.iterations = options.iterations || 100000; self.keylength = options.keylength || 4096/32; self.saltlength = options.saltlength || 4096/32; self.tokenTimeout = { activation: 10 * 60 * 1000, passwordRecovery: 10 * 60 * 1000 }; self.tokens = {}; if (_.isObject(options.tokenTimeout)) self.tokenTimeout = _.extend(self.tokenTimeout, options.tokenTimeout); if (options.mailer) self.mailer = options.mailer; function encrypt(text) { if(!text || !options.cipher) return text; var key = _.isString(options.key) ? new Buffer(options.key,'hex') : options.key; var cipher = crypto.createCipher(options.cipher, key); var crypted = cipher.update(text, 'utf8', 'binary'); crypted += cipher.final('binary'); return base58.encode(new Buffer(crypted, 'binary')); } function decrypt(text, callback) { if(!text || !options.cipher) return callback(null, text); var key = _.isString(options.key) ? new Buffer(options.key,'hex') : options.key; base58.decode(text, function(err, data) { if(err) return callback(err); var decipher = crypto.createDecipher(options.cipher, key); var decrypted = decipher.update(data, 'binary', 'utf8'); decrypted += decipher.final('utf8'); callback(null, decrypted); }); } function hex2uint8array(hex) { var bytes = new Uint8Array(hex.length/2); for(var i=0; i< hex.length-1; i+=2){ bytes[i] = (parseInt(hex.substr(i, 2), 16)); } return bytes; } self.getClientAuth = function(callback) { crypto.randomBytes(256, function(err, bytes) { if(err) return callback(err); callback(null, bytes.toString('hex')); }) } self.generatePBKDF2 = function(password, salt, iterations, keylength, callback) { crypto.pbkdf2(password, salt, iterations, keylength, function(err, key) { if(err) return callback(err); var res = ['pbkdf2', iterations, keylength, base58.encode(key), base58.encode(salt)].join(':'); callback(null, res); }) } self.generateStorageHash = function(password, salt, callback) { if(!password) return callback('No password provided') if(_.isFunction(salt)) { callback = salt; salt = undefined; } if(_.isString(salt)) { salt = new Buffer(salt, 'hex'); } if(!salt) { crypto.randomBytes(self.saltlength, function(err, _salt) { if(err) return callback(err); self.generatePBKDF2(password, _salt, self.iterations, self.keylength, function(err, key) { callback(err, encrypt(key)); }) }); } else { self.generatePBKDF2(password, salt, self.iterations, self.keylength, function(err, key) { callback(err, encrypt(key)); }) } } self.generateExchangeHash = function(password, callback) { if(options.client.sha256) { var hash = crypto.createHash('sha256').update(password).digest('hex'); callback(null, hash); } else if(options.client.scrypt) { var sc = options.client.scrypt; var hash = scrypt.crypto_scrypt(scrypt.encode_utf8(password), hex2uint8array(sc.salt), sc.n, sc.r, sc.p, sc.keyLength); callback(null, scrypt.to_hex(hash)); } } self.compareStorageHash = function(args, _hash, callback) { var hash = decrypt(_hash, function(err, hash) { if(err) return callback(err); if (!hash) return callback({ error : "Wrong password please try password recovery."}) var parts = hash.split(':'); if(parts.length != 5 || parts[0] != 'pbkdf2' || parseInt(parts[1]) != self.iterations) return callback({ error : "Wrong encoded hash parameters"}) var iterations = parseInt(parts[1]); var keylength = parseInt(parts[2]); base58.decode(parts[4], function(err, salt) { if(err) return callback(err); self.generatePBKDF2(args.password, salt, iterations, keylength, function(err, key) { if(err) return callback(err); callback(null, hash === key); }) }); }); } self.validateSignature = function(args, callback) { console.log("validateSignature",args); var sig = crypto.createHmac('sha256', new Buffer(args.auth, 'hex')).update(new Buffer(args.password, 'hex')).digest('hex'); callback(null, args.sig == sig); } self.compare = function(args, storedHash, callback) { console.log("WARNGING! - Signature Validation is Disabled"); // self.validateSignature(args, function(err, match) { // if(!match) // return callback({ error : "Wrong authentication signature"}); self.compareStorageHash(args, storedHash, function(err, match) { if(err) return callback(err); if(!match) return callback({ error : "Unknown user name or password"}) callback(null, true); }) // }) }; self.generateTotpSecretKey = function(length) { length = length || 10; return crypto.randomBytes(length).toString('hex'); }; self.getTotpKeyForGoogleAuthenticator = function (key) { return base32.encode(key); }; self.getBarcodeUrlPart = function (email, key) { return 'otpauth://totp/' + email + '?secret=' + self.getTotpKeyForGoogleAuthenticator(key)+'&issuer='+(options.totpissuer || ''); }; self.getBarcodeUrlForGoogleAuthenticator = function (email, key) { return 'https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=' + self.getBarcodeUrlPart(email, key) }; self.getDataForGoogleAuthenticator = function (email, key) { if (!key) return {}; return { totpKey: self.getTotpKeyForGoogleAuthenticator(key), barcodeUrl: self.getBarcodeUrlForGoogleAuthenticator(email, key), barcodeUrlPart: self.getBarcodeUrlPart(email, key) }; } self.verifyTotpToken = function (token, key) { return notp.totp.verify(token, key, {}); }; self.getUserTOTP = function(args, callback){ callback({error: 'No getUserTOTP handler.'}); } self.setUserTOTP = function(args, callback){ callback({error: 'No setUserTOTP handler.'}); } self.configureTOTP = function (args, callback) { if (!args.email) return callback({ error : "Email field is required."}); var email = args.email.toLowerCase(); if (args.stage == 'init' || args.stage == 'get-data') { self.getUserTOTP({ email : email }, function(err, result) { if(err) return callback(err); if(!result) return callback({ error : "Server Error. Please try again later." }); var totpData = {}; var enabled = false; if (result.totp && result.totp.key) { totpData = self.getDataForGoogleAuthenticator(email, result.totp.key); enabled = result.totp.enabled; send(); } else if (args.stage == 'init') { var totpKey = self.generateTotpSecretKey(); self.setUserTOTP({ email : email, totp: {enabled: false, key: totpKey} }, function(err, result) { if (err) return callback({ error : "Server Error. Please try again later." }); totpData = self.getDataForGoogleAuthenticator(email, totpKey); send(); }); } else { send() } function send () { var data = { enabled: enabled, totpData: enabled? {}: totpData }; console.log(data); return callback(null, data); } }); } else if (args.stage == 'change') { if (_.isUndefined(args.enable)) return callback({ error : "Enable/Disable field is required."}); if (args.code == undefined) return callback({ error : "One time password is required."}); self.getUserTOTP({ email : email }, function(err, result) { if(err) return callback({ error : "Server Error. Please try again later." }); if(!result) return callback({ error : "Server Error. Please try again later." }); if (!self.verifyTotpToken(args.code, result.totp.key)) { return callback({error : "Wrong one time password"}); } if (args.enable) { if (result.totp.enabled) { return callback(null, {success: true, message: 'Two-factor authentication is enabled'}); } self.setUserTOTP({ email : email, totp: true }, function(err, result) { if (err) return callback({ error : "Server Error. Please try again later." }); callback(null, {success: true, message: 'Two-factor authentication is enabled'}); }); } else { self.setUserTOTP({ email : email, totp: false}, function(err, result) { if (err) return callback({ error : "Server Error. Please try again later." }); callback(null, {success: true, message: 'Two-factor authentication is disabled'}); }); } }); } }; self.getUserByEmail = function(args, callback){ callback({error: 'No getUserByEmail handler.'}); } //TODO: override in IRISRpcAuthenticator self.activateAccountBegin = function(args, callback){ callback({error: 'No activateAccountBegin handler.'}); } self.activateAccountResend = function(args, callback){ callback({error: 'No activateAccountResend handler.'}); } self.activateAccountFinish = function(args, callback){ callback({error: 'No activateAccountBegin handler.'}); } self.activateAccount = function(args, callback){ switch(args.stage.toLowerCase()){ case 'begin': self.activateAccountBegin(args, callback); break; case 'resend': self.activateAccountResend(args, callback); break; case 'finish': self.activateAccountFinish(args, callback); break; default: callback({error: 'Invalid activateAccount stage.'}); break; } } self.passwordRecovery = function(args, callback){ switch(args.stage.toLowerCase()){ case 'begin': self.passwordRecoveryBegin(args, callback); break; case 'check': self.passwordRecoveryCheck(args, callback); break; case 'resend': self.passwordRecoveryResend(args, callback); break; case 'finish': self.passwordRecoveryFinish(args, callback); break; default: callback({error: "Invalid passwordRecovery stage."}); break; } } self.sendPasswordRecoveryTokenEmail = function(args, callback){ self.mailer.sendEmail('recovery', args); callback(null, true); } self.passwordRecoveryBegin = function(args, callback){ args.email = args.email.toLowerCase(); //var tokenData = self.getTokenData('passwordRecovery', function(o){o.email == args.email}); //if (tokenData) //return callback({error: "Password recovery already in process", alreadyRunning: true}) self.getUserByEmail(args.email, function(err, user){ if (err) return callback(err); if (!self.mailer) return callback({error: 'No Mailer configured.'}); args.to = args.email; args.token = self.createToken('passwordRecovery', {email: args.email}); self.sendPasswordRecoveryTokenEmail(args, callback); }); } self.passwordRecoveryCheck = function(args, callback){ var tokenData = self.getTokenData('passwordRecovery', args.token); if (!tokenData) return callback({error: "Invalid password recovery token.", tokenMissing: true}); if (!tokenData.email) return callback({error: "Invalid password recovery token.", tokenEmailMissing: true}); callback(null, {success: true}); } self.passwordRecoveryResend = function(args, callback){ args.email = args.email.toLowerCase(); var tokenData = self.getTokenData('passwordRecovery', function(o){o.email == args.email}); if (!tokenData || !tokenData.email) return callback({error: "Please reinitiate password recovery.", tokenMissing: true}); args.to = tokenData.email; args.token = tokenData.token; self.sendPasswordRecoveryTokenEmail(args, callback); } self.passwordRecoveryFinish = function(args, callback){ var tokenData = self.getTokenData('passwordRecovery', args.token); if (!args.password) return callback({error: "Password is required.", passwordMissing: true}); if (!tokenData) return callback({error: "Invalid password recovery token.", tokenMissing: true}); if (!tokenData.email) return callback({error: "Invalid password recovery token.", tokenEmailMissing: true}); self.generateStorageHash(args.password, function(err, storageHash) { self.setUserPassword({email: tokenData.email, password: storageHash}, function(err, result){ if (err) return res.status(401).json(err); self.mailer.sendEmail('passwordchanged', {email: tokenData.email, to: tokenData.email}) self.deleteTokenData('passwordRecovery', args.token); callback(null, {success: true, result: result}); }); }); } self.setUserPassword = function(args, callback){ callback({error: 'No setUserPassword handler.'}); } self.createToken = function(purpose, data, expiryTs){ expiryTs = expiryTs || Date.now() + (self.tokenTimeout[purpose] || 10 * 60 * 1000); data.ts = expiryTs; var idHex = crypto.createHash('sha1').update(UUID.v1()).digest('hex'); var token = base58.encodeSync(new Buffer(idHex, 'hex')); if (!self.tokens[purpose]) self.tokens[purpose] = {}; self.tokens[purpose][token] = _.extend({}, data); self.tokens[purpose][token].token = token; self.startTokenMonitor(); return token; //return {token: token, data: self.tokens[purpose][token]}; } self.getTokenData = function(purpose, token){ if (!self.tokens[purpose]) return false; if (_.isFunction(token)) return _.find(self.tokens[purpose], token); if (self.tokens[purpose][token]) return self.tokens[purpose][token]; return false; } self.deleteTokenData = function(purpose, token){ var d = false; if (self.tokens[purpose] && self.tokens[purpose][token]){ d = self.tokens[purpose][token]; delete self.tokens[purpose][token]; } return d; } self.startTokenMonitor = function(){ if (!self.tokenMonitorRunning) dpc(tokenRepair); } function tokenRepair() { var ts = Date.now(); var hasTokens = false; _.each(self.tokens, function(list, purpose){ _.each(list, function(data, token) { if(data.ts <= ts) delete self.tokens[purpose][token]; }); if (!hasTokens && _.keys(self.tokens[purpose]).length) hasTokens = true; }); if(hasTokens){ self.tokenMonitorRunning = true; dpc(60 * 1000, tokenRepair); }else{ self.tokenMonitorRunning = false; } //console.log('self.tokenMonitorRunning', self.tokenMonitorRunning, self.tokens) } } util.inherits(Authenticator, events.EventEmitter); function BasicAuthenticator(core, options) { var self = this; Authenticator.apply(self, arguments); if(!options.users) throw new Error("BasicAuthenticator requires 'users' in options"); self.mergePasswords = function (args){ var passFile = path.join(core.appFolder, 'config', 'password.json'); var pass = core.readJSON(passFile); if (!pass) pass = {} if (args && args.email && args.password) pass[args.email] = args.password; core.writeJSON(passFile, pass); _.each( options.users, function(u, k){ if (u.email && pass[u.email]) { options.users[k].pass = pass[u.email]; }; }); } self.mergePasswords(); self.setUserPassword = function(args, callback){ self.getUserByEmail(args.email, function(err, user){ if (err) return callback(err); self.mergePasswords(args); callback(null, true); }); } self.authenticate = function(args, callback) { var username = args.username.toLowerCase(); var password = options.users[username] ? options.users[username].password || options.users[username].pass : null; if(!password) return callback(null, false); self.compare(args, password, function(err, match) { if(err || !match) return callback(err, match); if (options.users[username] && options.users[username].totp && options.users[username].totp.enabled) { if (!args.totpToken) { return callback({request: 'TOTP'}); } if (!self.verifyTotpToken(args.totpToken, options.users[username].totp.key)) { return callback({error : "Wrong one time password"}); } } callback(err, { username : username, success : true }) }) } self.getUserByEmail = function(email, callback){ var user = false _.each(options.users, function(u){ if (u.email && u.email == email) { user = u; }; }); if (!user) return callback({error: 'Invalid email address, no such user.'}); callback(null, user); } } util.inherits(BasicAuthenticator, Authenticator); function MongoDbAuthenticator(core, options) { var self = this; Authenticator.apply(self, arguments); if(!options.collection) throw new Error("MongoDbAuthenticator requires 'collection' arguments."); self.users = {}; self.cacheTime = 5; // 5 minutes var _username = options.username || 'username'; var _password = options.password || 'password'; var _email = options.email || 'email'; var _emailRegex = options.emailRegex || /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i; var _insertEmail = options.insertEmail || false; var _confirmField = options.confirmField || false; var _confirmBeforeRecordCreation = options.confirmBeforeRecordCreation || false; //if (_confirmField && !_insertEmail) //throw new Error("If user account activation is required then please set options.insertEmail=true and set options.email={collection email field} if it is different than 'email' ."); if (_confirmField) _insertEmail = true; var usernameAlreadyExistsMsg = options.usernameAlreadyExistsMsg || ( _username=='email'? 'E-Mail':'Username')+' already exists.'; var emailAlreadyExistsMsg = options.emailAlreadyExistsMsg || 'E-Mail already exists.'; self.authenticate = function(args, callback) { if (self.users[args.username]) { var user = self.users[args.username]; if (_confirmField && user[_confirmField]!=1) return callback({ activationRequired: true }); self.compare(args, user[_password], function(err, match) { if(err || !match) return callback(err, match); if (user.totp && user.totp.enabled) { if (!args.totpToken) { return callback({request: 'TOTP'}); } if (!self.verifyTotpToken(args.totpToken, user.totp.key)) { return callback({error : "Wrong one time password"}); } else { delete self.users[args.username]; } } callback(err, user) }); } else { var q = { } q[_username] = args.username; options.collection.findOne(q, function (err, user) { if (err || !user) return callback({ error : 'Wrong user name or password' }); if (_confirmField && user[_confirmField]!=1) return callback({ activationRequired: true }); self.compare(args, user[_password], function(err, match) { if(err || !match) return callback(err, match); if (user.totp && user.totp.enabled) { self.users[args.username] = user; self.users[args.username].created = Date.now(); if (!args.totpToken) { return callback({request: 'TOTP'}); } if (!self.verifyTotpToken(args.totpToken, user.totp.key)) { return callback({error : "Wrong one time password"}); } else { delete self.users[args.username]; } } callback(err, user) }) }); } } self.getUserTOTP = function(args, callback){ self.getUserByEmail(args.email, function(err, user){ if (err) return callback(err); if (!user) return callback({error:"Server error. Please try gain later.", userMissing: true}); callback(null, {totp: user.totp || {} }); }) } self.setUserTOTP = function(args, callback){ var totp = args.totp; var email = args.email; var d, msg = ""; if (totp === true){ d = {$set: {'totp.enabled': true}}; msg = "Two-factor authentication is enabled"; }else if(totp === false){ d = {$unset: {totp: ''}}; msg = "Two-factor authentication is disabled"; }else if (_.isObject(totp) && totp.key && !_.isUndefined(totp.enabled)){ d = {$set: {totp: totp}}; msg = "Two-factor authentication updated."; }else{ return callback({error: "Invalid value for TOTP"}); } options.collection.update({ email : email }, d, function(err, result) { if (err) return callback({ error : "Server Error. Please try again later." }); callback(null, {success: true, message: msg}); }); } self.validateRegistration = function(args, callback){ console.log('validateRegistration: args', args) if (_insertEmail && ( !args.email || !_emailRegex.test(args.email)) ) return callback({error: 'Invalid E-Mail address.'}); if (_confirmBeforeRecordCreation) { var user = self.getTokenData('activation', function(o){ return (o[_username] == args.username || ( _insertEmail && o[_email] == args.email)); }); if (user && user[_username] == args.username) return callback({error: usernameAlreadyExistsMsg+' Account waiting for activation.'}); if (user && user[_email] == args.email) return callback({error: emailAlreadyExistsMsg+' Account with this E-mail waiting for activation.'}); } var q1 = { }, q = {$or:[]}, data = {}; q[_username] = args.username; data[_username] = args.username; q['$or'].push(q1); if (_insertEmail) { var q2 = { } q[_email] = args.email; q['$or'].push(q2); data[_email] = args.email; }; options.collection.findOne(q, function (err, user) { if (err) return callback(err); if (user && user[_username] == args.username) return callback({error: usernameAlreadyExistsMsg}); if (user && user[_email] == args.email) return callback({error: emailAlreadyExistsMsg}); callback(null, data); }); } self.activateAccountBegin = function(args, callback) { self.validateRegistration(args, function (err, data) { if (err) return callback(err); self.generateStorageHash(args.password, function(err, storageHash) { if (err) return callback(err); data[_password] = storageHash; if (_confirmBeforeRecordCreation) { var token = self.createToken('activation', data); var _data = _.extend(args, data); _data.to = _data.email = _data[_email]; _data.token = token; self.mailer.sendEmail('activation', _data); callback(null, {success: true, activationRequired: true}); }else{ var createCallback = options.createCallback || options.collection.insert; var context = options.createCallbackContext ? options.createCallbackContext: options.createCallback? self : options.collection; createCallback.call(context, data, function(err, result){ if (err) return callback(err); if (!result || !result.ops || !result.ops.pop()) return callback({error: 'Could not create account. Please try again.'}); if (_confirmField){ if (!self.mailer) return callback({error: 'No Mailer configured.'}); data = _.extend(args, data); data.to = data.email = data[_email]; data.token = self.createToken('activation', {username: data[_username]}); self.mailer.sendEmail('activation', data); } callback(null, {success: true, activationRequired: !!_confirmField}); }); } }); }); } self.activateAccountFinish = function(args, callback){ var data = self.getTokenData('activation', args.token); if (!data) return callback({error: 'Invalid activation token', tokenMissing: true}); if (_confirmBeforeRecordCreation) { delete data.token; delete data.ts; data[_confirmField] = true; var createCallback = options.createCallback || options.collection.insert; var context = options.createCallbackContext ? options.createCallbackContext: options.createCallback? self : options.collection; createCallback.call(context, data, function(err, result){ if (err) return callback(err); if (!result || !result.ops || !result.ops.pop()) return callback({error: 'Could not create account. Please try again.'}); self.deleteTokenData('activation', args.token); callback(null, true); }); }else{ var q = {}; q[_username] = data.username; options.collection.findOne(q, function (err, user) { if (err) return callback(err); if (!user) return callback({error: 'Invalid token'}); var data = {}; data[_confirmField] = true; options.collection.update(q, { $set: data}, function (err, success) { if (err || !success) return callback({error: 'Unable to activate account.'}); self.deleteTokenData('activation', args.token); callback(null, true); }); }); } } self.activateAccountResend = function(args, callback){ var query = {}; query[_username] = args.username; if (!_confirmField) return callback({error: "Server Error: _confirmField missing in login config", _confirmFieldMissing: true}) options.collection.findOne(query, function(err, user) { if(err) return callback(err); if (!user) return callback({error:'No such record.'}); if (user[_confirmField]) callback({error: "Account already activated"}); var data = user; data.to = data.email = data[_email]; data.token = self.createToken('activation', {username: data[_username]}); self.mailer.sendEmail('activation', data); callback(null, {success: true, activationRequired:true}) }); } // clean old user from memory setInterval(function() { _.each(self.users, function(user, i) { if (Date.now() - user.created > self.cacheTime * 1000 * 60) { delete self.users[i]; } }); }, 1000 * 60 * 5); self.on('user-login', function(user) { var conf = options.updateCollection; if (conf == false) return; var collection = options.collection, fieldName = 'last_login'; if (_.isObject(conf)) { collection = conf.collection || collection; fieldName = conf.fieldName || fieldName; }else if(_.isString(conf) ){ fieldName = conf; } var q = { }, data = {}; if (user[_username]) q[_username] = user[_username]; else if (user._id || user.id) q._id = user._id || user.id; else return; data[fieldName] = Date.now(); collection.update(q, { $set : data}, {safe:true}, function(err) { //console.log('collection.update'.red, err) }) }); self.getUserByEmail = function(email, callback){ var q = { } q[_email] = email; options.collection.findOne(q, function (err, user) { if (err || !user) return callback({error: 'Invalid email address, no such user.'}); callback(null, user); }); } self.setUserPassword = function(args, callback){ self.getUserByEmail(args.email, function(err, user){ if (err) return callback(err); var q = { } q[_email] = args.email; var data = {}; data[_password] = args.password; options.collection.update(q, { $set: data}, function (err, success) { if (err || !success) return callback({error: 'Unable to change your password.'}); callback(null, true); }); }); } } util.inherits(MongoDbAuthenticator, Authenticator); function IRISRpcAuthenticator(core, options) { var self = this; Authenticator.apply(self, arguments); if(!options.rpc) throw new Error("IRISRpcAuthenticator requires 'rpc' arguments."); var rpc = options.rpc; var ops = { authenticate: 'authenticate', passwordRecovery:'password-recovery', activateAccount: 'activate-account', configureTOTP:'configure-totp' } if (_.isObject(options.ops)) ops = _.extend(ops, options.ops); var methods = ['authenticate','passwordRecovery', 'activateAccount', 'configureTOTP']; //_.keys(ops); _.each(methods, function(method){ self[method] = function(args, callback){ args.op = ops[method]; rpc.dispatch(args, function(err, result) { callback(err, result); }); } }); } util.inherits(IRISRpcAuthenticator, Authenticator); var Client = function() { var self = this; self.args = CLIENT_ARGS; self.path = CLIENT_PATH; function require(filename) { var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.setAttribute('src',filename); document.head.appendChild(script); } var files = [ "/login/resources/hmac-sha256.js", "/login/resources/scrypt.js", "/login/resources/jquery.min.js" ]; function digest() { var file = files.shift(); if(!file) return finish(); var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.setAttribute('src',file); script.onload = function(){ setTimeout(digest); }; /* for IE Browsers */ ieLoadBugFix(script, function(){ setTimeout(digest); }); function ieLoadBugFix(scriptElement, callback) { if (scriptElement.readyState=='loaded' || scriptElement.readyState=='completed') callback(); else setTimeout(function() { ieLoadBugFix(scriptElement, callback); }, 100); } document.head.appendChild(script); } function finish() { self.scrypt = scrypt_module_factory(); self.onReady_ && self.onReady_.call(self, self); } self.ready = function(callback) { self.onReady_ = callback; }; function hex2uint8array(hex) { var bytes = new Uint8Array(hex.length/2); for(var i=0; i< hex.length-1; i+=2){ bytes[i] = parseInt(hex.substr(i, 2), 16); } return bytes; } self.encrypt = function(username, password, salt, callback) { if(!username) return callback({ error : "Please supply username."}); if(!password) return callback({ error : "Please supply password."}); var hash = null; if(self.args.scrypt) { var ts = Date.now(); var sc = self.args.scrypt; hash = self.scrypt.crypto_scrypt(self.scrypt.encode_utf8(password), hex2uint8array(sc.salt), sc.n, sc.r, sc.p, sc.keyLength); hash = self.scrypt.to_hex(hash); } else { hash = CryptoJS.SHA256(CryptoJS.enc.Utf8.parse(password)).toString(); } var sig = CryptoJS.HmacSHA256(CryptoJS.enc.Hex.parse(hash), CryptoJS.enc.Hex.parse(salt)).toString(); callback(null, { username : username, password : hash, sig : sig }); } function post(path, data, callback) { $.ajax({ dataType: "json", method : 'POST', url: path, data: data, error : function(err) { if(err.responseJSON) { if (err.responseJSON.error) callback(err.responseJSON); else if (err.responseJSON.request) { callback({ request : err.responseJSON.request }); } } else callback({ error : err.statusText }); }, success: function(o) { callback(null, o); } }) } self.post = post; self.changePassword = function(data, callback){ if(!data || !data.password) return callback({ error : "Please enter user name and password"}); post(self.path+'/challenge', {ispassrecovery: 1}, function(err, challenge) { if(err) return callback(err); self.encrypt('user', data.password, challenge.auth, function(err, d) { if(err) return callback(err); post(self.path+'/password-recovery/'+data.token, { password : d.password }, function(err, data) { if(err) return callback(err); callback(null, data); }) }) }) } self.register = function(data, callback) { if(!data || !data.username || !data.password) return callback({ error : "Please enter user name and password"}); post(self.path+'/challenge', {isregistration: 1}, function(err, challenge) { if(err) return callback(err); self.encrypt(data.username, data.password, challenge.auth, function(err, d) { if(err) return callback(err); d.totpToken = data.totpToken; d.email = data.email; post(self.path+'/register',d, function(err, resp) { callback(err, resp); }) }) }) } self.resendActivation = function(data, callback) { if(!data || !data.username) return callback({ error : "Please enter user name"}); post(self.path+'/resend-activation', data, function(err, resp) { callback(err, resp); }) } self.login = function(data, callback) { if(!data || !data.username || !data.password) return callback({ error : "Please enter user name and password"}); var totpToken = data.totpToken; post(self.path+'/challenge', {}, function(err, challenge) { if(err) return callback(err); self.encrypt(data.username, data.password, challenge.auth, function(err, data) { if(err) return callback(err); data.totpToken = totpToken; post(self.path+'/login',data, function(err, resp) { callback(err, resp); }) }) }) } digest(); } module.exports = { Login : Login, EmailHelper: EmailHelper, Authenticator : Authenticator, BasicAuthenticator : BasicAuthenticator, MongoDbAuthenticator : MongoDbAuthenticator, IRISRpcAuthenticator: IRISRpcAuthenticator }
lib/login.js
// // -- IRIS Toolkit - User Login // // Copyright (c) 2014 ASPECTRON Inc. // 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 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 fs = require('fs'); var _ = require('underscore'); var events = require('events'); var util = require('util'); var crypto = require('crypto'); var scrypt = require('./scrypt'); var base58 = require('iris-base58'); var path = require('path'); var notp = require('notp'); var base32 = require('thirty-two'); var UUID = require("node-uuid"); // http://stackoverflow.com/questions/14382725/how-to-get-the-correct-ip-address-of-a-client-into-a-node-socket-io-app-hosted-o function getClientIp(req) { var ipAddress; // Amazon EC2 / Heroku workaround to get real client IP var forwardedIpsStr = req.header('x-forwarded-for'); if (forwardedIpsStr) { // 'x-forwarded-for' header may return multiple IP addresses in // the format: "client IP, proxy 1 IP, proxy 2 IP" so take the // the first one var forwardedIps = forwardedIpsStr.split(','); ipAddress = forwardedIps[0]; } if (!ipAddress) { // Ensure getting client IP address still works in // development environment ipAddress = req.connection.remoteAddress; } return ipAddress; } function merge(dst, src) { _.each(src, function(v, k) { if(_.isArray(v)) { dst[k] = [ ]; merge(dst[k], v); } else if(_.isObject(v)) { if(!dst[k] || _.isString(dst[k]) || !_.isObject(dst[k])) dst[k] = { }; merge(dst[k], v); } else { if(_.isArray(src)) dst.push(v); else dst[k] = v; } }) } function EmailHelper(core, options){ var self = this; self.emailTpl = { recovery : { body: 'Please complete your password recovery by visiting the following link: <a href="{url}{token}">{url}{token}</a> .', subject: 'Please reset your password' }, passwordchanged:{ body: 'Your password have been changed.', subject: 'Password have been updated.' }, activation:{ body: 'Account is created but now you need to activate. Activate it by visiting following link: <a href="{url}{token}">{url}{token}</a> .', subject: 'Activate your account.' } } if ( _.isObject(options.emailTpl) ) merge(self.emailTpl, options.emailTpl); self.buildEmail = function(tpl, args){ html = tpl+''; _.each(args, function(v, k){ html = html.replace(new RegExp('{'+k+'}', 'g'), v); }); return html; } self.getMailer = function(){ return options.mailer || core.mailer; } self.sendEmail = function(tplKey, args, callback){ callback = callback || function(err){ err && console.log("SendEmail:error", err) }; var mailer = self.getMailer(); if (!mailer) return callback({error: 'No Mailer: Could not send email.'}); var tpl = self.emailTpl[tplKey]; if (!tpl) return callback({error: 'Email template missing for "'+tplKey+'".'}); var html = self.buildEmail(tpl.body, args); var text = tpl.textBody? self.buildEmail(tpl.textBody, args) : html; var mailOptions = { from: args.from || options.emailFrom || '[email protected]', to: args.to, subject: tpl.subject, html: html, text : text }; mailer[options.sendMailMethod || 'sendMail'](mailOptions, function (err, response) { console.log('mailer.sendMail', mailOptions, arguments); callback && callback(err, response); }); } } function Login(core, authenticator, options) { var self = this; events.EventEmitter.call(self); self.loginTracking = { } self.throttle = {attempts : 3, min : 3 }; self.passwordRecoveryTokens = {}; options.sessionKey = options.sessionKey || 'user'; if(_.isObject(options.throttle)) _.extend(self.throttle, options.throttle); self.authenticator = authenticator; if (!authenticator.mailer) authenticator.mailer = self; EmailHelper.call(self, core, options); function getLoginTracking(ip) { var o = self.loginTracking[ip]; if(!o) o = self.loginTracking[ip] = { unblock_ts : 0, attempts : 0, failures : 0 } return o; } self.authenticate = function(args, callback) { if(!self.authenticator) throw new Error("Login constructor requires authenticator argument"); return self.authenticator.authenticate(args, callback); } self._getLogin = function (viewPath, req, res) { res.setHeader('login-required', true); res.render(viewPath, { Client : self.getClientJavaScript(), req: req }, function(err, html) { if(err) { console.log(err); return res.end("Server Error"); } res.end(strip(html)); }); }; self.getLogin = function(req, res, next) { self._getLogin(options.view || path.join(__dirname, 'views/login.ejs'), req, res); } self._getPasswordRecovery = function(data, req, res, next) { var viewPath = options.passwordRecoveryView || path.join(__dirname, 'views/password-recovery.ejs'); if(!data.token) data.token = ''; data.req = req; res.render(viewPath, data, function(err, html) { if(err) return res.end("Server Error"); res.end(strip(html)); }); } self.getPasswordRecovery = function(req, res, next) { self._getPasswordRecovery( {Client : self.getClientJavaScript(), STAGE:'begin'}, req, res, next); } self.getPasswordRecoveryWithToken = function(req, res, next){ var token = req.params.token; var data = {Client : self.getClientJavaScript(), STAGE:'no-such-token'} self.authenticator.passwordRecovery({stage:'check', token: token}, function(err, success){ if (success){ data.STAGE = 'finish'; data.token = token; } self._getPasswordRecovery(data, req, res, next); }); } self.postPasswordRecovery = function(req, res, next) { var data = req.body; if (!data.email) return res.status(401).json({error: 'Email is required.'}); data.url = req.protocol + '://' + req.get('host') + (req.originalUrl.split('?')[0]+'/').replace(/\/\//g, "/"); data.stage = 'begin'; self.authenticator.passwordRecovery(data, function(err, data){ if (err) return res.status(401).json(err); res.status(200).json({success: true, data: data}); }); } self.postPasswordRecoveryWithToken = function(req, res, next){ var token = req.params.token; //var tokenData = self.passwordRecoveryTokens[token]; if(!token) return res.status(401).json({ error : "Password Recovery Error, <a href='"+(options.path || '')+"/password-recovery'>please restart password recovery process</a>. (Error Code: A7)"}) //if(!tokenData.email) //return res.status(401).json({ error : "Password Recovery Error, please restart password recovery process. (Error Code: A8)"}); var data = req.body; if (!data.password) return res.status(401).json({ error : "Password Recovery Error, password is required."}); self.authenticator.passwordRecovery({stage:'finish', token: token, password: data.password}, function(err, result){ delete req.session[options.sessionKey +'auth-passrecovery']; if (err) return res.status(401).json(err); res.json(result); }); } self.getActivationWithToken = function(req, res, next){ var token = req.params.token; if(!token) return req.redirectWithMsg('/', 'activation', {success: false, error:"Account activation Error, Token is required"}) self.authenticator.activateAccount({token: token, stage:'finish'}, function(err){ if (err) return req.redirectWithMsg('/', 'activation', {success: false, error:err}); req.redirectWithMsg(options.activationRedirectUrl || '/', 'activation', {success: true}) }) } self.postChallenge = function(req, res, next) { res.type('application/json'); if(req.body.isregistration || req.body.ispassrecovery){ self.authenticator.getClientAuth(function(err, auth) { req.session[options.sessionKey+ (req.body.ispassrecovery? 'auth-passrecovery' :'auth-reg')] = auth; res.status(200).json({ auth : auth }); }); return; } var ts = Date.now(); var ip = getClientIp(req); var o = getLoginTracking(ip); if(options.throttle && o.unblock_ts > ts) return res.status(401).json({ error : "Your access to the login system remains blocked for "+getDurationString(o.unblock_ts-ts), throttle : true, ts: parseInt( (o.unblock_ts-ts) / 1000 ) }); o.attempts++; if(options.throttle && o.attempts > self.throttle.attempts) { o.attempts = 0; o.failures++; o.unblock_ts = ts+(self.throttle.min*((o.failures+1)/2)*60*1000); return res.status(401).json({ error : "Your access to the login system has been blocked for "+getDurationString(o.unblock_ts-ts), throttle : true, ts: parseInt( (o.unblock_ts-ts) / 1000 ) }); } self.authenticator.getClientAuth(function(err, auth) { req.session[options.sessionKey+'auth'] = auth; res.status(200).json({ auth : auth }); }); } self.logout = function(req, res, next) { var user = req.session[options.sessionKey]; if(user){ delete req.session[options.sessionKey]; self.emit('user-logout', user, req, res, next); } } self.getLogout = function(req, res, next) { self.logout.apply(self, arguments); var redirect_uri = options.logoutRedirect || '/'; if(options.useRedirectUriAfterLogout && req.query && req.query.redirect_uri){ redirect_uri = req.query.redirect_uri; } res.redirect(redirect_uri); } self.postLogout = function(req, res, next) { self.logout.apply(self, arguments); res.send(200); } self.postLogin = function(req, res, next) { res.type('application/json'); if(!req.session[options.sessionKey+'auth']) return res.status(401).json({ error : "User name and password required" }); if(!req.body.username || !req.body.password || !req.body.sig) return res.status(401).json({ error : "User name and password required" }); var ts = Date.now(); var ip = getClientIp(req); var o = getLoginTracking(ip); if(options.throttle && o.unblock_ts > ts) return res.status(401).json({ error : "Your access to the login system remains blocked for another "+getDurationString(o.unblock_ts-ts), throttle : true, ts: parseInt( (o.unblock_ts-ts) / 1000 ) }); self.authenticate({ username : req.body.username, password : req.body.password, auth : req.session[options.sessionKey+'auth'], sig : req.body.sig, totpToken : req.body.totpToken }, function(err, user) { delete req.session[options.sessionKey+'auth']; if(!user) { if (err && err.activationRequired) return res.status(401).json({ error : "Waiting for account activation.", activationRequired: true}); if(options.throttle && o.attempts > self.throttle.attempts) { o.attempts = 0; o.failures++; o.unblock_ts = ts+(self.throttle.min*((o.failures+1)/2)*60*1000); res.status(401).json({ error : "Your access to the login system has been blocked for "+getDurationString(o.unblock_ts-ts), throttle : true, ts: parseInt( (o.unblock_ts-ts) / 1000 ) }); } else { if(err) res.status(401).json(err); else res.status(401).json({ error : "Wrong login credentials" }); } } else { if(user.blocked || user.blacklisted) { res.status(401).json({ error : "User access blocked by administration"}); } else { self.validateUser(user, function(err, userOk) { if(err) res.status(401).json(err); else { delete self.loginTracking[ip]; req.session[options.sessionKey] = user; delete req.session[options.sessionKey+'auth']; self.emit('user-login', user, req, res); (self.authenticator instanceof events.EventEmitter) && self.authenticator.emit('user-login', user); res.json({ success : true }); } }) } } }) } self.postRegister = function(req, res, next) { res.type('application/json'); var data = req.body; if(!req.session[options.sessionKey+'auth-reg']) return res.status(401).json({ error : "User name and password required" }); if(!data.username || !data.password || !data.sig) return res.status(401).json({ error : "User name and password required" }); data.url = req.protocol + '://' + req.get('host') + ((options.path || '')+'/activation/').replace(/\/\//g, "/"); self.register({ username : data.username, password : data.password, email : data.email, auth : req.session[options.sessionKey+'auth-reg'], sig : data.sig, totpToken : data.totpToken, url: data.url }, function(err, result) { delete req.session[options.sessionKey+'auth-reg']; if (!result) return res.status(401).json(err || {error: 'Unable to create account. Please try again later.'}); res.json(result); }); } self.register = function(args, callback) { if(!self.authenticator) throw new Error("Login constructor requires authenticator argument"); args.stage = 'begin'; self.authenticator.activateAccount(args, callback); } self.postConfigureTOTP = function(req, res, next){ self.authenticator.configureTOTP(req.body, function(err, result){ if (err) return res.status(401).json(err); res.json(err); }); } self.validateUser = function(user, callback) { /* if(!user.confirmed) { return callback({ error : "Waiting for user confirmation"}); } */ callback(null, true); } function strip(str) { return str; //return str.replace(/\s{2,}/g, ' ');//.replace(/ENTER/g,'\n'); //return str.replace(/[\n\r]/g, ' ').replace(/\s{2,}/g, ' ');//.replace(/ENTER/g,'\n'); //return str.replace(/[\n\r]/g, '\t').replace(/ {2,}/g, ' ');//.replace(/\/**\//g,'/*\n*/'); } function getDurationString(d) { var m = Math.floor(d / 1000 / 60); var s = Math.floor(d / 1000 % 60); if(s < 10) s = '0'+s; return m+' min '+s+' sec'; } self.init = function(app) { var _path = options.path || ''; app.get(_path+'/logout', self.getLogout); app.post(_path+'/logout', self.postLogout); app.get(_path+'/login', self.getLogin); app.get(_path+'/password-recovery', self.getPasswordRecovery); app.get(_path+'/password-recovery/:token', self.getPasswordRecoveryWithToken); app.post(_path+'/password-recovery', self.postPasswordRecovery); app.post(_path+'/password-recovery/:token', self.postPasswordRecoveryWithToken); app.post(_path+'/challenge', self.postChallenge); app.post(_path+'/login', self.postLogin); app.post(_path+'/register', self.postRegister); app.post(_path+'/configure-totp', self.postConfigureTOTP); app.get(_path+'/activation/:token', self.getActivationWithToken); app.use('/login/resources', core.express.static(path.join(__dirname, '../http'))); } self.redirectIfGuest = function(app, reqPath, redirectPath){ reqPath = reqPath || '*'; redirectPath = redirectPath || _path+'/login'; app.use(reqPath, function(req, res, next) { if(!req.session[options.sessionKey]) return res.redirect(redirectPath); next(); }); } self.getClientJavaScript = function() { var text = Client.toString(); text = text .replace("CLIENT_PATH", JSON.stringify(options.path || '')) .replace("CLIENT_ARGS", JSON.stringify(self.authenticator.client)); return "("+text+")()"; } } util.inherits(Login, events.EventEmitter); function Authenticator(core, options) { var self = this; events.EventEmitter.call(self); self.client = options.client; self.iterations = options.iterations || 100000; self.keylength = options.keylength || 4096/32; self.saltlength = options.saltlength || 4096/32; self.tokenTimeout = { activation: 10 * 60 * 1000, passwordRecovery: 10 * 60 * 1000 }; self.tokens = {}; if (_.isObject(options.tokenTimeout)) self.tokenTimeout = _.extend(self.tokenTimeout, options.tokenTimeout); if (options.mailer) self.mailer = options.mailer; function encrypt(text) { if(!text || !options.cipher) return text; var key = _.isString(options.key) ? new Buffer(options.key,'hex') : options.key; var cipher = crypto.createCipher(options.cipher, key); var crypted = cipher.update(text, 'utf8', 'binary'); crypted += cipher.final('binary'); return base58.encode(new Buffer(crypted, 'binary')); } function decrypt(text, callback) { if(!text || !options.cipher) return callback(null, text); var key = _.isString(options.key) ? new Buffer(options.key,'hex') : options.key; base58.decode(text, function(err, data) { if(err) return callback(err); var decipher = crypto.createDecipher(options.cipher, key); var decrypted = decipher.update(data, 'binary', 'utf8'); decrypted += decipher.final('utf8'); callback(null, decrypted); }); } function hex2uint8array(hex) { var bytes = new Uint8Array(hex.length/2); for(var i=0; i< hex.length-1; i+=2){ bytes[i] = (parseInt(hex.substr(i, 2), 16)); } return bytes; } self.getClientAuth = function(callback) { crypto.randomBytes(256, function(err, bytes) { if(err) return callback(err); callback(null, bytes.toString('hex')); }) } self.generatePBKDF2 = function(password, salt, iterations, keylength, callback) { crypto.pbkdf2(password, salt, iterations, keylength, function(err, key) { if(err) return callback(err); var res = ['pbkdf2', iterations, keylength, base58.encode(key), base58.encode(salt)].join(':'); callback(null, res); }) } self.generateStorageHash = function(password, salt, callback) { if(!password) return callback('No password provided') if(_.isFunction(salt)) { callback = salt; salt = undefined; } if(_.isString(salt)) { salt = new Buffer(salt, 'hex'); } if(!salt) { crypto.randomBytes(self.saltlength, function(err, _salt) { if(err) return callback(err); self.generatePBKDF2(password, _salt, self.iterations, self.keylength, function(err, key) { callback(err, encrypt(key)); }) }); } else { self.generatePBKDF2(password, salt, self.iterations, self.keylength, function(err, key) { callback(err, encrypt(key)); }) } } self.generateExchangeHash = function(password, callback) { if(options.client.sha256) { var hash = crypto.createHash('sha256').update(password).digest('hex'); callback(null, hash); } else if(options.client.scrypt) { var sc = options.client.scrypt; var hash = scrypt.crypto_scrypt(scrypt.encode_utf8(password), hex2uint8array(sc.salt), sc.n, sc.r, sc.p, sc.keyLength); callback(null, scrypt.to_hex(hash)); } } self.compareStorageHash = function(args, _hash, callback) { var hash = decrypt(_hash, function(err, hash) { if(err) return callback(err); if (!hash) return callback({ error : "Wrong password please try password recovery."}) var parts = hash.split(':'); if(parts.length != 5 || parts[0] != 'pbkdf2' || parseInt(parts[1]) != self.iterations) return callback({ error : "Wrong encoded hash parameters"}) var iterations = parseInt(parts[1]); var keylength = parseInt(parts[2]); base58.decode(parts[4], function(err, salt) { if(err) return callback(err); self.generatePBKDF2(args.password, salt, iterations, keylength, function(err, key) { if(err) return callback(err); callback(null, hash === key); }) }); }); } self.validateSignature = function(args, callback) { console.log("validateSignature",args); var sig = crypto.createHmac('sha256', new Buffer(args.auth, 'hex')).update(new Buffer(args.password, 'hex')).digest('hex'); callback(null, args.sig == sig); } self.compare = function(args, storedHash, callback) { console.log("WARNGING! - Signature Validation is Disabled"); // self.validateSignature(args, function(err, match) { // if(!match) // return callback({ error : "Wrong authentication signature"}); self.compareStorageHash(args, storedHash, function(err, match) { if(err) return callback(err); if(!match) return callback({ error : "Unknown user name or password"}) callback(null, true); }) // }) }; self.generateTotpSecretKey = function(length) { length = length || 10; return crypto.randomBytes(length).toString('hex'); }; self.getTotpKeyForGoogleAuthenticator = function (key) { return base32.encode(key); }; self.getBarcodeUrlPart = function (email, key) { return 'otpauth://totp/' + email + '?secret=' + self.getTotpKeyForGoogleAuthenticator(key)+'&issuer='+(options.totpissuer || ''); }; self.getBarcodeUrlForGoogleAuthenticator = function (email, key) { return 'https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=' + self.getBarcodeUrlPart(email, key) }; self.getDataForGoogleAuthenticator = function (email, key) { if (!key) return {}; return { totpKey: self.getTotpKeyForGoogleAuthenticator(key), barcodeUrl: self.getBarcodeUrlForGoogleAuthenticator(email, key), barcodeUrlPart: self.getBarcodeUrlPart(email, key) }; } self.verifyTotpToken = function (token, key) { return notp.totp.verify(token, key, {}); }; self.getUserTOTP = function(args, callback){ callback({error: 'No getUserTOTP handler.'}); } self.setUserTOTP = function(args, callback){ callback({error: 'No setUserTOTP handler.'}); } self.configureTOTP = function (args, callback) { if (!args.email) return callback({ error : "Email field is required."}); var email = args.email.toLowerCase(); if (args.stage == 'init' || args.stage == 'get-data') { self.getUserTOTP({ email : email }, function(err, result) { if(err) return callback(err); if(!result) return callback({ error : "Server Error. Please try again later." }); var totpData = {}; var enabled = false; if (result.totp && result.totp.key) { totpData = self.getDataForGoogleAuthenticator(email, result.totp.key); enabled = result.totp.enabled; send(); } else if (args.stage == 'init') { var totpKey = self.generateTotpSecretKey(); self.setUserTOTP({ email : email, totp: {enabled: false, key: totpKey} }, function(err, result) { if (err) return callback({ error : "Server Error. Please try again later." }); totpData = self.getDataForGoogleAuthenticator(email, totpKey); send(); }); } else { send() } function send () { var data = { enabled: enabled, totpData: enabled? {}: totpData }; console.log(data); return callback(null, data); } }); } else if (args.stage == 'change') { if (_.isUndefined(args.enable)) return callback({ error : "Enable/Disable field is required."}); if (args.code == undefined) return callback({ error : "One time password is required."}); self.getUserTOTP({ email : email }, function(err, result) { if(err) return callback({ error : "Server Error. Please try again later." }); if(!result) return callback({ error : "Server Error. Please try again later." }); if (!self.verifyTotpToken(args.code, result.totp.key)) { return callback({error : "Wrong one time password"}); } if (args.enable) { if (result.totp.enabled) { return callback(null, {success: true, message: 'Two-factor authentication is enabled'}); } self.setUserTOTP({ email : email, totp: true }, function(err, result) { if (err) return callback({ error : "Server Error. Please try again later." }); callback(null, {success: true, message: 'Two-factor authentication is enabled'}); }); } else { self.setUserTOTP({ email : email, totp: false}, function(err, result) { if (err) return callback({ error : "Server Error. Please try again later." }); callback(null, {success: true, message: 'Two-factor authentication is disabled'}); }); } }); } }; self.getUserByEmail = function(args, callback){ callback({error: 'No getUserByEmail handler.'}); } //TODO: override in IRISRpcAuthenticator self.activateAccountBegin = function(args, callback){ callback({error: 'No activateAccountBegin handler.'}); } self.activateAccountResend = function(args, callback){ callback({error: 'No activateAccountResend handler.'}); } self.activateAccountFinish = function(args, callback){ callback({error: 'No activateAccountBegin handler.'}); } self.activateAccount = function(args, callback){ switch(args.stage.toLowerCase()){ case 'begin': self.activateAccountBegin(args, callback); break; case 'resend': self.activateAccountResend(args, callback); break; case 'finish': self.activateAccountFinish(args, callback); break; default: callback({error: 'Invalid activateAccount stage.'}); break; } } self.passwordRecovery = function(args, callback){ switch(args.stage.toLowerCase()){ case 'begin': self.passwordRecoveryBegin(args, callback); break; case 'check': self.passwordRecoveryCheck(args, callback); break; case 'resend': self.passwordRecoveryResend(args, callback); break; case 'finish': self.passwordRecoveryFinish(args, callback); break; default: callback({error: "Invalid passwordRecovery stage."}); break; } } self.sendPasswordRecoveryTokenEmail = function(args, callback){ self.mailer.sendEmail('recovery', args); callback(null, true); } self.passwordRecoveryBegin = function(args, callback){ args.email = args.email.toLowerCase(); //var tokenData = self.getTokenData('passwordRecovery', function(o){o.email == args.email}); //if (tokenData) //return callback({error: "Password recovery already in process", alreadyRunning: true}) self.getUserByEmail(args.email, function(err, user){ if (err) return callback(err); if (!self.mailer) return callback({error: 'No Mailer configured.'}); args.to = args.email; args.token = self.createToken('passwordRecovery', {email: args.email}); self.sendPasswordRecoveryTokenEmail(args, callback); }); } self.passwordRecoveryCheck = function(args, callback){ var tokenData = self.getTokenData('passwordRecovery', args.token); if (!tokenData) return callback({error: "Invalid password recovery token.", tokenMissing: true}); if (!tokenData.email) return callback({error: "Invalid password recovery token.", tokenEmailMissing: true}); callback(null, {success: true}); } self.passwordRecoveryResend = function(args, callback){ args.email = args.email.toLowerCase(); var tokenData = self.getTokenData('passwordRecovery', function(o){o.email == args.email}); if (!tokenData || !tokenData.email) return callback({error: "Please reinitiate password recovery.", tokenMissing: true}); args.to = tokenData.email; args.token = tokenData.token; self.sendPasswordRecoveryTokenEmail(args, callback); } self.passwordRecoveryFinish = function(args, callback){ var tokenData = self.getTokenData('passwordRecovery', args.token); if (!args.password) return callback({error: "Password is required.", passwordMissing: true}); if (!tokenData) return callback({error: "Invalid password recovery token.", tokenMissing: true}); if (!tokenData.email) return callback({error: "Invalid password recovery token.", tokenEmailMissing: true}); self.generateStorageHash(args.password, function(err, storageHash) { self.setUserPassword({email: tokenData.email, password: storageHash}, function(err, result){ if (err) return res.status(401).json(err); self.mailer.sendEmail('passwordchanged', {email: tokenData.email, to: tokenData.email}) self.deleteTokenData('passwordRecovery', args.token); callback(null, {success: true, result: result}); }); }); } self.setUserPassword = function(args, callback){ callback({error: 'No setUserPassword handler.'}); } self.createToken = function(purpose, data, expiryTs){ expiryTs = expiryTs || Date.now() + (self.tokenTimeout[purpose] || 10 * 60 * 1000); data.ts = expiryTs; var idHex = crypto.createHash('sha1').update(UUID.v1()).digest('hex'); var token = base58.encodeSync(new Buffer(idHex, 'hex')); if (!self.tokens[purpose]) self.tokens[purpose] = {}; self.tokens[purpose][token] = _.extend({}, data); self.tokens[purpose][token].token = token; self.startTokenMonitor(); return token; //return {token: token, data: self.tokens[purpose][token]}; } self.getTokenData = function(purpose, token){ if (!self.tokens[purpose]) return false; if (_.isFunction(token)) return _.find(self.tokens[purpose], token); if (self.tokens[purpose][token]) return self.tokens[purpose][token]; return false; } self.deleteTokenData = function(purpose, token){ var d = false; if (self.tokens[purpose] && self.tokens[purpose][token]){ d = self.tokens[purpose][token]; delete self.tokens[purpose][token]; } return d; } self.startTokenMonitor = function(){ if (!self.tokenMonitorRunning) dpc(tokenRepair); } function tokenRepair() { var ts = Date.now(); var hasTokens = false; _.each(self.tokens, function(list, purpose){ _.each(list, function(data, token) { if(data.ts <= ts) delete self.tokens[purpose][token]; }); if (!hasTokens && _.keys(self.tokens[purpose]).length) hasTokens = true; }); if(hasTokens){ self.tokenMonitorRunning = true; dpc(60 * 1000, tokenRepair); }else{ self.tokenMonitorRunning = false; } //console.log('self.tokenMonitorRunning', self.tokenMonitorRunning, self.tokens) } } util.inherits(Authenticator, events.EventEmitter); function BasicAuthenticator(core, options) { var self = this; Authenticator.apply(self, arguments); if(!options.users) throw new Error("BasicAuthenticator requires 'users' in options"); self.mergePasswords = function (args){ var passFile = path.join(core.appFolder, 'config', 'password.json'); var pass = core.readJSON(passFile); if (!pass) pass = {} if (args && args.email && args.password) pass[args.email] = args.password; core.writeJSON(passFile, pass); _.each( options.users, function(u, k){ if (u.email && pass[u.email]) { options.users[k].pass = pass[u.email]; }; }); } self.mergePasswords(); self.setUserPassword = function(args, callback){ self.getUserByEmail(args.email, function(err, user){ if (err) return callback(err); self.mergePasswords(args); callback(null, true); }); } self.authenticate = function(args, callback) { var username = args.username.toLowerCase(); var password = options.users[username] ? options.users[username].password || options.users[username].pass : null; if(!password) return callback(null, false); self.compare(args, password, function(err, match) { if(err || !match) return callback(err, match); if (options.users[username] && options.users[username].totp && options.users[username].totp.enabled) { if (!args.totpToken) { return callback({request: 'TOTP'}); } if (!self.verifyTotpToken(args.totpToken, options.users[username].totp.key)) { return callback({error : "Wrong one time password"}); } } callback(err, { username : username, success : true }) }) } self.getUserByEmail = function(email, callback){ var user = false _.each(options.users, function(u){ if (u.email && u.email == email) { user = u; }; }); if (!user) return callback({error: 'Invalid email address, no such user.'}); callback(null, user); } } util.inherits(BasicAuthenticator, Authenticator); function MongoDbAuthenticator(core, options) { var self = this; Authenticator.apply(self, arguments); if(!options.collection) throw new Error("MongoDbAuthenticator requires 'collection' arguments."); self.users = {}; self.cacheTime = 5; // 5 minutes var _username = options.username || 'username'; var _password = options.password || 'password'; var _email = options.email || 'email'; var _emailRegex = options.emailRegex || /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i; var _insertEmail = options.insertEmail || false; var _confirmField = options.confirmField || false; var _confirmBeforeRecordCreation = options.confirmBeforeRecordCreation || false; //if (_confirmField && !_insertEmail) //throw new Error("If user account activation is required then please set options.insertEmail=true and set options.email={collection email field} if it is different than 'email' ."); if (_confirmField) _insertEmail = true; var usernameAlreadyExistsMsg = options.usernameAlreadyExistsMsg || ( _username=='email'? 'E-Mail':'Username')+' already exists.'; var emailAlreadyExistsMsg = options.emailAlreadyExistsMsg || 'E-Mail already exists.'; self.authenticate = function(args, callback) { if (self.users[args.username]) { var user = self.users[args.username]; if (_confirmField && user[_confirmField]!=1) return callback({ activationRequired: true }); self.compare(args, user[_password], function(err, match) { if(err || !match) return callback(err, match); if (user.totp && user.totp.enabled) { if (!args.totpToken) { return callback({request: 'TOTP'}); } if (!self.verifyTotpToken(args.totpToken, user.totp.key)) { return callback({error : "Wrong one time password"}); } else { delete self.users[args.username]; } } callback(err, user) }); } else { var q = { } q[_username] = args.username; options.collection.findOne(q, function (err, user) { if (err || !user) return callback({ error : 'Wrong user name or password' }); if (_confirmField && user[_confirmField]!=1) return callback({ activationRequired: true }); self.compare(args, user[_password], function(err, match) { if(err || !match) return callback(err, match); if (user.totp && user.totp.enabled) { self.users[args.username] = user; self.users[args.username].created = Date.now(); if (!args.totpToken) { return callback({request: 'TOTP'}); } if (!self.verifyTotpToken(args.totpToken, user.totp.key)) { return callback({error : "Wrong one time password"}); } else { delete self.users[args.username]; } } callback(err, user) }) }); } } self.getUserTOTP = function(args, callback){ self.getUserByEmail(args.email, function(err, user){ if (err) return callback(err); if (!user) return callback({error:"Server error. Please try gain later.", userMissing: true}); callback(null, {totp: user.totp || {} }); }) } self.setUserTOTP = function(args, callback){ var totp = args.totp; var email = args.email; var d, msg = ""; if (totp === true){ d = {$set: {'totp.enabled': true}}; msg = "Two-factor authentication is enabled"; }else if(totp === false){ d = {$unset: {totp: ''}}; msg = "Two-factor authentication is disabled"; }else if (_.isObject(totp) && totp.key && !_.isUndefined(totp.enabled)){ d = {$set: {totp: totp}}; msg = "Two-factor authentication updated."; }else{ return callback({error: "Invalid value for TOTP"}); } options.collection.update({ email : email }, d, function(err, result) { if (err) return callback({ error : "Server Error. Please try again later." }); callback(null, {success: true, message: msg}); }); } self.validateRegistration = function(args, callback){ console.log('validateRegistration: args', args) if (_insertEmail && ( !args.email || !_emailRegex.test(args.email)) ) return callback({error: 'Invalid E-Mail address.'}); if (_confirmBeforeRecordCreation) { var user = self.getTokenData('activation', function(o){ return (o[_username] == args.username || ( _insertEmail && o[_email] == args.email)); }); if (user && user[_username] == args.username) return callback({error: usernameAlreadyExistsMsg+' Account waiting for activation.'}); if (user && user[_email] == args.email) return callback({error: emailAlreadyExistsMsg+' Account with this E-mail waiting for activation.'}); } var q1 = { }, q = {$or:[]}, data = {}; q[_username] = args.username; data[_username] = args.username; q['$or'].push(q1); if (_insertEmail) { var q2 = { } q[_email] = args.email; q['$or'].push(q2); data[_email] = args.email; }; options.collection.findOne(q, function (err, user) { if (err) return callback(err); if (user && user[_username] == args.username) return callback({error: usernameAlreadyExistsMsg}); if (user && user[_email] == args.email) return callback({error: emailAlreadyExistsMsg}); callback(null, data); }); } self.activateAccountBegin = function(args, callback) { self.validateRegistration(args, function (err, data) { if (err) return callback(err); self.generateStorageHash(args.password, function(err, storageHash) { if (err) return callback(err); data[_password] = storageHash; if (_confirmBeforeRecordCreation) { var token = self.createToken('activation', data); var _data = _.extend(args, data); _data.to = _data.email = _data[_email]; _data.token = token; self.mailer.sendEmail('activation', _data); callback(null, {success: true, activationRequired: true}); }else{ var createCallback = options.createCallback || options.collection.insert; var context = options.createCallbackContext ? options.createCallbackContext: options.createCallback? self : options.collection; createCallback.call(context, data, function(err, result){ if (err) return callback(err); if (!result || !result.ops || !result.ops.pop()) return callback({error: 'Could not create account. Please try again.'}); if (_confirmField){ if (!self.mailer) return callback({error: 'No Mailer configured.'}); data = _.extend(args, data); data.to = data.email = data[_email]; data.token = self.createToken('activation', {username: data[_username]}); self.mailer.sendEmail('activation', data); } callback(null, {success: true, activationRequired: !!_confirmField}); }); } }); }); } self.activateAccountFinish = function(args, callback){ var data = self.getTokenData('activation', args.token); if (!data) return callback({error: 'Invalid activation token', tokenMissing: true}); if (_confirmBeforeRecordCreation) { delete data.token; delete data.ts; data[_confirmField] = true; var createCallback = options.createCallback || options.collection.insert; var context = options.createCallbackContext ? options.createCallbackContext: options.createCallback? self : options.collection; createCallback.call(context, data, function(err, result){ if (err) return callback(err); if (!result || !result.ops || !result.ops.pop()) return callback({error: 'Could not create account. Please try again.'}); self.deleteTokenData('activation', args.token); callback(null, true); }); }else{ var q = {}; q[_username] = data.username; options.collection.findOne(q, function (err, user) { if (err) return callback(err); if (!user) return callback({error: 'Invalid token'}); var data = {}; data[_confirmField] = true; options.collection.update(q, { $set: data}, function (err, success) { if (err || !success) return callback({error: 'Unable to activate account.'}); self.deleteTokenData('activation', args.token); callback(null, true); }); }); } } // clean old user from memory setInterval(function() { _.each(self.users, function(user, i) { if (Date.now() - user.created > self.cacheTime * 1000 * 60) { delete self.users[i]; } }); }, 1000 * 60 * 5); self.on('user-login', function(user) { var conf = options.updateCollection; if (conf == false) return; var collection = options.collection, fieldName = 'last_login'; if (_.isObject(conf)) { collection = conf.collection || collection; fieldName = conf.fieldName || fieldName; }else if(_.isString(conf) ){ fieldName = conf; } var q = { }, data = {}; if (user[_username]) q[_username] = user[_username]; else if (user._id || user.id) q._id = user._id || user.id; else return; data[fieldName] = Date.now(); collection.update(q, { $set : data}, {safe:true}, function(err) { //console.log('collection.update'.red, err) }) }); self.getUserByEmail = function(email, callback){ var q = { } q[_email] = email; options.collection.findOne(q, function (err, user) { if (err || !user) return callback({error: 'Invalid email address, no such user.'}); callback(null, user); }); } self.setUserPassword = function(args, callback){ self.getUserByEmail(args.email, function(err, user){ if (err) return callback(err); var q = { } q[_email] = args.email; var data = {}; data[_password] = args.password; options.collection.update(q, { $set: data}, function (err, success) { if (err || !success) return callback({error: 'Unable to change your password.'}); callback(null, true); }); }); } } util.inherits(MongoDbAuthenticator, Authenticator); function IRISRpcAuthenticator(core, options) { var self = this; Authenticator.apply(self, arguments); if(!options.rpc) throw new Error("IRISRpcAuthenticator requires 'rpc' arguments."); var rpc = options.rpc; var ops = { authenticate: 'authenticate', passwordRecovery:'password-recovery', activateAccount: 'activate-account', configureTOTP:'configure-totp' } if (_.isObject(options.ops)) ops = _.extend(ops, options.ops); var methods = ['authenticate','passwordRecovery', 'activateAccount', 'configureTOTP']; //_.keys(ops); _.each(methods, function(method){ self[method] = function(args, callback){ args.op = ops[method]; rpc.dispatch(args, function(err, result) { callback(err, result); }); } }); } util.inherits(IRISRpcAuthenticator, Authenticator); var Client = function() { var self = this; self.args = CLIENT_ARGS; self.path = CLIENT_PATH; function require(filename) { var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.setAttribute('src',filename); document.head.appendChild(script); } var files = [ "/login/resources/hmac-sha256.js", "/login/resources/scrypt.js", "/login/resources/jquery.min.js" ]; function digest() { var file = files.shift(); if(!file) return finish(); var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.setAttribute('src',file); script.onload = function(){ setTimeout(digest); }; /* for IE Browsers */ ieLoadBugFix(script, function(){ setTimeout(digest); }); function ieLoadBugFix(scriptElement, callback) { if (scriptElement.readyState=='loaded' || scriptElement.readyState=='completed') callback(); else setTimeout(function() { ieLoadBugFix(scriptElement, callback); }, 100); } document.head.appendChild(script); } function finish() { self.scrypt = scrypt_module_factory(); self.onReady_ && self.onReady_.call(self, self); } self.ready = function(callback) { self.onReady_ = callback; }; function hex2uint8array(hex) { var bytes = new Uint8Array(hex.length/2); for(var i=0; i< hex.length-1; i+=2){ bytes[i] = parseInt(hex.substr(i, 2), 16); } return bytes; } self.encrypt = function(username, password, salt, callback) { if(!username) return callback({ error : "Please supply username."}); if(!password) return callback({ error : "Please supply password."}); var hash = null; if(self.args.scrypt) { var ts = Date.now(); var sc = self.args.scrypt; hash = self.scrypt.crypto_scrypt(self.scrypt.encode_utf8(password), hex2uint8array(sc.salt), sc.n, sc.r, sc.p, sc.keyLength); hash = self.scrypt.to_hex(hash); } else { hash = CryptoJS.SHA256(CryptoJS.enc.Utf8.parse(password)).toString(); } var sig = CryptoJS.HmacSHA256(CryptoJS.enc.Hex.parse(hash), CryptoJS.enc.Hex.parse(salt)).toString(); callback(null, { username : username, password : hash, sig : sig }); } function post(path, data, callback) { $.ajax({ dataType: "json", method : 'POST', url: path, data: data, error : function(err) { if(err.responseJSON) { if (err.responseJSON.error) callback(err.responseJSON); else if (err.responseJSON.request) { callback({ request : err.responseJSON.request }); } } else callback({ error : err.statusText }); }, success: function(o) { callback(null, o); } }) } self.post = post; self.changePassword = function(data, callback){ if(!data || !data.password) return callback({ error : "Please enter user name and password"}); post(self.path+'/challenge', {ispassrecovery: 1}, function(err, challenge) { if(err) return callback(err); self.encrypt('user', data.password, challenge.auth, function(err, d) { if(err) return callback(err); post(self.path+'/password-recovery/'+data.token, { password : d.password }, function(err, data) { if(err) return callback(err); callback(null, data); }) }) }) } self.register = function(data, callback) { if(!data || !data.username || !data.password) return callback({ error : "Please enter user name and password"}); post(self.path+'/challenge', {isregistration: 1}, function(err, challenge) { if(err) return callback(err); self.encrypt(data.username, data.password, challenge.auth, function(err, d) { if(err) return callback(err); d.totpToken = data.totpToken; d.email = data.email; post(self.path+'/register',d, function(err, resp) { callback(err, resp); }) }) }) } self.login = function(data, callback) { if(!data || !data.username || !data.password) return callback({ error : "Please enter user name and password"}); var totpToken = data.totpToken; post(self.path+'/challenge', {}, function(err, challenge) { if(err) return callback(err); self.encrypt(data.username, data.password, challenge.auth, function(err, data) { if(err) return callback(err); data.totpToken = totpToken; post(self.path+'/login',data, function(err, resp) { callback(err, resp); }) }) }) } digest(); } module.exports = { Login : Login, EmailHelper: EmailHelper, Authenticator : Authenticator, BasicAuthenticator : BasicAuthenticator, MongoDbAuthenticator : MongoDbAuthenticator, IRISRpcAuthenticator: IRISRpcAuthenticator }
resend activation
lib/login.js
resend activation
<ide><path>ib/login.js <ide> req.redirectWithMsg(options.activationRedirectUrl || '/', 'activation', {success: true}) <ide> }) <ide> } <add> <add> self.getResendActivation = function(req, res, next) { <add> var viewPath = options.resendActivationView || path.join(__dirname, 'views/resend-activation.ejs'); <add> var data = {req: req, res: res, activePage: "resend-activation", Client : self.getClientJavaScript()}; <add> res.render(viewPath, data, function(err, html) { <add> if(err){ <add> res.render("resend-activation", data, function(err, html) { <add> if(err) <add> return res.end("Server Error"); <add> <add> res.end(strip(html)); <add> }); <add> return <add> } <add> <add> res.end(strip(html)); <add> }); <add> } <add> <add> self.postResendActivation = function(req, res, next) { <add> var data = req.body; <add> <add> if(!data.username) <add> return res.status(401).json({ error : "Username is required" }); <add> <add> data.url = req.protocol + '://' + req.get('host') + ((options.path || '')+'/activation/').replace(/\/\//g, "/"); <add> <add> self.resendActivation({ <add> username : data.username, <add> url: data.url <add> }, function(err, result) { <add> if (!result) <add> return res.status(401).json(err || {error: 'Unable to send activation code. Please try again later.'}); <add> <add> res.json(result); <add> }); <add> } <add> <add> self.resendActivation = function(args, callback) { <add> if(!self.authenticator) <add> throw new Error("Login constructor requires authenticator argument"); <add> args.stage = 'resend'; <add> self.authenticator.activateAccount(args, callback); <add> } <ide> <ide> self.postChallenge = function(req, res, next) { <ide> res.type('application/json'); <ide> app.post(_path+'/register', self.postRegister); <ide> app.post(_path+'/configure-totp', self.postConfigureTOTP); <ide> app.get(_path+'/activation/:token', self.getActivationWithToken); <add> app.get(_path+'/resend-activation/', self.getResendActivation); <add> app.post(_path+'/resend-activation/', self.postResendActivation); <ide> <ide> app.use('/login/resources', core.express.static(path.join(__dirname, '../http'))); <ide> } <ide> }); <ide> }); <ide> } <add> } <add> <add> self.activateAccountResend = function(args, callback){ <add> var query = {}; <add> query[_username] = args.username; <add> <add> if (!_confirmField) <add> return callback({error: "Server Error: _confirmField missing in login config", _confirmFieldMissing: true}) <add> <add> options.collection.findOne(query, function(err, user) { <add> if(err) <add> return callback(err); <add> <add> if (!user) <add> return callback({error:'No such record.'}); <add> <add> if (user[_confirmField]) <add> callback({error: "Account already activated"}); <add> <add> var data = user; <add> <add> data.to = data.email = data[_email]; <add> data.token = self.createToken('activation', {username: data[_username]}); <add> self.mailer.sendEmail('activation', data); <add> <add> callback(null, {success: true, activationRequired:true}) <add> }); <ide> } <ide> <ide> // clean old user from memory <ide> }) <ide> } <ide> <add> self.resendActivation = function(data, callback) { <add> if(!data || !data.username) <add> return callback({ error : "Please enter user name"}); <add> <add> post(self.path+'/resend-activation', data, function(err, resp) { <add> callback(err, resp); <add> }) <add> } <add> <ide> self.login = function(data, callback) { <ide> if(!data || !data.username || !data.password) <ide> return callback({ error : "Please enter user name and password"});
Java
epl-1.0
bd8b4345d17028f348e5651278a079d5e6a35390
0
junit-team/junit-lambda,sbrannen/junit-lambda
/* * Copyright 2015-2017 the original author or authors. * * 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 */ package org.junit.vintage.engine.discovery; import static java.util.stream.Collectors.toSet; import java.util.ArrayDeque; import java.util.Collections; import java.util.Deque; import java.util.Optional; import java.util.Set; import org.junit.platform.engine.TestDescriptor; import org.junit.platform.engine.UniqueId; import org.junit.runner.Description; import org.junit.vintage.engine.descriptor.RunnerTestDescriptor; import org.junit.vintage.engine.descriptor.VintageTestDescriptor; /** * @since 4.12 */ class UniqueIdFilter extends RunnerTestDescriptorAwareFilter { private final UniqueId uniqueId; private Deque<Description> path; private Set<Description> descendants; UniqueIdFilter(UniqueId uniqueId) { this.uniqueId = uniqueId; } @Override void initialize(RunnerTestDescriptor runnerTestDescriptor) { Optional<? extends TestDescriptor> identifiedTestDescriptor = runnerTestDescriptor.findByUniqueId(uniqueId); descendants = determineDescendants(identifiedTestDescriptor); path = determinePath(runnerTestDescriptor, identifiedTestDescriptor); } private Deque<Description> determinePath(RunnerTestDescriptor runnerTestDescriptor, Optional<? extends TestDescriptor> identifiedTestDescriptor) { Deque<Description> path = new ArrayDeque<>(); Optional<? extends TestDescriptor> current = identifiedTestDescriptor; while (current.isPresent() && !current.get().equals(runnerTestDescriptor)) { path.addFirst(((VintageTestDescriptor) current.get()).getDescription()); current = current.get().getParent(); } return path; } private Set<Description> determineDescendants(Optional<? extends TestDescriptor> identifiedTestDescriptor) { // @formatter:off return identifiedTestDescriptor.map( testDescriptor -> testDescriptor .getDescendants() .stream() .map(VintageTestDescriptor.class::cast) .map(VintageTestDescriptor::getDescription) .collect(toSet())) .orElseGet(Collections::emptySet); // @formatter:on } @Override public boolean shouldRun(Description description) { return path.contains(description) || descendants.contains(description); } @Override public String describe() { return "Unique ID " + uniqueId; } }
junit-vintage-engine/src/main/java/org/junit/vintage/engine/discovery/UniqueIdFilter.java
/* * Copyright 2015-2017 the original author or authors. * * 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 */ package org.junit.vintage.engine.discovery; import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; import java.util.Deque; import java.util.LinkedList; import java.util.Optional; import java.util.Set; import org.junit.platform.engine.TestDescriptor; import org.junit.platform.engine.UniqueId; import org.junit.runner.Description; import org.junit.vintage.engine.descriptor.RunnerTestDescriptor; import org.junit.vintage.engine.descriptor.VintageTestDescriptor; /** * @since 4.12 */ class UniqueIdFilter extends RunnerTestDescriptorAwareFilter { private final UniqueId uniqueId; private Deque<Description> path; private Set<Description> descendants; public UniqueIdFilter(UniqueId uniqueId) { this.uniqueId = uniqueId; } @Override void initialize(RunnerTestDescriptor runnerTestDescriptor) { Optional<? extends TestDescriptor> identifiedTestDescriptor = runnerTestDescriptor.findByUniqueId(uniqueId); descendants = determineDescendants(identifiedTestDescriptor); path = determinePath(runnerTestDescriptor, identifiedTestDescriptor); } private Deque<Description> determinePath(RunnerTestDescriptor runnerTestDescriptor, Optional<? extends TestDescriptor> identifiedTestDescriptor) { Deque<Description> path = new LinkedList<>(); Optional<? extends TestDescriptor> current = identifiedTestDescriptor; while (current.isPresent() && !current.get().equals(runnerTestDescriptor)) { path.addFirst(((VintageTestDescriptor) current.get()).getDescription()); current = current.get().getParent(); } return path; } private Set<Description> determineDescendants(Optional<? extends TestDescriptor> identifiedTestDescriptor) { if (identifiedTestDescriptor.isPresent()) { // @formatter:off return identifiedTestDescriptor.get() .getDescendants() .stream() .map(VintageTestDescriptor.class::cast) .map(VintageTestDescriptor::getDescription) .collect(toSet()); // @formatter:on } return emptySet(); } @Override public boolean shouldRun(Description description) { return path.contains(description) || descendants.contains(description); } @Override public String describe() { return "Unique ID " + uniqueId; } }
Use `Optional.map` and `ArrayDeque` more consistently - Use of `Optional.map` was reported by IntelliJ IDEA inspections. - `ArrayDeque` javadoc states that it is likely to be "faster than `LinkedList` when used as a queue".
junit-vintage-engine/src/main/java/org/junit/vintage/engine/discovery/UniqueIdFilter.java
Use `Optional.map` and `ArrayDeque` more consistently
<ide><path>unit-vintage-engine/src/main/java/org/junit/vintage/engine/discovery/UniqueIdFilter.java <ide> <ide> package org.junit.vintage.engine.discovery; <ide> <del>import static java.util.Collections.emptySet; <ide> import static java.util.stream.Collectors.toSet; <ide> <add>import java.util.ArrayDeque; <add>import java.util.Collections; <ide> import java.util.Deque; <del>import java.util.LinkedList; <ide> import java.util.Optional; <ide> import java.util.Set; <ide> <ide> private Deque<Description> path; <ide> private Set<Description> descendants; <ide> <del> public UniqueIdFilter(UniqueId uniqueId) { <add> UniqueIdFilter(UniqueId uniqueId) { <ide> this.uniqueId = uniqueId; <ide> } <ide> <ide> <ide> private Deque<Description> determinePath(RunnerTestDescriptor runnerTestDescriptor, <ide> Optional<? extends TestDescriptor> identifiedTestDescriptor) { <del> Deque<Description> path = new LinkedList<>(); <add> Deque<Description> path = new ArrayDeque<>(); <ide> Optional<? extends TestDescriptor> current = identifiedTestDescriptor; <ide> while (current.isPresent() && !current.get().equals(runnerTestDescriptor)) { <ide> path.addFirst(((VintageTestDescriptor) current.get()).getDescription()); <ide> } <ide> <ide> private Set<Description> determineDescendants(Optional<? extends TestDescriptor> identifiedTestDescriptor) { <del> if (identifiedTestDescriptor.isPresent()) { <del> // @formatter:off <del> return identifiedTestDescriptor.get() <del> .getDescendants() <del> .stream() <del> .map(VintageTestDescriptor.class::cast) <del> .map(VintageTestDescriptor::getDescription) <del> .collect(toSet()); <del> // @formatter:on <del> } <del> return emptySet(); <add> // @formatter:off <add> return identifiedTestDescriptor.map( <add> testDescriptor -> testDescriptor <add> .getDescendants() <add> .stream() <add> .map(VintageTestDescriptor.class::cast) <add> .map(VintageTestDescriptor::getDescription) <add> .collect(toSet())) <add> .orElseGet(Collections::emptySet); <add> // @formatter:on <ide> } <ide> <ide> @Override
Java
bsd-3-clause
4c7797ea4345d03930b85a5be0868f72e6090f37
0
TheMrMilchmann/lwjgl3,bsmr-java/lwjgl3,LWJGL/lwjgl3,code-disaster/lwjgl3,LWJGL/lwjgl3,bsmr-java/lwjgl3,bsmr-java/lwjgl3,LWJGL/lwjgl3,LWJGL/lwjgl3,bsmr-java/lwjgl3,code-disaster/lwjgl3,code-disaster/lwjgl3,LWJGL-CI/lwjgl3,TheMrMilchmann/lwjgl3,LWJGL-CI/lwjgl3,TheMrMilchmann/lwjgl3,LWJGL-CI/lwjgl3,LWJGL-CI/lwjgl3,TheMrMilchmann/lwjgl3,code-disaster/lwjgl3
/* * Copyright LWJGL. All rights reserved. * License terms: http://lwjgl.org/license.php */ package org.lwjgl.glfw; import org.lwjgl.LWJGLUtil; import org.lwjgl.LWJGLUtil.TokenFilter; import org.lwjgl.system.APIBuffer; import org.lwjgl.system.libffi.Closure; import java.io.PrintStream; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.Map; import static org.lwjgl.Pointer.*; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.system.APIUtil.*; import static org.lwjgl.system.MemoryUtil.*; /** * Utility class for GLFW callbacks. * <p/> * This class has been designed to work well with {@code import static}. */ public final class Callbacks { private Callbacks() {} /** @see GLFW#glfwSetErrorCallback */ public static void glfwSetCallback(GLFWErrorCallback cbfun) { glfwSetErrorCallback(cbfun); } /** @see GLFW#glfwSetMonitorCallback */ public static void glfwSetCallback(GLFWMonitorCallback cbfun) { glfwSetMonitorCallback(cbfun); } /** @see GLFW#glfwSetWindowPosCallback */ public static void glfwSetCallback(long window, GLFWWindowPosCallback cbfun) { glfwSetWindowPosCallback(window, cbfun); } /** @see GLFW#glfwSetWindowSizeCallback */ public static void glfwSetCallback(long window, GLFWWindowSizeCallback cbfun) { glfwSetWindowSizeCallback(window, cbfun); } /** @see GLFW#glfwSetWindowCloseCallback */ public static void glfwSetCallback(long window, GLFWWindowCloseCallback cbfun) { glfwSetWindowCloseCallback(window, cbfun); } /** @see GLFW#glfwSetWindowRefreshCallback */ public static void glfwSetCallback(long window, GLFWWindowRefreshCallback cbfun) { glfwSetWindowRefreshCallback(window, cbfun); } /** @see GLFW#glfwSetWindowFocusCallback */ public static void glfwSetCallback(long window, GLFWWindowFocusCallback cbfun) { glfwSetWindowFocusCallback(window, cbfun); } /** @see GLFW#glfwSetWindowIconifyCallback */ public static void glfwSetCallback(long window, GLFWWindowIconifyCallback cbfun) { glfwSetWindowIconifyCallback(window, cbfun); } /** @see GLFW#glfwSetFramebufferSizeCallback */ public static void glfwSetCallback(long window, GLFWFramebufferSizeCallback cbfun) { glfwSetFramebufferSizeCallback(window, cbfun); } /** @see GLFW#glfwSetKeyCallback */ public static void glfwSetCallback(long window, GLFWKeyCallback cbfun) { glfwSetKeyCallback(window, cbfun); } /** @see GLFW#glfwSetCharCallback */ public static void glfwSetCallback(long window, GLFWCharCallback cbfun) { glfwSetCharCallback(window, cbfun); } /** @see GLFW#glfwSetCharModsCallback */ public static void glfwSetCallback(long window, GLFWCharModsCallback cbfun) { glfwSetCharModsCallback(window, cbfun); } /** @see GLFW#glfwSetMouseButtonCallback */ public static void glfwSetCallback(long window, GLFWMouseButtonCallback cbfun) { glfwSetMouseButtonCallback(window, cbfun); } /** @see GLFW#glfwSetCursorPosCallback */ public static void glfwSetCallback(long window, GLFWCursorPosCallback cbfun) { glfwSetCursorPosCallback(window, cbfun); } /** @see GLFW#glfwSetCursorEnterCallback */ public static void glfwSetCallback(long window, GLFWCursorEnterCallback cbfun) { glfwSetCursorEnterCallback(window, cbfun); } /** @see GLFW#glfwSetScrollCallback */ public static void glfwSetCallback(long window, GLFWScrollCallback cbfun) { glfwSetScrollCallback(window, cbfun); } /** @see GLFW#glfwSetDropCallback */ public static void glfwSetCallback(long window, GLFWDropCallback cbfun) { glfwSetDropCallback(window, cbfun); } /** * Resets all callbacks for the specified GLFW window to {@code NULL} and {@link Closure#release releases} all previously set callbacks. * * @param window the GLFW window */ public static void releaseAllCallbacks(long window) { long[] callbacks = { nglfwSetWindowPosCallback(window, NULL), nglfwSetWindowSizeCallback(window, NULL), nglfwSetWindowCloseCallback(window, NULL), nglfwSetWindowRefreshCallback(window, NULL), nglfwSetWindowFocusCallback(window, NULL), nglfwSetWindowIconifyCallback(window, NULL), nglfwSetFramebufferSizeCallback(window, NULL), nglfwSetKeyCallback(window, NULL), nglfwSetCharCallback(window, NULL), nglfwSetCharModsCallback(window, NULL), nglfwSetMouseButtonCallback(window, NULL), nglfwSetCursorPosCallback(window, NULL), nglfwSetCursorEnterCallback(window, NULL), nglfwSetScrollCallback(window, NULL), nglfwSetDropCallback(window, NULL) }; for ( long callback : callbacks ) { if ( callback != NULL ) Closure.release(callback); } } /** * Returns a {@link GLFWErrorCallback} instance that prints the error in the standard error stream. * * @return the GLFWerrorCallback */ public static GLFWErrorCallback errorCallbackPrint() { return errorCallbackPrint(System.err); } /** * Returns a {@link GLFWErrorCallback} instance that prints the error in the specified {@link PrintStream}. * * @param stream the PrintStream to use * * @return the GLFWerrorCallback */ public static GLFWErrorCallback errorCallbackPrint(final PrintStream stream) { return new GLFWErrorCallback() { private final Map<Integer, String> ERROR_CODES = LWJGLUtil.getClassTokens(new TokenFilter() { @Override public boolean accept(Field field, int value) { return 0x10000 < value && value < 0x20000; } }, null, GLFW.class); @Override public void invoke(int error, long description) { String msg = errorCallbackDescriptionString(description); stream.printf("[LWJGL] %s error\n", ERROR_CODES.get(error)); stream.println("\tDescription : " + msg); stream.println("\tStacktrace :"); StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for ( int i = 4; i < stack.length; i++ ) { stream.print("\t\t"); stream.println(stack[i].toString()); } } }; } /** * Returns a {@link GLFWErrorCallback} instance that throws an {@link IllegalStateException} when an error occurs. * * @return the GLFWerrorCallback */ public static GLFWErrorCallback errorCallbackThrow() { return new GLFWErrorCallback() { @Override public void invoke(int error, long description) { throw new IllegalStateException(String.format("GLFW error [0x%X]: %s", error, errorCallbackDescriptionString(description))); } }; } /** * Converts the specified {@link GLFWErrorCallback} description string pointer to a {@link ByteBuffer}, with a capacity equal to the UTF-8 encoded string. * <p/> * This method may only be used inside a GLFWerrorCallback invocation. If you wish to use the ByteBuffer after the callback returns, you need to make a * copy. * * @param description a pointer to the UTF-8 encoded description string * * @return the description string, as a ByteBuffer */ public static ByteBuffer errorCallbackDescriptionBuffer(long description) { return memByteBufferNT1(description); } /** * Converts the specified {@link GLFWErrorCallback} description string pointer to a String. * <p/> * This method may only be used inside a GLFWerrorCallback invocation. * * @param description a pointer to the UTF-8 encoded description string * * @return the description string */ public static String errorCallbackDescriptionString(long description) { return memDecodeUTF8(description); } /** * Converts the specified {@link GLFWDropCallback} arguments to a ByteBuffer array. * <p/> * This method may only be used inside a GLFWdropCallback invocation. If you wish to use the array after the callback returns, you need to make a deep * copy. * * @param count the number of dropped files * @param names pointer to the array of UTF-8 encoded path names of the dropped files * * @return the array of names, as ByteBuffers */ public static ByteBuffer[] dropCallbackNamesBuffer(int count, long names) { ByteBuffer[] buffers = new ByteBuffer[count]; for ( int i = 0; i < count; i++ ) buffers[i] = memByteBufferNT1(memGetAddress(names + POINTER_SIZE * i)); return buffers; } /** * Converts the specified {@link GLFWDropCallback} arguments to a String array. * <p/> * This method may only be used inside a GLFWdropCallback invocation. * * @param count the number of dropped files * @param names pointer to the array of UTF-8 encoded path names of the dropped files * * @return the array of names, as Strings */ public static String[] dropCallbackNamesString(int count, long names) { String[] strings = new String[count]; for ( int i = 0; i < count; i++ ) strings[i] = memDecodeUTF8(memGetAddress(names + POINTER_SIZE * i)); return strings; } /** A functional interface that can be used with {@link #dropCallbackNamesApply(int, long, DropConsumerBuffer) dropCallbackNamesApply}. */ public interface DropConsumerBuffer { void accept(int index, ByteBuffer name); } /** A functional interface that can be used with {@link #dropCallbackNamesApply(int, long, DropConsumerString) dropCallbackNamesApply}. */ public interface DropConsumerString { void accept(int index, String name); } /** * Applies the specified {@link DropConsumerBuffer} to the specified {@link GLFWDropCallback} arguments. * <p/> * This method may only be used inside a GLFWdropCallback invocation. * * @param count the number of dropped files * @param names pointer to the array of UTF-8 encoded path names of the dropped files * @param consumer the DropConsumerBuffer to apply */ public static void dropCallbackNamesApply(int count, long names, DropConsumerBuffer consumer) { for ( int i = 0; i < count; i++ ) consumer.accept(i, memByteBufferNT1(memGetAddress(names + POINTER_SIZE * i))); } /** * Applies the specified {@link DropConsumerString} to the specified {@link GLFWDropCallback} arguments. * <p/> * This method may only be used inside a GLFWdropCallback invocation. * * @param count the number of dropped files * @param names pointer to the array of UTF-8 encoded path names of the dropped files * @param consumer the DropConsumerString to apply */ public static void dropCallbackNamesApply(int count, long names, DropConsumerString consumer) { for ( int i = 0; i < count; i++ ) consumer.accept(i, memDecodeUTF8(memGetAddress(names + POINTER_SIZE * i))); } /** * Invokes the specified callbacks using the current window and framebuffer sizes of the specified GLFW window. * * @param window the GLFW window * @param windowsizefun the window size callback, may be null * @param framebuffersizefun the framebuffer size callback, may be null */ public static void glfwInvoke(long window, GLFWWindowSizeCallback windowsizefun, GLFWFramebufferSizeCallback framebuffersizefun) { APIBuffer buffer = apiBuffer(); if ( framebuffersizefun != null ) { nglfwGetFramebufferSize(window, buffer.address() + 0, buffer.address() + 4); framebuffersizefun.invoke(window, buffer.intValue(0), buffer.intValue(4)); } if ( windowsizefun != null ) { nglfwGetWindowSize(window, buffer.address() + 0, buffer.address() + 4); windowsizefun.invoke(window, buffer.intValue(0), buffer.intValue(4)); } } }
src/core/org/lwjgl/glfw/Callbacks.java
/* * Copyright LWJGL. All rights reserved. * License terms: http://lwjgl.org/license.php */ package org.lwjgl.glfw; import org.lwjgl.LWJGLUtil; import org.lwjgl.LWJGLUtil.TokenFilter; import org.lwjgl.system.libffi.Closure; import java.io.PrintStream; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.Map; import static org.lwjgl.Pointer.*; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.system.MemoryUtil.*; /** * Utility class for GLFW callbacks. * <p/> * This class has been designed to work well with {@code import static}. */ public final class Callbacks { private Callbacks() {} /** @see GLFW#glfwSetErrorCallback */ public static void glfwSetCallback(GLFWErrorCallback cbfun) { glfwSetErrorCallback(cbfun); } /** @see GLFW#glfwSetMonitorCallback */ public static void glfwSetCallback(GLFWMonitorCallback cbfun) { glfwSetMonitorCallback(cbfun); } /** @see GLFW#glfwSetWindowPosCallback */ public static void glfwSetCallback(long window, GLFWWindowPosCallback cbfun) { glfwSetWindowPosCallback(window, cbfun); } /** @see GLFW#glfwSetWindowSizeCallback */ public static void glfwSetCallback(long window, GLFWWindowSizeCallback cbfun) { glfwSetWindowSizeCallback(window, cbfun); } /** @see GLFW#glfwSetWindowCloseCallback */ public static void glfwSetCallback(long window, GLFWWindowCloseCallback cbfun) { glfwSetWindowCloseCallback(window, cbfun); } /** @see GLFW#glfwSetWindowRefreshCallback */ public static void glfwSetCallback(long window, GLFWWindowRefreshCallback cbfun) { glfwSetWindowRefreshCallback(window, cbfun); } /** @see GLFW#glfwSetWindowFocusCallback */ public static void glfwSetCallback(long window, GLFWWindowFocusCallback cbfun) { glfwSetWindowFocusCallback(window, cbfun); } /** @see GLFW#glfwSetWindowIconifyCallback */ public static void glfwSetCallback(long window, GLFWWindowIconifyCallback cbfun) { glfwSetWindowIconifyCallback(window, cbfun); } /** @see GLFW#glfwSetFramebufferSizeCallback */ public static void glfwSetCallback(long window, GLFWFramebufferSizeCallback cbfun) { glfwSetFramebufferSizeCallback(window, cbfun); } /** @see GLFW#glfwSetKeyCallback */ public static void glfwSetCallback(long window, GLFWKeyCallback cbfun) { glfwSetKeyCallback(window, cbfun); } /** @see GLFW#glfwSetCharCallback */ public static void glfwSetCallback(long window, GLFWCharCallback cbfun) { glfwSetCharCallback(window, cbfun); } /** @see GLFW#glfwSetCharModsCallback */ public static void glfwSetCallback(long window, GLFWCharModsCallback cbfun) { glfwSetCharModsCallback(window, cbfun); } /** @see GLFW#glfwSetMouseButtonCallback */ public static void glfwSetCallback(long window, GLFWMouseButtonCallback cbfun) { glfwSetMouseButtonCallback(window, cbfun); } /** @see GLFW#glfwSetCursorPosCallback */ public static void glfwSetCallback(long window, GLFWCursorPosCallback cbfun) { glfwSetCursorPosCallback(window, cbfun); } /** @see GLFW#glfwSetCursorEnterCallback */ public static void glfwSetCallback(long window, GLFWCursorEnterCallback cbfun) { glfwSetCursorEnterCallback(window, cbfun); } /** @see GLFW#glfwSetScrollCallback */ public static void glfwSetCallback(long window, GLFWScrollCallback cbfun) { glfwSetScrollCallback(window, cbfun); } /** @see GLFW#glfwSetDropCallback */ public static void glfwSetCallback(long window, GLFWDropCallback cbfun) { glfwSetDropCallback(window, cbfun); } /** * Resets all callbacks for the specified GLFW window to {@code NULL} and {@link Closure#release releases} all previously set callbacks. * * @param window the GLFW window */ public static void releaseAllCallbacks(long window) { long[] callbacks = { nglfwSetWindowPosCallback(window, NULL), nglfwSetWindowSizeCallback(window, NULL), nglfwSetWindowCloseCallback(window, NULL), nglfwSetWindowRefreshCallback(window, NULL), nglfwSetWindowFocusCallback(window, NULL), nglfwSetWindowIconifyCallback(window, NULL), nglfwSetFramebufferSizeCallback(window, NULL), nglfwSetKeyCallback(window, NULL), nglfwSetCharCallback(window, NULL), nglfwSetCharModsCallback(window, NULL), nglfwSetMouseButtonCallback(window, NULL), nglfwSetCursorPosCallback(window, NULL), nglfwSetCursorEnterCallback(window, NULL), nglfwSetScrollCallback(window, NULL), nglfwSetDropCallback(window, NULL) }; for ( long callback : callbacks ) { if ( callback != NULL ) Closure.release(callback); } } /** * Returns a {@link GLFWErrorCallback} instance that prints the error in the standard error stream. * * @return the GLFWerrorCallback */ public static GLFWErrorCallback errorCallbackPrint() { return errorCallbackPrint(System.err); } /** * Returns a {@link GLFWErrorCallback} instance that prints the error in the specified {@link PrintStream}. * * @param stream the PrintStream to use * * @return the GLFWerrorCallback */ public static GLFWErrorCallback errorCallbackPrint(final PrintStream stream) { return new GLFWErrorCallback() { private final Map<Integer, String> ERROR_CODES = LWJGLUtil.getClassTokens(new TokenFilter() { @Override public boolean accept(Field field, int value) { return 0x10000 < value && value < 0x20000; } }, null, GLFW.class); @Override public void invoke(int error, long description) { String msg = errorCallbackDescriptionString(description); stream.printf("[LWJGL] %s error\n", ERROR_CODES.get(error)); stream.println("\tDescription : " + msg); stream.println("\tStacktrace :"); StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for ( int i = 4; i < stack.length; i++ ) { stream.print("\t\t"); stream.println(stack[i].toString()); } } }; } /** * Returns a {@link GLFWErrorCallback} instance that throws an {@link IllegalStateException} when an error occurs. * * @return the GLFWerrorCallback */ public static GLFWErrorCallback errorCallbackThrow() { return new GLFWErrorCallback() { @Override public void invoke(int error, long description) { throw new IllegalStateException(String.format("GLFW error [0x%X]: %s", error, errorCallbackDescriptionString(description))); } }; } /** * Converts the specified {@link GLFWErrorCallback} description string pointer to a {@link ByteBuffer}, with a capacity equal to the UTF-8 encoded string. * <p/> * This method may only be used inside a GLFWerrorCallback invocation. If you wish to use the ByteBuffer after the callback returns, you need to make a * copy. * * @param description a pointer to the UTF-8 encoded description string * * @return the description string, as a ByteBuffer */ public static ByteBuffer errorCallbackDescriptionBuffer(long description) { return memByteBufferNT1(description); } /** * Converts the specified {@link GLFWErrorCallback} description string pointer to a String. * <p/> * This method may only be used inside a GLFWerrorCallback invocation. * * @param description a pointer to the UTF-8 encoded description string * * @return the description string */ public static String errorCallbackDescriptionString(long description) { return memDecodeUTF8(description); } /** * Converts the specified {@link GLFWDropCallback} arguments to a ByteBuffer array. * <p/> * This method may only be used inside a GLFWdropCallback invocation. If you wish to use the array after the callback returns, you need to make a deep * copy. * * @param count the number of dropped files * @param names pointer to the array of UTF-8 encoded path names of the dropped files * * @return the array of names, as ByteBuffers */ public static ByteBuffer[] dropCallbackNamesBuffer(int count, long names) { ByteBuffer[] buffers = new ByteBuffer[count]; for ( int i = 0; i < count; i++ ) buffers[i] = memByteBufferNT1(memGetAddress(names + POINTER_SIZE * i)); return buffers; } /** * Converts the specified {@link GLFWDropCallback} arguments to a String array. * <p/> * This method may only be used inside a GLFWdropCallback invocation. * * @param count the number of dropped files * @param names pointer to the array of UTF-8 encoded path names of the dropped files * * @return the array of names, as Strings */ public static String[] dropCallbackNamesString(int count, long names) { String[] strings = new String[count]; for ( int i = 0; i < count; i++ ) strings[i] = memDecodeUTF8(memGetAddress(names + POINTER_SIZE * i)); return strings; } /** A functional interface that can be used with {@link #dropCallbackNamesApply(int, long, DropConsumerBuffer) dropCallbackNamesApply}. */ public interface DropConsumerBuffer { void accept(int index, ByteBuffer name); } /** A functional interface that can be used with {@link #dropCallbackNamesApply(int, long, DropConsumerString) dropCallbackNamesApply}. */ public interface DropConsumerString { void accept(int index, String name); } /** * Applies the specified {@link DropConsumerBuffer} to the specified {@link GLFWDropCallback} arguments. * <p/> * This method may only be used inside a GLFWdropCallback invocation. * * @param count the number of dropped files * @param names pointer to the array of UTF-8 encoded path names of the dropped files * @param consumer the DropConsumerBuffer to apply */ public static void dropCallbackNamesApply(int count, long names, DropConsumerBuffer consumer) { for ( int i = 0; i < count; i++ ) consumer.accept(i, memByteBufferNT1(memGetAddress(names + POINTER_SIZE * i))); } /** * Applies the specified {@link DropConsumerString} to the specified {@link GLFWDropCallback} arguments. * <p/> * This method may only be used inside a GLFWdropCallback invocation. * * @param count the number of dropped files * @param names pointer to the array of UTF-8 encoded path names of the dropped files * @param consumer the DropConsumerString to apply */ public static void dropCallbackNamesApply(int count, long names, DropConsumerString consumer) { for ( int i = 0; i < count; i++ ) consumer.accept(i, memDecodeUTF8(memGetAddress(names + POINTER_SIZE * i))); } }
Add helper method that easily invokes GLFWWindowSizeCallback/GLFWFramebufferSizeCallback The window/framebuffer size callbacks are not guaranteed to be called after glfwShowWindow(). This method is useful to trigger any changes that must be done to support HiDPI rendering.
src/core/org/lwjgl/glfw/Callbacks.java
Add helper method that easily invokes GLFWWindowSizeCallback/GLFWFramebufferSizeCallback
<ide><path>rc/core/org/lwjgl/glfw/Callbacks.java <ide> <ide> import org.lwjgl.LWJGLUtil; <ide> import org.lwjgl.LWJGLUtil.TokenFilter; <add>import org.lwjgl.system.APIBuffer; <ide> import org.lwjgl.system.libffi.Closure; <ide> <ide> import java.io.PrintStream; <ide> <ide> import static org.lwjgl.Pointer.*; <ide> import static org.lwjgl.glfw.GLFW.*; <add>import static org.lwjgl.system.APIUtil.*; <ide> import static org.lwjgl.system.MemoryUtil.*; <ide> <ide> /** <ide> consumer.accept(i, memDecodeUTF8(memGetAddress(names + POINTER_SIZE * i))); <ide> } <ide> <add> /** <add> * Invokes the specified callbacks using the current window and framebuffer sizes of the specified GLFW window. <add> * <add> * @param window the GLFW window <add> * @param windowsizefun the window size callback, may be null <add> * @param framebuffersizefun the framebuffer size callback, may be null <add> */ <add> public static void glfwInvoke(long window, GLFWWindowSizeCallback windowsizefun, GLFWFramebufferSizeCallback framebuffersizefun) { <add> APIBuffer buffer = apiBuffer(); <add> <add> if ( framebuffersizefun != null ) { <add> nglfwGetFramebufferSize(window, buffer.address() + 0, buffer.address() + 4); <add> framebuffersizefun.invoke(window, buffer.intValue(0), buffer.intValue(4)); <add> } <add> <add> if ( windowsizefun != null ) { <add> nglfwGetWindowSize(window, buffer.address() + 0, buffer.address() + 4); <add> windowsizefun.invoke(window, buffer.intValue(0), buffer.intValue(4)); <add> } <add> } <add> <ide> }
Java
apache-2.0
78153af0c3741213f9dc712d1759104844e72206
0
Yorxxx/playednext
package com.piticlistudio.playednext.game.ui.search.view; import android.content.Intent; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.Espresso; import android.support.test.espresso.ViewInteraction; import android.support.test.espresso.contrib.RecyclerViewActions; import android.support.test.rule.ActivityTestRule; import android.view.WindowManager; import android.widget.EditText; import com.piticlistudio.playednext.AndroidApplication; import com.piticlistudio.playednext.CustomMatchers; import com.piticlistudio.playednext.EmptyActivity; import com.piticlistudio.playednext.GameFactory; import com.piticlistudio.playednext.R; import com.piticlistudio.playednext.RecyclerViewItemCountAssertion; import com.piticlistudio.playednext.di.component.AppComponent; import com.piticlistudio.playednext.di.module.AppModule; import com.piticlistudio.playednext.game.model.entity.Game; import com.piticlistudio.playednext.game.ui.search.GameSearchComponent; import com.piticlistudio.playednext.game.ui.search.GameSearchContract; import com.piticlistudio.playednext.game.ui.search.GameSearchModule; import com.piticlistudio.playednext.gamerelation.ui.detail.view.GameRelationDetailActivity; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import java.util.ArrayList; import java.util.List; import it.cosenonjaviste.daggermock.DaggerMockRule; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.pressImeActionButton; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant; import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayingAtLeast; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withParent; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.not; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Test cases for GameSearchFragment * Created by jorge.garcia on 23/02/2017. */ public class GameSearchFragmentTest { @Rule public MockitoRule rule = MockitoJUnit.rule(); @Rule public DaggerMockRule<GameSearchComponent> componentRule = new DaggerMockRule<>(GameSearchComponent.class, new GameSearchModule()) .addComponentDependency(AppComponent.class, new AppModule(getApp())) .set(component -> getApp().setGameSearchComponent(component)); @Rule public ActivityTestRule<EmptyActivity> activityTestRule = new ActivityTestRule<>(EmptyActivity.class, false, false); @Mock GameSearchContract.Presenter presenter; private GameSearchFragment getFragment() { return activityTestRule.getActivity().currentFragment; } private AndroidApplication getApp() { return (AndroidApplication) InstrumentationRegistry.getInstrumentation() .getTargetContext().getApplicationContext(); } @Before public void setUp() throws Exception { activityTestRule.launchActivity(null); EmptyActivity activity = activityTestRule.getActivity(); Runnable wakeUpDevice = new Runnable() { public void run() { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }; activity.runOnUiThread(wakeUpDevice); } @Test public void Given_Launched_When_Attaches_Then_AttachesPresenter() throws Exception { verify(presenter).attachView(getFragment()); } @Test public void Given_Launched_When_onDestroyView_Then_DetachesPresenter() throws Exception { // Act getFragment().onDestroyView(); // Assert verify(presenter).detachView(false); } @Test public void Given_Idle_When_ActivityCreated_Then_ShowsInitialView() throws Exception { onView(withId(R.id.progress)).check(matches(not(isDisplayed()))); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(0)); onView(withId(R.id.initialstateview)).check(matches(isDisplayed())); onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withText(R.string.game_search_emptyview_title)).check(matches(isDisplayed())); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.searchview)).check(matches(isDisplayed())); onView(withId(R.id.searchview)).check(matches(CustomMatchers.isSearchIconified(false))); } @Test public void Given_SearchInput_When_InputsText_Then_RequestsPresenter() throws Exception { onView(withId(R.id.searchview)).perform(click()); onView(isAssignableFrom(EditText.class)).perform(typeText("mario")); verify(presenter).search("m", 0, getFragment().loadLimit); verify(presenter).search("ma", 0, getFragment().loadLimit); verify(presenter).search("mar", 0, getFragment().loadLimit); verify(presenter).search("mari", 0, getFragment().loadLimit); verify(presenter).search("mario", 0, getFragment().loadLimit); } @Test public void Given_SearchInput_When_SubmitText_Then_RequestsPresenter() throws Exception { onView(withId(R.id.searchview)).perform(click()); onView(isAssignableFrom(EditText.class)).perform(typeText("mario")); verify(presenter).search("m", 0, getFragment().loadLimit); verify(presenter).search("ma", 0, getFragment().loadLimit); verify(presenter).search("mar", 0, getFragment().loadLimit); verify(presenter).search("mari", 0, getFragment().loadLimit); verify(presenter).search("mario", 0, getFragment().loadLimit); onView(withId(R.id.search_src_text)).perform(pressImeActionButton()); verify(presenter, times(2)).search("mario", 0, getFragment().loadLimit); } @Test public void Given_Idle_When_PressCloseButton_Then_NotifiesListener() throws Exception { GameSearchFragment.IGameSearchFragmentListener listener = mock(GameSearchFragment.IGameSearchFragmentListener.class); getFragment().setListener(listener); // Act onView(withId(R.id.closeBtn)).perform(click()); Thread.sleep(500); // Assert verify(listener).onCloseSearchClicked(any()); } @Test public void Given_NoListener_When_PressCloseButton_Then_DoesNothing() throws Exception { getFragment().setListener(null); // Act onView(withId(R.id.closeBtn)).perform(click()); Thread.sleep(500); } @Test public void Given_Idle_When_ShowLoading_Then_ShowsLoading() throws Throwable { Espresso.closeSoftKeyboard(); activityTestRule.runOnUiThread(() -> getFragment().showLoading()); onView(withId(R.id.progress)).check(matches(CustomMatchers.isVisibleToUser(true))); } @Test public void Given_InitialViewState_When_ShowContent_Then_HidesInitialView() throws Throwable { onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(true))); activityTestRule.runOnUiThread(() -> getFragment().showContent()); Thread.sleep(500); // Assert onView(withId(R.id.progress)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(false))); } //@Test public void Given_ErrorViewState_When_ShowContent_Then_HidesErrorView() throws Throwable { activityTestRule.runOnUiThread(() -> getFragment().showError(new Exception("bla"))); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(true))); activityTestRule.runOnUiThread(() -> getFragment().showContent()); // Assert onView(withId(R.id.progress)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); } //@Test public void Given_EmptyList_When_SetData_Then_ShowsData() throws Throwable { List<Game> data = new ArrayList<>(); for (int i = 0; i < 10; i++) { data.add(GameFactory.provide(10, "title")); } // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); // Assert onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(10)); onView(withId(R.id.loadmore_progress)).check(doesNotExist()); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); } //@Test public void Given_EmptyList_When_SetEmptyData_Then_ShowsEmptyStateView() throws Throwable { List<Game> data = new ArrayList<>(); // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); // Assert onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(0)); onView(withId(R.id.loadmore_progress)).check(doesNotExist()); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(true))); } //@Test public void Given_EmptyStateView_When_SetFilledData_Then_ShowsData() throws Throwable { List<Game> data = new ArrayList<>(); for (int i = 0; i < 10; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(new ArrayList<>())); Thread.sleep(500); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(true))); // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); Thread.sleep(500); // Assert onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(10)); onView(withId(R.id.loadmore_progress)).check(doesNotExist()); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); } //@Test public void Given_settingMaxItems_When_SetData_Then_ShowDataAndLoadMoreRow() throws Throwable { Espresso.closeSoftKeyboard(); int maxItems = getFragment().loadLimit; List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); // Assert onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems + 1)); // Plus load more item } //@Test public void Given_MaxLoadedList_When_SwipingDown_Then_RequestsMoreData() throws Throwable { int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Assert onView(withId(R.id.loadmore_progress)).check(matches(isDisplayed())); verify(presenter).search("", maxItems + 1, maxItems); } //@Test public void given_alreadyLoadingMoreData_When_SwipesDown_Then_DoesNotRequestMoreData() throws Throwable { int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); onView(withId(R.id.loadmore_progress)).check(matches(isDisplayed())); // Scroll up again onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(0)); // Act onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Assert verify(presenter).search("", maxItems + 1, maxItems); } //@Test public void Given_NotFilledList_When_SwipingDown_Then_DoesNotRequestMoreData() throws Throwable { int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems / 2; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Assert verify(presenter, never()).search("", maxItems + 1, maxItems); } //@Test public void Given_FilledList_When_SetData_Then_AppendsData() throws Throwable { // Arrange int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems + 1)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); // Assert onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems * 2)); } //@Test public void Given_InitialViewState_When_ShowError_Then_ShowsErrorAndHideInitialView() throws Throwable { onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(true))); // Act Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); Thread.sleep(500); // Assert onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withText("bla")).check(matches(isDisplayed())); } //@Test public void Given_EmptyViewState_When_ShowError_Then_ShowsErrorAndHidesEmptyView() throws Throwable { // Arrange List<Game> data = new ArrayList<>(); activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(true))); // Act Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); Thread.sleep(500); // Assert onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withText("bla")).check(matches(isDisplayed())); } //@Test public void Given_IdleList_When_ShowError_Then_ShowsError() throws Throwable { // Arrange int maxItems = getFragment().loadLimit; List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems / 2; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> { getFragment().setData(data); getFragment().showContent(); }); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems / 2)); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); // Act Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); // Assert onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withText("bla")).check(matches(isDisplayed())); } //@Test public void Given_LoadingMoreItems_When_ShowError_Then_ShowsSnackbarError() throws Throwable { int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems + 1)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Act Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); Thread.sleep(1000); // Assert onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.searchlist)).check(matches(isDisplayingAtLeast(100))); // onView(allOf(withId(android.support.design.R.id.snackbar_text), withParent(withId(R.id.content)))).check(matches(isDisplayed())); onView(withText("bla")).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withId(android.support.design.R.id.snackbar_action)).check(matches(isDisplayed())); onView(withId(android.support.design.R.id.snackbar_action)).check(matches(withText(R.string.game_search_error_retry_button))); onView(withId(android.support.design.R.id.snackbar_action)).check(matches(isDisplayed())); } //@Test public void Given_LoadingMoreErrorIsDisplayed_When_ClickOnRetry_Then_RetriesRequest() throws Throwable { // Arrange int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); Thread.sleep(1000); // Act onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.searchlist)).check(matches(isDisplayingAtLeast(100))); onView(withId(android.support.design.R.id.snackbar_action)).check(matches(isDisplayed())); onView(withId(android.support.design.R.id.snackbar_action)).perform(click()); // Assert verify(presenter).search("", maxItems + 1, maxItems); } //@Test public void Given_FilledList_When_ClickOnItem_Then_LaunchesDetailView() throws Throwable { // Arrange int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title_" + i)); } activityTestRule.runOnUiThread(() -> { getFragment().setData(data); getFragment().showContent(); }); // ACt onView(withId(R.id.searchlist)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click())); // Assert onView(withId(R.id.searchlist)).check(doesNotExist()); onView(withId(R.id.backdrop)).check(matches(CustomMatchers.isVisibleToUser(true))); } }
app/src/androidTest/java/com/piticlistudio/playednext/game/ui/search/view/GameSearchFragmentTest.java
package com.piticlistudio.playednext.game.ui.search.view; import android.content.Intent; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.Espresso; import android.support.test.espresso.ViewInteraction; import android.support.test.espresso.contrib.RecyclerViewActions; import android.support.test.rule.ActivityTestRule; import android.view.WindowManager; import android.widget.EditText; import com.piticlistudio.playednext.AndroidApplication; import com.piticlistudio.playednext.CustomMatchers; import com.piticlistudio.playednext.EmptyActivity; import com.piticlistudio.playednext.GameFactory; import com.piticlistudio.playednext.R; import com.piticlistudio.playednext.RecyclerViewItemCountAssertion; import com.piticlistudio.playednext.di.component.AppComponent; import com.piticlistudio.playednext.di.module.AppModule; import com.piticlistudio.playednext.game.model.entity.Game; import com.piticlistudio.playednext.game.ui.search.GameSearchComponent; import com.piticlistudio.playednext.game.ui.search.GameSearchContract; import com.piticlistudio.playednext.game.ui.search.GameSearchModule; import com.piticlistudio.playednext.gamerelation.ui.detail.view.GameRelationDetailActivity; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import java.util.ArrayList; import java.util.List; import it.cosenonjaviste.daggermock.DaggerMockRule; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.pressImeActionButton; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant; import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayingAtLeast; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withParent; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.not; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Test cases for GameSearchFragment * Created by jorge.garcia on 23/02/2017. */ public class GameSearchFragmentTest { @Rule public MockitoRule rule = MockitoJUnit.rule(); @Rule public DaggerMockRule<GameSearchComponent> componentRule = new DaggerMockRule<>(GameSearchComponent.class, new GameSearchModule()) .addComponentDependency(AppComponent.class, new AppModule(getApp())) .set(component -> getApp().setGameSearchComponent(component)); @Rule public ActivityTestRule<EmptyActivity> activityTestRule = new ActivityTestRule<>(EmptyActivity.class, false, false); @Mock GameSearchContract.Presenter presenter; private GameSearchFragment getFragment() { return activityTestRule.getActivity().currentFragment; } private AndroidApplication getApp() { return (AndroidApplication) InstrumentationRegistry.getInstrumentation() .getTargetContext().getApplicationContext(); } @Before public void setUp() throws Exception { activityTestRule.launchActivity(null); EmptyActivity activity = activityTestRule.getActivity(); Runnable wakeUpDevice = new Runnable() { public void run() { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }; activity.runOnUiThread(wakeUpDevice); } @Test public void Given_Launched_When_Attaches_Then_AttachesPresenter() throws Exception { verify(presenter).attachView(getFragment()); } @Test public void Given_Launched_When_onDestroyView_Then_DetachesPresenter() throws Exception { // Act getFragment().onDestroyView(); // Assert verify(presenter).detachView(false); } @Test public void Given_Idle_When_ActivityCreated_Then_ShowsInitialView() throws Exception { onView(withId(R.id.progress)).check(matches(not(isDisplayed()))); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(0)); onView(withId(R.id.initialstateview)).check(matches(isDisplayed())); onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withText(R.string.game_search_emptyview_title)).check(matches(isDisplayed())); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.searchview)).check(matches(isDisplayed())); onView(withId(R.id.searchview)).check(matches(CustomMatchers.isSearchIconified(false))); } @Test public void Given_SearchInput_When_InputsText_Then_RequestsPresenter() throws Exception { onView(withId(R.id.searchview)).perform(click()); onView(isAssignableFrom(EditText.class)).perform(typeText("mario")); verify(presenter).search("m", 0, getFragment().loadLimit); verify(presenter).search("ma", 0, getFragment().loadLimit); verify(presenter).search("mar", 0, getFragment().loadLimit); verify(presenter).search("mari", 0, getFragment().loadLimit); verify(presenter).search("mario", 0, getFragment().loadLimit); } @Test public void Given_SearchInput_When_SubmitText_Then_RequestsPresenter() throws Exception { onView(withId(R.id.searchview)).perform(click()); onView(isAssignableFrom(EditText.class)).perform(typeText("mario")); verify(presenter).search("m", 0, getFragment().loadLimit); verify(presenter).search("ma", 0, getFragment().loadLimit); verify(presenter).search("mar", 0, getFragment().loadLimit); verify(presenter).search("mari", 0, getFragment().loadLimit); verify(presenter).search("mario", 0, getFragment().loadLimit); onView(withId(R.id.search_src_text)).perform(pressImeActionButton()); verify(presenter, times(2)).search("mario", 0, getFragment().loadLimit); } @Test public void Given_Idle_When_PressCloseButton_Then_NotifiesListener() throws Exception { GameSearchFragment.IGameSearchFragmentListener listener = mock(GameSearchFragment.IGameSearchFragmentListener.class); getFragment().setListener(listener); // Act onView(withId(R.id.closeBtn)).perform(click()); Thread.sleep(500); // Assert verify(listener).onCloseSearchClicked(any()); } @Test public void Given_NoListener_When_PressCloseButton_Then_DoesNothing() throws Exception { getFragment().setListener(null); // Act onView(withId(R.id.closeBtn)).perform(click()); Thread.sleep(500); } //@Test public void Given_Idle_When_ShowLoading_Then_ShowsLoading() throws Throwable { Espresso.closeSoftKeyboard(); activityTestRule.runOnUiThread(() -> getFragment().showLoading()); onView(withId(R.id.progress)).check(matches(CustomMatchers.isVisibleToUser(true))); } //@Test public void Given_InitialViewState_When_ShowContent_Then_HidesInitialView() throws Throwable { onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(true))); activityTestRule.runOnUiThread(() -> getFragment().showContent()); Thread.sleep(500); // Assert onView(withId(R.id.progress)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(false))); } //@Test public void Given_ErrorViewState_When_ShowContent_Then_HidesErrorView() throws Throwable { activityTestRule.runOnUiThread(() -> getFragment().showError(new Exception("bla"))); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(true))); activityTestRule.runOnUiThread(() -> getFragment().showContent()); // Assert onView(withId(R.id.progress)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); } //@Test public void Given_EmptyList_When_SetData_Then_ShowsData() throws Throwable { List<Game> data = new ArrayList<>(); for (int i = 0; i < 10; i++) { data.add(GameFactory.provide(10, "title")); } // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); // Assert onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(10)); onView(withId(R.id.loadmore_progress)).check(doesNotExist()); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); } //@Test public void Given_EmptyList_When_SetEmptyData_Then_ShowsEmptyStateView() throws Throwable { List<Game> data = new ArrayList<>(); // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); // Assert onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(0)); onView(withId(R.id.loadmore_progress)).check(doesNotExist()); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(true))); } //@Test public void Given_EmptyStateView_When_SetFilledData_Then_ShowsData() throws Throwable { List<Game> data = new ArrayList<>(); for (int i = 0; i < 10; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(new ArrayList<>())); Thread.sleep(500); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(true))); // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); Thread.sleep(500); // Assert onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(10)); onView(withId(R.id.loadmore_progress)).check(doesNotExist()); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); } //@Test public void Given_settingMaxItems_When_SetData_Then_ShowDataAndLoadMoreRow() throws Throwable { Espresso.closeSoftKeyboard(); int maxItems = getFragment().loadLimit; List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); // Assert onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems + 1)); // Plus load more item } //@Test public void Given_MaxLoadedList_When_SwipingDown_Then_RequestsMoreData() throws Throwable { int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Assert onView(withId(R.id.loadmore_progress)).check(matches(isDisplayed())); verify(presenter).search("", maxItems + 1, maxItems); } //@Test public void given_alreadyLoadingMoreData_When_SwipesDown_Then_DoesNotRequestMoreData() throws Throwable { int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); onView(withId(R.id.loadmore_progress)).check(matches(isDisplayed())); // Scroll up again onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(0)); // Act onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Assert verify(presenter).search("", maxItems + 1, maxItems); } //@Test public void Given_NotFilledList_When_SwipingDown_Then_DoesNotRequestMoreData() throws Throwable { int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems / 2; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Assert verify(presenter, never()).search("", maxItems + 1, maxItems); } //@Test public void Given_FilledList_When_SetData_Then_AppendsData() throws Throwable { // Arrange int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems + 1)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Act activityTestRule.runOnUiThread(() -> getFragment().setData(data)); // Assert onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems * 2)); } //@Test public void Given_InitialViewState_When_ShowError_Then_ShowsErrorAndHideInitialView() throws Throwable { onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(true))); // Act Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); Thread.sleep(500); // Assert onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withText("bla")).check(matches(isDisplayed())); } //@Test public void Given_EmptyViewState_When_ShowError_Then_ShowsErrorAndHidesEmptyView() throws Throwable { // Arrange List<Game> data = new ArrayList<>(); activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(true))); // Act Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); Thread.sleep(500); // Assert onView(withId(R.id.emptystateview)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withText("bla")).check(matches(isDisplayed())); } //@Test public void Given_IdleList_When_ShowError_Then_ShowsError() throws Throwable { // Arrange int maxItems = getFragment().loadLimit; List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems / 2; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> { getFragment().setData(data); getFragment().showContent(); }); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems / 2)); onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); // Act Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); // Assert onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withText("bla")).check(matches(isDisplayed())); } //@Test public void Given_LoadingMoreItems_When_ShowError_Then_ShowsSnackbarError() throws Throwable { int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).check(new RecyclerViewItemCountAssertion(maxItems + 1)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); // Act Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); Thread.sleep(1000); // Assert onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.searchlist)).check(matches(isDisplayingAtLeast(100))); // onView(allOf(withId(android.support.design.R.id.snackbar_text), withParent(withId(R.id.content)))).check(matches(isDisplayed())); onView(withText("bla")).check(matches(CustomMatchers.isVisibleToUser(true))); onView(withId(android.support.design.R.id.snackbar_action)).check(matches(isDisplayed())); onView(withId(android.support.design.R.id.snackbar_action)).check(matches(withText(R.string.game_search_error_retry_button))); onView(withId(android.support.design.R.id.snackbar_action)).check(matches(isDisplayed())); } //@Test public void Given_LoadingMoreErrorIsDisplayed_When_ClickOnRetry_Then_RetriesRequest() throws Throwable { // Arrange int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title")); } activityTestRule.runOnUiThread(() -> getFragment().setData(data)); onView(withId(R.id.searchlist)).perform(RecyclerViewActions.scrollToPosition(maxItems)); Throwable error = new Exception("bla"); activityTestRule.runOnUiThread(() -> getFragment().showError(error)); Thread.sleep(1000); // Act onView(withId(R.id.gamesearch_error)).check(matches(CustomMatchers.isVisibleToUser(false))); onView(withId(R.id.searchlist)).check(matches(isDisplayingAtLeast(100))); onView(withId(android.support.design.R.id.snackbar_action)).check(matches(isDisplayed())); onView(withId(android.support.design.R.id.snackbar_action)).perform(click()); // Assert verify(presenter).search("", maxItems + 1, maxItems); } //@Test public void Given_FilledList_When_ClickOnItem_Then_LaunchesDetailView() throws Throwable { // Arrange int maxItems = getFragment().loadLimit; Espresso.closeSoftKeyboard(); List<Game> data = new ArrayList<>(); for (int i = 0; i < maxItems; i++) { data.add(GameFactory.provide(10, "title_" + i)); } activityTestRule.runOnUiThread(() -> { getFragment().setData(data); getFragment().showContent(); }); // ACt onView(withId(R.id.searchlist)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click())); // Assert onView(withId(R.id.searchlist)).check(doesNotExist()); onView(withId(R.id.backdrop)).check(matches(CustomMatchers.isVisibleToUser(true))); } }
Enables two commented tests from GameSearchFragmentTest. Enables two previously commented out tests from GameSearchFragmentTest cases.
app/src/androidTest/java/com/piticlistudio/playednext/game/ui/search/view/GameSearchFragmentTest.java
Enables two commented tests from GameSearchFragmentTest.
<ide><path>pp/src/androidTest/java/com/piticlistudio/playednext/game/ui/search/view/GameSearchFragmentTest.java <ide> Thread.sleep(500); <ide> } <ide> <del> //@Test <add> @Test <ide> public void Given_Idle_When_ShowLoading_Then_ShowsLoading() throws Throwable { <ide> <ide> Espresso.closeSoftKeyboard(); <ide> onView(withId(R.id.progress)).check(matches(CustomMatchers.isVisibleToUser(true))); <ide> } <ide> <del> //@Test <add> @Test <ide> public void Given_InitialViewState_When_ShowContent_Then_HidesInitialView() throws Throwable { <ide> <ide> onView(withId(R.id.initialstateview)).check(matches(CustomMatchers.isVisibleToUser(true)));
Java
mit
5d0d5fdadb20e596ed706ff208e8b06a61b769e3
0
bedditor/ohtu-Alarmclock
package ohtu.beddit.alarm; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import ohtu.beddit.activity.AlarmActivity; import java.util.Calendar; public class AlarmReceiver extends BroadcastReceiver { private final String TAG = "Alarm Receiver"; private int wakeUpAttemptInterval; //how often (seconds) we try to wake up private int checkTime; //how long (seconds) it may take to do the checking private AlarmService alarmService; @Override public void onReceive(Context context, Intent intent) { alarmService = new AlarmServiceImpl(context); AlarmChecker alarmChecker = new AlarmCheckerRandomImpl(0); checkTime = alarmChecker.getCheckTime(); wakeUpAttemptInterval = alarmChecker.getWakeUpAttemptInterval(); Log.v(TAG, "Received alarm"); Log.v(TAG, "second until last wake up "+ getSecondsUntilLastWakeUpTime(context)); if(getSecondsUntilLastWakeUpTime(context) < 3){ //last time reached, wake up Log.v(TAG, "Wake up time reached, starting alarm"); startAlarm(context); } else if(getSecondsUntilLastWakeUpTime(context) <= checkTime){ //no time to do any more checking, schedule final wake up Log.v(TAG, "No time to check anymore, schedule wake up"); alarmService.addAlarmTry(context, getLastWakeUpTime(context)); } else if(alarmChecker.wakeUpNow()){ //check if we should wake up now Log.v(TAG, "Alarm checker gave permission to wake up, starting alarm"); startAlarm(context); } else{ // schedule next try Log.v(TAG, "Scheduling next try"); scheduleNextTry(context); } } private void startAlarm(Context context) { Intent newintent = new Intent(context, AlarmActivity.class); newintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); context.startActivity(newintent); } private int getSecondsUntilLastWakeUpTime(Context context){ Calendar currentTime = Calendar.getInstance(); Calendar wakeUpTime = getLastWakeUpTime(context); long timeDifference = wakeUpTime.getTimeInMillis() - currentTime.getTimeInMillis(); return (int)(timeDifference/1000); } private Calendar getLastWakeUpTime(Context context){ Calendar twoHoursBeforeCurrentTime = Calendar.getInstance(); twoHoursBeforeCurrentTime.add(Calendar.HOUR_OF_DAY, -2); Calendar wakeUpTime = Calendar.getInstance(); wakeUpTime.set(Calendar.HOUR_OF_DAY, alarmService.getAlarmHours(context)); wakeUpTime.set(Calendar.MINUTE, alarmService.getAlarmMinutes(context)); wakeUpTime.set(Calendar.SECOND, 0); wakeUpTime.set(Calendar.MILLISECOND, 0); /* If wake up time is a lot before current time, change day. The day will be not changed if its just before current time to avoid problems. 45 min max interval guarantees that the day will be set right. */ if(wakeUpTime.before(twoHoursBeforeCurrentTime)){ wakeUpTime.add(Calendar.DAY_OF_YEAR, 1); } return wakeUpTime; } private void scheduleNextTry(Context context){ Calendar timeForNextTry = Calendar.getInstance(); timeForNextTry.add(Calendar.SECOND, wakeUpAttemptInterval); Calendar lastWakeUpTime = getLastWakeUpTime(context); if(timeForNextTry.before(lastWakeUpTime)){ //still time for another interval Log.v(TAG, "next try scheduled to "+timeForNextTry.get(Calendar.HOUR_OF_DAY)+":"+timeForNextTry.get(Calendar.MINUTE)+":"+timeForNextTry.get(Calendar.SECOND)); alarmService.addAlarmTry(context, timeForNextTry); } else{ //no more time, schedule final wake up Log.v(TAG, "next try scheduled to last wake up time "+lastWakeUpTime.get(Calendar.HOUR_OF_DAY)+":"+lastWakeUpTime.get(Calendar.MINUTE)+":"+lastWakeUpTime.get(Calendar.SECOND)); alarmService.addAlarmTry(context, lastWakeUpTime); } } }
beddit_alarm/src/ohtu/beddit/alarm/AlarmReceiver.java
package ohtu.beddit.alarm; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import ohtu.beddit.activity.AlarmActivity; import java.util.Calendar; public class AlarmReceiver extends BroadcastReceiver { private final String TAG = "Alarm Receiver"; private int wakeUpAttemptInterval; //how often (seconds) we try to wake up private int checkTime; //how long (seconds) it may take to do the checking private AlarmService alarmService; @Override public void onReceive(Context context, Intent intent) { alarmService = new AlarmServiceImpl(context); AlarmChecker alarmChecker = new AlarmCheckerRandomImpl(0); checkTime = alarmChecker.getCheckTime(); wakeUpAttemptInterval = alarmChecker.getWakeUpAttemptInterval(); Log.v(TAG, "Received alarm"); Log.v(TAG, "second until last wake up "+ getSecondsUntilLastWakeUpTime(context)); if(getSecondsUntilLastWakeUpTime(context) < 5){ //last time reached, wake up Log.v(TAG, "Wake up time reached, starting alarm"); startAlarm(context); } else if(getSecondsUntilLastWakeUpTime(context) <= checkTime){ //no time to do any more checking, schedule final wake up Log.v(TAG, "No time to check anymore, schedule wake up"); alarmService.addAlarmTry(context, getLastWakeUpTime(context)); } else if(alarmChecker.wakeUpNow()){ //check if we should wake up now Log.v(TAG, "Alarm checker gave permission to wake up, starting alarm"); startAlarm(context); } else{ // schedule next try Log.v(TAG, "Scheduling next try"); scheduleNextTry(context); } } private void startAlarm(Context context) { Intent newintent = new Intent(context, AlarmActivity.class); newintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); context.startActivity(newintent); } private int getSecondsUntilLastWakeUpTime(Context context){ Calendar currentTime = Calendar.getInstance(); Calendar wakeUpTime = getLastWakeUpTime(context); long timeDifference = wakeUpTime.getTimeInMillis() - currentTime.getTimeInMillis(); return (int)(timeDifference/1000); } private Calendar getLastWakeUpTime(Context context){ Calendar twoHoursBeforeCurrentTime = Calendar.getInstance(); twoHoursBeforeCurrentTime.add(Calendar.HOUR_OF_DAY, -2); Calendar wakeUpTime = Calendar.getInstance(); wakeUpTime.set(Calendar.HOUR_OF_DAY, alarmService.getAlarmHours(context)); wakeUpTime.set(Calendar.MINUTE, alarmService.getAlarmMinutes(context)); wakeUpTime.set(Calendar.SECOND, 0); wakeUpTime.set(Calendar.MILLISECOND, 0); /* If wake up time is a lot before current time, change day. The day will be not changed if its just before current time to avoid problems. 45 min max interval guarantees that the day will be set right. */ if(wakeUpTime.before(twoHoursBeforeCurrentTime)){ wakeUpTime.add(Calendar.DAY_OF_YEAR, 1); } return wakeUpTime; } private void scheduleNextTry(Context context){ Calendar timeForNextTry = Calendar.getInstance(); timeForNextTry.add(Calendar.SECOND, wakeUpAttemptInterval); Calendar lastPossibleTry = getLastWakeUpTime(context); lastPossibleTry.add(Calendar.SECOND, -checkTime); if(timeForNextTry.before(lastPossibleTry)){ Log.v(TAG, "next try scheduled to "+timeForNextTry.get(Calendar.HOUR_OF_DAY)+":"+timeForNextTry.get(Calendar.MINUTE)+":"+timeForNextTry.get(Calendar.SECOND)); alarmService.addAlarmTry(context, timeForNextTry); } else{ Log.v(TAG, "next try scheduled to last possible try "+lastPossibleTry.get(Calendar.HOUR_OF_DAY)+":"+lastPossibleTry.get(Calendar.MINUTE)+":"+lastPossibleTry.get(Calendar.SECOND)); alarmService.addAlarmTry(context, lastPossibleTry); } } }
pieni yksinkertaistus alarmReceiveriin
beddit_alarm/src/ohtu/beddit/alarm/AlarmReceiver.java
pieni yksinkertaistus alarmReceiveriin
<ide><path>eddit_alarm/src/ohtu/beddit/alarm/AlarmReceiver.java <ide> <ide> Log.v(TAG, "Received alarm"); <ide> Log.v(TAG, "second until last wake up "+ getSecondsUntilLastWakeUpTime(context)); <del> if(getSecondsUntilLastWakeUpTime(context) < 5){ //last time reached, wake up <add> if(getSecondsUntilLastWakeUpTime(context) < 3){ //last time reached, wake up <ide> Log.v(TAG, "Wake up time reached, starting alarm"); <ide> startAlarm(context); <ide> } <ide> Log.v(TAG, "Scheduling next try"); <ide> scheduleNextTry(context); <ide> } <add> } <ide> <del> } <ide> <ide> private void startAlarm(Context context) { <ide> Intent newintent = new Intent(context, AlarmActivity.class); <ide> Calendar timeForNextTry = Calendar.getInstance(); <ide> timeForNextTry.add(Calendar.SECOND, wakeUpAttemptInterval); <ide> <del> Calendar lastPossibleTry = getLastWakeUpTime(context); <del> lastPossibleTry.add(Calendar.SECOND, -checkTime); <add> Calendar lastWakeUpTime = getLastWakeUpTime(context); <ide> <del> if(timeForNextTry.before(lastPossibleTry)){ <add> if(timeForNextTry.before(lastWakeUpTime)){ //still time for another interval <ide> Log.v(TAG, "next try scheduled to "+timeForNextTry.get(Calendar.HOUR_OF_DAY)+":"+timeForNextTry.get(Calendar.MINUTE)+":"+timeForNextTry.get(Calendar.SECOND)); <ide> alarmService.addAlarmTry(context, timeForNextTry); <ide> } <del> else{ <del> Log.v(TAG, "next try scheduled to last possible try "+lastPossibleTry.get(Calendar.HOUR_OF_DAY)+":"+lastPossibleTry.get(Calendar.MINUTE)+":"+lastPossibleTry.get(Calendar.SECOND)); <del> alarmService.addAlarmTry(context, lastPossibleTry); <add> else{ //no more time, schedule final wake up <add> Log.v(TAG, "next try scheduled to last wake up time "+lastWakeUpTime.get(Calendar.HOUR_OF_DAY)+":"+lastWakeUpTime.get(Calendar.MINUTE)+":"+lastWakeUpTime.get(Calendar.SECOND)); <add> alarmService.addAlarmTry(context, lastWakeUpTime); <ide> } <ide> } <ide>
Java
mpl-2.0
f7b22a6a955fb73ce8003ddc0dd350dce4f3ffbb
0
sainaen/rhino,tuchida/rhino,swannodette/rhino,rasmuserik/rhino,swannodette/rhino,tuchida/rhino,AlexTrotsenko/rhino,sainaen/rhino,tejassaoji/RhinoCoarseTainting,jsdoc3/rhino,tejassaoji/RhinoCoarseTainting,ashwinrayaprolu1984/rhino,lv7777/egit_test,qhanam/rhino,ashwinrayaprolu1984/rhino,sam/htmlunit-rhino-fork,tejassaoji/RhinoCoarseTainting,Distrotech/rhino,sam/htmlunit-rhino-fork,swannodette/rhino,tntim96/htmlunit-rhino-fork,Angelfirenze/rhino,AlexTrotsenko/rhino,tuchida/rhino,tntim96/rhino-apigee,ashwinrayaprolu1984/rhino,Pilarbrist/rhino,swannodette/rhino,ashwinrayaprolu1984/rhino,Angelfirenze/rhino,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,InstantWebP2P/rhino-android,jsdoc3/rhino,sainaen/rhino,lv7777/egit_test,tntim96/htmlunit-rhino-fork,ashwinrayaprolu1984/rhino,Pilarbrist/rhino,tejassaoji/RhinoCoarseTainting,ashwinrayaprolu1984/rhino,tejassaoji/RhinoCoarseTainting,tntim96/rhino-jscover,sam/htmlunit-rhino-fork,tntim96/rhino-jscover-repackaged,tejassaoji/RhinoCoarseTainting,tntim96/rhino-jscover-repackaged,swannodette/rhino,swannodette/rhino,lv7777/egit_test,tejassaoji/RhinoCoarseTainting,tuchida/rhino,qhanam/rhino,AlexTrotsenko/rhino,Angelfirenze/rhino,tuchida/rhino,swannodette/rhino,Angelfirenze/rhino,sainaen/rhino,lv7777/egit_test,sainaen/rhino,qhanam/rhino,ashwinrayaprolu1984/rhino,lv7777/egit_test,AlexTrotsenko/rhino,tntim96/rhino-apigee,qhanam/rhino,Angelfirenze/rhino,lv7777/egit_test,sam/htmlunit-rhino-fork,tntim96/rhino-jscover,jsdoc3/rhino,InstantWebP2P/rhino-android,Pilarbrist/rhino,Angelfirenze/rhino,Pilarbrist/rhino,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,Angelfirenze/rhino,Distrotech/rhino,rasmuserik/rhino,sainaen/rhino,tuchida/rhino,tuchida/rhino,Pilarbrist/rhino,tntim96/rhino-apigee,AlexTrotsenko/rhino,AlexTrotsenko/rhino,Pilarbrist/rhino,sainaen/rhino,lv7777/egit_test,Pilarbrist/rhino
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (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.mozilla.org/NPL/ * * 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. * * The Original Code is Rhino JavaScript Debugger code, released * November 21, 2000. * * The Initial Developer of the Original Code is SeeBeyond Corporation. * Portions created by SeeBeyond are * Copyright (C) 2000 SeeBeyond Technology Corporation. All * Rights Reserved. * * Contributor(s): * Igor Bukanov * Matt Gould * Christopher Oliver * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ package org.mozilla.javascript.tools.debugger; import javax.swing.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.*; import java.util.StringTokenizer; import java.util.*; import java.io.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import java.lang.reflect.Method; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Kit; import org.mozilla.javascript.tools.shell.ConsoleTextArea; import org.mozilla.javascript.tools.debugger.downloaded.JTreeTable; import org.mozilla.javascript.tools.debugger.downloaded.TreeTableModel; import org.mozilla.javascript.tools.debugger.downloaded.TreeTableModelAdapter; class MessageDialogWrapper { static void showMessageDialog(Component parent, String msg, String title, int flags) { if (msg.length() > 60) { StringBuffer buf = new StringBuffer(); int len = msg.length(); int j = 0; int i; for (i = 0; i < len; i++, j++) { char c = msg.charAt(i); buf.append(c); if (Character.isWhitespace(c)) { int remainder = len - i; int k; for (k = i + 1; k < len; k++) { if (Character.isWhitespace(msg.charAt(k))) { break; } } if (k < len) { int nextWordLen = k - i; if (j + nextWordLen > 60) { buf.append('\n'); j = 0; } } } } msg = buf.toString(); } JOptionPane.showMessageDialog(parent, msg, title, flags); } }; class EvalTextArea extends JTextArea implements KeyListener, DocumentListener { DebugGui debugGui; private java.util.Vector history; private int historyIndex = -1; private int outputMark = 0; public void select(int start, int end) { //requestFocus(); super.select(start, end); } public EvalTextArea(DebugGui debugGui) { super(); this.debugGui = debugGui; history = new java.util.Vector(); Document doc = getDocument(); doc.addDocumentListener(this); addKeyListener(this); setLineWrap(true); setFont(new Font("Monospaced", 0, 12)); append("% "); outputMark = doc.getLength(); } synchronized void returnPressed() { Document doc = getDocument(); int len = doc.getLength(); Segment segment = new Segment(); try { doc.getText(outputMark, len - outputMark, segment); } catch (javax.swing.text.BadLocationException ignored) { ignored.printStackTrace(); } String text = segment.toString(); if (debugGui.dim.stringIsCompilableUnit(text)) { if (text.trim().length() > 0) { history.addElement(text); historyIndex = history.size(); } append("\n"); String result = debugGui.dim.eval(text); if (result.length() > 0) { append(result); append("\n"); } append("% "); outputMark = doc.getLength(); } else { append("\n"); } } public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if (code == KeyEvent.VK_BACK_SPACE || code == KeyEvent.VK_LEFT) { if (outputMark == getCaretPosition()) { e.consume(); } } else if (code == KeyEvent.VK_HOME) { int caretPos = getCaretPosition(); if (caretPos == outputMark) { e.consume(); } else if (caretPos > outputMark) { if (!e.isControlDown()) { if (e.isShiftDown()) { moveCaretPosition(outputMark); } else { setCaretPosition(outputMark); } e.consume(); } } } else if (code == KeyEvent.VK_ENTER) { returnPressed(); e.consume(); } else if (code == KeyEvent.VK_UP) { historyIndex--; if (historyIndex >= 0) { if (historyIndex >= history.size()) { historyIndex = history.size() -1; } if (historyIndex >= 0) { String str = (String)history.elementAt(historyIndex); int len = getDocument().getLength(); replaceRange(str, outputMark, len); int caretPos = outputMark + str.length(); select(caretPos, caretPos); } else { historyIndex++; } } else { historyIndex++; } e.consume(); } else if (code == KeyEvent.VK_DOWN) { int caretPos = outputMark; if (history.size() > 0) { historyIndex++; if (historyIndex < 0) {historyIndex = 0;} int len = getDocument().getLength(); if (historyIndex < history.size()) { String str = (String)history.elementAt(historyIndex); replaceRange(str, outputMark, len); caretPos = outputMark + str.length(); } else { historyIndex = history.size(); replaceRange("", outputMark, len); } } select(caretPos, caretPos); e.consume(); } } public void keyTyped(KeyEvent e) { int keyChar = e.getKeyChar(); if (keyChar == 0x8 /* KeyEvent.VK_BACK_SPACE */) { if (outputMark == getCaretPosition()) { e.consume(); } } else if (getCaretPosition() < outputMark) { setCaretPosition(outputMark); } } public synchronized void keyReleased(KeyEvent e) { } public synchronized void write(String str) { insert(str, outputMark); int len = str.length(); outputMark += len; select(outputMark, outputMark); } public synchronized void insertUpdate(DocumentEvent e) { int len = e.getLength(); int off = e.getOffset(); if (outputMark > off) { outputMark += len; } } public synchronized void removeUpdate(DocumentEvent e) { int len = e.getLength(); int off = e.getOffset(); if (outputMark > off) { if (outputMark >= off + len) { outputMark -= len; } else { outputMark = off; } } } public synchronized void postUpdateUI() { // this attempts to cleanup the damage done by updateComponentTreeUI //requestFocus(); setCaret(getCaret()); select(outputMark, outputMark); } public synchronized void changedUpdate(DocumentEvent e) { } }; class EvalWindow extends JInternalFrame implements ActionListener { EvalTextArea evalTextArea; public void setEnabled(boolean b) { super.setEnabled(b); evalTextArea.setEnabled(b); } public EvalWindow(String name, DebugGui debugGui) { super(name, true, false, true, true); evalTextArea = new EvalTextArea(debugGui); evalTextArea.setRows(24); evalTextArea.setColumns(80); JScrollPane scroller = new JScrollPane(evalTextArea); setContentPane(scroller); //scroller.setPreferredSize(new Dimension(600, 400)); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cut")) { evalTextArea.cut(); } else if (cmd.equals("Copy")) { evalTextArea.copy(); } else if (cmd.equals("Paste")) { evalTextArea.paste(); } } }; class JSInternalConsole extends JInternalFrame implements ActionListener { ConsoleTextArea consoleTextArea; public InputStream getIn() { return consoleTextArea.getIn(); } public PrintStream getOut() { return consoleTextArea.getOut(); } public PrintStream getErr() { return consoleTextArea.getErr(); } public JSInternalConsole(String name) { super(name, true, false, true, true); consoleTextArea = new ConsoleTextArea(null); consoleTextArea.setRows(24); consoleTextArea.setColumns(80); JScrollPane scroller = new JScrollPane(consoleTextArea); setContentPane(scroller); pack(); addInternalFrameListener(new InternalFrameAdapter() { public void internalFrameActivated(InternalFrameEvent e) { // hack if (consoleTextArea.hasFocus()) { consoleTextArea.getCaret().setVisible(false); consoleTextArea.getCaret().setVisible(true); } } }); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cut")) { consoleTextArea.cut(); } else if (cmd.equals("Copy")) { consoleTextArea.copy(); } else if (cmd.equals("Paste")) { consoleTextArea.paste(); } } }; class FilePopupMenu extends JPopupMenu { FileTextArea w; int x, y; FilePopupMenu(FileTextArea w) { super(); this.w = w; JMenuItem item; add(item = new JMenuItem("Set Breakpoint")); item.addActionListener(w); add(item = new JMenuItem("Clear Breakpoint")); item.addActionListener(w); add(item = new JMenuItem("Run")); item.addActionListener(w); } void show(JComponent comp, int x, int y) { this.x = x; this.y = y; super.show(comp, x, y); } }; class FileTextArea extends JTextArea implements ActionListener, PopupMenuListener, KeyListener, MouseListener { FileWindow w; FilePopupMenu popup; FileTextArea(FileWindow w) { this.w = w; popup = new FilePopupMenu(this); popup.addPopupMenuListener(this); addMouseListener(this); addKeyListener(this); setFont(new Font("Monospaced", 0, 12)); } void select(int pos) { if (pos >= 0) { try { int line = getLineOfOffset(pos); Rectangle rect = modelToView(pos); if (rect == null) { select(pos, pos); } else { try { Rectangle nrect = modelToView(getLineStartOffset(line + 1)); if (nrect != null) { rect = nrect; } } catch (Exception exc) { } JViewport vp = (JViewport)getParent(); Rectangle viewRect = vp.getViewRect(); if (viewRect.y + viewRect.height > rect.y) { // need to scroll up select(pos, pos); } else { // need to scroll down rect.y += (viewRect.height - rect.height)/2; scrollRectToVisible(rect); select(pos, pos); } } } catch (BadLocationException exc) { select(pos, pos); //exc.printStackTrace(); } } } public void mousePressed(MouseEvent e) { checkPopup(e); } public void mouseClicked(MouseEvent e) { checkPopup(e); requestFocus(); getCaret().setVisible(true); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseReleased(MouseEvent e) { checkPopup(e); } private void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(this, e.getX(), e.getY()); } } public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } public void popupMenuCanceled(PopupMenuEvent e) { } public void actionPerformed(ActionEvent e) { int pos = viewToModel(new Point(popup.x, popup.y)); popup.setVisible(false); String cmd = e.getActionCommand(); int line = -1; try { line = getLineOfOffset(pos); } catch (Exception exc) { } if (cmd.equals("Set Breakpoint")) { w.setBreakPoint(line + 1); } else if (cmd.equals("Clear Breakpoint")) { w.clearBreakPoint(line + 1); } else if (cmd.equals("Run")) { w.load(); } } public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_ENTER: case KeyEvent.VK_DELETE: e.consume(); break; } } public void keyTyped(KeyEvent e) { e.consume(); } public void keyReleased(KeyEvent e) { e.consume(); } } class MoreWindows extends JDialog implements ActionListener { private String value = null; private JList list; Hashtable fileWindows; JButton setButton; JButton refreshButton; JButton cancelButton; public String showDialog(Component comp) { value = null; setLocationRelativeTo(comp); setVisible(true); return value; } private void setValue(String newValue) { value = newValue; list.setSelectedValue(value, true); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cancel")) { setVisible(false); value = null; } else if (cmd.equals("Select")) { value = (String)list.getSelectedValue(); setVisible(false); JInternalFrame w = (JInternalFrame)fileWindows.get(value); if (w != null) { try { w.show(); w.setSelected(true); } catch (Exception exc) { } } } } class MouseHandler extends MouseAdapter { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { setButton.doClick(); } } }; MoreWindows(JFrame frame, Hashtable fileWindows, String title, String labelText) { super(frame, title, true); this.fileWindows = fileWindows; //buttons cancelButton = new JButton("Cancel"); setButton = new JButton("Select"); cancelButton.addActionListener(this); setButton.addActionListener(this); getRootPane().setDefaultButton(setButton); //dim part of the dialog list = new JList(new DefaultListModel()); DefaultListModel model = (DefaultListModel)list.getModel(); model.clear(); //model.fireIntervalRemoved(model, 0, size); Enumeration e = fileWindows.keys(); while (e.hasMoreElements()) { String data = e.nextElement().toString(); model.addElement(data); } list.setSelectedIndex(0); //model.fireIntervalAdded(model, 0, data.length); setButton.setEnabled(true); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addMouseListener(new MouseHandler()); JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(320, 240)); //XXX: Must do the following, too, or else the scroller thinks //XXX: it's taller than it is: listScroller.setMinimumSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); //Create a container so that we can add a title around //the scroll pane. Can't add a title directly to the //scroll pane because its background would be white. //Lay out the label and scroll pane from top to button. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS)); JLabel label = new JLabel(labelText); label.setLabelFor (list); listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton); //Put everything together, using the content pane's BorderLayout. Container contentPane = getContentPane(); contentPane.add(listPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.SOUTH); pack(); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent ke) { int code = ke.getKeyCode(); if (code == KeyEvent.VK_ESCAPE) { ke.consume(); value = null; setVisible(false); } } }); } }; class FindFunction extends JDialog implements ActionListener { private String value = null; private JList list; DebugGui debugGui; JButton setButton; JButton refreshButton; JButton cancelButton; public String showDialog(Component comp) { value = null; setLocationRelativeTo(comp); setVisible(true); return value; } private void setValue(String newValue) { value = newValue; list.setSelectedValue(value, true); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cancel")) { setVisible(false); value = null; } else if (cmd.equals("Select")) { if (list.getSelectedIndex() < 0) { return; } try { value = (String)list.getSelectedValue(); } catch (ArrayIndexOutOfBoundsException exc) { return; } setVisible(false); Dim.FunctionSource item = debugGui.dim.functionSourceByName(value); if (item != null) { Dim.SourceInfo si = item.sourceInfo(); String url = si.url(); int lineNumber = item.firstLine(); FileWindow w = debugGui.getFileWindow(url); if (w == null) { debugGui.createFileWindow(si, lineNumber); w = debugGui.getFileWindow(url); w.setPosition(-1); } int start = w.getPosition(lineNumber-1); int end = w.getPosition(lineNumber)-1; w.textArea.select(start); w.textArea.setCaretPosition(start); w.textArea.moveCaretPosition(end); try { w.show(); debugGui.requestFocus(); w.requestFocus(); w.textArea.requestFocus(); } catch (Exception exc) { } } } } class MouseHandler extends MouseAdapter { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { setButton.doClick(); } } }; FindFunction(DebugGui debugGui, String title, String labelText) { super(debugGui, title, true); this.debugGui = debugGui; cancelButton = new JButton("Cancel"); setButton = new JButton("Select"); cancelButton.addActionListener(this); setButton.addActionListener(this); getRootPane().setDefaultButton(setButton); list = new JList(new DefaultListModel()); DefaultListModel model = (DefaultListModel)list.getModel(); model.clear(); String[] a = debugGui.dim.functionNames(); java.util.Arrays.sort(a); for (int i = 0; i < a.length; i++) { model.addElement(a[i]); } list.setSelectedIndex(0); setButton.setEnabled(a.length > 0); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addMouseListener(new MouseHandler()); JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(320, 240)); listScroller.setMinimumSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); //Create a container so that we can add a title around //the scroll pane. Can't add a title directly to the //scroll pane because its background would be white. //Lay out the label and scroll pane from top to button. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS)); JLabel label = new JLabel(labelText); label.setLabelFor (list); listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton); //Put everything together, using the content pane's BorderLayout. Container contentPane = getContentPane(); contentPane.add(listPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.SOUTH); pack(); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent ke) { int code = ke.getKeyCode(); if (code == KeyEvent.VK_ESCAPE) { ke.consume(); value = null; setVisible(false); } } }); } }; class FileHeader extends JPanel implements MouseListener { private int pressLine = -1; FileWindow fileWindow; public void mouseEntered(MouseEvent e) { } public void mousePressed(MouseEvent e) { Font font = fileWindow.textArea.getFont(); FontMetrics metrics = getFontMetrics(font); int h = metrics.getHeight(); pressLine = e.getY() / h; } public void mouseClicked(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseReleased(MouseEvent e) { if (e.getComponent() == this && (e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) { int x = e.getX(); int y = e.getY(); Font font = fileWindow.textArea.getFont(); FontMetrics metrics = getFontMetrics(font); int h = metrics.getHeight(); int line = y/h; if (line == pressLine) { fileWindow.toggleBreakPoint(line + 1); } else { pressLine = -1; } } } FileHeader(FileWindow fileWindow) { this.fileWindow = fileWindow; addMouseListener(this); update(); } void update() { FileTextArea textArea = fileWindow.textArea; Font font = textArea.getFont(); setFont(font); FontMetrics metrics = getFontMetrics(font); int h = metrics.getHeight(); int lineCount = textArea.getLineCount() + 1; String dummy = Integer.toString(lineCount); if (dummy.length() < 2) { dummy = "99"; } Dimension d = new Dimension(); d.width = metrics.stringWidth(dummy) + 16; d.height = lineCount * h + 100; setPreferredSize(d); setSize(d); } public void paint(Graphics g) { super.paint(g); FileTextArea textArea = fileWindow.textArea; Font font = textArea.getFont(); g.setFont(font); FontMetrics metrics = getFontMetrics(font); Rectangle clip = g.getClipBounds(); g.setColor(getBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); int left = getX(); int ascent = metrics.getMaxAscent(); int h = metrics.getHeight(); int lineCount = textArea.getLineCount() + 1; String dummy = Integer.toString(lineCount); if (dummy.length() < 2) { dummy = "99"; } int maxWidth = metrics.stringWidth(dummy); int startLine = clip.y / h; int endLine = (clip.y + clip.height) / h + 1; int width = getWidth(); if (endLine > lineCount) endLine = lineCount; for (int i = startLine; i < endLine; i++) { String text; int pos = -2; try { pos = textArea.getLineStartOffset(i); } catch (BadLocationException ignored) { } boolean isBreakPoint = fileWindow.isBreakPoint(i + 1); text = Integer.toString(i + 1) + " "; int w = metrics.stringWidth(text); int y = i * h; g.setColor(Color.blue); g.drawString(text, 0, y + ascent); int x = width - ascent; if (isBreakPoint) { g.setColor(new Color(0x80, 0x00, 0x00)); int dy = y + ascent - 9; g.fillOval(x, dy, 9, 9); g.drawOval(x, dy, 8, 8); g.drawOval(x, dy, 9, 9); } if (pos == fileWindow.currentPos) { Polygon arrow = new Polygon(); int dx = x; y += ascent - 10; int dy = y; arrow.addPoint(dx, dy + 3); arrow.addPoint(dx + 5, dy + 3); for (x = dx + 5; x <= dx + 10; x++, y++) { arrow.addPoint(x, y); } for (x = dx + 9; x >= dx + 5; x--, y++) { arrow.addPoint(x, y); } arrow.addPoint(dx + 5, dy + 7); arrow.addPoint(dx, dy + 7); g.setColor(Color.yellow); g.fillPolygon(arrow); g.setColor(Color.black); g.drawPolygon(arrow); } } } }; class FileWindow extends JInternalFrame implements ActionListener { DebugGui debugGui; Dim.SourceInfo sourceInfo; FileTextArea textArea; FileHeader fileHeader; JScrollPane p; int currentPos; JLabel statusBar; public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cut")) { // textArea.cut(); } else if (cmd.equals("Copy")) { textArea.copy(); } else if (cmd.equals("Paste")) { // textArea.paste(); } } void load() { String url = getUrl(); if (url != null) { new Thread(new LoadFile(debugGui,url,sourceInfo.source())).start(); } } public int getPosition(int line) { int result = -1; try { result = textArea.getLineStartOffset(line); } catch (javax.swing.text.BadLocationException exc) { } return result; } boolean isBreakPoint(int line) { return sourceInfo.breakableLine(line) && sourceInfo.breakpoint(line); } void toggleBreakPoint(int line) { if (!isBreakPoint(line)) { setBreakPoint(line); } else { clearBreakPoint(line); } } void setBreakPoint(int line) { if (sourceInfo.breakableLine(line)) { boolean changed = sourceInfo.breakpoint(line, true); if (changed) { fileHeader.repaint(); } } } void clearBreakPoint(int line) { if (sourceInfo.breakableLine(line)) { boolean changed = sourceInfo.breakpoint(line, false); if (changed) { fileHeader.repaint(); } } } FileWindow(DebugGui debugGui, Dim.SourceInfo sourceInfo) { super(DebugGui.getShortName(sourceInfo.url()), true, true, true, true); this.debugGui = debugGui; this.sourceInfo = sourceInfo; updateToolTip(); currentPos = -1; textArea = new FileTextArea(this); textArea.setRows(24); textArea.setColumns(80); p = new JScrollPane(); fileHeader = new FileHeader(this); p.setViewportView(textArea); p.setRowHeaderView(fileHeader); setContentPane(p); pack(); updateText(sourceInfo); textArea.select(0); } private void updateToolTip() { // in case fileName is very long, try to set tool tip on frame Component c = getComponent(1); // this will work at least for Metal L&F if (c != null && c instanceof JComponent) { ((JComponent)c).setToolTipText(getUrl()); } } public String getUrl() { return sourceInfo.url(); } void updateText(Dim.SourceInfo sourceInfo) { this.sourceInfo = sourceInfo; String newText = sourceInfo.source(); if (!textArea.getText().equals(newText)) { textArea.setText(newText); int pos = 0; if (currentPos != -1) { pos = currentPos; } textArea.select(pos); } fileHeader.update(); fileHeader.repaint(); } void setPosition(int pos) { textArea.select(pos); currentPos = pos; fileHeader.repaint(); } void select(int start, int end) { int docEnd = textArea.getDocument().getLength(); textArea.select(docEnd, docEnd); textArea.select(start, end); } public void dispose() { debugGui.removeWindow(this); super.dispose(); } }; class MyTableModel extends AbstractTableModel { DebugGui debugGui; Vector expressions; Vector values; MyTableModel(DebugGui debugGui) { this.debugGui = debugGui; expressions = new Vector(); values = new Vector(); expressions.addElement(""); values.addElement(""); } public int getColumnCount() { return 2; } public int getRowCount() { return expressions.size(); } public String getColumnName(int column) { switch (column) { case 0: return "Expression"; case 1: return "Value"; } return null; } public boolean isCellEditable(int row, int column) { return true; } public Object getValueAt(int row, int column) { switch (column) { case 0: return expressions.elementAt(row); case 1: return values.elementAt(row); } return ""; } public void setValueAt(Object value, int row, int column) { switch (column) { case 0: String expr = value.toString(); expressions.setElementAt(expr, row); String result = ""; if (expr.length() > 0) { result = debugGui.dim.eval(expr); if (result == null) result = ""; } values.setElementAt(result, row); updateModel(); if (row + 1 == expressions.size()) { expressions.addElement(""); values.addElement(""); fireTableRowsInserted(row + 1, row + 1); } break; case 1: // just reset column 2; ignore edits fireTableDataChanged(); } } void updateModel() { for (int i = 0; i < expressions.size(); ++i) { Object value = expressions.elementAt(i); String expr = value.toString(); String result = ""; if (expr.length() > 0) { result = debugGui.dim.eval(expr); if (result == null) result = ""; } else { result = ""; } result = result.replace('\n', ' '); values.setElementAt(result, i); } fireTableDataChanged(); } }; class Evaluator extends JTable { MyTableModel tableModel; Evaluator(DebugGui debugGui) { super(new MyTableModel(debugGui)); tableModel = (MyTableModel)getModel(); } } class VariableModel implements TreeTableModel { static class VariableNode { Object object; Object id; VariableNode[] children; VariableNode(Object object, Object id) { this.object = object; this.id = id; } public String toString() { return (id instanceof String) ? (String)id : "[" + ((Integer)id).intValue() + "]"; } } // Names of the columns. private static final String[] cNames = { " Name", " Value"}; // Types of the columns. private static final Class[] cTypes = {TreeTableModel.class, String.class}; private static final VariableNode[] CHILDLESS = new VariableNode[0]; private Dim debugger; private VariableNode root; VariableModel() { } VariableModel(Dim debugger, Object scope) { this.debugger = debugger; this.root = new VariableNode(scope, "this"); } // // The TreeModel interface // public Object getRoot() { if (debugger == null) { return ""; } return root; } public int getChildCount(Object nodeObj) { if (debugger == null) { return 0; } VariableNode node = (VariableNode)nodeObj; return children(node).length; } public Object getChild(Object nodeObj, int i) { if (debugger == null) { return null; } VariableNode node = (VariableNode)nodeObj; return children(node)[i]; } public boolean isLeaf(Object nodeObj) { if (debugger == null) { return true; } VariableNode node = (VariableNode)nodeObj; return children(node).length == 0; } public int getIndexOfChild(Object parentObj, Object childObj) { if (debugger == null) { return -1; } VariableNode parent = (VariableNode)parentObj; VariableNode child = (VariableNode)childObj; VariableNode[] children = children(parent); for (int i = 0; i != children.length; ++i) { if (children[i] == child) { return i; } } return -1; } public boolean isCellEditable(Object node, int column) { return column == 0; } public void setValueAt(Object value, Object node, int column) { } public void addTreeModelListener(TreeModelListener l) { } public void removeTreeModelListener(TreeModelListener l) { } public void valueForPathChanged(TreePath path, Object newValue) { } // // The TreeTableNode interface. // public int getColumnCount() { return cNames.length; } public String getColumnName(int column) { return cNames[column]; } public Class getColumnClass(int column) { return cTypes[column]; } public Object getValueAt(Object nodeObj, int column) { if (debugger == null) { return null; } VariableNode node = (VariableNode)nodeObj; switch (column) { case 0: // Name return node.toString(); case 1: // Value String result; try { result = debugger.objectToString(getValue(node)); } catch (RuntimeException exc) { result = exc.getMessage(); } StringBuffer buf = new StringBuffer(); int len = result.length(); for (int i = 0; i < len; i++) { char ch = result.charAt(i); if (Character.isISOControl(ch)) { ch = ' '; } buf.append(ch); } return buf.toString(); } return null; } private VariableNode[] children(VariableNode node) { if (node.children != null) { return node.children; } VariableNode[] children; Object value = getValue(node); Object[] ids = debugger.getObjectIds(value); if (ids.length == 0) { children = CHILDLESS; } else { java.util.Arrays.sort(ids, new java.util.Comparator() { public int compare(Object l, Object r) { if (l instanceof String) { if (r instanceof Integer) { return -1; } return ((String)l).compareToIgnoreCase((String)r); } else { if (r instanceof String) { return 1; } int lint = ((Integer)l).intValue(); int rint = ((Integer)r).intValue(); return lint - rint; } } }); children = new VariableNode[ids.length]; for (int i = 0; i != ids.length; ++i) { children[i] = new VariableNode(value, ids[i]); } } node.children = children; return children; } Object getValue(VariableNode node) { try { return debugger.getObjectProperty(node.object, node.id); } catch (Exception exc) { return "undefined"; } } } class MyTreeTable extends JTreeTable { public MyTreeTable(VariableModel model) { super(model); } public JTree resetTree(TreeTableModel treeTableModel) { tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); tree.setSelectionModel(selectionWrapper); setSelectionModel(selectionWrapper.getListSelectionModel()); // Make the tree and table row heights the same. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(18); } // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); setShowGrid(true); setIntercellSpacing(new Dimension(1,1)); tree.setRootVisible(false); tree.setShowsRootHandles(true); DefaultTreeCellRenderer r = (DefaultTreeCellRenderer)tree.getCellRenderer(); r.setOpenIcon(null); r.setClosedIcon(null); r.setLeafIcon(null); return tree; } public boolean isCellEditable(EventObject e) { if (e instanceof MouseEvent) { MouseEvent me = (MouseEvent)e; // If the modifiers are not 0 (or the left mouse button), // tree may try and toggle the selection, and table // will then try and toggle, resulting in the // selection remaining the same. To avoid this, we // only dispatch when the modifiers are 0 (or the left mouse // button). if (me.getModifiers() == 0 || ((me.getModifiers() & (InputEvent.BUTTON1_MASK|1024)) != 0 && (me.getModifiers() & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.ALT_MASK | InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK | 64 | //SHIFT_DOWN_MASK 128 | //CTRL_DOWN_MASK 512 | // ALT_DOWN_MASK 2048 | //BUTTON2_DOWN_MASK 4096 //BUTTON3_DOWN_MASK )) == 0)) { int row = rowAtPoint(me.getPoint()); for (int counter = getColumnCount() - 1; counter >= 0; counter--) { if (TreeTableModel.class == getColumnClass(counter)) { MouseEvent newME = new MouseEvent (MyTreeTable.this.tree, me.getID(), me.getWhen(), me.getModifiers(), me.getX() - getCellRect(row, counter, true).x, me.getY(), me.getClickCount(), me.isPopupTrigger()); MyTreeTable.this.tree.dispatchEvent(newME); break; } } } if (me.getClickCount() >= 3) { return true; } return false; } if (e == null) { return true; } return false; } }; class ContextWindow extends JPanel implements ActionListener { DebugGui debugGui; JComboBox context; Vector toolTips; JTabbedPane tabs; JTabbedPane tabs2; MyTreeTable thisTable; MyTreeTable localsTable; MyTableModel tableModel; Evaluator evaluator; EvalTextArea cmdLine; JSplitPane split; boolean enabled; ContextWindow(final DebugGui debugGui) { super(); this.debugGui = debugGui; enabled = false; JPanel left = new JPanel(); JToolBar t1 = new JToolBar(); t1.setName("Variables"); t1.setLayout(new GridLayout()); t1.add(left); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout()); JPanel p2 = new JPanel(); p2.setLayout(new GridLayout()); p1.add(t1); JLabel label = new JLabel("Context:"); context = new JComboBox(); context.setLightWeightPopupEnabled(false); toolTips = new java.util.Vector(); label.setBorder(context.getBorder()); context.addActionListener(this); context.setActionCommand("ContextSwitch"); GridBagLayout layout = new GridBagLayout(); left.setLayout(layout); GridBagConstraints lc = new GridBagConstraints(); lc.insets.left = 5; lc.anchor = GridBagConstraints.WEST; lc.ipadx = 5; layout.setConstraints(label, lc); left.add(label); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.WEST; layout.setConstraints(context, c); left.add(context); tabs = new JTabbedPane(SwingConstants.BOTTOM); tabs.setPreferredSize(new Dimension(500,300)); thisTable = new MyTreeTable(new VariableModel()); JScrollPane jsp = new JScrollPane(thisTable); jsp.getViewport().setViewSize(new Dimension(5,2)); tabs.add("this", jsp); localsTable = new MyTreeTable(new VariableModel()); localsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); localsTable.setPreferredSize(null); jsp = new JScrollPane(localsTable); tabs.add("Locals", jsp); c.weightx = c.weighty = 1; c.gridheight = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.WEST; layout.setConstraints(tabs, c); left.add(tabs); evaluator = new Evaluator(debugGui); cmdLine = new EvalTextArea(debugGui); //cmdLine.requestFocus(); tableModel = evaluator.tableModel; jsp = new JScrollPane(evaluator); JToolBar t2 = new JToolBar(); t2.setName("Evaluate"); tabs2 = new JTabbedPane(SwingConstants.BOTTOM); tabs2.add("Watch", jsp); tabs2.add("Evaluate", new JScrollPane(cmdLine)); tabs2.setPreferredSize(new Dimension(500,300)); t2.setLayout(new GridLayout()); t2.add(tabs2); p2.add(t2); evaluator.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p1, p2); split.setOneTouchExpandable(true); DebugGui.setResizeWeight(split, 0.5); setLayout(new BorderLayout()); add(split, BorderLayout.CENTER); final JToolBar finalT1 = t1; final JToolBar finalT2 = t2; final JPanel finalP1 = p1; final JPanel finalP2 = p2; final JSplitPane finalSplit = split; final JPanel finalThis = this; ComponentListener clistener = new ComponentListener() { boolean t1Docked = true; boolean t2Docked = true; void check(Component comp) { Component thisParent = finalThis.getParent(); if (thisParent == null) { return; } Component parent = finalT1.getParent(); boolean leftDocked = true; boolean rightDocked = true; boolean adjustVerticalSplit = false; if (parent != null) { if (parent != finalP1) { while (!(parent instanceof JFrame)) { parent = parent.getParent(); } JFrame frame = (JFrame)parent; debugGui.addTopLevel("Variables", frame); // We need the following hacks because: // - We want an undocked toolbar to be // resizable. // - We are using JToolbar as a container of a // JComboBox. Without this JComboBox's popup // can get left floating when the toolbar is // re-docked. // // We make the frame resizable and then // remove JToolbar's window listener // and insert one of our own that first ensures // the JComboBox's popup window is closed // and then calls JToolbar's window listener. if (!frame.isResizable()) { frame.setResizable(true); frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); final EventListener[] l = frame.getListeners(WindowListener.class); frame.removeWindowListener((WindowListener)l[0]); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { context.hidePopup(); ((WindowListener)l[0]).windowClosing(e); } }); //adjustVerticalSplit = true; } leftDocked = false; } else { leftDocked = true; } } parent = finalT2.getParent(); if (parent != null) { if (parent != finalP2) { while (!(parent instanceof JFrame)) { parent = parent.getParent(); } JFrame frame = (JFrame)parent; debugGui.addTopLevel("Evaluate", frame); frame.setResizable(true); rightDocked = false; } else { rightDocked = true; } } if (leftDocked && t2Docked && rightDocked && t2Docked) { // no change return; } t1Docked = leftDocked; t2Docked = rightDocked; JSplitPane split = (JSplitPane)thisParent; if (leftDocked) { if (rightDocked) { finalSplit.setDividerLocation(0.5); } else { finalSplit.setDividerLocation(1.0); } if (adjustVerticalSplit) { split.setDividerLocation(0.66); } } else if (rightDocked) { finalSplit.setDividerLocation(0.0); split.setDividerLocation(0.66); } else { // both undocked split.setDividerLocation(1.0); } } public void componentHidden(ComponentEvent e) { check(e.getComponent()); } public void componentMoved(ComponentEvent e) { check(e.getComponent()); } public void componentResized(ComponentEvent e) { check(e.getComponent()); } public void componentShown(ComponentEvent e) { check(e.getComponent()); } }; p1.addContainerListener(new ContainerListener() { public void componentAdded(ContainerEvent e) { Component thisParent = finalThis.getParent(); JSplitPane split = (JSplitPane)thisParent; if (e.getChild() == finalT1) { if (finalT2.getParent() == finalP2) { // both docked finalSplit.setDividerLocation(0.5); } else { // left docked only finalSplit.setDividerLocation(1.0); } split.setDividerLocation(0.66); } } public void componentRemoved(ContainerEvent e) { Component thisParent = finalThis.getParent(); JSplitPane split = (JSplitPane)thisParent; if (e.getChild() == finalT1) { if (finalT2.getParent() == finalP2) { // right docked only finalSplit.setDividerLocation(0.0); split.setDividerLocation(0.66); } else { // both undocked split.setDividerLocation(1.0); } } } }); t1.addComponentListener(clistener); t2.addComponentListener(clistener); disable(); } public void actionPerformed(ActionEvent e) { if (!enabled) return; if (e.getActionCommand().equals("ContextSwitch")) { Dim.ContextData contextData = debugGui.dim.currentContextData(); if (contextData == null) { return; } int frameIndex = context.getSelectedIndex(); context.setToolTipText(toolTips.elementAt(frameIndex).toString()); int frameCount = contextData.frameCount(); if (frameIndex >= frameCount) { return; } Dim.StackFrame frame = contextData.getFrame(frameIndex); Object scope = frame.scope(); Object thisObj = frame.thisObj(); thisTable.resetTree(new VariableModel(debugGui.dim, thisObj)); VariableModel scopeModel; if (scope != thisObj) { scopeModel = new VariableModel(debugGui.dim, scope); } else { scopeModel = new VariableModel(); } localsTable.resetTree(scopeModel); debugGui.dim.contextSwitch(frameIndex); debugGui.showStopLine(frame); tableModel.updateModel(); } } public void disable() { context.setEnabled(false); thisTable.setEnabled(false); localsTable.setEnabled(false); evaluator.setEnabled(false); cmdLine.setEnabled(false); } public void enable() { context.setEnabled(true); thisTable.setEnabled(true); localsTable.setEnabled(true); evaluator.setEnabled(true); cmdLine.setEnabled(true); } public void disableUpdate() { enabled = false; } public void enableUpdate() { enabled = true; } }; class Menubar extends JMenuBar implements ActionListener { private Vector interruptOnlyItems = new Vector(); private Vector runOnlyItems = new Vector(); DebugGui debugGui; JMenu windowMenu; JCheckBoxMenuItem breakOnExceptions; JCheckBoxMenuItem breakOnEnter; JCheckBoxMenuItem breakOnReturn; JMenu getDebugMenu() { return getMenu(2); } Menubar(DebugGui debugGui) { super(); this.debugGui = debugGui; String[] fileItems = {"Open...", "Run...", "", "Exit"}; String[] fileCmds = {"Open", "Load", "", "Exit"}; char[] fileShortCuts = {'0', 'N', '\0', 'X'}; int[] fileAccelerators = {KeyEvent.VK_O, KeyEvent.VK_N, 0, KeyEvent.VK_Q}; String[] editItems = {"Cut", "Copy", "Paste", "Go to function..."}; char[] editShortCuts = {'T', 'C', 'P', 'F'}; String[] debugItems = {"Break", "Go", "Step Into", "Step Over", "Step Out"}; char[] debugShortCuts = {'B', 'G', 'I', 'O', 'T'}; String[] plafItems = {"Metal", "Windows", "Motif"}; char [] plafShortCuts = {'M', 'W', 'F'}; int[] debugAccelerators = {KeyEvent.VK_PAUSE, KeyEvent.VK_F5, KeyEvent.VK_F11, KeyEvent.VK_F7, KeyEvent.VK_F8, 0, 0}; JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('E'); JMenu plafMenu = new JMenu("Platform"); plafMenu.setMnemonic('P'); JMenu debugMenu = new JMenu("Debug"); debugMenu.setMnemonic('D'); windowMenu = new JMenu("Window"); windowMenu.setMnemonic('W'); for (int i = 0; i < fileItems.length; ++i) { if (fileItems[i].length() == 0) { fileMenu.addSeparator(); } else { JMenuItem item = new JMenuItem(fileItems[i], fileShortCuts[i]); item.setActionCommand(fileCmds[i]); item.addActionListener(this); fileMenu.add(item); if (fileAccelerators[i] != 0) { KeyStroke k = KeyStroke.getKeyStroke(fileAccelerators[i], Event.CTRL_MASK); item.setAccelerator(k); } } } for (int i = 0; i < editItems.length; ++i) { JMenuItem item = new JMenuItem(editItems[i], editShortCuts[i]); item.addActionListener(this); editMenu.add(item); } for (int i = 0; i < plafItems.length; ++i) { JMenuItem item = new JMenuItem(plafItems[i], plafShortCuts[i]); item.addActionListener(this); plafMenu.add(item); } for (int i = 0; i < debugItems.length; ++i) { JMenuItem item = new JMenuItem(debugItems[i], debugShortCuts[i]); item.addActionListener(this); if (debugAccelerators[i] != 0) { KeyStroke k = KeyStroke.getKeyStroke(debugAccelerators[i], 0); item.setAccelerator(k); } if (i != 0) { interruptOnlyItems.add(item); } else { runOnlyItems.add(item); } debugMenu.add(item); } breakOnExceptions = new JCheckBoxMenuItem("Break on Exceptions"); breakOnExceptions.setMnemonic('X'); breakOnExceptions.addActionListener(this); breakOnExceptions.setSelected(false); debugMenu.add(breakOnExceptions); breakOnEnter = new JCheckBoxMenuItem("Break on Function Enter"); breakOnEnter.setMnemonic('E'); breakOnEnter.addActionListener(this); breakOnEnter.setSelected(false); debugMenu.add(breakOnEnter); breakOnReturn = new JCheckBoxMenuItem("Break on Function Return"); breakOnReturn.setMnemonic('R'); breakOnReturn.addActionListener(this); breakOnReturn.setSelected(false); debugMenu.add(breakOnReturn); add(fileMenu); add(editMenu); //add(plafMenu); add(debugMenu); JMenuItem item; windowMenu.add(item = new JMenuItem("Cascade", 'A')); item.addActionListener(this); windowMenu.add(item = new JMenuItem("Tile", 'T')); item.addActionListener(this); windowMenu.addSeparator(); windowMenu.add(item = new JMenuItem("Console", 'C')); item.addActionListener(this); add(windowMenu); updateEnabled(false); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); String plaf_name = null; if (cmd.equals("Metal")) { plaf_name = "javax.swing.plaf.metal.MetalLookAndFeel"; } else if (cmd.equals("Windows")) { plaf_name = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; } else if (cmd.equals("Motif")) { plaf_name = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; } else { Object source = e.getSource(); if (source == breakOnExceptions) { debugGui.dim.breakOnExceptions = breakOnExceptions.isSelected(); } else if (source == breakOnEnter) { debugGui.dim.breakOnEnter = breakOnEnter.isSelected(); } else if (source == breakOnReturn) { debugGui.dim.breakOnReturn = breakOnReturn.isSelected(); } else { debugGui.actionPerformed(e); } return; } try { UIManager.setLookAndFeel(plaf_name); SwingUtilities.updateComponentTreeUI(debugGui); SwingUtilities.updateComponentTreeUI(debugGui.dlg); } catch (Exception ignored) { //ignored.printStackTrace(); } } void addFile(String url) { int count = windowMenu.getItemCount(); JMenuItem item; if (count == 4) { windowMenu.addSeparator(); count++; } JMenuItem lastItem = windowMenu.getItem(count -1); boolean hasMoreWin = false; int maxWin = 5; if (lastItem != null && lastItem.getText().equals("More Windows...")) { hasMoreWin = true; maxWin++; } if (!hasMoreWin && count - 4 == 5) { windowMenu.add(item = new JMenuItem("More Windows...", 'M')); item.setActionCommand("More Windows..."); item.addActionListener(this); return; } else if (count - 4 <= maxWin) { if (hasMoreWin) { count--; windowMenu.remove(lastItem); } String shortName = DebugGui.getShortName(url); windowMenu.add(item = new JMenuItem((char)('0' + (count-4)) + " " + shortName, '0' + (count - 4))); if (hasMoreWin) { windowMenu.add(lastItem); } } else { return; } item.setActionCommand(url); item.addActionListener(this); } void updateEnabled(boolean interrupted) { for (int i = 0; i != interruptOnlyItems.size(); ++i) { JMenuItem item = (JMenuItem)interruptOnlyItems.elementAt(i); item.setEnabled(interrupted); } for (int i = 0; i != runOnlyItems.size(); ++i) { JMenuItem item = (JMenuItem)runOnlyItems.elementAt(i); item.setEnabled(!interrupted); } } } class OpenFile implements Runnable { DebugGui debugGui; String fileName; String text; OpenFile(DebugGui debugGui, String fileName, String text) { this.debugGui = debugGui; this.fileName = fileName; this.text = text; } public void run() { try { debugGui.dim.compileScript(fileName, text); } catch (RuntimeException ex) { MessageDialogWrapper.showMessageDialog(debugGui, ex.getMessage(), "Error Compiling "+fileName, JOptionPane.ERROR_MESSAGE); } } } class LoadFile implements Runnable { DebugGui debugGui; String fileName; String text; LoadFile(DebugGui debugGui, String fileName, String text) { this.debugGui = debugGui; this.fileName = fileName; this.text = text; } public void run() { try { debugGui.dim.evalScript(fileName, text); } catch (RuntimeException ex) { MessageDialogWrapper.showMessageDialog(debugGui, ex.getMessage(), "Run error for "+fileName, JOptionPane.ERROR_MESSAGE); } } } class DebugGui extends JFrame implements GuiCallback { Dim dim; Runnable exitAction; JDesktopPane desk; ContextWindow context; Menubar menubar; JToolBar toolBar; JSInternalConsole console; EvalWindow evalWindow; JSplitPane split1; JLabel statusBar; java.util.Hashtable toplevels = new java.util.Hashtable(); java.util.Hashtable fileWindows = new java.util.Hashtable(); FileWindow currentWindow; JFileChooser dlg; private static EventQueue awtEventQueue; DebugGui(Dim dim, String title) { super(title); this.dim = dim; init(); } public void setVisible(boolean b) { super.setVisible(b); if (b) { // this needs to be done after the window is visible console.consoleTextArea.requestFocus(); context.split.setDividerLocation(0.5); try { console.setMaximum(true); console.setSelected(true); console.show(); console.consoleTextArea.requestFocus(); } catch (Exception exc) { } } } void addTopLevel(String key, JFrame frame) { if (frame != this) { toplevels.put(key, frame); } } void init() { menubar = new Menubar(this); setJMenuBar(menubar); toolBar = new JToolBar(); JButton button; JButton breakButton, goButton, stepIntoButton, stepOverButton, stepOutButton; String [] toolTips = {"Break (Pause)", "Go (F5)", "Step Into (F11)", "Step Over (F7)", "Step Out (F8)"}; int count = 0; button = breakButton = new JButton("Break"); JButton focusButton = button; button.setToolTipText("Break"); button.setActionCommand("Break"); button.addActionListener(menubar); button.setEnabled(true); button.setToolTipText(toolTips[count++]); button = goButton = new JButton("Go"); button.setToolTipText("Go"); button.setActionCommand("Go"); button.addActionListener(menubar); button.setEnabled(false); button.setToolTipText(toolTips[count++]); button = stepIntoButton = new JButton("Step Into"); button.setToolTipText("Step Into"); button.setActionCommand("Step Into"); button.addActionListener(menubar); button.setEnabled(false); button.setToolTipText(toolTips[count++]); button = stepOverButton = new JButton("Step Over"); button.setToolTipText("Step Over"); button.setActionCommand("Step Over"); button.setEnabled(false); button.addActionListener(menubar); button.setToolTipText(toolTips[count++]); button = stepOutButton = new JButton("Step Out"); button.setToolTipText("Step Out"); button.setActionCommand("Step Out"); button.setEnabled(false); button.addActionListener(menubar); button.setToolTipText(toolTips[count++]); Dimension dim = stepOverButton.getPreferredSize(); breakButton.setPreferredSize(dim); breakButton.setMinimumSize(dim); breakButton.setMaximumSize(dim); breakButton.setSize(dim); goButton.setPreferredSize(dim); goButton.setMinimumSize(dim); goButton.setMaximumSize(dim); stepIntoButton.setPreferredSize(dim); stepIntoButton.setMinimumSize(dim); stepIntoButton.setMaximumSize(dim); stepOverButton.setPreferredSize(dim); stepOverButton.setMinimumSize(dim); stepOverButton.setMaximumSize(dim); stepOutButton.setPreferredSize(dim); stepOutButton.setMinimumSize(dim); stepOutButton.setMaximumSize(dim); toolBar.add(breakButton); toolBar.add(goButton); toolBar.add(stepIntoButton); toolBar.add(stepOverButton); toolBar.add(stepOutButton); JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); getContentPane().add(toolBar, BorderLayout.NORTH); getContentPane().add(contentPane, BorderLayout.CENTER); desk = new JDesktopPane(); desk.setPreferredSize(new Dimension(600, 300)); desk.setMinimumSize(new Dimension(150, 50)); desk.add(console = new JSInternalConsole("JavaScript Console")); context = new ContextWindow(this); context.setPreferredSize(new Dimension(600, 120)); context.setMinimumSize(new Dimension(50, 50)); split1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, desk, context); split1.setOneTouchExpandable(true); DebugGui.setResizeWeight(split1, 0.66); contentPane.add(split1, BorderLayout.CENTER); statusBar = new JLabel(); statusBar.setText("Thread: "); contentPane.add(statusBar, BorderLayout.SOUTH); dlg = new JFileChooser(); javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { if (f.isDirectory()) { return true; } String n = f.getName(); int i = n.lastIndexOf('.'); if (i > 0 && i < n.length() -1) { String ext = n.substring(i + 1).toLowerCase(); if (ext.equals("js")) { return true; } } return false; } public String getDescription() { return "JavaScript Files (*.js)"; } }; dlg.addChoosableFileFilter(filter); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exit(); } }); } void exit() { if (exitAction != null) { SwingUtilities.invokeLater(exitAction); } dim.setReturnValue(Dim.EXIT); } FileWindow getFileWindow(String url) { if (url == null || url.equals("<stdin>")) { return null; } return (FileWindow)fileWindows.get(url); } static String getShortName(String url) { int lastSlash = url.lastIndexOf('/'); if (lastSlash < 0) { lastSlash = url.lastIndexOf('\\'); } String shortName = url; if (lastSlash >= 0 && lastSlash + 1 < url.length()) { shortName = url.substring(lastSlash + 1); } return shortName; } void removeWindow(FileWindow w) { fileWindows.remove(w.getUrl()); JMenu windowMenu = getWindowMenu(); int count = windowMenu.getItemCount(); JMenuItem lastItem = windowMenu.getItem(count -1); String name = getShortName(w.getUrl()); for (int i = 5; i < count; i++) { JMenuItem item = windowMenu.getItem(i); if (item == null) continue; // separator String text = item.getText(); //1 D:\foo.js //2 D:\bar.js int pos = text.indexOf(' '); if (text.substring(pos + 1).equals(name)) { windowMenu.remove(item); // Cascade [0] // Tile [1] // ------- [2] // Console [3] // ------- [4] if (count == 6) { // remove the final separator windowMenu.remove(4); } else { int j = i - 4; for (;i < count -1; i++) { JMenuItem thisItem = windowMenu.getItem(i); if (thisItem != null) { //1 D:\foo.js //2 D:\bar.js text = thisItem.getText(); if (text.equals("More Windows...")) { break; } else { pos = text.indexOf(' '); thisItem.setText((char)('0' + j) + " " + text.substring(pos + 1)); thisItem.setMnemonic('0' + j); j++; } } } if (count - 6 == 0 && lastItem != item) { if (lastItem.getText().equals("More Windows...")) { windowMenu.remove(lastItem); } } } break; } } windowMenu.revalidate(); } void showStopLine(Dim.StackFrame frame) { String sourceName = frame.getUrl(); if (sourceName == null || sourceName.equals("<stdin>")) { if (console.isVisible()) { console.show(); } } else { int lineNumber = frame.getLineNumber(); FileWindow w = getFileWindow(sourceName); if (w != null) { setFilePosition(w, lineNumber); } else { Dim.SourceInfo si = frame.sourceInfo(); createFileWindow(si, lineNumber); } } } void createFileWindow(Dim.SourceInfo sourceInfo, int line) { boolean activate = true; String url = sourceInfo.url(); FileWindow w = new FileWindow(this, sourceInfo); fileWindows.put(url, w); if (line != -1) { if (currentWindow != null) { currentWindow.setPosition(-1); } try { w.setPosition(w.textArea.getLineStartOffset(line-1)); } catch (BadLocationException exc) { try { w.setPosition(w.textArea.getLineStartOffset(0)); } catch (BadLocationException ee) { w.setPosition(-1); } } } desk.add(w); if (line != -1) { currentWindow = w; } menubar.addFile(url); w.setVisible(true); if (activate) { try { w.setMaximum(true); w.setSelected(true); w.moveToFront(); } catch (Exception exc) { } } } void setFilePosition(FileWindow w, int line) { boolean activate = true; JTextArea ta = w.textArea; try { if (line == -1) { w.setPosition(-1); if (currentWindow == w) { currentWindow = null; } } else { int loc = ta.getLineStartOffset(line-1); if (currentWindow != null && currentWindow != w) { currentWindow.setPosition(-1); } w.setPosition(loc); currentWindow = w; } } catch (BadLocationException exc) { // fix me } if (activate) { if (w.isIcon()) { desk.getDesktopManager().deiconifyFrame(w); } desk.getDesktopManager().activateFrame(w); try { w.show(); w.toFront(); // required for correct frame layering (JDK 1.4.1) w.setSelected(true); } catch (Exception exc) { } } } // Implementing GuiCallback public void updateSourceText(final Dim.SourceInfo sourceInfo) { SwingUtilities.invokeLater(new Runnable() { public void run() { String fileName = sourceInfo.url(); FileWindow w = getFileWindow(fileName); if (w != null) { w.updateText(sourceInfo); w.show(); } else if (!fileName.equals("<stdin>")) { createFileWindow(sourceInfo, -1); } } }); } public void enterInterrupt(final Dim.StackFrame lastFrame, final String threadTitle, final String alertMessage) { if (SwingUtilities.isEventDispatchThread()) { enterInterruptImpl(lastFrame, threadTitle, alertMessage); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { enterInterruptImpl(lastFrame, threadTitle, alertMessage); } }); } } public boolean isGuiEventThread() { return SwingUtilities.isEventDispatchThread(); } public void dispatchNextGuiEvent() throws InterruptedException { EventQueue queue = awtEventQueue; if (queue == null) { queue = Toolkit.getDefaultToolkit().getSystemEventQueue(); awtEventQueue = queue; } AWTEvent event = queue.getNextEvent(); if (event instanceof ActiveEvent) { ((ActiveEvent)event).dispatch(); } else { Object source = event.getSource(); if (source instanceof Component) { Component comp = (Component)source; comp.dispatchEvent(event); } else if (source instanceof MenuComponent) { ((MenuComponent)source).dispatchEvent(event); } } } void enterInterruptImpl(Dim.StackFrame lastFrame, String threadTitle, String alertMessage) { statusBar.setText("Thread: " + threadTitle); showStopLine(lastFrame); if (alertMessage != null) { MessageDialogWrapper.showMessageDialog(this, alertMessage, "Exception in Script", JOptionPane.ERROR_MESSAGE); } ((Menubar)getJMenuBar()).updateEnabled(true); toolBar.setEnabled(true); // raise the debugger window toFront(); Dim.ContextData contextData = lastFrame.contextData(); context.enable(); JComboBox ctx = context.context; Vector toolTips = context.toolTips; context.disableUpdate(); int frameCount = contextData.frameCount(); ctx.removeAllItems(); // workaround for JDK 1.4 bug that caches selected value even after // removeAllItems() is called ctx.setSelectedItem(null); toolTips.removeAllElements(); for (int i = 0; i < frameCount; i++) { Dim.StackFrame frame = contextData.getFrame(i); String url = frame.getUrl(); int lineNumber = frame.getLineNumber(); String shortName = url; if (url.length() > 20) { shortName = "..." + url.substring(url.length() - 17); } String location = "\"" + shortName + "\", line " + lineNumber; ctx.insertItemAt(location, i); location = "\"" + url + "\", line " + lineNumber; toolTips.addElement(location); } context.enableUpdate(); ctx.setSelectedIndex(0); ctx.setMinimumSize(new Dimension(50, ctx.getMinimumSize().height)); } JMenu getWindowMenu() { return menubar.getMenu(3); } String chooseFile(String title) { dlg.setDialogTitle(title); File CWD = null; String dir = System.getProperty("user.dir"); if (dir != null) { CWD = new File(dir); } if (CWD != null) { dlg.setCurrentDirectory(CWD); } int returnVal = dlg.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { String result = dlg.getSelectedFile().getCanonicalPath(); CWD = dlg.getSelectedFile().getParentFile(); Properties props = System.getProperties(); props.put("user.dir", CWD.getPath()); System.setProperties(props); return result; }catch (IOException ignored) { }catch (SecurityException ignored) { } } return null; } JInternalFrame getSelectedFrame() { JInternalFrame[] frames = desk.getAllFrames(); for (int i = 0; i < frames.length; i++) { if (frames[i].isShowing()) { return frames[i]; } } return frames[frames.length - 1]; } void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); int returnValue = -1; if (cmd.equals("Cut") || cmd.equals("Copy") || cmd.equals("Paste")) { JInternalFrame f = getSelectedFrame(); if (f != null && f instanceof ActionListener) { ((ActionListener)f).actionPerformed(e); } } else if (cmd.equals("Step Over")) { returnValue = Dim.STEP_OVER; } else if (cmd.equals("Step Into")) { returnValue = Dim.STEP_INTO; } else if (cmd.equals("Step Out")) { returnValue = Dim.STEP_OUT; } else if (cmd.equals("Go")) { returnValue = Dim.GO; } else if (cmd.equals("Break")) { dim.breakFlag = true; } else if (cmd.equals("Exit")) { exit(); } else if (cmd.equals("Open")) { String fileName = chooseFile("Select a file to compile"); if (fileName != null) { String text = readFile(fileName); if (text != null) { new Thread(new OpenFile(this, fileName, text)).start(); } } } else if (cmd.equals("Load")) { String fileName = chooseFile("Select a file to execute"); if (fileName != null) { String text = readFile(fileName); if (text != null) { new Thread(new LoadFile(this, fileName, text)).start(); } } } else if (cmd.equals("More Windows...")) { MoreWindows dlg = new MoreWindows(this, fileWindows, "Window", "Files"); dlg.showDialog(this); } else if (cmd.equals("Console")) { if (console.isIcon()) { desk.getDesktopManager().deiconifyFrame(console); } console.show(); desk.getDesktopManager().activateFrame(console); console.consoleTextArea.requestFocus(); } else if (cmd.equals("Cut")) { } else if (cmd.equals("Copy")) { } else if (cmd.equals("Paste")) { } else if (cmd.equals("Go to function...")) { FindFunction dlg = new FindFunction(this, "Go to function", "Function"); dlg.showDialog(this); } else if (cmd.equals("Tile")) { JInternalFrame[] frames = desk.getAllFrames(); int count = frames.length; int rows, cols; rows = cols = (int)Math.sqrt(count); if (rows*cols < count) { cols++; if (rows * cols < count) { rows++; } } Dimension size = desk.getSize(); int w = size.width/cols; int h = size.height/rows; int x = 0; int y = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int index = (i*cols) + j; if (index >= frames.length) { break; } JInternalFrame f = frames[index]; try { f.setIcon(false); f.setMaximum(false); } catch (Exception exc) { } desk.getDesktopManager().setBoundsForFrame(f, x, y, w, h); x += w; } y += h; x = 0; } } else if (cmd.equals("Cascade")) { JInternalFrame[] frames = desk.getAllFrames(); int count = frames.length; int x, y, w, h; x = y = 0; h = desk.getHeight(); int d = h / count; if (d > 30) d = 30; for (int i = count -1; i >= 0; i--, x += d, y += d) { JInternalFrame f = frames[i]; try { f.setIcon(false); f.setMaximum(false); } catch (Exception exc) { } Dimension dimen = f.getPreferredSize(); w = dimen.width; h = dimen.height; desk.getDesktopManager().setBoundsForFrame(f, x, y, w, h); } } else { Object obj = getFileWindow(cmd); if (obj != null) { FileWindow w = (FileWindow)obj; try { if (w.isIcon()) { w.setIcon(false); } w.setVisible(true); w.moveToFront(); w.setSelected(true); } catch (Exception exc) { } } } if (returnValue != -1) { disableInterruptOnlyGui(); dim.setReturnValue(returnValue); } } private void disableInterruptOnlyGui() { if (currentWindow != null) currentWindow.setPosition(-1); ((Menubar)getJMenuBar()).updateEnabled(false); context.disable(); boolean b = true; for (int ci = 0, cc = toolBar.getComponentCount(); ci < cc; ci++) { toolBar.getComponent(ci).setEnabled(b); b = false; } } static void setResizeWeight(JSplitPane pane, double weight) { // call through reflection for portability // pre-1.3 JDK JSplitPane doesn't have this method try { Method m = JSplitPane.class.getMethod("setResizeWeight", new Class[]{double.class}); m.invoke(pane, new Object[]{new Double(weight)}); } catch (NoSuchMethodException exc) { } catch (IllegalAccessException exc) { } catch (java.lang.reflect.InvocationTargetException exc) { } } String readFile(String fileName) { String text; try { Reader r = new FileReader(fileName); try { text = Kit.readReader(r); } finally { r.close(); } } catch (IOException ex) { MessageDialogWrapper.showMessageDialog(this, ex.getMessage(), "Error reading "+fileName, JOptionPane.ERROR_MESSAGE); text = null; } return text; } }
toolsrc/org/mozilla/javascript/tools/debugger/DebugGui.java
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (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.mozilla.org/NPL/ * * 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. * * The Original Code is Rhino JavaScript Debugger code, released * November 21, 2000. * * The Initial Developer of the Original Code is SeeBeyond Corporation. * Portions created by SeeBeyond are * Copyright (C) 2000 SeeBeyond Technology Corporation. All * Rights Reserved. * * Contributor(s): * Igor Bukanov * Matt Gould * Christopher Oliver * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ package org.mozilla.javascript.tools.debugger; import javax.swing.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.*; import java.util.StringTokenizer; import java.util.*; import java.io.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import java.lang.reflect.Method; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.Kit; import org.mozilla.javascript.tools.shell.ConsoleTextArea; import org.mozilla.javascript.tools.debugger.downloaded.JTreeTable; import org.mozilla.javascript.tools.debugger.downloaded.TreeTableModel; import org.mozilla.javascript.tools.debugger.downloaded.TreeTableModelAdapter; class MessageDialogWrapper { static void showMessageDialog(Component parent, String msg, String title, int flags) { if (msg.length() > 60) { StringBuffer buf = new StringBuffer(); int len = msg.length(); int j = 0; int i; for (i = 0; i < len; i++, j++) { char c = msg.charAt(i); buf.append(c); if (Character.isWhitespace(c)) { int remainder = len - i; int k; for (k = i + 1; k < len; k++) { if (Character.isWhitespace(msg.charAt(k))) { break; } } if (k < len) { int nextWordLen = k - i; if (j + nextWordLen > 60) { buf.append('\n'); j = 0; } } } } msg = buf.toString(); } JOptionPane.showMessageDialog(parent, msg, title, flags); } }; class EvalTextArea extends JTextArea implements KeyListener, DocumentListener { DebugGui debugGui; private java.util.Vector history; private int historyIndex = -1; private int outputMark = 0; public void select(int start, int end) { //requestFocus(); super.select(start, end); } public EvalTextArea(DebugGui debugGui) { super(); this.debugGui = debugGui; history = new java.util.Vector(); Document doc = getDocument(); doc.addDocumentListener(this); addKeyListener(this); setLineWrap(true); setFont(new Font("Monospaced", 0, 12)); append("% "); outputMark = doc.getLength(); } synchronized void returnPressed() { Document doc = getDocument(); int len = doc.getLength(); Segment segment = new Segment(); try { doc.getText(outputMark, len - outputMark, segment); } catch (javax.swing.text.BadLocationException ignored) { ignored.printStackTrace(); } String text = segment.toString(); if (debugGui.dim.stringIsCompilableUnit(text)) { if (text.trim().length() > 0) { history.addElement(text); historyIndex = history.size(); } append("\n"); String result = debugGui.dim.eval(text); if (result.length() > 0) { append(result); append("\n"); } append("% "); outputMark = doc.getLength(); } else { append("\n"); } } public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); if (code == KeyEvent.VK_BACK_SPACE || code == KeyEvent.VK_LEFT) { if (outputMark == getCaretPosition()) { e.consume(); } } else if (code == KeyEvent.VK_HOME) { int caretPos = getCaretPosition(); if (caretPos == outputMark) { e.consume(); } else if (caretPos > outputMark) { if (!e.isControlDown()) { if (e.isShiftDown()) { moveCaretPosition(outputMark); } else { setCaretPosition(outputMark); } e.consume(); } } } else if (code == KeyEvent.VK_ENTER) { returnPressed(); e.consume(); } else if (code == KeyEvent.VK_UP) { historyIndex--; if (historyIndex >= 0) { if (historyIndex >= history.size()) { historyIndex = history.size() -1; } if (historyIndex >= 0) { String str = (String)history.elementAt(historyIndex); int len = getDocument().getLength(); replaceRange(str, outputMark, len); int caretPos = outputMark + str.length(); select(caretPos, caretPos); } else { historyIndex++; } } else { historyIndex++; } e.consume(); } else if (code == KeyEvent.VK_DOWN) { int caretPos = outputMark; if (history.size() > 0) { historyIndex++; if (historyIndex < 0) {historyIndex = 0;} int len = getDocument().getLength(); if (historyIndex < history.size()) { String str = (String)history.elementAt(historyIndex); replaceRange(str, outputMark, len); caretPos = outputMark + str.length(); } else { historyIndex = history.size(); replaceRange("", outputMark, len); } } select(caretPos, caretPos); e.consume(); } } public void keyTyped(KeyEvent e) { int keyChar = e.getKeyChar(); if (keyChar == 0x8 /* KeyEvent.VK_BACK_SPACE */) { if (outputMark == getCaretPosition()) { e.consume(); } } else if (getCaretPosition() < outputMark) { setCaretPosition(outputMark); } } public synchronized void keyReleased(KeyEvent e) { } public synchronized void write(String str) { insert(str, outputMark); int len = str.length(); outputMark += len; select(outputMark, outputMark); } public synchronized void insertUpdate(DocumentEvent e) { int len = e.getLength(); int off = e.getOffset(); if (outputMark > off) { outputMark += len; } } public synchronized void removeUpdate(DocumentEvent e) { int len = e.getLength(); int off = e.getOffset(); if (outputMark > off) { if (outputMark >= off + len) { outputMark -= len; } else { outputMark = off; } } } public synchronized void postUpdateUI() { // this attempts to cleanup the damage done by updateComponentTreeUI //requestFocus(); setCaret(getCaret()); select(outputMark, outputMark); } public synchronized void changedUpdate(DocumentEvent e) { } }; class EvalWindow extends JInternalFrame implements ActionListener { EvalTextArea evalTextArea; public void setEnabled(boolean b) { super.setEnabled(b); evalTextArea.setEnabled(b); } public EvalWindow(String name, DebugGui debugGui) { super(name, true, false, true, true); evalTextArea = new EvalTextArea(debugGui); evalTextArea.setRows(24); evalTextArea.setColumns(80); JScrollPane scroller = new JScrollPane(evalTextArea); setContentPane(scroller); //scroller.setPreferredSize(new Dimension(600, 400)); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cut")) { evalTextArea.cut(); } else if (cmd.equals("Copy")) { evalTextArea.copy(); } else if (cmd.equals("Paste")) { evalTextArea.paste(); } } }; class JSInternalConsole extends JInternalFrame implements ActionListener { ConsoleTextArea consoleTextArea; public InputStream getIn() { return consoleTextArea.getIn(); } public PrintStream getOut() { return consoleTextArea.getOut(); } public PrintStream getErr() { return consoleTextArea.getErr(); } public JSInternalConsole(String name) { super(name, true, false, true, true); consoleTextArea = new ConsoleTextArea(null); consoleTextArea.setRows(24); consoleTextArea.setColumns(80); JScrollPane scroller = new JScrollPane(consoleTextArea); setContentPane(scroller); pack(); addInternalFrameListener(new InternalFrameAdapter() { public void internalFrameActivated(InternalFrameEvent e) { // hack if (consoleTextArea.hasFocus()) { consoleTextArea.getCaret().setVisible(false); consoleTextArea.getCaret().setVisible(true); } } }); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cut")) { consoleTextArea.cut(); } else if (cmd.equals("Copy")) { consoleTextArea.copy(); } else if (cmd.equals("Paste")) { consoleTextArea.paste(); } } }; class FilePopupMenu extends JPopupMenu { FileTextArea w; int x, y; FilePopupMenu(FileTextArea w) { super(); this.w = w; JMenuItem item; add(item = new JMenuItem("Set Breakpoint")); item.addActionListener(w); add(item = new JMenuItem("Clear Breakpoint")); item.addActionListener(w); add(item = new JMenuItem("Run")); item.addActionListener(w); } void show(JComponent comp, int x, int y) { this.x = x; this.y = y; super.show(comp, x, y); } }; class FileTextArea extends JTextArea implements ActionListener, PopupMenuListener, KeyListener, MouseListener { FileWindow w; FilePopupMenu popup; FileTextArea(FileWindow w) { this.w = w; popup = new FilePopupMenu(this); popup.addPopupMenuListener(this); addMouseListener(this); addKeyListener(this); setFont(new Font("Monospaced", 0, 12)); } void select(int pos) { if (pos >= 0) { try { int line = getLineOfOffset(pos); Rectangle rect = modelToView(pos); if (rect == null) { select(pos, pos); } else { try { Rectangle nrect = modelToView(getLineStartOffset(line + 1)); if (nrect != null) { rect = nrect; } } catch (Exception exc) { } JViewport vp = (JViewport)getParent(); Rectangle viewRect = vp.getViewRect(); if (viewRect.y + viewRect.height > rect.y) { // need to scroll up select(pos, pos); } else { // need to scroll down rect.y += (viewRect.height - rect.height)/2; scrollRectToVisible(rect); select(pos, pos); } } } catch (BadLocationException exc) { select(pos, pos); //exc.printStackTrace(); } } } public void mousePressed(MouseEvent e) { checkPopup(e); } public void mouseClicked(MouseEvent e) { checkPopup(e); requestFocus(); getCaret().setVisible(true); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseReleased(MouseEvent e) { checkPopup(e); } private void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(this, e.getX(), e.getY()); } } public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } public void popupMenuCanceled(PopupMenuEvent e) { } public void actionPerformed(ActionEvent e) { int pos = viewToModel(new Point(popup.x, popup.y)); popup.setVisible(false); String cmd = e.getActionCommand(); int line = -1; try { line = getLineOfOffset(pos); } catch (Exception exc) { } if (cmd.equals("Set Breakpoint")) { w.setBreakPoint(line + 1); } else if (cmd.equals("Clear Breakpoint")) { w.clearBreakPoint(line + 1); } else if (cmd.equals("Run")) { w.load(); } } public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_ENTER: case KeyEvent.VK_DELETE: e.consume(); break; } } public void keyTyped(KeyEvent e) { e.consume(); } public void keyReleased(KeyEvent e) { e.consume(); } } class MoreWindows extends JDialog implements ActionListener { private String value = null; private JList list; Hashtable fileWindows; JButton setButton; JButton refreshButton; JButton cancelButton; public String showDialog(Component comp) { value = null; setLocationRelativeTo(comp); setVisible(true); return value; } private void setValue(String newValue) { value = newValue; list.setSelectedValue(value, true); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cancel")) { setVisible(false); value = null; } else if (cmd.equals("Select")) { value = (String)list.getSelectedValue(); setVisible(false); JInternalFrame w = (JInternalFrame)fileWindows.get(value); if (w != null) { try { w.show(); w.setSelected(true); } catch (Exception exc) { } } } } class MouseHandler extends MouseAdapter { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { setButton.doClick(); } } }; MoreWindows(JFrame frame, Hashtable fileWindows, String title, String labelText) { super(frame, title, true); this.fileWindows = fileWindows; //buttons cancelButton = new JButton("Cancel"); setButton = new JButton("Select"); cancelButton.addActionListener(this); setButton.addActionListener(this); getRootPane().setDefaultButton(setButton); //dim part of the dialog list = new JList(new DefaultListModel()); DefaultListModel model = (DefaultListModel)list.getModel(); model.clear(); //model.fireIntervalRemoved(model, 0, size); Enumeration e = fileWindows.keys(); while (e.hasMoreElements()) { String data = e.nextElement().toString(); model.addElement(data); } list.setSelectedIndex(0); //model.fireIntervalAdded(model, 0, data.length); setButton.setEnabled(true); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addMouseListener(new MouseHandler()); JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(320, 240)); //XXX: Must do the following, too, or else the scroller thinks //XXX: it's taller than it is: listScroller.setMinimumSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); //Create a container so that we can add a title around //the scroll pane. Can't add a title directly to the //scroll pane because its background would be white. //Lay out the label and scroll pane from top to button. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS)); JLabel label = new JLabel(labelText); label.setLabelFor (list); listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton); //Put everything together, using the content pane's BorderLayout. Container contentPane = getContentPane(); contentPane.add(listPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.SOUTH); pack(); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent ke) { int code = ke.getKeyCode(); if (code == KeyEvent.VK_ESCAPE) { ke.consume(); value = null; setVisible(false); } } }); } }; class FindFunction extends JDialog implements ActionListener { private String value = null; private JList list; DebugGui debugGui; JButton setButton; JButton refreshButton; JButton cancelButton; public String showDialog(Component comp) { value = null; setLocationRelativeTo(comp); setVisible(true); return value; } private void setValue(String newValue) { value = newValue; list.setSelectedValue(value, true); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cancel")) { setVisible(false); value = null; } else if (cmd.equals("Select")) { if (list.getSelectedIndex() < 0) { return; } try { value = (String)list.getSelectedValue(); } catch (ArrayIndexOutOfBoundsException exc) { return; } setVisible(false); Dim.FunctionSource item = debugGui.dim.functionSourceByName(value); if (item != null) { Dim.SourceInfo si = item.sourceInfo(); String url = si.url(); int lineNumber = item.firstLine(); FileWindow w = debugGui.getFileWindow(url); if (w == null) { debugGui.createFileWindow(si, lineNumber); w = debugGui.getFileWindow(url); w.setPosition(-1); } int start = w.getPosition(lineNumber-1); int end = w.getPosition(lineNumber)-1; w.textArea.select(start); w.textArea.setCaretPosition(start); w.textArea.moveCaretPosition(end); try { w.show(); debugGui.requestFocus(); w.requestFocus(); w.textArea.requestFocus(); } catch (Exception exc) { } } } } class MouseHandler extends MouseAdapter { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { setButton.doClick(); } } }; FindFunction(DebugGui debugGui, String title, String labelText) { super(debugGui, title, true); this.debugGui = debugGui; cancelButton = new JButton("Cancel"); setButton = new JButton("Select"); cancelButton.addActionListener(this); setButton.addActionListener(this); getRootPane().setDefaultButton(setButton); list = new JList(new DefaultListModel()); DefaultListModel model = (DefaultListModel)list.getModel(); model.clear(); String[] a = debugGui.dim.functionNames(); java.util.Arrays.sort(a); for (int i = 0; i < a.length; i++) { model.addElement(a[i]); } list.setSelectedIndex(0); setButton.setEnabled(a.length > 0); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addMouseListener(new MouseHandler()); JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(320, 240)); listScroller.setMinimumSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); //Create a container so that we can add a title around //the scroll pane. Can't add a title directly to the //scroll pane because its background would be white. //Lay out the label and scroll pane from top to button. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS)); JLabel label = new JLabel(labelText); label.setLabelFor (list); listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton); //Put everything together, using the content pane's BorderLayout. Container contentPane = getContentPane(); contentPane.add(listPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.SOUTH); pack(); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent ke) { int code = ke.getKeyCode(); if (code == KeyEvent.VK_ESCAPE) { ke.consume(); value = null; setVisible(false); } } }); } }; class FileHeader extends JPanel implements MouseListener { private int pressLine = -1; FileWindow fileWindow; public void mouseEntered(MouseEvent e) { } public void mousePressed(MouseEvent e) { Font font = fileWindow.textArea.getFont(); FontMetrics metrics = getFontMetrics(font); int h = metrics.getHeight(); pressLine = e.getY() / h; } public void mouseClicked(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseReleased(MouseEvent e) { if (e.getComponent() == this && (e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0) { int x = e.getX(); int y = e.getY(); Font font = fileWindow.textArea.getFont(); FontMetrics metrics = getFontMetrics(font); int h = metrics.getHeight(); int line = y/h; if (line == pressLine) { fileWindow.toggleBreakPoint(line + 1); } else { pressLine = -1; } } } FileHeader(FileWindow fileWindow) { this.fileWindow = fileWindow; addMouseListener(this); update(); } void update() { FileTextArea textArea = fileWindow.textArea; Font font = textArea.getFont(); setFont(font); FontMetrics metrics = getFontMetrics(font); int h = metrics.getHeight(); int lineCount = textArea.getLineCount() + 1; String dummy = Integer.toString(lineCount); if (dummy.length() < 2) { dummy = "99"; } Dimension d = new Dimension(); d.width = metrics.stringWidth(dummy) + 16; d.height = lineCount * h + 100; setPreferredSize(d); setSize(d); } public void paint(Graphics g) { super.paint(g); FileTextArea textArea = fileWindow.textArea; Font font = textArea.getFont(); g.setFont(font); FontMetrics metrics = getFontMetrics(font); Rectangle clip = g.getClipBounds(); g.setColor(getBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); int left = getX(); int ascent = metrics.getMaxAscent(); int h = metrics.getHeight(); int lineCount = textArea.getLineCount() + 1; String dummy = Integer.toString(lineCount); if (dummy.length() < 2) { dummy = "99"; } int maxWidth = metrics.stringWidth(dummy); int startLine = clip.y / h; int endLine = (clip.y + clip.height) / h + 1; int width = getWidth(); if (endLine > lineCount) endLine = lineCount; for (int i = startLine; i < endLine; i++) { String text; int pos = -2; try { pos = textArea.getLineStartOffset(i); } catch (BadLocationException ignored) { } boolean isBreakPoint = fileWindow.isBreakPoint(i + 1); text = Integer.toString(i + 1) + " "; int w = metrics.stringWidth(text); int y = i * h; g.setColor(Color.blue); g.drawString(text, 0, y + ascent); int x = width - ascent; if (isBreakPoint) { g.setColor(new Color(0x80, 0x00, 0x00)); int dy = y + ascent - 9; g.fillOval(x, dy, 9, 9); g.drawOval(x, dy, 8, 8); g.drawOval(x, dy, 9, 9); } if (pos == fileWindow.currentPos) { Polygon arrow = new Polygon(); int dx = x; y += ascent - 10; int dy = y; arrow.addPoint(dx, dy + 3); arrow.addPoint(dx + 5, dy + 3); for (x = dx + 5; x <= dx + 10; x++, y++) { arrow.addPoint(x, y); } for (x = dx + 9; x >= dx + 5; x--, y++) { arrow.addPoint(x, y); } arrow.addPoint(dx + 5, dy + 7); arrow.addPoint(dx, dy + 7); g.setColor(Color.yellow); g.fillPolygon(arrow); g.setColor(Color.black); g.drawPolygon(arrow); } } } }; class FileWindow extends JInternalFrame implements ActionListener { DebugGui debugGui; Dim.SourceInfo sourceInfo; FileTextArea textArea; FileHeader fileHeader; JScrollPane p; int currentPos; JLabel statusBar; public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cut")) { // textArea.cut(); } else if (cmd.equals("Copy")) { textArea.copy(); } else if (cmd.equals("Paste")) { // textArea.paste(); } } void load() { String url = getUrl(); if (url != null) { new Thread(new LoadFile(debugGui,url,sourceInfo.source())).start(); } } public int getPosition(int line) { int result = -1; try { result = textArea.getLineStartOffset(line); } catch (javax.swing.text.BadLocationException exc) { } return result; } boolean isBreakPoint(int line) { return sourceInfo.breakableLine(line) && sourceInfo.breakpoint(line); } void toggleBreakPoint(int line) { if (!isBreakPoint(line)) { setBreakPoint(line); } else { clearBreakPoint(line); } } void setBreakPoint(int line) { if (sourceInfo.breakableLine(line)) { boolean changed = sourceInfo.breakpoint(line, true); if (changed) { fileHeader.repaint(); } } } void clearBreakPoint(int line) { if (sourceInfo.breakableLine(line)) { boolean changed = sourceInfo.breakpoint(line, false); if (changed) { fileHeader.repaint(); } } } FileWindow(DebugGui debugGui, Dim.SourceInfo sourceInfo) { super(DebugGui.getShortName(sourceInfo.url()), true, true, true, true); this.debugGui = debugGui; this.sourceInfo = sourceInfo; updateToolTip(); currentPos = -1; textArea = new FileTextArea(this); textArea.setRows(24); textArea.setColumns(80); p = new JScrollPane(); fileHeader = new FileHeader(this); p.setViewportView(textArea); p.setRowHeaderView(fileHeader); setContentPane(p); pack(); updateText(sourceInfo); textArea.select(0); } private void updateToolTip() { // in case fileName is very long, try to set tool tip on frame Component c = getComponent(1); // this will work at least for Metal L&F if (c != null && c instanceof JComponent) { ((JComponent)c).setToolTipText(getUrl()); } } public String getUrl() { return sourceInfo.url(); } void updateText(Dim.SourceInfo sourceInfo) { this.sourceInfo = sourceInfo; String newText = sourceInfo.source(); if (!textArea.getText().equals(newText)) { textArea.setText(newText); int pos = 0; if (currentPos != -1) { pos = currentPos; } textArea.select(pos); } fileHeader.update(); fileHeader.repaint(); } void setPosition(int pos) { textArea.select(pos); currentPos = pos; fileHeader.repaint(); } void select(int start, int end) { int docEnd = textArea.getDocument().getLength(); textArea.select(docEnd, docEnd); textArea.select(start, end); } public void dispose() { debugGui.removeWindow(this); super.dispose(); } }; class MyTableModel extends AbstractTableModel { DebugGui debugGui; Vector expressions; Vector values; MyTableModel(DebugGui debugGui) { this.debugGui = debugGui; expressions = new Vector(); values = new Vector(); expressions.addElement(""); values.addElement(""); } public int getColumnCount() { return 2; } public int getRowCount() { return expressions.size(); } public String getColumnName(int column) { switch (column) { case 0: return "Expression"; case 1: return "Value"; } return null; } public boolean isCellEditable(int row, int column) { return true; } public Object getValueAt(int row, int column) { switch (column) { case 0: return expressions.elementAt(row); case 1: return values.elementAt(row); } return ""; } public void setValueAt(Object value, int row, int column) { switch (column) { case 0: String expr = value.toString(); expressions.setElementAt(expr, row); String result = ""; if (expr.length() > 0) { result = debugGui.dim.eval(expr); if (result == null) result = ""; } values.setElementAt(result, row); updateModel(); if (row + 1 == expressions.size()) { expressions.addElement(""); values.addElement(""); fireTableRowsInserted(row + 1, row + 1); } break; case 1: // just reset column 2; ignore edits fireTableDataChanged(); } } void updateModel() { for (int i = 0; i < expressions.size(); ++i) { Object value = expressions.elementAt(i); String expr = value.toString(); String result = ""; if (expr.length() > 0) { result = debugGui.dim.eval(expr); if (result == null) result = ""; } else { result = ""; } result = result.replace('\n', ' '); values.setElementAt(result, i); } fireTableDataChanged(); } }; class Evaluator extends JTable { MyTableModel tableModel; Evaluator(DebugGui debugGui) { super(new MyTableModel(debugGui)); tableModel = (MyTableModel)getModel(); } } class VariableModel implements TreeTableModel { static class VariableNode { Object object; Object id; VariableNode[] children; VariableNode(Object object, Object id) { this.object = object; this.id = id; } public String toString() { return (id instanceof String) ? (String)id : "[" + ((Integer)id).intValue() + "]"; } } // Names of the columns. private static final String[] cNames = { " Name", " Value"}; // Types of the columns. private static final Class[] cTypes = {TreeTableModel.class, String.class}; private static final VariableNode[] CHILDLESS = new VariableNode[0]; private Dim debugger; private VariableNode root; VariableModel() { } VariableModel(Dim debugger, Object scope) { this.debugger = debugger; this.root = new VariableNode(scope, "this"); } // // The TreeModel interface // public Object getRoot() { if (debugger == null) { return ""; } return root; } public int getChildCount(Object nodeObj) { if (debugger == null) { return 0; } VariableNode node = (VariableNode)nodeObj; return children(node).length; } public Object getChild(Object nodeObj, int i) { if (debugger == null) { return null; } VariableNode node = (VariableNode)nodeObj; return children(node)[i]; } public boolean isLeaf(Object nodeObj) { if (debugger == null) { return true; } VariableNode node = (VariableNode)nodeObj; return children(node).length == 0; } public int getIndexOfChild(Object parentObj, Object childObj) { if (debugger == null) { return -1; } VariableNode parent = (VariableNode)parentObj; VariableNode child = (VariableNode)childObj; VariableNode[] children = children(parent); for (int i = 0; i != children.length; ++i) { if (children[i] == child) { return i; } } return -1; } public boolean isCellEditable(Object node, int column) { return column == 0; } public void setValueAt(Object value, Object node, int column) { } public void addTreeModelListener(TreeModelListener l) { } public void removeTreeModelListener(TreeModelListener l) { } public void valueForPathChanged(TreePath path, Object newValue) { } // // The TreeTableNode interface. // public int getColumnCount() { return cNames.length; } public String getColumnName(int column) { return cNames[column]; } public Class getColumnClass(int column) { return cTypes[column]; } public Object getValueAt(Object nodeObj, int column) { if (debugger == null) { return null; } VariableNode node = (VariableNode)nodeObj; switch (column) { case 0: // Name return node.toString(); case 1: // Value String result; try { result = debugger.objectToString(getValue(node)); } catch (RuntimeException exc) { result = exc.getMessage(); } StringBuffer buf = new StringBuffer(); int len = result.length(); for (int i = 0; i < len; i++) { char ch = result.charAt(i); if (Character.isISOControl(ch)) { ch = ' '; } buf.append(ch); } return buf.toString(); } return null; } private VariableNode[] children(VariableNode node) { if (node.children != null) { return node.children; } VariableNode[] children; Object value = getValue(node); Object[] ids = debugger.getObjectIds(value); if (ids.length == 0) { children = CHILDLESS; } else { java.util.Arrays.sort(ids, new java.util.Comparator() { public int compare(Object l, Object r) { if (l instanceof String) { if (r instanceof Integer) { return -1; } return ((String)l).compareToIgnoreCase((String)r); } else { if (r instanceof String) { return 1; } int lint = ((Integer)l).intValue(); int rint = ((Integer)r).intValue(); return lint - rint; } } }); children = new VariableNode[ids.length]; for (int i = 0; i != ids.length; ++i) { children[i] = new VariableNode(value, ids[i]); } } node.children = children; return children; } Object getValue(VariableNode node) { try { return debugger.getObjectProperty(node.object, node.id); } catch (Exception exc) { return "undefined"; } } } class MyTreeTable extends JTreeTable { public MyTreeTable(VariableModel model) { super(model); } public JTree resetTree(TreeTableModel treeTableModel) { tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); tree.setSelectionModel(selectionWrapper); setSelectionModel(selectionWrapper.getListSelectionModel()); // Make the tree and table row heights the same. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(18); } // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); setShowGrid(true); setIntercellSpacing(new Dimension(1,1)); tree.setRootVisible(false); tree.setShowsRootHandles(true); DefaultTreeCellRenderer r = (DefaultTreeCellRenderer)tree.getCellRenderer(); r.setOpenIcon(null); r.setClosedIcon(null); r.setLeafIcon(null); return tree; } public boolean isCellEditable(EventObject e) { if (e instanceof MouseEvent) { MouseEvent me = (MouseEvent)e; // If the modifiers are not 0 (or the left mouse button), // tree may try and toggle the selection, and table // will then try and toggle, resulting in the // selection remaining the same. To avoid this, we // only dispatch when the modifiers are 0 (or the left mouse // button). if (me.getModifiers() == 0 || ((me.getModifiers() & (InputEvent.BUTTON1_MASK|1024)) != 0 && (me.getModifiers() & (InputEvent.SHIFT_MASK | InputEvent.CTRL_MASK | InputEvent.ALT_MASK | InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK | 64 | //SHIFT_DOWN_MASK 128 | //CTRL_DOWN_MASK 512 | // ALT_DOWN_MASK 2048 | //BUTTON2_DOWN_MASK 4096 //BUTTON3_DOWN_MASK )) == 0)) { int row = rowAtPoint(me.getPoint()); for (int counter = getColumnCount() - 1; counter >= 0; counter--) { if (TreeTableModel.class == getColumnClass(counter)) { MouseEvent newME = new MouseEvent (MyTreeTable.this.tree, me.getID(), me.getWhen(), me.getModifiers(), me.getX() - getCellRect(row, counter, true).x, me.getY(), me.getClickCount(), me.isPopupTrigger()); MyTreeTable.this.tree.dispatchEvent(newME); break; } } } if (me.getClickCount() >= 3) { return true; } return false; } if (e == null) { return true; } return false; } }; class ContextWindow extends JPanel implements ActionListener { DebugGui debugGui; JComboBox context; Vector toolTips; JTabbedPane tabs; JTabbedPane tabs2; MyTreeTable thisTable; MyTreeTable localsTable; MyTableModel tableModel; Evaluator evaluator; EvalTextArea cmdLine; JSplitPane split; boolean enabled; ContextWindow(final DebugGui debugGui) { super(); this.debugGui = debugGui; enabled = false; JPanel left = new JPanel(); JToolBar t1 = new JToolBar(); t1.setName("Variables"); t1.setLayout(new GridLayout()); t1.add(left); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout()); JPanel p2 = new JPanel(); p2.setLayout(new GridLayout()); p1.add(t1); JLabel label = new JLabel("Context:"); context = new JComboBox(); context.setLightWeightPopupEnabled(false); toolTips = new java.util.Vector(); label.setBorder(context.getBorder()); context.addActionListener(this); context.setActionCommand("ContextSwitch"); GridBagLayout layout = new GridBagLayout(); left.setLayout(layout); GridBagConstraints lc = new GridBagConstraints(); lc.insets.left = 5; lc.anchor = GridBagConstraints.WEST; lc.ipadx = 5; layout.setConstraints(label, lc); left.add(label); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.WEST; layout.setConstraints(context, c); left.add(context); tabs = new JTabbedPane(SwingConstants.BOTTOM); tabs.setPreferredSize(new Dimension(500,300)); thisTable = new MyTreeTable(new VariableModel()); JScrollPane jsp = new JScrollPane(thisTable); jsp.getViewport().setViewSize(new Dimension(5,2)); tabs.add("this", jsp); localsTable = new MyTreeTable(new VariableModel()); localsTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); localsTable.setPreferredSize(null); jsp = new JScrollPane(localsTable); tabs.add("Locals", jsp); c.weightx = c.weighty = 1; c.gridheight = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.WEST; layout.setConstraints(tabs, c); left.add(tabs); evaluator = new Evaluator(debugGui); cmdLine = new EvalTextArea(debugGui); //cmdLine.requestFocus(); tableModel = evaluator.tableModel; jsp = new JScrollPane(evaluator); JToolBar t2 = new JToolBar(); t2.setName("Evaluate"); tabs2 = new JTabbedPane(SwingConstants.BOTTOM); tabs2.add("Watch", jsp); tabs2.add("Evaluate", new JScrollPane(cmdLine)); tabs2.setPreferredSize(new Dimension(500,300)); t2.setLayout(new GridLayout()); t2.add(tabs2); p2.add(t2); evaluator.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p1, p2); split.setOneTouchExpandable(true); DebugGui.setResizeWeight(split, 0.5); setLayout(new BorderLayout()); add(split, BorderLayout.CENTER); final JToolBar finalT1 = t1; final JToolBar finalT2 = t2; final JPanel finalP1 = p1; final JPanel finalP2 = p2; final JSplitPane finalSplit = split; final JPanel finalThis = this; ComponentListener clistener = new ComponentListener() { boolean t1Docked = true; boolean t2Docked = true; void check(Component comp) { Component thisParent = finalThis.getParent(); if (thisParent == null) { return; } Component parent = finalT1.getParent(); boolean leftDocked = true; boolean rightDocked = true; boolean adjustVerticalSplit = false; if (parent != null) { if (parent != finalP1) { while (!(parent instanceof JFrame)) { parent = parent.getParent(); } JFrame frame = (JFrame)parent; debugGui.addTopLevel("Variables", frame); // We need the following hacks because: // - We want an undocked toolbar to be // resizable. // - We are using JToolbar as a container of a // JComboBox. Without this JComboBox's popup // can get left floating when the toolbar is // re-docked. // // We make the frame resizable and then // remove JToolbar's window listener // and insert one of our own that first ensures // the JComboBox's popup window is closed // and then calls JToolbar's window listener. if (!frame.isResizable()) { frame.setResizable(true); frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); final EventListener[] l = frame.getListeners(WindowListener.class); frame.removeWindowListener((WindowListener)l[0]); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { context.hidePopup(); ((WindowListener)l[0]).windowClosing(e); } }); //adjustVerticalSplit = true; } leftDocked = false; } else { leftDocked = true; } } parent = finalT2.getParent(); if (parent != null) { if (parent != finalP2) { while (!(parent instanceof JFrame)) { parent = parent.getParent(); } JFrame frame = (JFrame)parent; debugGui.addTopLevel("Evaluate", frame); frame.setResizable(true); rightDocked = false; } else { rightDocked = true; } } if (leftDocked && t2Docked && rightDocked && t2Docked) { // no change return; } t1Docked = leftDocked; t2Docked = rightDocked; JSplitPane split = (JSplitPane)thisParent; if (leftDocked) { if (rightDocked) { finalSplit.setDividerLocation(0.5); } else { finalSplit.setDividerLocation(1.0); } if (adjustVerticalSplit) { split.setDividerLocation(0.66); } } else if (rightDocked) { finalSplit.setDividerLocation(0.0); split.setDividerLocation(0.66); } else { // both undocked split.setDividerLocation(1.0); } } public void componentHidden(ComponentEvent e) { check(e.getComponent()); } public void componentMoved(ComponentEvent e) { check(e.getComponent()); } public void componentResized(ComponentEvent e) { check(e.getComponent()); } public void componentShown(ComponentEvent e) { check(e.getComponent()); } }; p1.addContainerListener(new ContainerListener() { public void componentAdded(ContainerEvent e) { Component thisParent = finalThis.getParent(); JSplitPane split = (JSplitPane)thisParent; if (e.getChild() == finalT1) { if (finalT2.getParent() == finalP2) { // both docked finalSplit.setDividerLocation(0.5); } else { // left docked only finalSplit.setDividerLocation(1.0); } split.setDividerLocation(0.66); } } public void componentRemoved(ContainerEvent e) { Component thisParent = finalThis.getParent(); JSplitPane split = (JSplitPane)thisParent; if (e.getChild() == finalT1) { if (finalT2.getParent() == finalP2) { // right docked only finalSplit.setDividerLocation(0.0); split.setDividerLocation(0.66); } else { // both undocked split.setDividerLocation(1.0); } } } }); t1.addComponentListener(clistener); t2.addComponentListener(clistener); disable(); } public void actionPerformed(ActionEvent e) { if (!enabled) return; if (e.getActionCommand().equals("ContextSwitch")) { Dim.ContextData contextData = debugGui.dim.currentContextData(); if (contextData == null) { return; } int frameIndex = context.getSelectedIndex(); context.setToolTipText(toolTips.elementAt(frameIndex).toString()); int frameCount = contextData.frameCount(); if (frameIndex >= frameCount) { return; } Dim.StackFrame frame = contextData.getFrame(frameIndex); Object scope = frame.scope(); Object thisObj = frame.thisObj(); thisTable.resetTree(new VariableModel(debugGui.dim, thisObj)); VariableModel scopeModel; if (scope != thisObj) { scopeModel = new VariableModel(debugGui.dim, scope); } else { scopeModel = new VariableModel(); } localsTable.resetTree(scopeModel); debugGui.dim.contextSwitch(frameIndex); debugGui.showStopLine(frame); tableModel.updateModel(); } } public void disable() { context.setEnabled(false); thisTable.setEnabled(false); localsTable.setEnabled(false); evaluator.setEnabled(false); cmdLine.setEnabled(false); } public void enable() { context.setEnabled(true); thisTable.setEnabled(true); localsTable.setEnabled(true); evaluator.setEnabled(true); cmdLine.setEnabled(true); } public void disableUpdate() { enabled = false; } public void enableUpdate() { enabled = true; } }; class Menubar extends JMenuBar implements ActionListener { DebugGui debugGui; JMenu windowMenu; JCheckBoxMenuItem breakOnExceptions; JCheckBoxMenuItem breakOnEnter; JCheckBoxMenuItem breakOnReturn; JMenu getDebugMenu() { return getMenu(2); } Menubar(DebugGui debugGui) { super(); this.debugGui = debugGui; String[] fileItems = {"Open...", "Run...", "", "Exit"}; String[] fileCmds = {"Open", "Load", "", "Exit"}; char[] fileShortCuts = {'0', 'N', '\0', 'X'}; int[] fileAccelerators = {KeyEvent.VK_O, KeyEvent.VK_N, 0, KeyEvent.VK_Q}; String[] editItems = {"Cut", "Copy", "Paste", "Go to function..."}; char[] editShortCuts = {'T', 'C', 'P', 'F'}; String[] debugItems = {"Break", "Go", "Step Into", "Step Over", "Step Out"}; char[] debugShortCuts = {'B', 'G', 'I', 'O', 'T'}; String[] plafItems = {"Metal", "Windows", "Motif"}; char [] plafShortCuts = {'M', 'W', 'F'}; int[] debugAccelerators = {KeyEvent.VK_PAUSE, KeyEvent.VK_F5, KeyEvent.VK_F11, KeyEvent.VK_F7, KeyEvent.VK_F8, 0, 0}; JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic('E'); JMenu plafMenu = new JMenu("Platform"); plafMenu.setMnemonic('P'); JMenu debugMenu = new JMenu("Debug"); debugMenu.setMnemonic('D'); windowMenu = new JMenu("Window"); windowMenu.setMnemonic('W'); for (int i = 0; i < fileItems.length; ++i) { if (fileItems[i].length() == 0) { fileMenu.addSeparator(); } else { JMenuItem item = new JMenuItem(fileItems[i], fileShortCuts[i]); item.setActionCommand(fileCmds[i]); item.addActionListener(this); fileMenu.add(item); if (fileAccelerators[i] != 0) { KeyStroke k = KeyStroke.getKeyStroke(fileAccelerators[i], Event.CTRL_MASK); item.setAccelerator(k); } } } for (int i = 0; i < editItems.length; ++i) { JMenuItem item = new JMenuItem(editItems[i], editShortCuts[i]); item.addActionListener(this); editMenu.add(item); } for (int i = 0; i < plafItems.length; ++i) { JMenuItem item = new JMenuItem(plafItems[i], plafShortCuts[i]); item.addActionListener(this); plafMenu.add(item); } for (int i = 0; i < debugItems.length; ++i) { JMenuItem item = new JMenuItem(debugItems[i], debugShortCuts[i]); item.addActionListener(this); if (debugAccelerators[i] != 0) { KeyStroke k = KeyStroke.getKeyStroke(debugAccelerators[i], 0); item.setAccelerator(k); } if (i != 0) { item.setEnabled(false); } debugMenu.add(item); } breakOnExceptions = new JCheckBoxMenuItem("Break on Exceptions"); breakOnExceptions.setMnemonic('X'); breakOnExceptions.addActionListener(this); breakOnExceptions.setSelected(false); debugMenu.add(breakOnExceptions); breakOnEnter = new JCheckBoxMenuItem("Break on Function Enter"); breakOnEnter.setMnemonic('E'); breakOnEnter.addActionListener(this); breakOnEnter.setSelected(false); debugMenu.add(breakOnEnter); breakOnReturn = new JCheckBoxMenuItem("Break on Function Return"); breakOnReturn.setMnemonic('R'); breakOnReturn.addActionListener(this); breakOnReturn.setSelected(false); debugMenu.add(breakOnReturn); add(fileMenu); add(editMenu); //add(plafMenu); add(debugMenu); JMenuItem item; windowMenu.add(item = new JMenuItem("Cascade", 'A')); item.addActionListener(this); windowMenu.add(item = new JMenuItem("Tile", 'T')); item.addActionListener(this); windowMenu.addSeparator(); windowMenu.add(item = new JMenuItem("Console", 'C')); item.addActionListener(this); add(windowMenu); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); String plaf_name = null; if (cmd.equals("Metal")) { plaf_name = "javax.swing.plaf.metal.MetalLookAndFeel"; } else if (cmd.equals("Windows")) { plaf_name = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; } else if (cmd.equals("Motif")) { plaf_name = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; } else { Object source = e.getSource(); if (source == breakOnExceptions) { debugGui.dim.breakOnExceptions = breakOnExceptions.isSelected(); } else if (source == breakOnEnter) { debugGui.dim.breakOnEnter = breakOnEnter.isSelected(); } else if (source == breakOnReturn) { debugGui.dim.breakOnReturn = breakOnReturn.isSelected(); } else { debugGui.actionPerformed(e); } return; } try { UIManager.setLookAndFeel(plaf_name); SwingUtilities.updateComponentTreeUI(debugGui); SwingUtilities.updateComponentTreeUI(debugGui.dlg); } catch (Exception ignored) { //ignored.printStackTrace(); } } void addFile(String url) { int count = windowMenu.getItemCount(); JMenuItem item; if (count == 4) { windowMenu.addSeparator(); count++; } JMenuItem lastItem = windowMenu.getItem(count -1); boolean hasMoreWin = false; int maxWin = 5; if (lastItem != null && lastItem.getText().equals("More Windows...")) { hasMoreWin = true; maxWin++; } if (!hasMoreWin && count - 4 == 5) { windowMenu.add(item = new JMenuItem("More Windows...", 'M')); item.setActionCommand("More Windows..."); item.addActionListener(this); return; } else if (count - 4 <= maxWin) { if (hasMoreWin) { count--; windowMenu.remove(lastItem); } String shortName = DebugGui.getShortName(url); windowMenu.add(item = new JMenuItem((char)('0' + (count-4)) + " " + shortName, '0' + (count - 4))); if (hasMoreWin) { windowMenu.add(lastItem); } } else { return; } item.setActionCommand(url); item.addActionListener(this); } } class OpenFile implements Runnable { DebugGui debugGui; String fileName; String text; OpenFile(DebugGui debugGui, String fileName, String text) { this.debugGui = debugGui; this.fileName = fileName; this.text = text; } public void run() { try { debugGui.dim.compileScript(fileName, text); } catch (RuntimeException ex) { MessageDialogWrapper.showMessageDialog(debugGui, ex.getMessage(), "Error Compiling "+fileName, JOptionPane.ERROR_MESSAGE); } } } class LoadFile implements Runnable { DebugGui debugGui; String fileName; String text; LoadFile(DebugGui debugGui, String fileName, String text) { this.debugGui = debugGui; this.fileName = fileName; this.text = text; } public void run() { try { debugGui.dim.evalScript(fileName, text); } catch (RuntimeException ex) { MessageDialogWrapper.showMessageDialog(debugGui, ex.getMessage(), "Run error for "+fileName, JOptionPane.ERROR_MESSAGE); } } } class DebugGui extends JFrame implements GuiCallback { Dim dim; Runnable exitAction; JDesktopPane desk; ContextWindow context; Menubar menubar; JToolBar toolBar; JSInternalConsole console; EvalWindow evalWindow; JSplitPane split1; JLabel statusBar; java.util.Hashtable toplevels = new java.util.Hashtable(); java.util.Hashtable fileWindows = new java.util.Hashtable(); FileWindow currentWindow; JFileChooser dlg; private static EventQueue awtEventQueue; DebugGui(Dim dim, String title) { super(title); this.dim = dim; init(); } public void setVisible(boolean b) { super.setVisible(b); if (b) { // this needs to be done after the window is visible console.consoleTextArea.requestFocus(); context.split.setDividerLocation(0.5); try { console.setMaximum(true); console.setSelected(true); console.show(); console.consoleTextArea.requestFocus(); } catch (Exception exc) { } } } void addTopLevel(String key, JFrame frame) { if (frame != this) { toplevels.put(key, frame); } } void init() { menubar = new Menubar(this); setJMenuBar(menubar); toolBar = new JToolBar(); JButton button; JButton breakButton, goButton, stepIntoButton, stepOverButton, stepOutButton; String [] toolTips = {"Break (Pause)", "Go (F5)", "Step Into (F11)", "Step Over (F7)", "Step Out (F8)"}; int count = 0; button = breakButton = new JButton("Break"); JButton focusButton = button; button.setToolTipText("Break"); button.setActionCommand("Break"); button.addActionListener(menubar); button.setEnabled(true); button.setToolTipText(toolTips[count++]); button = goButton = new JButton("Go"); button.setToolTipText("Go"); button.setActionCommand("Go"); button.addActionListener(menubar); button.setEnabled(false); button.setToolTipText(toolTips[count++]); button = stepIntoButton = new JButton("Step Into"); button.setToolTipText("Step Into"); button.setActionCommand("Step Into"); button.addActionListener(menubar); button.setEnabled(false); button.setToolTipText(toolTips[count++]); button = stepOverButton = new JButton("Step Over"); button.setToolTipText("Step Over"); button.setActionCommand("Step Over"); button.setEnabled(false); button.addActionListener(menubar); button.setToolTipText(toolTips[count++]); button = stepOutButton = new JButton("Step Out"); button.setToolTipText("Step Out"); button.setActionCommand("Step Out"); button.setEnabled(false); button.addActionListener(menubar); button.setToolTipText(toolTips[count++]); Dimension dim = stepOverButton.getPreferredSize(); breakButton.setPreferredSize(dim); breakButton.setMinimumSize(dim); breakButton.setMaximumSize(dim); breakButton.setSize(dim); goButton.setPreferredSize(dim); goButton.setMinimumSize(dim); goButton.setMaximumSize(dim); stepIntoButton.setPreferredSize(dim); stepIntoButton.setMinimumSize(dim); stepIntoButton.setMaximumSize(dim); stepOverButton.setPreferredSize(dim); stepOverButton.setMinimumSize(dim); stepOverButton.setMaximumSize(dim); stepOutButton.setPreferredSize(dim); stepOutButton.setMinimumSize(dim); stepOutButton.setMaximumSize(dim); toolBar.add(breakButton); toolBar.add(goButton); toolBar.add(stepIntoButton); toolBar.add(stepOverButton); toolBar.add(stepOutButton); JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); getContentPane().add(toolBar, BorderLayout.NORTH); getContentPane().add(contentPane, BorderLayout.CENTER); desk = new JDesktopPane(); desk.setPreferredSize(new Dimension(600, 300)); desk.setMinimumSize(new Dimension(150, 50)); desk.add(console = new JSInternalConsole("JavaScript Console")); context = new ContextWindow(this); context.setPreferredSize(new Dimension(600, 120)); context.setMinimumSize(new Dimension(50, 50)); split1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, desk, context); split1.setOneTouchExpandable(true); DebugGui.setResizeWeight(split1, 0.66); contentPane.add(split1, BorderLayout.CENTER); statusBar = new JLabel(); statusBar.setText("Thread: "); contentPane.add(statusBar, BorderLayout.SOUTH); dlg = new JFileChooser(); javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { if (f.isDirectory()) { return true; } String n = f.getName(); int i = n.lastIndexOf('.'); if (i > 0 && i < n.length() -1) { String ext = n.substring(i + 1).toLowerCase(); if (ext.equals("js")) { return true; } } return false; } public String getDescription() { return "JavaScript Files (*.js)"; } }; dlg.addChoosableFileFilter(filter); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { exit(); } }); } void exit() { if (exitAction != null) { SwingUtilities.invokeLater(exitAction); } dim.setReturnValue(Dim.EXIT); } FileWindow getFileWindow(String url) { if (url == null || url.equals("<stdin>")) { return null; } return (FileWindow)fileWindows.get(url); } static String getShortName(String url) { int lastSlash = url.lastIndexOf('/'); if (lastSlash < 0) { lastSlash = url.lastIndexOf('\\'); } String shortName = url; if (lastSlash >= 0 && lastSlash + 1 < url.length()) { shortName = url.substring(lastSlash + 1); } return shortName; } void removeWindow(FileWindow w) { fileWindows.remove(w.getUrl()); JMenu windowMenu = getWindowMenu(); int count = windowMenu.getItemCount(); JMenuItem lastItem = windowMenu.getItem(count -1); String name = getShortName(w.getUrl()); for (int i = 5; i < count; i++) { JMenuItem item = windowMenu.getItem(i); if (item == null) continue; // separator String text = item.getText(); //1 D:\foo.js //2 D:\bar.js int pos = text.indexOf(' '); if (text.substring(pos + 1).equals(name)) { windowMenu.remove(item); // Cascade [0] // Tile [1] // ------- [2] // Console [3] // ------- [4] if (count == 6) { // remove the final separator windowMenu.remove(4); } else { int j = i - 4; for (;i < count -1; i++) { JMenuItem thisItem = windowMenu.getItem(i); if (thisItem != null) { //1 D:\foo.js //2 D:\bar.js text = thisItem.getText(); if (text.equals("More Windows...")) { break; } else { pos = text.indexOf(' '); thisItem.setText((char)('0' + j) + " " + text.substring(pos + 1)); thisItem.setMnemonic('0' + j); j++; } } } if (count - 6 == 0 && lastItem != item) { if (lastItem.getText().equals("More Windows...")) { windowMenu.remove(lastItem); } } } break; } } windowMenu.revalidate(); } void showStopLine(Dim.StackFrame frame) { String sourceName = frame.getUrl(); if (sourceName == null || sourceName.equals("<stdin>")) { if (console.isVisible()) { console.show(); } } else { int lineNumber = frame.getLineNumber(); FileWindow w = getFileWindow(sourceName); if (w != null) { setFilePosition(w, lineNumber); } else { Dim.SourceInfo si = frame.sourceInfo(); createFileWindow(si, lineNumber); } } } void createFileWindow(Dim.SourceInfo sourceInfo, int line) { boolean activate = true; String url = sourceInfo.url(); FileWindow w = new FileWindow(this, sourceInfo); fileWindows.put(url, w); if (line != -1) { if (currentWindow != null) { currentWindow.setPosition(-1); } try { w.setPosition(w.textArea.getLineStartOffset(line-1)); } catch (BadLocationException exc) { try { w.setPosition(w.textArea.getLineStartOffset(0)); } catch (BadLocationException ee) { w.setPosition(-1); } } } desk.add(w); if (line != -1) { currentWindow = w; } menubar.addFile(url); w.setVisible(true); if (activate) { try { w.setMaximum(true); w.setSelected(true); w.moveToFront(); } catch (Exception exc) { } } } void setFilePosition(FileWindow w, int line) { boolean activate = true; JTextArea ta = w.textArea; try { if (line == -1) { w.setPosition(-1); if (currentWindow == w) { currentWindow = null; } } else { int loc = ta.getLineStartOffset(line-1); if (currentWindow != null && currentWindow != w) { currentWindow.setPosition(-1); } w.setPosition(loc); currentWindow = w; } } catch (BadLocationException exc) { // fix me } if (activate) { if (w.isIcon()) { desk.getDesktopManager().deiconifyFrame(w); } desk.getDesktopManager().activateFrame(w); try { w.show(); w.toFront(); // required for correct frame layering (JDK 1.4.1) w.setSelected(true); } catch (Exception exc) { } } } // Implementing GuiCallback public void updateSourceText(final Dim.SourceInfo sourceInfo) { SwingUtilities.invokeLater(new Runnable() { public void run() { String fileName = sourceInfo.url(); FileWindow w = getFileWindow(fileName); if (w != null) { w.updateText(sourceInfo); w.show(); } else if (!fileName.equals("<stdin>")) { createFileWindow(sourceInfo, -1); } } }); } public void enterInterrupt(final Dim.StackFrame lastFrame, final String threadTitle, final String alertMessage) { if (SwingUtilities.isEventDispatchThread()) { enterInterruptImpl(lastFrame, threadTitle, alertMessage); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { enterInterruptImpl(lastFrame, threadTitle, alertMessage); } }); } } public boolean isGuiEventThread() { return SwingUtilities.isEventDispatchThread(); } public void dispatchNextGuiEvent() throws InterruptedException { EventQueue queue = awtEventQueue; if (queue == null) { queue = Toolkit.getDefaultToolkit().getSystemEventQueue(); awtEventQueue = queue; } AWTEvent event = queue.getNextEvent(); if (event instanceof ActiveEvent) { ((ActiveEvent)event).dispatch(); } else { Object source = event.getSource(); if (source instanceof Component) { Component comp = (Component)source; comp.dispatchEvent(event); } else if (source instanceof MenuComponent) { ((MenuComponent)source).dispatchEvent(event); } } } void enterInterruptImpl(Dim.StackFrame lastFrame, String threadTitle, String alertMessage) { statusBar.setText("Thread: " + threadTitle); showStopLine(lastFrame); if (alertMessage != null) { MessageDialogWrapper.showMessageDialog(this, alertMessage, "Exception in Script", JOptionPane.ERROR_MESSAGE); } JMenu menu = getJMenuBar().getMenu(0); //menu.getItem(0).setEnabled(false); // File->Load menu = getJMenuBar().getMenu(2); menu.getItem(0).setEnabled(false); // Debug->Break int count = menu.getItemCount(); for (int i = 1; i < count; ++i) { menu.getItem(i).setEnabled(true); } boolean b = false; for (int ci = 0, cc = toolBar.getComponentCount(); ci < cc; ci++) { toolBar.getComponent(ci).setEnabled(b); b = true; } toolBar.setEnabled(true); // raise the debugger window toFront(); Dim.ContextData contextData = lastFrame.contextData(); context.enable(); JComboBox ctx = context.context; Vector toolTips = context.toolTips; context.disableUpdate(); int frameCount = contextData.frameCount(); ctx.removeAllItems(); // workaround for JDK 1.4 bug that caches selected value even after // removeAllItems() is called ctx.setSelectedItem(null); toolTips.removeAllElements(); for (int i = 0; i < frameCount; i++) { Dim.StackFrame frame = contextData.getFrame(i); String url = frame.getUrl(); int lineNumber = frame.getLineNumber(); String shortName = url; if (url.length() > 20) { shortName = "..." + url.substring(url.length() - 17); } String location = "\"" + shortName + "\", line " + lineNumber; ctx.insertItemAt(location, i); location = "\"" + url + "\", line " + lineNumber; toolTips.addElement(location); } context.enableUpdate(); ctx.setSelectedIndex(0); ctx.setMinimumSize(new Dimension(50, ctx.getMinimumSize().height)); } JMenu getWindowMenu() { return menubar.getMenu(3); } String chooseFile(String title) { dlg.setDialogTitle(title); File CWD = null; String dir = System.getProperty("user.dir"); if (dir != null) { CWD = new File(dir); } if (CWD != null) { dlg.setCurrentDirectory(CWD); } int returnVal = dlg.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { String result = dlg.getSelectedFile().getCanonicalPath(); CWD = dlg.getSelectedFile().getParentFile(); Properties props = System.getProperties(); props.put("user.dir", CWD.getPath()); System.setProperties(props); return result; }catch (IOException ignored) { }catch (SecurityException ignored) { } } return null; } JInternalFrame getSelectedFrame() { JInternalFrame[] frames = desk.getAllFrames(); for (int i = 0; i < frames.length; i++) { if (frames[i].isShowing()) { return frames[i]; } } return frames[frames.length - 1]; } void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); int returnValue = -1; if (cmd.equals("Cut") || cmd.equals("Copy") || cmd.equals("Paste")) { JInternalFrame f = getSelectedFrame(); if (f != null && f instanceof ActionListener) { ((ActionListener)f).actionPerformed(e); } } else if (cmd.equals("Step Over")) { returnValue = Dim.STEP_OVER; } else if (cmd.equals("Step Into")) { returnValue = Dim.STEP_INTO; } else if (cmd.equals("Step Out")) { returnValue = Dim.STEP_OUT; } else if (cmd.equals("Go")) { returnValue = Dim.GO; } else if (cmd.equals("Break")) { dim.breakFlag = true; } else if (cmd.equals("Exit")) { exit(); } else if (cmd.equals("Open")) { String fileName = chooseFile("Select a file to compile"); if (fileName != null) { String text = readFile(fileName); if (text != null) { new Thread(new OpenFile(this, fileName, text)).start(); } } } else if (cmd.equals("Load")) { String fileName = chooseFile("Select a file to execute"); if (fileName != null) { String text = readFile(fileName); if (text != null) { new Thread(new LoadFile(this, fileName, text)).start(); } } } else if (cmd.equals("More Windows...")) { MoreWindows dlg = new MoreWindows(this, fileWindows, "Window", "Files"); dlg.showDialog(this); } else if (cmd.equals("Console")) { if (console.isIcon()) { desk.getDesktopManager().deiconifyFrame(console); } console.show(); desk.getDesktopManager().activateFrame(console); console.consoleTextArea.requestFocus(); } else if (cmd.equals("Cut")) { } else if (cmd.equals("Copy")) { } else if (cmd.equals("Paste")) { } else if (cmd.equals("Go to function...")) { FindFunction dlg = new FindFunction(this, "Go to function", "Function"); dlg.showDialog(this); } else if (cmd.equals("Tile")) { JInternalFrame[] frames = desk.getAllFrames(); int count = frames.length; int rows, cols; rows = cols = (int)Math.sqrt(count); if (rows*cols < count) { cols++; if (rows * cols < count) { rows++; } } Dimension size = desk.getSize(); int w = size.width/cols; int h = size.height/rows; int x = 0; int y = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int index = (i*cols) + j; if (index >= frames.length) { break; } JInternalFrame f = frames[index]; try { f.setIcon(false); f.setMaximum(false); } catch (Exception exc) { } desk.getDesktopManager().setBoundsForFrame(f, x, y, w, h); x += w; } y += h; x = 0; } } else if (cmd.equals("Cascade")) { JInternalFrame[] frames = desk.getAllFrames(); int count = frames.length; int x, y, w, h; x = y = 0; h = desk.getHeight(); int d = h / count; if (d > 30) d = 30; for (int i = count -1; i >= 0; i--, x += d, y += d) { JInternalFrame f = frames[i]; try { f.setIcon(false); f.setMaximum(false); } catch (Exception exc) { } Dimension dimen = f.getPreferredSize(); w = dimen.width; h = dimen.height; desk.getDesktopManager().setBoundsForFrame(f, x, y, w, h); } } else { Object obj = getFileWindow(cmd); if (obj != null) { FileWindow w = (FileWindow)obj; try { if (w.isIcon()) { w.setIcon(false); } w.setVisible(true); w.moveToFront(); w.setSelected(true); } catch (Exception exc) { } } } if (returnValue != -1) { disableInterruptOnlyGui(); dim.setReturnValue(returnValue); } } private void disableInterruptOnlyGui() { if (currentWindow != null) currentWindow.setPosition(-1); JMenu menu = getJMenuBar().getMenu(0); menu.getItem(0).setEnabled(true); // File->Load menu = getJMenuBar().getMenu(2); menu.getItem(0).setEnabled(true); // Debug->Break int count = menu.getItemCount() - 1; int i = 1; for (; i < count; ++i) { menu.getItem(i).setEnabled(false); } context.disable(); boolean b = true; for (int ci = 0, cc = toolBar.getComponentCount(); ci < cc; ci++) { toolBar.getComponent(ci).setEnabled(b); b = false; } } static void setResizeWeight(JSplitPane pane, double weight) { // call through reflection for portability // pre-1.3 JDK JSplitPane doesn't have this method try { Method m = JSplitPane.class.getMethod("setResizeWeight", new Class[]{double.class}); m.invoke(pane, new Object[]{new Double(weight)}); } catch (NoSuchMethodException exc) { } catch (IllegalAccessException exc) { } catch (java.lang.reflect.InvocationTargetException exc) { } } String readFile(String fileName) { String text; try { Reader r = new FileReader(fileName); try { text = Kit.readReader(r); } finally { r.close(); } } catch (IOException ex) { MessageDialogWrapper.showMessageDialog(this, ex.getMessage(), "Error reading "+fileName, JOptionPane.ERROR_MESSAGE); text = null; } return text; } }
Fix menu enable/disable misbehavior.
toolsrc/org/mozilla/javascript/tools/debugger/DebugGui.java
Fix menu enable/disable misbehavior.
<ide><path>oolsrc/org/mozilla/javascript/tools/debugger/DebugGui.java <ide> class Menubar extends JMenuBar implements ActionListener <ide> { <ide> <add> private Vector interruptOnlyItems = new Vector(); <add> private Vector runOnlyItems = new Vector(); <add> <ide> DebugGui debugGui; <ide> JMenu windowMenu; <ide> JCheckBoxMenuItem breakOnExceptions; <ide> item.setAccelerator(k); <ide> } <ide> if (i != 0) { <del> item.setEnabled(false); <add> interruptOnlyItems.add(item); <add> } else { <add> runOnlyItems.add(item); <ide> } <ide> debugMenu.add(item); <ide> } <ide> item.addActionListener(this); <ide> add(windowMenu); <ide> <add> updateEnabled(false); <ide> } <ide> <ide> public void actionPerformed(ActionEvent e) { <ide> } <ide> item.setActionCommand(url); <ide> item.addActionListener(this); <add> } <add> <add> void updateEnabled(boolean interrupted) <add> { <add> for (int i = 0; i != interruptOnlyItems.size(); ++i) { <add> JMenuItem item = (JMenuItem)interruptOnlyItems.elementAt(i); <add> item.setEnabled(interrupted); <add> } <add> <add> for (int i = 0; i != runOnlyItems.size(); ++i) { <add> JMenuItem item = (JMenuItem)runOnlyItems.elementAt(i); <add> item.setEnabled(!interrupted); <add> } <ide> } <ide> <ide> } <ide> JOptionPane.ERROR_MESSAGE); <ide> } <ide> <del> JMenu menu = getJMenuBar().getMenu(0); <del> //menu.getItem(0).setEnabled(false); // File->Load <del> menu = getJMenuBar().getMenu(2); <del> menu.getItem(0).setEnabled(false); // Debug->Break <del> int count = menu.getItemCount(); <del> for (int i = 1; i < count; ++i) { <del> menu.getItem(i).setEnabled(true); <del> } <del> boolean b = false; <del> for (int ci = 0, cc = toolBar.getComponentCount(); ci < cc; ci++) { <del> toolBar.getComponent(ci).setEnabled(b); <del> b = true; <del> } <add> ((Menubar)getJMenuBar()).updateEnabled(true); <ide> toolBar.setEnabled(true); <ide> // raise the debugger window <ide> toFront(); <ide> private void disableInterruptOnlyGui() <ide> { <ide> if (currentWindow != null) currentWindow.setPosition(-1); <del> JMenu menu = getJMenuBar().getMenu(0); <del> menu.getItem(0).setEnabled(true); // File->Load <del> menu = getJMenuBar().getMenu(2); <del> menu.getItem(0).setEnabled(true); // Debug->Break <del> int count = menu.getItemCount() - 1; <del> int i = 1; <del> for (; i < count; ++i) { <del> menu.getItem(i).setEnabled(false); <del> } <add> ((Menubar)getJMenuBar()).updateEnabled(false); <ide> context.disable(); <ide> boolean b = true; <ide> for (int ci = 0, cc = toolBar.getComponentCount(); ci < cc; ci++) {
JavaScript
apache-2.0
2fba44409a6295482ac5a0fd1b5f903703154373
0
adam-serene/serene-mvp,adam-serene/serene-mvp
const express = require('express'); const router = express.Router(); const path = require('path'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const session = require('express-session'); const passport = require('passport'); const FitbitStrategy = require( 'passport-fitbit-oauth2' ).FitbitOAuth2Strategy; const knex = require('../knex'); require('dotenv').config() router.use(cookieParser()); router.use(bodyParser.json()); router.use(bodyParser.urlencoded({ extended: false })); router.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true })); router.use(passport.initialize()); router.use(passport.session()); // Serve static files from the React app // app.use(express.static(path.join(__dirname, 'client/build'))); //passport-fitbit-oauth2 routing passport.use(new FitbitStrategy({ clientID: '228QJJ', clientSecret: '743b00ca7fc644e5469cbb5deee23c44', callbackURL: "http://serene-green.herokuapp.com/auth/fitbit/callback" // callbackURL: "http://localhost:5000/auth/fitbit/callback" }, function onSuccessfulLogin(token, refreshToken, profile, done) { // This is a great place to find or create a user in the database knex.update({ fitbitToken: token, }) .into('users') .where('id', 1) .returning('fitbitToken') .then(data=>{ console.log(data); }) // This function happens once after a successful login // Whatever you pass to `done` gets passed to `serializeUser` console.log(token); done(null, {token, profile}); } )); passport.serializeUser(function(user, done) { // console.log('serializeUser', user); done(null, user); }); passport.deserializeUser(function(obj, done) { // console.log('deserializeUser', obj); done(null, obj); }); router.get('/success', function(req, res, next) { // res.send(req.user); res.send('Successful login!') }); router.get('/failure', function(req, res, next) { // res.send(req.user); res.send('Try again...') }); router.get('/', passport.authenticate('fitbit', {scope: ['activity','heartrate','location','profile']} )); router.get('/callback', passport.authenticate('fitbit', { successRedirect: '/success', failureRedirect: '/failure' } )); // catch 404 and forward to error handler router.use(function(req, res, next) { const err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (router.get('env') === 'development') { router.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user router.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = router;
routes/passport.js
const express = require('express'); const router = express.Router(); const path = require('path'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const session = require('express-session'); const passport = require('passport'); const FitbitStrategy = require( 'passport-fitbit-oauth2' ).FitbitOAuth2Strategy; const knex = require('../knex'); require('dotenv').config() router.use(cookieParser()); router.use(bodyParser.json()); router.use(bodyParser.urlencoded({ extended: false })); router.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true })); router.use(passport.initialize()); router.use(passport.session()); // Serve static files from the React app // app.use(express.static(path.join(__dirname, 'client/build'))); //passport-fitbit-oauth2 routing passport.use(new FitbitStrategy({ clientID: process.env.FITBIT_OAUTH2_CLIENT_ID, clientSecret: process.env.FITBIT_OAUTH2_SECRET, // callbackURL: "http://serene-green.herokuapp.com/auth/fitbit/callback" callbackURL: "http://localhost:5000/auth/fitbit/callback" }, function onSuccessfulLogin(token, refreshToken, profile, done) { // This is a great place to find or create a user in the database knex.update({ fitbitToken: token, }) .into('users') .where('id', 1) .returning('fitbitToken') .then(data=>{ console.log(data); }) // This function happens once after a successful login // Whatever you pass to `done` gets passed to `serializeUser` console.log(token); done(null, {token, profile}); } )); passport.serializeUser(function(user, done) { // console.log('serializeUser', user); done(null, user); }); passport.deserializeUser(function(obj, done) { // console.log('deserializeUser', obj); done(null, obj); }); router.get('/success', function(req, res, next) { // res.send(req.user); res.send('Successful login!') }); router.get('/failure', function(req, res, next) { // res.send(req.user); res.send('Try again...') }); router.get('/', passport.authenticate('fitbit', {scope: ['activity','heartrate','location','profile']} )); router.get('/callback', passport.authenticate('fitbit', { successRedirect: '/success', failureRedirect: '/failure' } )); // catch 404 and forward to error handler router.use(function(req, res, next) { const err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (router.get('env') === 'development') { router.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user router.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = router;
reveal OAuth Client ID
routes/passport.js
reveal OAuth Client ID
<ide><path>outes/passport.js <ide> <ide> //passport-fitbit-oauth2 routing <ide> passport.use(new FitbitStrategy({ <del> clientID: process.env.FITBIT_OAUTH2_CLIENT_ID, <del> clientSecret: process.env.FITBIT_OAUTH2_SECRET, <del> // callbackURL: "http://serene-green.herokuapp.com/auth/fitbit/callback" <del> callbackURL: "http://localhost:5000/auth/fitbit/callback" <add> clientID: '228QJJ', <add> clientSecret: '743b00ca7fc644e5469cbb5deee23c44', <add> callbackURL: "http://serene-green.herokuapp.com/auth/fitbit/callback" <add> // callbackURL: "http://localhost:5000/auth/fitbit/callback" <ide> }, <ide> function onSuccessfulLogin(token, refreshToken, profile, done) { <ide>
Java
mit
023496f455f78d14ec2d44addc426b65174f5491
0
spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror
package kawa; import kawa.lang.*; import gnu.kawa.lispexpr.LispReader; import kawa.standard.*; import gnu.mapping.*; import gnu.expr.*; import java.io.*; import gnu.text.*; import gnu.lists.*; /** Utility functions (static methods) for kawa.repl. * Should probably be merged with kawa.repl. FIXME. */ public class Shell { private static Class[] noClasses = { }; private static Class[] boolClasses = { Boolean.TYPE }; private static Class[] xmlPrinterClasses = {gnu.lists.Consumer.class, java.lang.Object.class }; private static Class[] httpPrinterClasses = {gnu.mapping.OutPort.class }; private static Object portArg = "(port)"; /** A table of names of known output formats. * For each entry, the first Object is the format name. * The next entries are a class name, the name of a static method in that * class, and the parameter types (as a Class[] suitable for getMethod). * The remain values are arguments (passed to invoke), except that if an * argument is the spacial value portArg, it is replaced by the * destination OutPort. */ static Object[][] formats = { { "scheme", "gnu.kawa.functions.DisplayFormat", "getSchemeFormat", boolClasses, Boolean.FALSE }, { "readable-scheme", "gnu.kawa.functions.DisplayFormat", "getSchemeFormat", boolClasses, Boolean.TRUE }, { "elisp", "gnu.kawa.functions.DisplayFormat", "getEmacsLispFormat", boolClasses, Boolean.FALSE }, { "readable-elisp", "gnu.kawa.functions.DisplayFormat", "getEmacsLispFormat", boolClasses, Boolean.TRUE }, { "clisp", "gnu.kawa.functions.DisplayFormat", "getCommonLispFormat", boolClasses, Boolean.FALSE }, { "readable-clisp", "gnu.kawa.functions.DisplayFormat", "getCommonLispFormat", boolClasses, Boolean.TRUE }, { "commonlisp", "gnu.kawa.functions.DisplayFormat", "getCommonLispFormat", boolClasses, Boolean.FALSE }, { "readable-commonlisp", "gnu.kawa.functions.DisplayFormat", "getCommonLispFormat", boolClasses, Boolean.TRUE }, { "xml", "gnu.xml.XMLPrinter", "make", xmlPrinterClasses, portArg, null }, { "html", "gnu.xml.XMLPrinter", "make", xmlPrinterClasses, portArg, "html" }, { "xhtml", "gnu.xml.XMLPrinter", "make", xmlPrinterClasses, portArg, "xhtml" }, { "cgi", "gnu.kawa.xml.HttpPrinter", "make", httpPrinterClasses, portArg }, { "ignore", "gnu.lists.VoidConsumer", "getInstance", noClasses }, { null } }; public static String defaultFormatName; public static Object[] defaultFormatInfo; public static java.lang.reflect.Method defaultFormatMethod; /** Specify the default output format. * @param name The name of the format, as an entry in the formats table. */ public static void setDefaultFormat(String name) { name = name.intern(); defaultFormatName = name; for (int i = 0; ; i++) { Object[] info = formats[i]; Object iname = info[0]; if (iname == null) { System.err.println ("kawa: unknown output format '"+name+"'"); System.exit (-1); } else if (iname == name) { defaultFormatInfo = info; try { Class formatClass = Class.forName((String) info[1]); defaultFormatMethod = formatClass.getMethod((String) info[2], (Class[]) info[3]); } catch (Throwable ex) { System.err.println("kawa: caught "+ex+" while looking for format '"+name+"'"); System.exit (-1); } break; } } if (! defaultFormatInfo[1].equals("gnu.lists.VoidConsumer")) ModuleBody.setMainPrintValues(true); } /** Return a Consumer that formats using the appropriate format. * The format is chosen depending on specified defaults. * @param out The output where formatted output is sent to. */ public static Consumer getOutputConsumer(OutPort out) { Object[] info = defaultFormatInfo; if (out == null) return VoidConsumer.getInstance(); else if (info == null) return Interpreter.getInterpreter().getOutputConsumer(out); try { Object args[] = new Object[info.length - 4]; System.arraycopy(info, 4, args, 0, args.length); for (int i = args.length; --i >= 0; ) if (args[i] == portArg) args[i] = out; Object format = defaultFormatMethod.invoke(null, args); if (format instanceof FormatToConsumer) { out.objectFormat = (FormatToConsumer) format; return out; } else return (Consumer) format; } catch (Throwable ex) { throw new RuntimeException("cannot get output-format '" + defaultFormatName + "' - caught " + ex); } } public static void run (Interpreter interp) { run(interp, interp.getEnvironment()); } public static void run (Interpreter interp, Environment env) { InPort inp = InPort.inDefault (); if (inp instanceof TtyInPort) { Procedure prompter = interp.getPrompter(); if (prompter != null) ((TtyInPort)inp).setPrompter(prompter); } run(interp, env, inp, OutPort.outDefault(), OutPort.errDefault()); } public static void run (Interpreter interp, Environment env, InPort inp, OutPort pout, OutPort perr) { Consumer out; FormatToConsumer saveFormat = null; if (pout != null) saveFormat = pout.objectFormat; out = getOutputConsumer(pout); try { run(interp, env, inp, out, perr); } finally { if (pout != null) pout.objectFormat = saveFormat; } } public static void run (Interpreter interp, Environment env, InPort inp, Consumer out, OutPort perr) { SourceMessages messages = new SourceMessages(); Lexer lexer = interp.getLexer(inp, messages); // Wrong for the case of '-f' '-': boolean interactive = inp instanceof TtyInPort; lexer.setInteractive(interactive); CallContext ctx = CallContext.getInstance(); Consumer saveConsumer = null; if (out != null) { saveConsumer = ctx.consumer; ctx.consumer = out; } try { for (;;) { try { Compilation comp = interp.parse(env, lexer); if (comp == null) // end-of-file break; comp.getModule().setName("atInteractiveLevel"); // FIXME if (lexer.checkErrors(perr, 20)) continue; // Skip whitespace, in case somebody calls (read-char) or similar. int ch; for (;;) { ch = inp.read(); if (ch < 0 || ch == '\r' || ch == '\n') break; if (ch != ' ' && ch != '\t') { inp.unread(); break; } } ModuleExp.evalModule(env, ctx, comp); if (messages.checkErrors(perr, 20)) continue; ctx.runUntilDone(); if (ch < 0) break; } catch (WrongArguments e) { if (e.usage != null) perr.println("usage: "+e.usage); e.printStackTrace(perr); } catch (java.lang.ClassCastException e) { perr.println("Invalid parameter, was: "+ e.getMessage()); e.printStackTrace(perr); } catch (gnu.text.SyntaxException e) { e.printAll(perr, 20); e.clear(); } catch (java.io.IOException e) { messages.printAll(perr, 20); String msg = new SourceError(inp, 'e', "").toString(); msg = msg.substring(0, msg.length() - 2); perr.println(msg + " (or later): caught IOException"); e.printStackTrace(perr); if (! interactive) return; } catch (Throwable e) { e.printStackTrace(perr); if (! interactive) return; } } } finally { if (out != null) ctx.consumer = saveConsumer; } } public static void runString (String str, Interpreter interp, Environment env) { run(interp, env, new CharArrayInPort(str), ModuleBody.getMainPrintValues() ? OutPort.outDefault() : null, OutPort.errDefault()); } public static void runFile (String fname) { Environment env = Environment.getCurrent(); try { if (fname.equals ("-")) kawa.standard.load.loadSource(InPort.inDefault(), env); else kawa.standard.load.apply(fname, env, false); } catch (gnu.text.SyntaxException e) { e.printAll(OutPort.errDefault(), 20); } catch (FileNotFoundException e) { System.err.println("Cannot open file "+fname); System.exit(1); } catch (Throwable e) { e.printStackTrace(System.err); System.exit(1); } } }
kawa/Shell.java
package kawa; import kawa.lang.*; import gnu.kawa.lispexpr.LispReader; import kawa.standard.*; import gnu.mapping.*; import gnu.expr.*; import java.io.*; import gnu.text.*; import gnu.lists.*; /** Utility functions (static methods) for kawa.repl. * Should probably be merged with kawa.repl. FIXME. */ public class Shell { private static Class[] noClasses = { }; private static Class[] boolClasses = { Boolean.TYPE }; private static Class[] xmlPrinterClasses = {gnu.lists.Consumer.class, java.lang.Object.class }; private static Class[] httpPrinterClasses = {gnu.mapping.OutPort.class }; private static Object portArg = "(port)"; /** A table of names of known output formats. * For each entry, the first Object is the format name. * The next entries are a class name, the name of a static method in that * class, and the parameter types (as a Class[] suitable for getMethod). * The remain values are arguments (passed to invoke), except that if an * argument is the spacial value portArg, it is replaced by the * destination OutPort. */ static Object[][] formats = { { "scheme", "gnu.kawa.functions.DisplayFormat", "getSchemeFormat", boolClasses, Boolean.FALSE }, { "readable-scheme", "gnu.kawa.functions.DisplayFormat", "getSchemeFormat", boolClasses, Boolean.TRUE }, { "elisp", "gnu.kawa.functions.DisplayFormat", "getEmacsLispFormat", boolClasses, Boolean.FALSE }, { "readable-elisp", "gnu.kawa.functions.DisplayFormat", "getEmacsLispFormat", boolClasses, Boolean.TRUE }, { "clisp", "gnu.kawa.functions.DisplayFormat", "getCommonLispFormat", boolClasses, Boolean.FALSE }, { "readable-clisp", "gnu.kawa.functions.DisplayFormat", "getCommonLispFormat", boolClasses, Boolean.TRUE }, { "commonlisp", "gnu.kawa.functions.DisplayFormat", "getCommonLispFormat", boolClasses, Boolean.FALSE }, { "readable-commonlisp", "gnu.kawa.functions.DisplayFormat", "getCommonLispFormat", boolClasses, Boolean.TRUE }, { "xml", "gnu.xml.XMLPrinter", "make", xmlPrinterClasses, portArg, null }, { "html", "gnu.xml.XMLPrinter", "make", xmlPrinterClasses, portArg, "html" }, { "xhtml", "gnu.xml.XMLPrinter", "make", xmlPrinterClasses, portArg, "xhtml" }, { "cgi", "gnu.kawa.xml.HttpPrinter", "make", httpPrinterClasses, portArg }, { "ignore", "gnu.lists.VoidConsumer", "getInstance", noClasses }, { null } }; public static String defaultFormatName; public static Object[] defaultFormatInfo; public static java.lang.reflect.Method defaultFormatMethod; /** Specify the default output format. * @param name The name of the format, as an entry in the formats table. */ public static void setDefaultFormat(String name) { name = name.intern(); defaultFormatName = name; for (int i = 0; ; i++) { Object[] info = formats[i]; Object iname = info[0]; if (iname == null) { System.err.println ("kawa: unknown output format '"+name+"'"); System.exit (-1); } else if (iname == name) { defaultFormatInfo = info; try { Class formatClass = Class.forName((String) info[1]); defaultFormatMethod = formatClass.getMethod((String) info[2], (Class[]) info[3]); } catch (Throwable ex) { System.err.println("kawa: caught "+ex+" while looking for format '"+name+"'"); System.exit (-1); } break; } } if (! defaultFormatInfo[1].equals("gnu.lists.VoidConsumer")) ModuleBody.setMainPrintValues(true); } /** Return a Consumer that formats using the appropriate format. * The format is choses depending on specified defaults. * @param out The output where formatted output is sent to. */ public static Consumer getOutputConsumer(OutPort out) { Object[] info = defaultFormatInfo; if (out == null) return VoidConsumer.getInstance(); else if (info == null) return Interpreter.getInterpreter().getOutputConsumer(out); try { Object args[] = new Object[info.length - 4]; System.arraycopy(info, 4, args, 0, args.length); for (int i = args.length; --i >= 0; ) if (args[i] == portArg) args[i] = out; Object format = defaultFormatMethod.invoke(null, args); if (format instanceof FormatToConsumer) { out.objectFormat = (FormatToConsumer) format; return out; } else return (Consumer) format; } catch (Throwable ex) { throw new RuntimeException("cannot get output-format '" + defaultFormatName + "' - caught " + ex); } } public static void run (Interpreter interp) { run(interp, interp.getEnvironment()); } public static void run (Interpreter interp, Environment env) { InPort inp = InPort.inDefault (); if (inp instanceof TtyInPort) { Procedure prompter = interp.getPrompter(); if (prompter != null) ((TtyInPort)inp).setPrompter(prompter); } run(interp, env, inp, OutPort.outDefault(), OutPort.errDefault()); } public static void run (Interpreter interp, Environment env, InPort inp, OutPort pout, OutPort perr) { Consumer out; FormatToConsumer saveFormat = null; if (pout != null) saveFormat = pout.objectFormat; out = getOutputConsumer(pout); try { run(interp, env, inp, out, perr); } finally { if (pout != null) pout.objectFormat = saveFormat; } } public static void run (Interpreter interp, Environment env, InPort inp, Consumer out, OutPort perr) { SourceMessages messages = new SourceMessages(); Lexer lexer = interp.getLexer(inp, messages); // Wrong for the case of '-f' '-': boolean interactive = inp instanceof TtyInPort; lexer.setInteractive(interactive); CallContext ctx = CallContext.getInstance(); Consumer saveConsumer = null; if (out != null) { saveConsumer = ctx.consumer; ctx.consumer = out; } try { for (;;) { try { Compilation comp = interp.parse(env, lexer); if (comp == null) // end-of-file break; comp.getModule().setName("atInteractiveLevel"); // FIXME if (lexer.checkErrors(perr, 20)) continue; // Skip whitespace, in case somebody calls (read-char) or similar. int ch; for (;;) { ch = inp.read(); if (ch < 0 || ch == '\r' || ch == '\n') break; if (ch != ' ' && ch != '\t') { inp.unread(); break; } } ModuleExp.evalModule(env, ctx, comp); if (messages.checkErrors(perr, 20)) continue; ctx.runUntilDone(); if (ch < 0) break; } catch (WrongArguments e) { if (e.usage != null) perr.println("usage: "+e.usage); e.printStackTrace(perr); } catch (java.lang.ClassCastException e) { perr.println("Invalid parameter, was: "+ e.getMessage()); e.printStackTrace(perr); } catch (gnu.text.SyntaxException e) { e.printAll(perr, 20); e.clear(); } catch (java.io.IOException e) { messages.printAll(perr, 20); String msg = new SourceError(inp, 'e', "").toString(); msg = msg.substring(0, msg.length() - 2); perr.println(msg + " (or later): caught IOException"); e.printStackTrace(perr); if (! interactive) return; } catch (Throwable e) { e.printStackTrace(perr); if (! interactive) return; } } } finally { if (out != null) ctx.consumer = saveConsumer; } } public static void runString (String str, Interpreter interp, Environment env) { run(interp, env, new CharArrayInPort(str), ModuleBody.getMainPrintValues() ? OutPort.outDefault() : null, OutPort.errDefault()); } public static void runFile (String fname) { Environment env = Environment.getCurrent(); try { if (fname.equals ("-")) kawa.standard.load.loadSource(InPort.inDefault(), env); else kawa.standard.load.apply(fname, env, false); } catch (gnu.text.SyntaxException e) { e.printAll(OutPort.errDefault(), 20); } catch (FileNotFoundException e) { System.err.println("Cannot open file "+fname); System.exit(1); } catch (Throwable e) { e.printStackTrace(System.err); System.exit(1); } } }
Fix typo in comment. git-svn-id: 169764d5f12c41a1cff66b81d896619f3ce5473d@3224 5e0a886f-7f45-49c5-bc19-40643649e37f
kawa/Shell.java
Fix typo in comment.
<ide><path>awa/Shell.java <ide> } <ide> <ide> /** Return a Consumer that formats using the appropriate format. <del> * The format is choses depending on specified defaults. <add> * The format is chosen depending on specified defaults. <ide> * @param out The output where formatted output is sent to. <ide> */ <ide> public static Consumer getOutputConsumer(OutPort out)
Java
apache-2.0
a6c4cdaba3b1a38fec08b6bb0ea0d562c8202cd5
0
wso2/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent; import org.apache.axiom.om.OMElement; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.claim.mgt.ClaimManagementException; import org.wso2.carbon.consent.mgt.core.ConsentManager; import org.wso2.carbon.consent.mgt.core.exception.ConsentManagementClientException; import org.wso2.carbon.consent.mgt.core.exception.ConsentManagementException; import org.wso2.carbon.consent.mgt.core.model.AddReceiptResponse; import org.wso2.carbon.consent.mgt.core.model.ConsentPurpose; import org.wso2.carbon.consent.mgt.core.model.PIICategory; import org.wso2.carbon.consent.mgt.core.model.PIICategoryValidity; import org.wso2.carbon.consent.mgt.core.model.Purpose; import org.wso2.carbon.consent.mgt.core.model.PurposeCategory; import org.wso2.carbon.consent.mgt.core.model.Receipt; import org.wso2.carbon.consent.mgt.core.model.ReceiptInput; import org.wso2.carbon.consent.mgt.core.model.ReceiptListResponse; import org.wso2.carbon.consent.mgt.core.model.ReceiptPurposeInput; import org.wso2.carbon.consent.mgt.core.model.ReceiptService; import org.wso2.carbon.consent.mgt.core.model.ReceiptServiceInput; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants; import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentDisabledException; import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException; import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceDataHolder; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.application.common.model.ServiceProvider; import org.wso2.carbon.identity.application.common.model.User; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementService; import org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException; import org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim; import org.wso2.carbon.identity.core.util.IdentityConfigParser; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; 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 java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.xml.namespace.QName; import static org.apache.commons.collections.CollectionUtils.isEmpty; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; import static org.apache.commons.collections.MapUtils.isNotEmpty; import static org.apache.commons.lang.ArrayUtils.isEmpty; import static org.apache.commons.lang.StringUtils.EMPTY; import static org.apache.commons.lang.StringUtils.isBlank; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.wso2.carbon.consent.mgt.core.constant.ConsentConstants.ACTIVE_STATE; import static org.wso2.carbon.consent.mgt.core.constant.ConsentConstants.ErrorMessages.ERROR_CODE_PII_CAT_NAME_INVALID; import static org.wso2.carbon.consent.mgt.core.constant.ConsentConstants.ErrorMessages.ERROR_CODE_PURPOSE_CAT_NAME_INVALID; import static org.wso2.carbon.consent.mgt.core.constant.ConsentConstants.ErrorMessages.ERROR_CODE_PURPOSE_NAME_INVALID; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONFIG_ELEM_CONSENT; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONFIG_ELEM_ENABLE_SSO_CONSENT_MANAGEMENT; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONFIG_PROMPT_SUBJECT_CLAIM_REQUESTED_CONSENT; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONSENT_VALIDITY_TYPE_SEPARATOR; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONSENT_VALIDITY_TYPE_VALID_UNTIL; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONSENT_VALIDITY_TYPE_VALID_UNTIL_INDEFINITE; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.FEDERATED_USER_DOMAIN_PREFIX; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.FEDERATED_USER_DOMAIN_SEPARATOR; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.USERNAME_CLAIM; import static org.wso2.carbon.identity.claim.metadata.mgt.util.ClaimConstants.DESCRIPTION_PROPERTY; import static org.wso2.carbon.identity.claim.metadata.mgt.util.ClaimConstants.DISPLAY_NAME_PROPERTY; import static org.wso2.carbon.identity.core.util.IdentityCoreConstants.IDENTITY_DEFAULT_NAMESPACE; /** * Implementation of {@link SSOConsentService}. */ public class SSOConsentServiceImpl implements SSOConsentService { private static final Log log = LogFactory.getLog(SSOConsentServiceImpl.class); private static final String DEFAULT_PURPOSE = "DEFAULT"; private static final String DEFAULT_PURPOSE_CATEGORY = "DEFAULT"; private static final String DEFAULT_PURPOSE_GROUP = "DEFAULT"; private static final String DEFAULT_PURPOSE_GROUP_TYPE = "SP"; private boolean ssoConsentEnabled = true; public SSOConsentServiceImpl() { readSSOConsentEnabledConfig(); } /** * Get consent required claims for a given service from a user considering existing user consents. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ @Override public ConsentClaimsData getConsentRequiredClaimsWithExistingConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser) throws SSOConsentServiceException { return getConsentRequiredClaims(serviceProvider, authenticatedUser, true, null); } /** * Get consent required claims for a given service from a user considering existing user consents. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @param claimsListOfScopes Claims list of requested scopes. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ @Override public ConsentClaimsData getConsentRequiredClaimsWithExistingConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, List<String> claimsListOfScopes) throws SSOConsentServiceException { return getConsentRequiredClaims(serviceProvider, authenticatedUser, true, claimsListOfScopes); } /** * Get consent required claims for a given service from a user ignoring existing user consents. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ @Override public ConsentClaimsData getConsentRequiredClaimsWithoutExistingConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser) throws SSOConsentServiceException { return getConsentRequiredClaims(serviceProvider, authenticatedUser, false, null); } /** * Get consent required claims for a given service from a user ignoring existing user consents and considering * requested scopes. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @param claimsListOfScopes Claims list of requested scopes. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ @Override public ConsentClaimsData getConsentRequiredClaimsWithoutExistingConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, List<String> claimsListOfScopes) throws SSOConsentServiceException { return getConsentRequiredClaims(serviceProvider, authenticatedUser, false, claimsListOfScopes); } /** * Get consent required claims for a given service from a user. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @param useExistingConsents Use existing consent given by the user. * @param claimsListOfScopes Claims list of requested scopes. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ protected ConsentClaimsData getConsentRequiredClaims(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, boolean useExistingConsents, List<String> claimsListOfScopes) throws SSOConsentServiceException { if (!isSSOConsentManagementEnabled(serviceProvider)) { String message = "Consent management for SSO is disabled."; throw new SSOConsentDisabledException(message, message); } if (serviceProvider == null) { throw new SSOConsentServiceException("Service provider cannot be null."); } String spName = serviceProvider.getApplicationName(); String spTenantDomain = getSPTenantDomain(serviceProvider); String subject = buildSubjectWithUserStoreDomain(authenticatedUser); String tenantDomain = authenticatedUser.getTenantDomain(); ClaimMapping[] claimMappings = getSpClaimMappings(serviceProvider); if (claimMappings == null || claimMappings.length == 0) { if (log.isDebugEnabled()) { log.debug("No claim mapping configured from the application. Hence skipping getting consent."); } return new ConsentClaimsData(); } if (claimsListOfScopes != null) { try { claimMappings = FrameworkUtils.getFilteredScopeClaims(claimsListOfScopes, Arrays.asList(claimMappings), tenantDomain).toArray(new ClaimMapping[0]); } catch (ClaimManagementException e) { throw new SSOConsentServiceException("Error occurred while filtering claims of requested scopes"); } } List<String> requestedClaims = new ArrayList<>(); List<String> mandatoryClaims = new ArrayList<>(); Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes(); String subjectClaimUri = getSubjectClaimUri(serviceProvider); boolean subjectClaimUriRequested = false; boolean subjectClaimUriMandatory = false; boolean promptSubjectClaimRequestedConsent = true; if (StringUtils.isNotBlank(IdentityUtil.getProperty(CONFIG_PROMPT_SUBJECT_CLAIM_REQUESTED_CONSENT))) { promptSubjectClaimRequestedConsent = Boolean.parseBoolean(IdentityUtil.getProperty(CONFIG_PROMPT_SUBJECT_CLAIM_REQUESTED_CONSENT)); } if (isPassThroughScenario(claimMappings, userAttributes)) { for (Map.Entry<ClaimMapping, String> userAttribute : userAttributes.entrySet()) { String remoteClaimUri = userAttribute.getKey().getRemoteClaim().getClaimUri(); if (subjectClaimUri.equals(remoteClaimUri) || IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR.equals(remoteClaimUri)) { continue; } mandatoryClaims.add(remoteClaimUri); } } else { boolean isCustomClaimMapping = isCustomClaimMapping(serviceProvider); for (ClaimMapping claimMapping : claimMappings) { if (isCustomClaimMapping) { if (subjectClaimUri.equals(claimMapping.getRemoteClaim().getClaimUri())) { subjectClaimUri = claimMapping.getLocalClaim().getClaimUri(); if (promptSubjectClaimRequestedConsent) { if (claimMapping.isMandatory()) { subjectClaimUriMandatory = true; } else if (claimMapping.isRequested()) { subjectClaimUriRequested = true; } } continue; } } else { if (subjectClaimUri.equals(claimMapping.getLocalClaim().getClaimUri())) { if (promptSubjectClaimRequestedConsent) { if (claimMapping.isMandatory()) { subjectClaimUriMandatory = true; } else if (claimMapping.isRequested()) { subjectClaimUriRequested = true; } } continue; } } if (claimMapping.isMandatory()) { mandatoryClaims.add(claimMapping.getLocalClaim().getClaimUri()); } else if (claimMapping.isRequested()) { requestedClaims.add(claimMapping.getLocalClaim().getClaimUri()); } } } if (promptSubjectClaimRequestedConsent) { if (subjectClaimUriMandatory) { mandatoryClaims.add(subjectClaimUri); } else if (subjectClaimUriRequested) { requestedClaims.add(subjectClaimUri); } } List<ClaimMetaData> receiptConsentMetaData = new ArrayList<>(); List<ClaimMetaData> receiptConsentDeniedMetaData; Receipt receipt = getConsentReceiptOfUser(serviceProvider, authenticatedUser, spName, spTenantDomain, subject); if (useExistingConsents && receipt != null) { receiptConsentMetaData = getRequestedClaimsFromReceipt(receipt, true); List<String> claimsWithConsent = getClaimsFromConsentMetaData(receiptConsentMetaData); receiptConsentDeniedMetaData = getRequestedClaimsFromReceipt(receipt, false); List<String> claimsDeniedConsent = getClaimsFromConsentMetaData(receiptConsentDeniedMetaData); mandatoryClaims.removeAll(claimsWithConsent); requestedClaims.removeAll(claimsWithConsent); requestedClaims.removeAll(claimsDeniedConsent); } ConsentClaimsData consentClaimsData = getConsentRequiredClaimData(mandatoryClaims, requestedClaims, spTenantDomain); consentClaimsData.setClaimsWithConsent(receiptConsentMetaData); return consentClaimsData; } private boolean isCustomClaimMapping(ServiceProvider serviceProvider) { return !serviceProvider.getClaimConfig().isLocalClaimDialect(); } private boolean isPassThroughScenario(ClaimMapping[] claimMappings, Map<ClaimMapping, String> userAttributes) { return isEmpty(claimMappings) && isNotEmpty(userAttributes); } private String getSubjectClaimUri(ServiceProvider serviceProvider) { String subjectClaimUri = serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSubjectClaimUri(); if (isBlank(subjectClaimUri)) { subjectClaimUri = USERNAME_CLAIM; } return subjectClaimUri; } private void readSSOConsentEnabledConfig() { IdentityConfigParser identityConfigParser = IdentityConfigParser.getInstance(); OMElement consentElement = identityConfigParser.getConfigElement(CONFIG_ELEM_CONSENT); if (consentElement != null) { OMElement ssoConsentEnabledElem = consentElement.getFirstChildWithName( new QName(IDENTITY_DEFAULT_NAMESPACE, CONFIG_ELEM_ENABLE_SSO_CONSENT_MANAGEMENT)); if (ssoConsentEnabledElem != null) { String ssoConsentEnabledElemText = ssoConsentEnabledElem.getText(); if (isNotBlank(ssoConsentEnabledElemText)) { ssoConsentEnabled = Boolean.parseBoolean(ssoConsentEnabledElemText); if (isDebugEnabled()) { logDebug("Consent management for SSO is set to " + ssoConsentEnabled + " from configurations."); } return; } } } ssoConsentEnabled = true; } private ClaimMapping[] getSpClaimMappings(ServiceProvider serviceProvider) { if (serviceProvider.getClaimConfig() != null) { return serviceProvider.getClaimConfig().getClaimMappings(); } else { return new ClaimMapping[0]; } } private String getSPTenantDomain(ServiceProvider serviceProvider) { String spTenantDomain; User owner = serviceProvider.getOwner(); if (owner != null) { spTenantDomain = owner.getTenantDomain(); } else { spTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } return spTenantDomain; } /** * Process the provided user consent and creates a consent receipt. * * @param consentApprovedClaimIds Consent approved claims by the user. * @param serviceProvider Service provider receiving consent. * @param authenticatedUser Authenticated user providing consent. * @param consentClaimsData Claims which the consent requested for. * @throws SSOConsentServiceException If error occurs while processing user consent. */ @Override public void processConsent(List<Integer> consentApprovedClaimIds, ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, ConsentClaimsData consentClaimsData) throws SSOConsentServiceException { processConsent(consentApprovedClaimIds, serviceProvider, authenticatedUser, consentClaimsData, false); } @Override public void processConsent(List<Integer> consentApprovedClaimIds, ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, ConsentClaimsData consentClaimsData, boolean overrideExistingConsent) throws SSOConsentServiceException { if (!isSSOConsentManagementEnabled(serviceProvider)) { String message = "Consent management for SSO is disabled."; throw new SSOConsentDisabledException(message, message); } if (isDebugEnabled()) { logDebug("User: " + authenticatedUser.getAuthenticatedSubjectIdentifier() + " has approved consent."); } UserConsent userConsent = processUserConsent(consentApprovedClaimIds, consentClaimsData); if (isEmpty(userConsent.getApprovedClaims()) && isEmpty(userConsent.getDisapprovedClaims())) { if (isDebugEnabled()) { logDebug("User: " + authenticatedUser.getAuthenticatedSubjectIdentifier() + " has not provided new " + "approved/disapproved consent. Hence skipping the consent progress."); } return; } String subject = buildSubjectWithUserStoreDomain(authenticatedUser); List<ClaimMetaData> claimsWithConsent; List<ClaimMetaData> claimsDeniedConsent; if (!overrideExistingConsent) { String spName = serviceProvider.getApplicationName(); String spTenantDomain = getSPTenantDomain(serviceProvider); Receipt receipt = getConsentReceiptOfUser(serviceProvider, authenticatedUser, spName, spTenantDomain, subject); claimsWithConsent = getUserRequestedClaims(receipt, userConsent, true); claimsDeniedConsent = getUserRequestedClaims(receipt, userConsent, false); } else { claimsWithConsent = userConsent.getApprovedClaims(); claimsDeniedConsent = userConsent.getDisapprovedClaims(); } String spTenantDomain = getSPTenantDomain(serviceProvider); String subjectTenantDomain = authenticatedUser.getTenantDomain(); if (isNotEmpty(claimsWithConsent) || isNotEmpty(claimsDeniedConsent)) { addReceipt(subject, subjectTenantDomain, serviceProvider, spTenantDomain, claimsWithConsent, claimsDeniedConsent); } } /** * Retrieves claims which a user has provided consent for a given service provider. * * @param serviceProvider Service provider to retrieve the consent against. * @param authenticatedUser Authenticated user to related to consent claim retrieval. * @return List of claim which the user has provided consent for the given service provider. * @throws SSOConsentServiceException If error occurs while retrieve user consents. */ @Override public List<ClaimMetaData> getClaimsWithConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser) throws SSOConsentServiceException { if (!isSSOConsentManagementEnabled(serviceProvider)) { String message = "Consent management for SSO is disabled."; throw new SSOConsentDisabledException(message, message); } if (serviceProvider == null) { throw new SSOConsentServiceException("Service provider cannot be null."); } String spName = serviceProvider.getApplicationName(); List<ClaimMetaData> receiptConsentMetaData = new ArrayList<>(); String spTenantDomain = getSPTenantDomain(serviceProvider); String subject = buildSubjectWithUserStoreDomain(authenticatedUser); Receipt receipt = getConsentReceiptOfUser(serviceProvider, authenticatedUser, spName, spTenantDomain, subject); if (receipt == null) { return receiptConsentMetaData; } else { receiptConsentMetaData = getRequestedClaimsFromReceipt(receipt, true); } return receiptConsentMetaData; } /** * Specifies whether consent management for SSO is enabled or disabled. * * @param serviceProvider Service provider to check whether consent management is enabled. * @return true if enabled, false otherwise. */ @Override public boolean isSSOConsentManagementEnabled(ServiceProvider serviceProvider) { return ssoConsentEnabled; } private Receipt getConsentReceiptOfUser(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, String spName, String spTenantDomain, String subject) throws SSOConsentServiceException { int receiptListLimit = 2; List<ReceiptListResponse> receiptListResponses; try { receiptListResponses = getReceiptListOfUserForSP(authenticatedUser, spName, spTenantDomain, subject, receiptListLimit); if (isDebugEnabled()) { String message = String.format("Retrieved %s receipts for user: %s, service provider: %s in tenant " + "domain %s", receiptListResponses.size(), subject, serviceProvider, spTenantDomain); logDebug(message); } if (hasUserMultipleReceipts(receiptListResponses)) { throw new SSOConsentServiceException("Consent Management Error", "User cannot have more than one " + "ACTIVE consent per service provider."); } else if (hasUserSingleReceipt(receiptListResponses)) { String receiptId = getFirstConsentReceiptFromList(receiptListResponses); return getReceipt(authenticatedUser, receiptId); } else { return null; } } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent Management Error", "Error while retrieving user consents.", e); } } private void addReceipt(String subject, String subjectTenantDomain, ServiceProvider serviceProvider, String spTenantDomain, List<ClaimMetaData> claimsWithConsent, List<ClaimMetaData> claimsDeniedConsent) throws SSOConsentServiceException { ReceiptInput receiptInput = buildReceiptInput(subject, serviceProvider, spTenantDomain, claimsWithConsent, claimsDeniedConsent); AddReceiptResponse receiptResponse; try { startTenantFlowWithUser(subject, subjectTenantDomain); receiptResponse = getConsentManager().addConsent(receiptInput); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent receipt error", "Error while adding the consent " + "receipt", e); } finally { PrivilegedCarbonContext.endTenantFlow(); } if (isDebugEnabled()) { logDebug("Successfully added consent receipt: " + receiptResponse.getConsentReceiptId()); } } private ReceiptInput buildReceiptInput(String subject, ServiceProvider serviceProvider, String spTenantDomain, List<ClaimMetaData> claimsWithConsent, List<ClaimMetaData> claimsDeniedConsent) throws SSOConsentServiceException { String collectionMethod = "Web Form - Sign-in"; String jurisdiction = "NONE"; String language = "us_EN"; String consentType = "EXPLICIT"; String termination = CONSENT_VALIDITY_TYPE_VALID_UNTIL + CONSENT_VALIDITY_TYPE_SEPARATOR + CONSENT_VALIDITY_TYPE_VALID_UNTIL_INDEFINITE; String policyUrl = "NONE"; Purpose purpose = getDefaultPurpose(); PurposeCategory purposeCategory = getDefaultPurposeCategory(); List<PIICategoryValidity> piiCategoryIds = getPiiCategoryValidityForClaims(claimsWithConsent, claimsDeniedConsent, termination); List<ReceiptServiceInput> serviceInputs = new ArrayList<>(); List<ReceiptPurposeInput> purposeInputs = new ArrayList<>(); List<Integer> purposeCategoryIds = new ArrayList<>(); Map<String, String> properties = new HashMap<>(); purposeCategoryIds.add(purposeCategory.getId()); ReceiptPurposeInput purposeInput = getReceiptPurposeInput(consentType, termination, purpose, piiCategoryIds, purposeCategoryIds); purposeInputs.add(purposeInput); ReceiptServiceInput serviceInput = getReceiptServiceInput(serviceProvider, spTenantDomain, purposeInputs); serviceInputs.add(serviceInput); return getReceiptInput(subject, collectionMethod, jurisdiction, language, policyUrl, serviceInputs, properties); } private ReceiptInput getReceiptInput(String subject, String collectionMethod, String jurisdiction, String language, String policyUrl, List<ReceiptServiceInput> serviceInputs, Map<String, String> properties) { ReceiptInput receiptInput = new ReceiptInput(); receiptInput.setCollectionMethod(collectionMethod); receiptInput.setJurisdiction(jurisdiction); receiptInput.setLanguage(language); receiptInput.setPolicyUrl(policyUrl); receiptInput.setServices(serviceInputs); receiptInput.setProperties(properties); receiptInput.setPiiPrincipalId(subject); return receiptInput; } private ReceiptServiceInput getReceiptServiceInput(ServiceProvider serviceProvider, String spTenantDomain, List<ReceiptPurposeInput> purposeInputs) { ReceiptServiceInput serviceInput = new ReceiptServiceInput(); serviceInput.setPurposes(purposeInputs); serviceInput.setTenantDomain(spTenantDomain); if (serviceProvider == null) { return serviceInput; } String spName = serviceProvider.getApplicationName(); String spDescription; spDescription = serviceProvider.getDescription(); if (StringUtils.isBlank(spDescription)) { spDescription = spName; } serviceInput.setService(spName); serviceInput.setSpDisplayName(spName); serviceInput.setSpDescription(spDescription); return serviceInput; } private ReceiptPurposeInput getReceiptPurposeInput(String consentType, String termination, Purpose purpose, List<PIICategoryValidity> piiCategoryIds, List<Integer> purposeCategoryIds) { ReceiptPurposeInput purposeInput = new ReceiptPurposeInput(); purposeInput.setPrimaryPurpose(true); purposeInput.setTermination(termination); purposeInput.setConsentType(consentType); purposeInput.setThirdPartyDisclosure(false); purposeInput.setPurposeId(purpose.getId()); purposeInput.setPurposeCategoryId(purposeCategoryIds); purposeInput.setPiiCategory(piiCategoryIds); return purposeInput; } private List<PIICategoryValidity> getPiiCategoryValidityForClaims(List<ClaimMetaData> claimsWithConsent, List<ClaimMetaData> claimsDeniedConsent, String termination) throws SSOConsentServiceException { List<PIICategoryValidity> piiCategoryIds = new ArrayList<>(); List<PIICategoryValidity> piiCategoryIdsForClaimsWithConsent = getPiiCategoryValidityForRequestedClaims(claimsWithConsent, true, termination); List<PIICategoryValidity> piiCategoryIdsForDeniedConsentClaims = getPiiCategoryValidityForRequestedClaims(claimsDeniedConsent, false, termination); piiCategoryIds.addAll(piiCategoryIdsForClaimsWithConsent); piiCategoryIds.addAll(piiCategoryIdsForDeniedConsentClaims); return piiCategoryIds; } private List<PIICategoryValidity> getPiiCategoryValidityForRequestedClaims(List<ClaimMetaData> requestedClaims, boolean isConsented, String termination) throws SSOConsentServiceException { List<PIICategoryValidity> piiCategoryIds = new ArrayList<>(); if (CollectionUtils.isEmpty(requestedClaims)) { return piiCategoryIds; } for (ClaimMetaData requestedClaim : requestedClaims) { if (requestedClaim == null || requestedClaim.getClaimUri() == null) { continue; } PIICategory piiCategory; try { piiCategory = getConsentManager().getPIICategoryByName(requestedClaim.getClaimUri()); } catch (ConsentManagementClientException e) { if (isInvalidPIICategoryError(e)) { piiCategory = addPIICategoryForClaim(requestedClaim); } else { throw new SSOConsentServiceException("Consent PII category error", "Error while retrieving" + " PII category: " + DEFAULT_PURPOSE_CATEGORY, e); } } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent PII category error", "Error while retrieving " + "PII category: " + DEFAULT_PURPOSE_CATEGORY, e); } PIICategoryValidity piiCategoryValidity = new PIICategoryValidity(piiCategory.getId(), termination); piiCategoryValidity.setConsented(isConsented); piiCategoryIds.add(piiCategoryValidity); } return piiCategoryIds; } private PIICategory addPIICategoryForClaim(ClaimMetaData claim) throws SSOConsentServiceException { PIICategory piiCategory; PIICategory piiCategoryInput = new PIICategory(claim.getClaimUri(), claim.getDescription(), false, claim .getDisplayName()); try { piiCategory = getConsentManager().addPIICategory(piiCategoryInput); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent PII category error", "Error while adding" + " PII category:" + DEFAULT_PURPOSE_CATEGORY, e); } return piiCategory; } private boolean isInvalidPIICategoryError(ConsentManagementClientException e) { return ERROR_CODE_PII_CAT_NAME_INVALID.getCode().equals(e.getErrorCode()); } private PurposeCategory getDefaultPurposeCategory() throws SSOConsentServiceException { PurposeCategory purposeCategory; try { purposeCategory = getConsentManager().getPurposeCategoryByName(DEFAULT_PURPOSE_CATEGORY); } catch (ConsentManagementClientException e) { if (isInvalidPurposeCategoryError(e)) { purposeCategory = addDefaultPurposeCategory(); } else { throw new SSOConsentServiceException("Consent purpose category error", "Error while retrieving" + " purpose category: " + DEFAULT_PURPOSE_CATEGORY, e); } } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent purpose category error", "Error while retrieving " + "purpose category: " + DEFAULT_PURPOSE_CATEGORY, e); } return purposeCategory; } private PurposeCategory addDefaultPurposeCategory() throws SSOConsentServiceException { PurposeCategory purposeCategory; PurposeCategory defaultPurposeCategory = new PurposeCategory(DEFAULT_PURPOSE_CATEGORY, "For core functionalities of the product"); try { purposeCategory = getConsentManager().addPurposeCategory(defaultPurposeCategory); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent purpose category error", "Error while adding" + " purpose category: " + DEFAULT_PURPOSE_CATEGORY, e); } return purposeCategory; } private boolean isInvalidPurposeCategoryError(ConsentManagementClientException e) { return ERROR_CODE_PURPOSE_CAT_NAME_INVALID.getCode().equals(e.getErrorCode()); } private Purpose getDefaultPurpose() throws SSOConsentServiceException { Purpose purpose; try { purpose = getConsentManager().getPurposeByName(DEFAULT_PURPOSE, DEFAULT_PURPOSE_GROUP, DEFAULT_PURPOSE_GROUP_TYPE); } catch (ConsentManagementClientException e) { if (isInvalidPurposeError(e)) { purpose = addDefaultPurpose(); } else { throw new SSOConsentServiceException("Consent purpose error", "Error while retrieving purpose: " + DEFAULT_PURPOSE, e); } } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent purpose error", "Error while retrieving purpose: " + DEFAULT_PURPOSE, e); } return purpose; } private Purpose addDefaultPurpose() throws SSOConsentServiceException { Purpose purpose; Purpose defaultPurpose = new Purpose(DEFAULT_PURPOSE, "For core functionalities of the product", DEFAULT_PURPOSE_GROUP, DEFAULT_PURPOSE_GROUP_TYPE); try { purpose = getConsentManager().addPurpose(defaultPurpose); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent purpose error", "Error while adding purpose: " + DEFAULT_PURPOSE, e); } return purpose; } private boolean isInvalidPurposeError(ConsentManagementClientException e) { return ERROR_CODE_PURPOSE_NAME_INVALID.getCode().equals(e.getErrorCode()); } private UserConsent processUserConsent(List<Integer> consentApprovedClaimIds, ConsentClaimsData consentClaimsData) throws SSOConsentServiceException { UserConsent userConsent = new UserConsent(); List<ClaimMetaData> approvedClamMetaData = buildApprovedClaimList(consentApprovedClaimIds, consentClaimsData); List<ClaimMetaData> consentRequiredClaimMetaData = getConsentRequiredClaimMetaData(consentClaimsData); List<ClaimMetaData> disapprovedClaims = buildDisapprovedClaimList(consentRequiredClaimMetaData, approvedClamMetaData); if (isMandatoryClaimsDisapproved(consentClaimsData.getMandatoryClaims(), disapprovedClaims)) { throw new SSOConsentServiceException("Consent Denied for Mandatory Attributes", "User denied consent to share mandatory attributes."); } userConsent.setApprovedClaims(approvedClamMetaData); userConsent.setDisapprovedClaims(disapprovedClaims); return userConsent; } private List<ClaimMetaData> getUserRequestedClaims(Receipt receipt, UserConsent userConsent, boolean isConsented) { List<ClaimMetaData> requestedClaims = new ArrayList<>(); if (isConsented) { requestedClaims.addAll(userConsent.getApprovedClaims()); } else { requestedClaims.addAll(userConsent.getDisapprovedClaims()); } if (receipt == null) { return requestedClaims; } List<PIICategoryValidity> piiCategoriesFromServices = getPIICategoriesFromServices(receipt.getServices()); if (isConsented) { piiCategoriesFromServices.removeIf(piiCategoryValidity -> !piiCategoryValidity.isConsented()); } else { piiCategoriesFromServices.removeIf(PIICategoryValidity::isConsented); } List<ClaimMetaData> claimsFromPIICategoryValidity = getClaimsFromPIICategoryValidity(piiCategoriesFromServices); requestedClaims.addAll(claimsFromPIICategoryValidity); /* When consent denied requested claim is updated as mandatory, that claim should remove from the requested denied claims list. */ if (!isConsented && CollectionUtils.isNotEmpty(requestedClaims) && CollectionUtils.isNotEmpty(userConsent.getApprovedClaims())) { requestedClaims.removeAll(userConsent.getApprovedClaims()); } return getDistinctClaims(requestedClaims); } private List<ClaimMetaData> getDistinctClaims(List<ClaimMetaData> claimsWithConsent) { return claimsWithConsent.stream() .filter(distinctByKey(ClaimMetaData::getClaimUri)) .collect(Collectors.toList()); } private Predicate<ClaimMetaData> distinctByKey(Function<ClaimMetaData, String> keyExtractor) { final Set<String> claimUris = new HashSet<>(); return claimUri -> claimUris.add(keyExtractor.apply(claimUri)); } private List<ClaimMetaData> getConsentRequiredClaimMetaData(ConsentClaimsData consentClaimsData) { List<ClaimMetaData> consentRequiredClaims = new ArrayList<>(); if (isNotEmpty(consentClaimsData.getMandatoryClaims())) { consentRequiredClaims.addAll(consentClaimsData.getMandatoryClaims()); } if (isNotEmpty(consentClaimsData.getRequestedClaims())) { consentRequiredClaims.addAll(consentClaimsData.getRequestedClaims()); } return consentRequiredClaims; } private List<ClaimMetaData> buildDisapprovedClaimList(List<ClaimMetaData> consentRequiredClaims, List<ClaimMetaData> approvedClaims) { List<ClaimMetaData> disapprovedClaims = new ArrayList<>(); if (isNotEmpty(consentRequiredClaims)) { consentRequiredClaims.removeAll(approvedClaims); disapprovedClaims = consentRequiredClaims; } return disapprovedClaims; } private List<ClaimMetaData> buildApprovedClaimList(List<Integer> consentApprovedClaimIds, ConsentClaimsData consentClaimsData) { List<ClaimMetaData> approvedClaims = new ArrayList<>(); for (Integer claimId : consentApprovedClaimIds) { ClaimMetaData consentClaim = new ClaimMetaData(); consentClaim.setId(claimId); List<ClaimMetaData> mandatoryClaims = consentClaimsData.getMandatoryClaims(); int claimIndex = mandatoryClaims.indexOf(consentClaim); if (claimIndex != -1) { approvedClaims.add(mandatoryClaims.get(claimIndex)); } List<ClaimMetaData> requestedClaims = consentClaimsData.getRequestedClaims(); claimIndex = requestedClaims.indexOf(consentClaim); if (claimIndex != -1) { approvedClaims.add(requestedClaims.get(claimIndex)); } } return approvedClaims; } private String buildSubjectWithUserStoreDomain(AuthenticatedUser authenticatedUser) { String userStoreDomain; if (authenticatedUser.isFederatedUser()) { userStoreDomain = getFederatedUserDomain(authenticatedUser.getFederatedIdPName()); } else { userStoreDomain = authenticatedUser.getUserStoreDomain(); } return UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), userStoreDomain); } private String getFederatedUserDomain(String authenticatedIDP) { if (isNotBlank(authenticatedIDP)) { return FEDERATED_USER_DOMAIN_PREFIX + FEDERATED_USER_DOMAIN_SEPARATOR + authenticatedIDP; } else { return FEDERATED_USER_DOMAIN_PREFIX; } } private List<ReceiptListResponse> getReceiptListOfUserForSP(AuthenticatedUser authenticatedUser, String serviceProvider, String spTenantDomain, String subject, int limit) throws ConsentManagementException { List<ReceiptListResponse> receiptListResponses; startTenantFlowWithUser(subject, authenticatedUser.getTenantDomain()); try { receiptListResponses = getConsentManager().searchReceipts(limit, 0, subject, spTenantDomain, serviceProvider, ACTIVE_STATE); } finally { PrivilegedCarbonContext.endTenantFlow(); } return receiptListResponses; } private List<PIICategoryValidity> getPIICategoriesFromServices(List<ReceiptService> receiptServices) { List<PIICategoryValidity> piiCategoryValidityMap = new ArrayList<>(); for (ReceiptService receiptService : receiptServices) { List<ConsentPurpose> purposes = receiptService.getPurposes(); for (ConsentPurpose purpose : purposes) { piiCategoryValidityMap.addAll(piiCategoryValidityMap.size(), purpose.getPiiCategory()); } } return piiCategoryValidityMap; } private List<ClaimMetaData> getRequestedClaimsFromReceipt(Receipt receipt, boolean isConsented) { List<ReceiptService> services = receipt.getServices(); List<PIICategoryValidity> piiCategories = getPIICategoriesFromServices(services); if (isConsented) { piiCategories.removeIf(piiCategoryValidity -> !piiCategoryValidity.isConsented()); } else { piiCategories.removeIf(PIICategoryValidity::isConsented); } List<ClaimMetaData> claimsFromPIICategoryValidity = getClaimsFromPIICategoryValidity(piiCategories); if (isDebugEnabled()) { String message = String.format("User: %s has provided consent in receipt: %s for claims: " + claimsFromPIICategoryValidity, receipt.getPiiPrincipalId(), receipt.getConsentReceiptId()); logDebug(message); } return claimsFromPIICategoryValidity; } private List<ClaimMetaData> getClaimsFromPIICategoryValidity(List<PIICategoryValidity> piiCategories) { List<ClaimMetaData> claimMetaDataList = new ArrayList<>(); for (PIICategoryValidity piiCategoryValidity : piiCategories) { if (isConsentForClaimValid(piiCategoryValidity)) { ClaimMetaData claimMetaData = new ClaimMetaData(); claimMetaData.setClaimUri(piiCategoryValidity.getName()); claimMetaData.setDisplayName(piiCategoryValidity.getDisplayName()); claimMetaDataList.add(claimMetaData); } } return claimMetaDataList; } protected boolean isConsentForClaimValid(PIICategoryValidity piiCategoryValidity) { String consentValidity = piiCategoryValidity.getValidity(); if (isEmpty(consentValidity)) { return true; } List<String> consentValidityEntries = Arrays.asList(consentValidity.split(SSOConsentConstants .CONSENT_VALIDITY_SEPARATOR)); for (String consentValidityEntry : consentValidityEntries) { if (isSupportedExpiryType(consentValidityEntry)) { String[] validityEntry = consentValidityEntry.split(CONSENT_VALIDITY_TYPE_SEPARATOR, 2); if (validityEntry.length == 2) { try { String validTime = validityEntry[1]; if (isDebugEnabled()) { String message = String.format("Validity time for PII category: %s is %s.", piiCategoryValidity.getName(), validTime); logDebug(message); } if (isExpiryIndefinite(validTime)) { return true; } long consentExpiryInMillis = Long.parseLong(validTime); long currentTimeMillis = System.currentTimeMillis(); return isExpired(currentTimeMillis, consentExpiryInMillis); } catch (NumberFormatException e) { if (isDebugEnabled()) { String message = String.format("Cannot parse timestamp: %s. for PII category %s.", consentValidity, piiCategoryValidity.getName()); logDebug(message); } } } return false; } } return true; } private boolean isSupportedExpiryType(String consentValidityEntry) { return consentValidityEntry.toUpperCase().startsWith(CONSENT_VALIDITY_TYPE_VALID_UNTIL); } private boolean isExpired(long currentTimeMillis, long consentExpiryInMillis) { return consentExpiryInMillis > currentTimeMillis; } private boolean isExpiryIndefinite(String validTime) { return CONSENT_VALIDITY_TYPE_VALID_UNTIL_INDEFINITE.equalsIgnoreCase(validTime); } private boolean isMandatoryClaimsDisapproved(List<ClaimMetaData> consentMandatoryClaims, List<ClaimMetaData> disapprovedClaims) { return isNotEmpty(consentMandatoryClaims) && !Collections.disjoint(disapprovedClaims, consentMandatoryClaims); } private ConsentClaimsData getConsentRequiredClaimData(List<String> mandatoryClaims, List<String> requestedClaims, String tenantDomain) throws SSOConsentServiceException { ConsentClaimsData consentClaimsData = new ConsentClaimsData(); try { List<LocalClaim> localClaims = getClaimMetadataManagementService().getLocalClaims(tenantDomain); List<ClaimMetaData> mandatoryClaimsMetaData = new ArrayList<>(); List<ClaimMetaData> requestedClaimsMetaData = new ArrayList<>(); int claimId = 0; if (isNotEmpty(localClaims)) { for (LocalClaim localClaim : localClaims) { if (isAllRequiredClaimsChecked(mandatoryClaims, requestedClaims)) { break; } String claimURI = localClaim.getClaimURI(); if (mandatoryClaims.remove(claimURI)) { ClaimMetaData claimMetaData = buildClaimMetaData(claimId, localClaim, claimURI); mandatoryClaimsMetaData.add(claimMetaData); claimId++; } else if (requestedClaims.remove(claimURI)) { ClaimMetaData claimMetaData = buildClaimMetaData(claimId, localClaim, claimURI); requestedClaimsMetaData.add(claimMetaData); claimId++; } } } if (isNotEmpty(mandatoryClaims)) { for (String claimUri : mandatoryClaims) { ClaimMetaData claimMetaData = buildClaimMetaData(claimId, claimUri); mandatoryClaimsMetaData.add(claimMetaData); claimId++; } } if (isNotEmpty(requestedClaims)) { for (String claimUri : mandatoryClaims) { ClaimMetaData claimMetaData = buildClaimMetaData(claimId, claimUri); requestedClaimsMetaData.add(claimMetaData); claimId++; } } consentClaimsData.setMandatoryClaims(mandatoryClaimsMetaData); consentClaimsData.setRequestedClaims(requestedClaimsMetaData); } catch (ClaimMetadataException e) { throw new SSOConsentServiceException("Error while retrieving local claims", "Error occurred while " + "retrieving local claims for tenant: " + tenantDomain, e); } return consentClaimsData; } private boolean isAllRequiredClaimsChecked(List<String> mandatoryClaims, List<String> requestedClaims) { return isEmpty(mandatoryClaims) && isEmpty(requestedClaims); } private ClaimMetaData buildClaimMetaData(int claimId, String claimUri) { LocalClaim localClaim = new LocalClaim(claimUri); return buildClaimMetaData(claimId, localClaim, claimUri); } private ClaimMetaData buildClaimMetaData(int claimId, LocalClaim localClaim, String claimURI) { ClaimMetaData claimMetaData = new ClaimMetaData(); claimMetaData.setId(claimId); claimMetaData.setClaimUri(claimURI); String displayName = localClaim.getClaimProperties().get(DISPLAY_NAME_PROPERTY); if (isNotBlank(displayName)) { claimMetaData.setDisplayName(displayName); } else { claimMetaData.setDisplayName(claimURI); } String description = localClaim.getClaimProperty(DESCRIPTION_PROPERTY); if (isNotBlank(description)) { claimMetaData.setDescription(description); } else { claimMetaData.setDescription(EMPTY); } return claimMetaData; } private List<String> getClaimsFromConsentMetaData(List<ClaimMetaData> claimMetaDataList) { List<String> claims = new ArrayList<>(); for (ClaimMetaData claimMetaData : claimMetaDataList) { claims.add(claimMetaData.getClaimUri()); } return claims; } private String getFirstConsentReceiptFromList(List<ReceiptListResponse> receiptListResponses) { return receiptListResponses.get(0).getConsentReceiptId(); } private Receipt getReceipt(AuthenticatedUser authenticatedUser, String receiptId) throws SSOConsentServiceException { Receipt currentReceipt; String subject = buildSubjectWithUserStoreDomain(authenticatedUser); try { initializeTenantRegistry(authenticatedUser); startTenantFlowWithUser(subject, authenticatedUser.getTenantDomain()); currentReceipt = getConsentManager().getReceipt(receiptId); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent Management Error", "Error while retrieving user consents.", e); } catch (IdentityException e) { throw new SSOConsentServiceException("Consent Management Error", "Error while initializing registry for " + "the tenant domain: " + authenticatedUser.getTenantDomain(), e); } finally { PrivilegedCarbonContext.endTenantFlow(); } return currentReceipt; } private void initializeTenantRegistry(AuthenticatedUser authenticatedUser) throws IdentityException { IdentityTenantUtil.initializeRegistry( IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain())); } private boolean hasUserSingleReceipt(List<ReceiptListResponse> receiptListResponses) { return receiptListResponses.size() == 1; } private boolean hasUserMultipleReceipts(List<ReceiptListResponse> receiptListResponses) { return receiptListResponses.size() > 1; } private void startTenantFlowWithUser(String subject, String subjectTenantDomain) { startTenantFlow(subjectTenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(subject); } private void startTenantFlow(String tenantDomain) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } private boolean isDebugEnabled() { return log.isDebugEnabled(); } private void logDebug(String message) { log.debug(message); } private ConsentManager getConsentManager() { return FrameworkServiceDataHolder.getInstance().getConsentManager(); } private ClaimMetadataManagementService getClaimMetadataManagementService() { return FrameworkServiceDataHolder.getInstance().getClaimMetadataManagementService(); } }
components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/handler/request/impl/consent/SSOConsentServiceImpl.java
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent; import org.apache.axiom.om.OMElement; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.claim.mgt.ClaimManagementException; import org.wso2.carbon.consent.mgt.core.ConsentManager; import org.wso2.carbon.consent.mgt.core.exception.ConsentManagementClientException; import org.wso2.carbon.consent.mgt.core.exception.ConsentManagementException; import org.wso2.carbon.consent.mgt.core.model.AddReceiptResponse; import org.wso2.carbon.consent.mgt.core.model.ConsentPurpose; import org.wso2.carbon.consent.mgt.core.model.PIICategory; import org.wso2.carbon.consent.mgt.core.model.PIICategoryValidity; import org.wso2.carbon.consent.mgt.core.model.Purpose; import org.wso2.carbon.consent.mgt.core.model.PurposeCategory; import org.wso2.carbon.consent.mgt.core.model.Receipt; import org.wso2.carbon.consent.mgt.core.model.ReceiptInput; import org.wso2.carbon.consent.mgt.core.model.ReceiptListResponse; import org.wso2.carbon.consent.mgt.core.model.ReceiptPurposeInput; import org.wso2.carbon.consent.mgt.core.model.ReceiptService; import org.wso2.carbon.consent.mgt.core.model.ReceiptServiceInput; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants; import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentDisabledException; import org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException; import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceDataHolder; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.application.common.model.ServiceProvider; import org.wso2.carbon.identity.application.common.model.User; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementService; import org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException; import org.wso2.carbon.identity.claim.metadata.mgt.model.LocalClaim; import org.wso2.carbon.identity.core.util.IdentityConfigParser; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; 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 java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.xml.namespace.QName; import static org.apache.commons.collections.CollectionUtils.isEmpty; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; import static org.apache.commons.collections.MapUtils.isNotEmpty; import static org.apache.commons.lang.ArrayUtils.isEmpty; import static org.apache.commons.lang.StringUtils.EMPTY; import static org.apache.commons.lang.StringUtils.isBlank; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.wso2.carbon.consent.mgt.core.constant.ConsentConstants.ACTIVE_STATE; import static org.wso2.carbon.consent.mgt.core.constant.ConsentConstants.ErrorMessages.ERROR_CODE_PII_CAT_NAME_INVALID; import static org.wso2.carbon.consent.mgt.core.constant.ConsentConstants.ErrorMessages.ERROR_CODE_PURPOSE_CAT_NAME_INVALID; import static org.wso2.carbon.consent.mgt.core.constant.ConsentConstants.ErrorMessages.ERROR_CODE_PURPOSE_NAME_INVALID; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONFIG_ELEM_CONSENT; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONFIG_ELEM_ENABLE_SSO_CONSENT_MANAGEMENT; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONFIG_PROMPT_SUBJECT_CLAIM_REQUESTED_CONSENT; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONSENT_VALIDITY_TYPE_SEPARATOR; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONSENT_VALIDITY_TYPE_VALID_UNTIL; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.CONSENT_VALIDITY_TYPE_VALID_UNTIL_INDEFINITE; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.FEDERATED_USER_DOMAIN_PREFIX; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.FEDERATED_USER_DOMAIN_SEPARATOR; import static org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.constant.SSOConsentConstants.USERNAME_CLAIM; import static org.wso2.carbon.identity.claim.metadata.mgt.util.ClaimConstants.DESCRIPTION_PROPERTY; import static org.wso2.carbon.identity.claim.metadata.mgt.util.ClaimConstants.DISPLAY_NAME_PROPERTY; import static org.wso2.carbon.identity.core.util.IdentityCoreConstants.IDENTITY_DEFAULT_NAMESPACE; /** * Implementation of {@link SSOConsentService}. */ public class SSOConsentServiceImpl implements SSOConsentService { private static final Log log = LogFactory.getLog(SSOConsentServiceImpl.class); private static final String DEFAULT_PURPOSE = "DEFAULT"; private static final String DEFAULT_PURPOSE_CATEGORY = "DEFAULT"; private static final String DEFAULT_PURPOSE_GROUP = "DEFAULT"; private static final String DEFAULT_PURPOSE_GROUP_TYPE = "SP"; private boolean ssoConsentEnabled = true; public SSOConsentServiceImpl() { readSSOConsentEnabledConfig(); } /** * Get consent required claims for a given service from a user considering existing user consents. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ @Override public ConsentClaimsData getConsentRequiredClaimsWithExistingConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser) throws SSOConsentServiceException { return getConsentRequiredClaims(serviceProvider, authenticatedUser, true, null); } /** * Get consent required claims for a given service from a user considering existing user consents. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @param claimsListOfScopes Claims list of requested scopes. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ @Override public ConsentClaimsData getConsentRequiredClaimsWithExistingConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, List<String> claimsListOfScopes) throws SSOConsentServiceException { return getConsentRequiredClaims(serviceProvider, authenticatedUser, true, claimsListOfScopes); } /** * Get consent required claims for a given service from a user ignoring existing user consents. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ @Override public ConsentClaimsData getConsentRequiredClaimsWithoutExistingConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser) throws SSOConsentServiceException { return getConsentRequiredClaims(serviceProvider, authenticatedUser, false, null); } /** * Get consent required claims for a given service from a user ignoring existing user consents and considering * requested scopes. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @param claimsListOfScopes Claims list of requested scopes. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ @Override public ConsentClaimsData getConsentRequiredClaimsWithoutExistingConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, List<String> claimsListOfScopes) throws SSOConsentServiceException { return getConsentRequiredClaims(serviceProvider, authenticatedUser, false, claimsListOfScopes); } /** * Get consent required claims for a given service from a user. * * @param serviceProvider Service provider requesting consent. * @param authenticatedUser Authenticated user requesting consent form. * @param useExistingConsents Use existing consent given by the user. * @param claimsListOfScopes Claims list of requested scopes. * @return ConsentClaimsData which contains mandatory and required claims for consent. * @throws SSOConsentServiceException If error occurs while building claim information. */ protected ConsentClaimsData getConsentRequiredClaims(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, boolean useExistingConsents, List<String> claimsListOfScopes) throws SSOConsentServiceException { if (!isSSOConsentManagementEnabled(serviceProvider)) { String message = "Consent management for SSO is disabled."; throw new SSOConsentDisabledException(message, message); } if (serviceProvider == null) { throw new SSOConsentServiceException("Service provider cannot be null."); } String spName = serviceProvider.getApplicationName(); String spTenantDomain = getSPTenantDomain(serviceProvider); String subject = buildSubjectWithUserStoreDomain(authenticatedUser); ClaimMapping[] claimMappings = getSpClaimMappings(serviceProvider); if (claimMappings == null || claimMappings.length == 0) { if (log.isDebugEnabled()) { log.debug("No claim mapping configured from the application. Hence skipping getting consent."); } return new ConsentClaimsData(); } if (claimsListOfScopes != null) { try { claimMappings = FrameworkUtils.getFilteredScopeClaims(claimsListOfScopes, Arrays.asList(claimMappings)).toArray(new ClaimMapping[0]); } catch (ClaimManagementException e) { throw new SSOConsentServiceException("Error occurred while filtering claims of requested scopes"); } } List<String> requestedClaims = new ArrayList<>(); List<String> mandatoryClaims = new ArrayList<>(); Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes(); String subjectClaimUri = getSubjectClaimUri(serviceProvider); boolean subjectClaimUriRequested = false; boolean subjectClaimUriMandatory = false; boolean promptSubjectClaimRequestedConsent = true; if (StringUtils.isNotBlank(IdentityUtil.getProperty(CONFIG_PROMPT_SUBJECT_CLAIM_REQUESTED_CONSENT))) { promptSubjectClaimRequestedConsent = Boolean.parseBoolean(IdentityUtil.getProperty(CONFIG_PROMPT_SUBJECT_CLAIM_REQUESTED_CONSENT)); } if (isPassThroughScenario(claimMappings, userAttributes)) { for (Map.Entry<ClaimMapping, String> userAttribute : userAttributes.entrySet()) { String remoteClaimUri = userAttribute.getKey().getRemoteClaim().getClaimUri(); if (subjectClaimUri.equals(remoteClaimUri) || IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR.equals(remoteClaimUri)) { continue; } mandatoryClaims.add(remoteClaimUri); } } else { boolean isCustomClaimMapping = isCustomClaimMapping(serviceProvider); for (ClaimMapping claimMapping : claimMappings) { if (isCustomClaimMapping) { if (subjectClaimUri.equals(claimMapping.getRemoteClaim().getClaimUri())) { subjectClaimUri = claimMapping.getLocalClaim().getClaimUri(); if (promptSubjectClaimRequestedConsent) { if (claimMapping.isMandatory()) { subjectClaimUriMandatory = true; } else if (claimMapping.isRequested()) { subjectClaimUriRequested = true; } } continue; } } else { if (subjectClaimUri.equals(claimMapping.getLocalClaim().getClaimUri())) { if (promptSubjectClaimRequestedConsent) { if (claimMapping.isMandatory()) { subjectClaimUriMandatory = true; } else if (claimMapping.isRequested()) { subjectClaimUriRequested = true; } } continue; } } if (claimMapping.isMandatory()) { mandatoryClaims.add(claimMapping.getLocalClaim().getClaimUri()); } else if (claimMapping.isRequested()) { requestedClaims.add(claimMapping.getLocalClaim().getClaimUri()); } } } if (promptSubjectClaimRequestedConsent) { if (subjectClaimUriMandatory) { mandatoryClaims.add(subjectClaimUri); } else if (subjectClaimUriRequested) { requestedClaims.add(subjectClaimUri); } } List<ClaimMetaData> receiptConsentMetaData = new ArrayList<>(); List<ClaimMetaData> receiptConsentDeniedMetaData; Receipt receipt = getConsentReceiptOfUser(serviceProvider, authenticatedUser, spName, spTenantDomain, subject); if (useExistingConsents && receipt != null) { receiptConsentMetaData = getRequestedClaimsFromReceipt(receipt, true); List<String> claimsWithConsent = getClaimsFromConsentMetaData(receiptConsentMetaData); receiptConsentDeniedMetaData = getRequestedClaimsFromReceipt(receipt, false); List<String> claimsDeniedConsent = getClaimsFromConsentMetaData(receiptConsentDeniedMetaData); mandatoryClaims.removeAll(claimsWithConsent); requestedClaims.removeAll(claimsWithConsent); requestedClaims.removeAll(claimsDeniedConsent); } ConsentClaimsData consentClaimsData = getConsentRequiredClaimData(mandatoryClaims, requestedClaims, spTenantDomain); consentClaimsData.setClaimsWithConsent(receiptConsentMetaData); return consentClaimsData; } private boolean isCustomClaimMapping(ServiceProvider serviceProvider) { return !serviceProvider.getClaimConfig().isLocalClaimDialect(); } private boolean isPassThroughScenario(ClaimMapping[] claimMappings, Map<ClaimMapping, String> userAttributes) { return isEmpty(claimMappings) && isNotEmpty(userAttributes); } private String getSubjectClaimUri(ServiceProvider serviceProvider) { String subjectClaimUri = serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSubjectClaimUri(); if (isBlank(subjectClaimUri)) { subjectClaimUri = USERNAME_CLAIM; } return subjectClaimUri; } private void readSSOConsentEnabledConfig() { IdentityConfigParser identityConfigParser = IdentityConfigParser.getInstance(); OMElement consentElement = identityConfigParser.getConfigElement(CONFIG_ELEM_CONSENT); if (consentElement != null) { OMElement ssoConsentEnabledElem = consentElement.getFirstChildWithName( new QName(IDENTITY_DEFAULT_NAMESPACE, CONFIG_ELEM_ENABLE_SSO_CONSENT_MANAGEMENT)); if (ssoConsentEnabledElem != null) { String ssoConsentEnabledElemText = ssoConsentEnabledElem.getText(); if (isNotBlank(ssoConsentEnabledElemText)) { ssoConsentEnabled = Boolean.parseBoolean(ssoConsentEnabledElemText); if (isDebugEnabled()) { logDebug("Consent management for SSO is set to " + ssoConsentEnabled + " from configurations."); } return; } } } ssoConsentEnabled = true; } private ClaimMapping[] getSpClaimMappings(ServiceProvider serviceProvider) { if (serviceProvider.getClaimConfig() != null) { return serviceProvider.getClaimConfig().getClaimMappings(); } else { return new ClaimMapping[0]; } } private String getSPTenantDomain(ServiceProvider serviceProvider) { String spTenantDomain; User owner = serviceProvider.getOwner(); if (owner != null) { spTenantDomain = owner.getTenantDomain(); } else { spTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } return spTenantDomain; } /** * Process the provided user consent and creates a consent receipt. * * @param consentApprovedClaimIds Consent approved claims by the user. * @param serviceProvider Service provider receiving consent. * @param authenticatedUser Authenticated user providing consent. * @param consentClaimsData Claims which the consent requested for. * @throws SSOConsentServiceException If error occurs while processing user consent. */ @Override public void processConsent(List<Integer> consentApprovedClaimIds, ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, ConsentClaimsData consentClaimsData) throws SSOConsentServiceException { processConsent(consentApprovedClaimIds, serviceProvider, authenticatedUser, consentClaimsData, false); } @Override public void processConsent(List<Integer> consentApprovedClaimIds, ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, ConsentClaimsData consentClaimsData, boolean overrideExistingConsent) throws SSOConsentServiceException { if (!isSSOConsentManagementEnabled(serviceProvider)) { String message = "Consent management for SSO is disabled."; throw new SSOConsentDisabledException(message, message); } if (isDebugEnabled()) { logDebug("User: " + authenticatedUser.getAuthenticatedSubjectIdentifier() + " has approved consent."); } UserConsent userConsent = processUserConsent(consentApprovedClaimIds, consentClaimsData); if (isEmpty(userConsent.getApprovedClaims()) && isEmpty(userConsent.getDisapprovedClaims())) { if (isDebugEnabled()) { logDebug("User: " + authenticatedUser.getAuthenticatedSubjectIdentifier() + " has not provided new " + "approved/disapproved consent. Hence skipping the consent progress."); } return; } String subject = buildSubjectWithUserStoreDomain(authenticatedUser); List<ClaimMetaData> claimsWithConsent; List<ClaimMetaData> claimsDeniedConsent; if (!overrideExistingConsent) { String spName = serviceProvider.getApplicationName(); String spTenantDomain = getSPTenantDomain(serviceProvider); Receipt receipt = getConsentReceiptOfUser(serviceProvider, authenticatedUser, spName, spTenantDomain, subject); claimsWithConsent = getUserRequestedClaims(receipt, userConsent, true); claimsDeniedConsent = getUserRequestedClaims(receipt, userConsent, false); } else { claimsWithConsent = userConsent.getApprovedClaims(); claimsDeniedConsent = userConsent.getDisapprovedClaims(); } String spTenantDomain = getSPTenantDomain(serviceProvider); String subjectTenantDomain = authenticatedUser.getTenantDomain(); if (isNotEmpty(claimsWithConsent) || isNotEmpty(claimsDeniedConsent)) { addReceipt(subject, subjectTenantDomain, serviceProvider, spTenantDomain, claimsWithConsent, claimsDeniedConsent); } } /** * Retrieves claims which a user has provided consent for a given service provider. * * @param serviceProvider Service provider to retrieve the consent against. * @param authenticatedUser Authenticated user to related to consent claim retrieval. * @return List of claim which the user has provided consent for the given service provider. * @throws SSOConsentServiceException If error occurs while retrieve user consents. */ @Override public List<ClaimMetaData> getClaimsWithConsents(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser) throws SSOConsentServiceException { if (!isSSOConsentManagementEnabled(serviceProvider)) { String message = "Consent management for SSO is disabled."; throw new SSOConsentDisabledException(message, message); } if (serviceProvider == null) { throw new SSOConsentServiceException("Service provider cannot be null."); } String spName = serviceProvider.getApplicationName(); List<ClaimMetaData> receiptConsentMetaData = new ArrayList<>(); String spTenantDomain = getSPTenantDomain(serviceProvider); String subject = buildSubjectWithUserStoreDomain(authenticatedUser); Receipt receipt = getConsentReceiptOfUser(serviceProvider, authenticatedUser, spName, spTenantDomain, subject); if (receipt == null) { return receiptConsentMetaData; } else { receiptConsentMetaData = getRequestedClaimsFromReceipt(receipt, true); } return receiptConsentMetaData; } /** * Specifies whether consent management for SSO is enabled or disabled. * * @param serviceProvider Service provider to check whether consent management is enabled. * @return true if enabled, false otherwise. */ @Override public boolean isSSOConsentManagementEnabled(ServiceProvider serviceProvider) { return ssoConsentEnabled; } private Receipt getConsentReceiptOfUser(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser, String spName, String spTenantDomain, String subject) throws SSOConsentServiceException { int receiptListLimit = 2; List<ReceiptListResponse> receiptListResponses; try { receiptListResponses = getReceiptListOfUserForSP(authenticatedUser, spName, spTenantDomain, subject, receiptListLimit); if (isDebugEnabled()) { String message = String.format("Retrieved %s receipts for user: %s, service provider: %s in tenant " + "domain %s", receiptListResponses.size(), subject, serviceProvider, spTenantDomain); logDebug(message); } if (hasUserMultipleReceipts(receiptListResponses)) { throw new SSOConsentServiceException("Consent Management Error", "User cannot have more than one " + "ACTIVE consent per service provider."); } else if (hasUserSingleReceipt(receiptListResponses)) { String receiptId = getFirstConsentReceiptFromList(receiptListResponses); return getReceipt(authenticatedUser, receiptId); } else { return null; } } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent Management Error", "Error while retrieving user consents.", e); } } private void addReceipt(String subject, String subjectTenantDomain, ServiceProvider serviceProvider, String spTenantDomain, List<ClaimMetaData> claimsWithConsent, List<ClaimMetaData> claimsDeniedConsent) throws SSOConsentServiceException { ReceiptInput receiptInput = buildReceiptInput(subject, serviceProvider, spTenantDomain, claimsWithConsent, claimsDeniedConsent); AddReceiptResponse receiptResponse; try { startTenantFlowWithUser(subject, subjectTenantDomain); receiptResponse = getConsentManager().addConsent(receiptInput); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent receipt error", "Error while adding the consent " + "receipt", e); } finally { PrivilegedCarbonContext.endTenantFlow(); } if (isDebugEnabled()) { logDebug("Successfully added consent receipt: " + receiptResponse.getConsentReceiptId()); } } private ReceiptInput buildReceiptInput(String subject, ServiceProvider serviceProvider, String spTenantDomain, List<ClaimMetaData> claimsWithConsent, List<ClaimMetaData> claimsDeniedConsent) throws SSOConsentServiceException { String collectionMethod = "Web Form - Sign-in"; String jurisdiction = "NONE"; String language = "us_EN"; String consentType = "EXPLICIT"; String termination = CONSENT_VALIDITY_TYPE_VALID_UNTIL + CONSENT_VALIDITY_TYPE_SEPARATOR + CONSENT_VALIDITY_TYPE_VALID_UNTIL_INDEFINITE; String policyUrl = "NONE"; Purpose purpose = getDefaultPurpose(); PurposeCategory purposeCategory = getDefaultPurposeCategory(); List<PIICategoryValidity> piiCategoryIds = getPiiCategoryValidityForClaims(claimsWithConsent, claimsDeniedConsent, termination); List<ReceiptServiceInput> serviceInputs = new ArrayList<>(); List<ReceiptPurposeInput> purposeInputs = new ArrayList<>(); List<Integer> purposeCategoryIds = new ArrayList<>(); Map<String, String> properties = new HashMap<>(); purposeCategoryIds.add(purposeCategory.getId()); ReceiptPurposeInput purposeInput = getReceiptPurposeInput(consentType, termination, purpose, piiCategoryIds, purposeCategoryIds); purposeInputs.add(purposeInput); ReceiptServiceInput serviceInput = getReceiptServiceInput(serviceProvider, spTenantDomain, purposeInputs); serviceInputs.add(serviceInput); return getReceiptInput(subject, collectionMethod, jurisdiction, language, policyUrl, serviceInputs, properties); } private ReceiptInput getReceiptInput(String subject, String collectionMethod, String jurisdiction, String language, String policyUrl, List<ReceiptServiceInput> serviceInputs, Map<String, String> properties) { ReceiptInput receiptInput = new ReceiptInput(); receiptInput.setCollectionMethod(collectionMethod); receiptInput.setJurisdiction(jurisdiction); receiptInput.setLanguage(language); receiptInput.setPolicyUrl(policyUrl); receiptInput.setServices(serviceInputs); receiptInput.setProperties(properties); receiptInput.setPiiPrincipalId(subject); return receiptInput; } private ReceiptServiceInput getReceiptServiceInput(ServiceProvider serviceProvider, String spTenantDomain, List<ReceiptPurposeInput> purposeInputs) { ReceiptServiceInput serviceInput = new ReceiptServiceInput(); serviceInput.setPurposes(purposeInputs); serviceInput.setTenantDomain(spTenantDomain); if (serviceProvider == null) { return serviceInput; } String spName = serviceProvider.getApplicationName(); String spDescription; spDescription = serviceProvider.getDescription(); if (StringUtils.isBlank(spDescription)) { spDescription = spName; } serviceInput.setService(spName); serviceInput.setSpDisplayName(spName); serviceInput.setSpDescription(spDescription); return serviceInput; } private ReceiptPurposeInput getReceiptPurposeInput(String consentType, String termination, Purpose purpose, List<PIICategoryValidity> piiCategoryIds, List<Integer> purposeCategoryIds) { ReceiptPurposeInput purposeInput = new ReceiptPurposeInput(); purposeInput.setPrimaryPurpose(true); purposeInput.setTermination(termination); purposeInput.setConsentType(consentType); purposeInput.setThirdPartyDisclosure(false); purposeInput.setPurposeId(purpose.getId()); purposeInput.setPurposeCategoryId(purposeCategoryIds); purposeInput.setPiiCategory(piiCategoryIds); return purposeInput; } private List<PIICategoryValidity> getPiiCategoryValidityForClaims(List<ClaimMetaData> claimsWithConsent, List<ClaimMetaData> claimsDeniedConsent, String termination) throws SSOConsentServiceException { List<PIICategoryValidity> piiCategoryIds = new ArrayList<>(); List<PIICategoryValidity> piiCategoryIdsForClaimsWithConsent = getPiiCategoryValidityForRequestedClaims(claimsWithConsent, true, termination); List<PIICategoryValidity> piiCategoryIdsForDeniedConsentClaims = getPiiCategoryValidityForRequestedClaims(claimsDeniedConsent, false, termination); piiCategoryIds.addAll(piiCategoryIdsForClaimsWithConsent); piiCategoryIds.addAll(piiCategoryIdsForDeniedConsentClaims); return piiCategoryIds; } private List<PIICategoryValidity> getPiiCategoryValidityForRequestedClaims(List<ClaimMetaData> requestedClaims, boolean isConsented, String termination) throws SSOConsentServiceException { List<PIICategoryValidity> piiCategoryIds = new ArrayList<>(); if (CollectionUtils.isEmpty(requestedClaims)) { return piiCategoryIds; } for (ClaimMetaData requestedClaim : requestedClaims) { if (requestedClaim == null || requestedClaim.getClaimUri() == null) { continue; } PIICategory piiCategory; try { piiCategory = getConsentManager().getPIICategoryByName(requestedClaim.getClaimUri()); } catch (ConsentManagementClientException e) { if (isInvalidPIICategoryError(e)) { piiCategory = addPIICategoryForClaim(requestedClaim); } else { throw new SSOConsentServiceException("Consent PII category error", "Error while retrieving" + " PII category: " + DEFAULT_PURPOSE_CATEGORY, e); } } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent PII category error", "Error while retrieving " + "PII category: " + DEFAULT_PURPOSE_CATEGORY, e); } PIICategoryValidity piiCategoryValidity = new PIICategoryValidity(piiCategory.getId(), termination); piiCategoryValidity.setConsented(isConsented); piiCategoryIds.add(piiCategoryValidity); } return piiCategoryIds; } private PIICategory addPIICategoryForClaim(ClaimMetaData claim) throws SSOConsentServiceException { PIICategory piiCategory; PIICategory piiCategoryInput = new PIICategory(claim.getClaimUri(), claim.getDescription(), false, claim .getDisplayName()); try { piiCategory = getConsentManager().addPIICategory(piiCategoryInput); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent PII category error", "Error while adding" + " PII category:" + DEFAULT_PURPOSE_CATEGORY, e); } return piiCategory; } private boolean isInvalidPIICategoryError(ConsentManagementClientException e) { return ERROR_CODE_PII_CAT_NAME_INVALID.getCode().equals(e.getErrorCode()); } private PurposeCategory getDefaultPurposeCategory() throws SSOConsentServiceException { PurposeCategory purposeCategory; try { purposeCategory = getConsentManager().getPurposeCategoryByName(DEFAULT_PURPOSE_CATEGORY); } catch (ConsentManagementClientException e) { if (isInvalidPurposeCategoryError(e)) { purposeCategory = addDefaultPurposeCategory(); } else { throw new SSOConsentServiceException("Consent purpose category error", "Error while retrieving" + " purpose category: " + DEFAULT_PURPOSE_CATEGORY, e); } } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent purpose category error", "Error while retrieving " + "purpose category: " + DEFAULT_PURPOSE_CATEGORY, e); } return purposeCategory; } private PurposeCategory addDefaultPurposeCategory() throws SSOConsentServiceException { PurposeCategory purposeCategory; PurposeCategory defaultPurposeCategory = new PurposeCategory(DEFAULT_PURPOSE_CATEGORY, "For core functionalities of the product"); try { purposeCategory = getConsentManager().addPurposeCategory(defaultPurposeCategory); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent purpose category error", "Error while adding" + " purpose category: " + DEFAULT_PURPOSE_CATEGORY, e); } return purposeCategory; } private boolean isInvalidPurposeCategoryError(ConsentManagementClientException e) { return ERROR_CODE_PURPOSE_CAT_NAME_INVALID.getCode().equals(e.getErrorCode()); } private Purpose getDefaultPurpose() throws SSOConsentServiceException { Purpose purpose; try { purpose = getConsentManager().getPurposeByName(DEFAULT_PURPOSE, DEFAULT_PURPOSE_GROUP, DEFAULT_PURPOSE_GROUP_TYPE); } catch (ConsentManagementClientException e) { if (isInvalidPurposeError(e)) { purpose = addDefaultPurpose(); } else { throw new SSOConsentServiceException("Consent purpose error", "Error while retrieving purpose: " + DEFAULT_PURPOSE, e); } } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent purpose error", "Error while retrieving purpose: " + DEFAULT_PURPOSE, e); } return purpose; } private Purpose addDefaultPurpose() throws SSOConsentServiceException { Purpose purpose; Purpose defaultPurpose = new Purpose(DEFAULT_PURPOSE, "For core functionalities of the product", DEFAULT_PURPOSE_GROUP, DEFAULT_PURPOSE_GROUP_TYPE); try { purpose = getConsentManager().addPurpose(defaultPurpose); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent purpose error", "Error while adding purpose: " + DEFAULT_PURPOSE, e); } return purpose; } private boolean isInvalidPurposeError(ConsentManagementClientException e) { return ERROR_CODE_PURPOSE_NAME_INVALID.getCode().equals(e.getErrorCode()); } private UserConsent processUserConsent(List<Integer> consentApprovedClaimIds, ConsentClaimsData consentClaimsData) throws SSOConsentServiceException { UserConsent userConsent = new UserConsent(); List<ClaimMetaData> approvedClamMetaData = buildApprovedClaimList(consentApprovedClaimIds, consentClaimsData); List<ClaimMetaData> consentRequiredClaimMetaData = getConsentRequiredClaimMetaData(consentClaimsData); List<ClaimMetaData> disapprovedClaims = buildDisapprovedClaimList(consentRequiredClaimMetaData, approvedClamMetaData); if (isMandatoryClaimsDisapproved(consentClaimsData.getMandatoryClaims(), disapprovedClaims)) { throw new SSOConsentServiceException("Consent Denied for Mandatory Attributes", "User denied consent to share mandatory attributes."); } userConsent.setApprovedClaims(approvedClamMetaData); userConsent.setDisapprovedClaims(disapprovedClaims); return userConsent; } private List<ClaimMetaData> getUserRequestedClaims(Receipt receipt, UserConsent userConsent, boolean isConsented) { List<ClaimMetaData> requestedClaims = new ArrayList<>(); if (isConsented) { requestedClaims.addAll(userConsent.getApprovedClaims()); } else { requestedClaims.addAll(userConsent.getDisapprovedClaims()); } if (receipt == null) { return requestedClaims; } List<PIICategoryValidity> piiCategoriesFromServices = getPIICategoriesFromServices(receipt.getServices()); if (isConsented) { piiCategoriesFromServices.removeIf(piiCategoryValidity -> !piiCategoryValidity.isConsented()); } else { piiCategoriesFromServices.removeIf(PIICategoryValidity::isConsented); } List<ClaimMetaData> claimsFromPIICategoryValidity = getClaimsFromPIICategoryValidity(piiCategoriesFromServices); requestedClaims.addAll(claimsFromPIICategoryValidity); /* When consent denied requested claim is updated as mandatory, that claim should remove from the requested denied claims list. */ if (!isConsented && CollectionUtils.isNotEmpty(requestedClaims) && CollectionUtils.isNotEmpty(userConsent.getApprovedClaims())) { requestedClaims.removeAll(userConsent.getApprovedClaims()); } return getDistinctClaims(requestedClaims); } private List<ClaimMetaData> getDistinctClaims(List<ClaimMetaData> claimsWithConsent) { return claimsWithConsent.stream() .filter(distinctByKey(ClaimMetaData::getClaimUri)) .collect(Collectors.toList()); } private Predicate<ClaimMetaData> distinctByKey(Function<ClaimMetaData, String> keyExtractor) { final Set<String> claimUris = new HashSet<>(); return claimUri -> claimUris.add(keyExtractor.apply(claimUri)); } private List<ClaimMetaData> getConsentRequiredClaimMetaData(ConsentClaimsData consentClaimsData) { List<ClaimMetaData> consentRequiredClaims = new ArrayList<>(); if (isNotEmpty(consentClaimsData.getMandatoryClaims())) { consentRequiredClaims.addAll(consentClaimsData.getMandatoryClaims()); } if (isNotEmpty(consentClaimsData.getRequestedClaims())) { consentRequiredClaims.addAll(consentClaimsData.getRequestedClaims()); } return consentRequiredClaims; } private List<ClaimMetaData> buildDisapprovedClaimList(List<ClaimMetaData> consentRequiredClaims, List<ClaimMetaData> approvedClaims) { List<ClaimMetaData> disapprovedClaims = new ArrayList<>(); if (isNotEmpty(consentRequiredClaims)) { consentRequiredClaims.removeAll(approvedClaims); disapprovedClaims = consentRequiredClaims; } return disapprovedClaims; } private List<ClaimMetaData> buildApprovedClaimList(List<Integer> consentApprovedClaimIds, ConsentClaimsData consentClaimsData) { List<ClaimMetaData> approvedClaims = new ArrayList<>(); for (Integer claimId : consentApprovedClaimIds) { ClaimMetaData consentClaim = new ClaimMetaData(); consentClaim.setId(claimId); List<ClaimMetaData> mandatoryClaims = consentClaimsData.getMandatoryClaims(); int claimIndex = mandatoryClaims.indexOf(consentClaim); if (claimIndex != -1) { approvedClaims.add(mandatoryClaims.get(claimIndex)); } List<ClaimMetaData> requestedClaims = consentClaimsData.getRequestedClaims(); claimIndex = requestedClaims.indexOf(consentClaim); if (claimIndex != -1) { approvedClaims.add(requestedClaims.get(claimIndex)); } } return approvedClaims; } private String buildSubjectWithUserStoreDomain(AuthenticatedUser authenticatedUser) { String userStoreDomain; if (authenticatedUser.isFederatedUser()) { userStoreDomain = getFederatedUserDomain(authenticatedUser.getFederatedIdPName()); } else { userStoreDomain = authenticatedUser.getUserStoreDomain(); } return UserCoreUtil.addDomainToName(authenticatedUser.getUserName(), userStoreDomain); } private String getFederatedUserDomain(String authenticatedIDP) { if (isNotBlank(authenticatedIDP)) { return FEDERATED_USER_DOMAIN_PREFIX + FEDERATED_USER_DOMAIN_SEPARATOR + authenticatedIDP; } else { return FEDERATED_USER_DOMAIN_PREFIX; } } private List<ReceiptListResponse> getReceiptListOfUserForSP(AuthenticatedUser authenticatedUser, String serviceProvider, String spTenantDomain, String subject, int limit) throws ConsentManagementException { List<ReceiptListResponse> receiptListResponses; startTenantFlowWithUser(subject, authenticatedUser.getTenantDomain()); try { receiptListResponses = getConsentManager().searchReceipts(limit, 0, subject, spTenantDomain, serviceProvider, ACTIVE_STATE); } finally { PrivilegedCarbonContext.endTenantFlow(); } return receiptListResponses; } private List<PIICategoryValidity> getPIICategoriesFromServices(List<ReceiptService> receiptServices) { List<PIICategoryValidity> piiCategoryValidityMap = new ArrayList<>(); for (ReceiptService receiptService : receiptServices) { List<ConsentPurpose> purposes = receiptService.getPurposes(); for (ConsentPurpose purpose : purposes) { piiCategoryValidityMap.addAll(piiCategoryValidityMap.size(), purpose.getPiiCategory()); } } return piiCategoryValidityMap; } private List<ClaimMetaData> getRequestedClaimsFromReceipt(Receipt receipt, boolean isConsented) { List<ReceiptService> services = receipt.getServices(); List<PIICategoryValidity> piiCategories = getPIICategoriesFromServices(services); if (isConsented) { piiCategories.removeIf(piiCategoryValidity -> !piiCategoryValidity.isConsented()); } else { piiCategories.removeIf(PIICategoryValidity::isConsented); } List<ClaimMetaData> claimsFromPIICategoryValidity = getClaimsFromPIICategoryValidity(piiCategories); if (isDebugEnabled()) { String message = String.format("User: %s has provided consent in receipt: %s for claims: " + claimsFromPIICategoryValidity, receipt.getPiiPrincipalId(), receipt.getConsentReceiptId()); logDebug(message); } return claimsFromPIICategoryValidity; } private List<ClaimMetaData> getClaimsFromPIICategoryValidity(List<PIICategoryValidity> piiCategories) { List<ClaimMetaData> claimMetaDataList = new ArrayList<>(); for (PIICategoryValidity piiCategoryValidity : piiCategories) { if (isConsentForClaimValid(piiCategoryValidity)) { ClaimMetaData claimMetaData = new ClaimMetaData(); claimMetaData.setClaimUri(piiCategoryValidity.getName()); claimMetaData.setDisplayName(piiCategoryValidity.getDisplayName()); claimMetaDataList.add(claimMetaData); } } return claimMetaDataList; } protected boolean isConsentForClaimValid(PIICategoryValidity piiCategoryValidity) { String consentValidity = piiCategoryValidity.getValidity(); if (isEmpty(consentValidity)) { return true; } List<String> consentValidityEntries = Arrays.asList(consentValidity.split(SSOConsentConstants .CONSENT_VALIDITY_SEPARATOR)); for (String consentValidityEntry : consentValidityEntries) { if (isSupportedExpiryType(consentValidityEntry)) { String[] validityEntry = consentValidityEntry.split(CONSENT_VALIDITY_TYPE_SEPARATOR, 2); if (validityEntry.length == 2) { try { String validTime = validityEntry[1]; if (isDebugEnabled()) { String message = String.format("Validity time for PII category: %s is %s.", piiCategoryValidity.getName(), validTime); logDebug(message); } if (isExpiryIndefinite(validTime)) { return true; } long consentExpiryInMillis = Long.parseLong(validTime); long currentTimeMillis = System.currentTimeMillis(); return isExpired(currentTimeMillis, consentExpiryInMillis); } catch (NumberFormatException e) { if (isDebugEnabled()) { String message = String.format("Cannot parse timestamp: %s. for PII category %s.", consentValidity, piiCategoryValidity.getName()); logDebug(message); } } } return false; } } return true; } private boolean isSupportedExpiryType(String consentValidityEntry) { return consentValidityEntry.toUpperCase().startsWith(CONSENT_VALIDITY_TYPE_VALID_UNTIL); } private boolean isExpired(long currentTimeMillis, long consentExpiryInMillis) { return consentExpiryInMillis > currentTimeMillis; } private boolean isExpiryIndefinite(String validTime) { return CONSENT_VALIDITY_TYPE_VALID_UNTIL_INDEFINITE.equalsIgnoreCase(validTime); } private boolean isMandatoryClaimsDisapproved(List<ClaimMetaData> consentMandatoryClaims, List<ClaimMetaData> disapprovedClaims) { return isNotEmpty(consentMandatoryClaims) && !Collections.disjoint(disapprovedClaims, consentMandatoryClaims); } private ConsentClaimsData getConsentRequiredClaimData(List<String> mandatoryClaims, List<String> requestedClaims, String tenantDomain) throws SSOConsentServiceException { ConsentClaimsData consentClaimsData = new ConsentClaimsData(); try { List<LocalClaim> localClaims = getClaimMetadataManagementService().getLocalClaims(tenantDomain); List<ClaimMetaData> mandatoryClaimsMetaData = new ArrayList<>(); List<ClaimMetaData> requestedClaimsMetaData = new ArrayList<>(); int claimId = 0; if (isNotEmpty(localClaims)) { for (LocalClaim localClaim : localClaims) { if (isAllRequiredClaimsChecked(mandatoryClaims, requestedClaims)) { break; } String claimURI = localClaim.getClaimURI(); if (mandatoryClaims.remove(claimURI)) { ClaimMetaData claimMetaData = buildClaimMetaData(claimId, localClaim, claimURI); mandatoryClaimsMetaData.add(claimMetaData); claimId++; } else if (requestedClaims.remove(claimURI)) { ClaimMetaData claimMetaData = buildClaimMetaData(claimId, localClaim, claimURI); requestedClaimsMetaData.add(claimMetaData); claimId++; } } } if (isNotEmpty(mandatoryClaims)) { for (String claimUri : mandatoryClaims) { ClaimMetaData claimMetaData = buildClaimMetaData(claimId, claimUri); mandatoryClaimsMetaData.add(claimMetaData); claimId++; } } if (isNotEmpty(requestedClaims)) { for (String claimUri : mandatoryClaims) { ClaimMetaData claimMetaData = buildClaimMetaData(claimId, claimUri); requestedClaimsMetaData.add(claimMetaData); claimId++; } } consentClaimsData.setMandatoryClaims(mandatoryClaimsMetaData); consentClaimsData.setRequestedClaims(requestedClaimsMetaData); } catch (ClaimMetadataException e) { throw new SSOConsentServiceException("Error while retrieving local claims", "Error occurred while " + "retrieving local claims for tenant: " + tenantDomain, e); } return consentClaimsData; } private boolean isAllRequiredClaimsChecked(List<String> mandatoryClaims, List<String> requestedClaims) { return isEmpty(mandatoryClaims) && isEmpty(requestedClaims); } private ClaimMetaData buildClaimMetaData(int claimId, String claimUri) { LocalClaim localClaim = new LocalClaim(claimUri); return buildClaimMetaData(claimId, localClaim, claimUri); } private ClaimMetaData buildClaimMetaData(int claimId, LocalClaim localClaim, String claimURI) { ClaimMetaData claimMetaData = new ClaimMetaData(); claimMetaData.setId(claimId); claimMetaData.setClaimUri(claimURI); String displayName = localClaim.getClaimProperties().get(DISPLAY_NAME_PROPERTY); if (isNotBlank(displayName)) { claimMetaData.setDisplayName(displayName); } else { claimMetaData.setDisplayName(claimURI); } String description = localClaim.getClaimProperty(DESCRIPTION_PROPERTY); if (isNotBlank(description)) { claimMetaData.setDescription(description); } else { claimMetaData.setDescription(EMPTY); } return claimMetaData; } private List<String> getClaimsFromConsentMetaData(List<ClaimMetaData> claimMetaDataList) { List<String> claims = new ArrayList<>(); for (ClaimMetaData claimMetaData : claimMetaDataList) { claims.add(claimMetaData.getClaimUri()); } return claims; } private String getFirstConsentReceiptFromList(List<ReceiptListResponse> receiptListResponses) { return receiptListResponses.get(0).getConsentReceiptId(); } private Receipt getReceipt(AuthenticatedUser authenticatedUser, String receiptId) throws SSOConsentServiceException { Receipt currentReceipt; String subject = buildSubjectWithUserStoreDomain(authenticatedUser); try { initializeTenantRegistry(authenticatedUser); startTenantFlowWithUser(subject, authenticatedUser.getTenantDomain()); currentReceipt = getConsentManager().getReceipt(receiptId); } catch (ConsentManagementException e) { throw new SSOConsentServiceException("Consent Management Error", "Error while retrieving user consents.", e); } catch (IdentityException e) { throw new SSOConsentServiceException("Consent Management Error", "Error while initializing registry for " + "the tenant domain: " + authenticatedUser.getTenantDomain(), e); } finally { PrivilegedCarbonContext.endTenantFlow(); } return currentReceipt; } private void initializeTenantRegistry(AuthenticatedUser authenticatedUser) throws IdentityException { IdentityTenantUtil.initializeRegistry( IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain())); } private boolean hasUserSingleReceipt(List<ReceiptListResponse> receiptListResponses) { return receiptListResponses.size() == 1; } private boolean hasUserMultipleReceipts(List<ReceiptListResponse> receiptListResponses) { return receiptListResponses.size() > 1; } private void startTenantFlowWithUser(String subject, String subjectTenantDomain) { startTenantFlow(subjectTenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(subject); } private void startTenantFlow(String tenantDomain) { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } private boolean isDebugEnabled() { return log.isDebugEnabled(); } private void logDebug(String message) { log.debug(message); } private ConsentManager getConsentManager() { return FrameworkServiceDataHolder.getInstance().getConsentManager(); } private ClaimMetadataManagementService getClaimMetadataManagementService() { return FrameworkServiceDataHolder.getInstance().getClaimMetadataManagementService(); } }
Resolve the tenant domain from the authenticated user.
components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/handler/request/impl/consent/SSOConsentServiceImpl.java
Resolve the tenant domain from the authenticated user.
<ide><path>omponents/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/handler/request/impl/consent/SSOConsentServiceImpl.java <ide> String spName = serviceProvider.getApplicationName(); <ide> String spTenantDomain = getSPTenantDomain(serviceProvider); <ide> String subject = buildSubjectWithUserStoreDomain(authenticatedUser); <add> String tenantDomain = authenticatedUser.getTenantDomain(); <ide> <ide> ClaimMapping[] claimMappings = getSpClaimMappings(serviceProvider); <ide> <ide> if (claimsListOfScopes != null) { <ide> try { <ide> claimMappings = FrameworkUtils.getFilteredScopeClaims(claimsListOfScopes, <del> Arrays.asList(claimMappings)).toArray(new ClaimMapping[0]); <add> Arrays.asList(claimMappings), tenantDomain).toArray(new ClaimMapping[0]); <ide> } catch (ClaimManagementException e) { <ide> throw new SSOConsentServiceException("Error occurred while filtering claims of requested scopes"); <ide> }
Java
mit
error: pathspec 'src/mr_kitten/Interface.java' did not match any file(s) known to git
b2512f14e67f91731347da53b398a509f8f1e937
1
ElodieCarpentier/Mr-Kitten,ElodieCarpentier/Mr-Kitten,ElodieCarpentier/Mr-Kitten,ElodieCarpentier/MrKitten_visual,ElodieCarpentier/MrKitten_visual,ElodieCarpentier/MrKitten_visual
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mr_kitten; /** * * @author Arya */ public interface Interface { }
src/mr_kitten/Interface.java
Initialisation d'une interface
src/mr_kitten/Interface.java
Initialisation d'une interface
<ide><path>rc/mr_kitten/Interface.java <add>/* <add> * To change this license header, choose License Headers in Project Properties. <add> * To change this template file, choose Tools | Templates <add> * and open the template in the editor. <add> */ <add>package mr_kitten; <add> <add>/** <add> * <add> * @author Arya <add> */ <add>public interface Interface { <add> <add>}
Java
apache-2.0
b27697ecaf66cf38091d6f595846637751dc8e08
0
sangramjadhav/testrs
2385cbde-2ece-11e5-905b-74de2bd44bed
hello.java
23853606-2ece-11e5-905b-74de2bd44bed
2385cbde-2ece-11e5-905b-74de2bd44bed
hello.java
2385cbde-2ece-11e5-905b-74de2bd44bed
<ide><path>ello.java <del>23853606-2ece-11e5-905b-74de2bd44bed <add>2385cbde-2ece-11e5-905b-74de2bd44bed
Java
mit
00ca6337111765a0253e7f42f3a4382ad1e54d0e
0
anasabau/FlightManager,anasabau/FlightManager
package ro.uvt.entity; import java.time.LocalDate; import ro.uvt.entity.dao.Persistent; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import lombok.Data; import lombok.NoArgsConstructor; /** * * @author Dan */ @Entity @Data @NoArgsConstructor public class Flight implements Persistent { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToOne private Plane plane_id; @OneToOne private Airport departure_airport; @OneToOne private Airport arival_airport; private LocalDate departure_time; private LocalDate arival_time; private FlightState state = FlightState.SATIONED; @OneToOne private Users pilot; @ManyToMany(mappedBy = "flights") private Set<Itinerary> itineraries; public Flight(Plane plane_id, Airport departure_airport, Airport arival_airport, LocalDate departure_time, Users pilot) { this.plane_id = plane_id; this.departure_airport = departure_airport; this.arival_airport = arival_airport; this.departure_time = departure_time; this.pilot = pilot; } }
FlightManager/entity/src/main/java/ro/uvt/entity/Flight.java
package ro.uvt.entity; import ro.uvt.entity.dao.Persistent; import java.util.Date; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import lombok.Data; import lombok.NoArgsConstructor; /** * * @author Dan */ @Entity @Data @NoArgsConstructor public class Flight implements Persistent { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToOne private Plane plane_id; @OneToOne private Airport departure_airport; @OneToOne private Airport arival_airport; @Temporal(TemporalType.TIMESTAMP) private Date departure_time; @Temporal(TemporalType.TIMESTAMP) private Date arival_time; private FlightState state = FlightState.SATIONED; @OneToOne private Users pilot; @ManyToMany(mappedBy = "flights") private Set<Itinerary> itineraries; public Flight(Plane plane_id, Airport departure_airport, Airport arival_airport, Date departure_time, Users pilot) { this.plane_id = plane_id; this.departure_airport = departure_airport; this.arival_airport = arival_airport; this.departure_time = departure_time; this.pilot = pilot; } }
javaee-8 migration, Date to LocalDate
FlightManager/entity/src/main/java/ro/uvt/entity/Flight.java
javaee-8 migration, Date to LocalDate
<ide><path>lightManager/entity/src/main/java/ro/uvt/entity/Flight.java <ide> package ro.uvt.entity; <ide> <add>import java.time.LocalDate; <ide> import ro.uvt.entity.dao.Persistent; <del>import java.util.Date; <ide> import java.util.Set; <ide> import javax.persistence.Entity; <ide> import javax.persistence.GeneratedValue; <ide> import javax.persistence.Id; <ide> import javax.persistence.ManyToMany; <ide> import javax.persistence.OneToOne; <del>import javax.persistence.Temporal; <del>import javax.persistence.TemporalType; <ide> import lombok.Data; <ide> import lombok.NoArgsConstructor; <ide> <ide> @OneToOne <ide> private Airport arival_airport; <ide> <del> @Temporal(TemporalType.TIMESTAMP) <del> private Date departure_time; <add> <add> private LocalDate departure_time; <ide> <del> @Temporal(TemporalType.TIMESTAMP) <del> private Date arival_time; <add> <add> private LocalDate arival_time; <ide> <ide> private FlightState state = FlightState.SATIONED; <ide> <ide> @ManyToMany(mappedBy = "flights") <ide> private Set<Itinerary> itineraries; <ide> <del> public Flight(Plane plane_id, Airport departure_airport, Airport arival_airport, Date departure_time, Users pilot) { <add> public Flight(Plane plane_id, Airport departure_airport, Airport arival_airport, LocalDate departure_time, Users pilot) { <ide> this.plane_id = plane_id; <ide> this.departure_airport = departure_airport; <ide> this.arival_airport = arival_airport;
Java
apache-2.0
error: pathspec 'java/leetcode/peeking_iterator/PeekingIterator.java' did not match any file(s) known to git
9e5182f8164d34aa915321a139fe85f423ae0358
1
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
package leetcode.peeking_iterator; import java.util.Iterator; class PeekingIterator implements Iterator<Integer> { private Iterator<Integer> mIterator; private Integer mNext; private boolean mHasNext; private final void nextInternal(){ mHasNext = mIterator.hasNext(); if(mHasNext){ mNext = mIterator.next(); } } public PeekingIterator(Iterator<Integer> iterator) { mIterator = iterator; nextInternal(); } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { return mNext; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { if(mHasNext){ Integer ret = mNext; nextInternal(); return ret; }else{ return null; // don't know how to handle } } @Override public boolean hasNext() { return mHasNext; } @Override public void remove() { } }
java/leetcode/peeking_iterator/PeekingIterator.java
Add solution for 284. Peeking Iterator 284. Peeking Iterator: https://leetcode.com/problems/peeking-iterator/
java/leetcode/peeking_iterator/PeekingIterator.java
Add solution for 284. Peeking Iterator
<ide><path>ava/leetcode/peeking_iterator/PeekingIterator.java <add>package leetcode.peeking_iterator; <add> <add>import java.util.Iterator; <add> <add>class PeekingIterator implements Iterator<Integer> { <add> <add> private Iterator<Integer> mIterator; <add> private Integer mNext; <add> private boolean mHasNext; <add> <add> private final void nextInternal(){ <add> mHasNext = mIterator.hasNext(); <add> if(mHasNext){ <add> mNext = mIterator.next(); <add> } <add> } <add> <add> public PeekingIterator(Iterator<Integer> iterator) { <add> mIterator = iterator; <add> nextInternal(); <add> } <add> <add> // Returns the next element in the iteration without advancing the iterator. <add> public Integer peek() { <add> return mNext; <add> } <add> <add> // hasNext() and next() should behave the same as in the Iterator interface. <add> // Override them if needed. <add> @Override <add> public Integer next() { <add> if(mHasNext){ <add> Integer ret = mNext; <add> nextInternal(); <add> return ret; <add> }else{ <add> return null; // don't know how to handle <add> } <add> } <add> <add> @Override <add> public boolean hasNext() { <add> return mHasNext; <add> } <add> <add> @Override <add> public void remove() { <add> <add> } <add>}
Java
apache-2.0
f3420318ac28923b0cc99402ecbc82a5436998eb
0
vivantech/kc_fixes,vivantech/kc_fixes,vivantech/kc_fixes,vivantech/kc_fixes,vivantech/kc_fixes,vivantech/kc_fixes
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.award.web.struts.action; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.kra.authorization.KraAuthorizationConstants; import org.kuali.kra.award.*; import org.kuali.kra.award.awardhierarchy.AwardHierarchy; import org.kuali.kra.award.awardhierarchy.AwardHierarchyBean; import org.kuali.kra.award.awardhierarchy.AwardHierarchyService; import org.kuali.kra.award.awardhierarchy.AwardHierarchyTempObject; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncPendingChangeBean; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncType; import org.kuali.kra.award.awardhierarchy.sync.service.AwardSyncCreationService; import org.kuali.kra.award.awardhierarchy.sync.service.AwardSyncService; import org.kuali.kra.award.budget.AwardBudgetService; import org.kuali.kra.award.contacts.AwardPerson; import org.kuali.kra.award.contacts.AwardProjectPersonsSaveRule; import org.kuali.kra.award.customdata.AwardCustomData; import org.kuali.kra.award.document.AwardDocument; import org.kuali.kra.award.home.Award; import org.kuali.kra.award.home.AwardAmountInfo; import org.kuali.kra.award.home.AwardComment; import org.kuali.kra.award.home.AwardService; import org.kuali.kra.award.home.approvedsubawards.AwardApprovedSubaward; import org.kuali.kra.award.paymentreports.ReportClass; import org.kuali.kra.award.paymentreports.awardreports.AwardReportTerm; import org.kuali.kra.award.paymentreports.awardreports.AwardReportTermRecipient; import org.kuali.kra.award.paymentreports.awardreports.reporting.service.ReportTrackingService; import org.kuali.kra.award.paymentreports.closeout.CloseoutReportTypeValuesFinder; import org.kuali.kra.award.timeandmoney.AwardDirectFandADistribution; import org.kuali.kra.award.version.service.AwardVersionService; import org.kuali.kra.bo.versioning.VersionHistory; import org.kuali.kra.bo.versioning.VersionStatus; import org.kuali.kra.budget.web.struts.action.BudgetParentActionBase; import org.kuali.kra.common.notification.service.KcNotificationService; import org.kuali.kra.infrastructure.*; import org.kuali.kra.krms.service.KrmsRulesExecutionService; import org.kuali.kra.service.*; import org.kuali.kra.subaward.service.SubAwardService; import org.kuali.kra.timeandmoney.AwardHierarchyNode; import org.kuali.kra.timeandmoney.document.TimeAndMoneyDocument; import org.kuali.kra.timeandmoney.history.TransactionDetail; import org.kuali.kra.timeandmoney.history.TransactionDetailType; import org.kuali.kra.timeandmoney.rules.TimeAndMoneyAwardDateSaveRuleImpl; import org.kuali.kra.timeandmoney.transactions.AwardAmountTransaction; import org.kuali.kra.web.struts.action.AuditActionHelper; import org.kuali.kra.web.struts.action.AuditActionHelper.ValidationState; import org.kuali.kra.web.struts.action.StrutsConfirmation; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.core.api.util.ConcreteKeyValue; import org.kuali.rice.core.api.util.KeyValue; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.coreservice.framework.parameter.ParameterConstants; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.kew.api.KewApiConstants; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.kns.question.ConfirmationQuestion; import org.kuali.rice.kns.util.KNSGlobalVariables; import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase; import org.kuali.rice.kns.web.struts.form.KualiForm; import org.kuali.rice.krad.bo.PersistableBusinessObject; import org.kuali.rice.krad.rules.rule.event.KualiDocumentEvent; import org.kuali.rice.krad.service.*; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; import static org.apache.commons.lang.StringUtils.replace; import static org.kuali.rice.krad.util.KRADConstants.CONFIRMATION_QUESTION; /** * * This class represents base Action class for all the Award pages. */ public class AwardAction extends BudgetParentActionBase { protected static final String AWARD_ID_PARAMETER_NAME = "awardId"; private static final String INITIAL_TRANSACTION_COMMENT = "Initial Time And Money creation transaction"; private static final String REPORTS_PROPERTY_NAME = "Reports"; private static final String PAYMENT_INVOICES_PROPERTY_NAME = "Payments and Invoices"; private static final String COMFIRMATION_PARAM_STRING = "After Award {0} information is synchronized, make sure that the Award Sponsor Contacts information is also synchronized with the same sponsor template. Failing to do so will result in data inconsistency. Are you sure you want to replace current {0} information with selected {1} template information?"; private static final String SUPER_USER_ACTION_REQUESTS = "superUserActionRequests"; private enum SuperUserAction { SUPER_USER_APPROVE, TAKE_SUPER_USER_ACTIONS } private ParameterService parameterService; private transient AwardBudgetService awardBudgetService; private transient AwardService awardService; private transient ReportTrackingService reportTrackingService; private transient KcNotificationService notificationService; private transient SubAwardService subAwardService; TimeAndMoneyAwardDateSaveRuleImpl timeAndMoneyAwardDateSaveRuleImpl; private static final Log LOG = LogFactory.getLog( AwardAction.class ); //question constants private static final String QUESTION_VERIFY_SYNC="VerifySync"; private static final String QUESTION_VERIFY_EMPTY_SYNC="VerifyEmptySync"; private static final AwardTemplateSyncScope[] DEFAULT_SCOPES_REQUIRE_VERIFY_FOR_EMPTY = new AwardTemplateSyncScope[] { AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB, AwardTemplateSyncScope.SPONSOR_CONTACTS_TAB, AwardTemplateSyncScope.REPORTS_TAB }; private static final AwardTemplateSyncScope[] DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES = new AwardTemplateSyncScope[] { AwardTemplateSyncScope.AWARD_PAGE, AwardTemplateSyncScope.COST_SHARE, AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB, AwardTemplateSyncScope.SPONSOR_CONTACTS_TAB, AwardTemplateSyncScope.TERMS_TAB, AwardTemplateSyncScope.REPORTS_TAB, AwardTemplateSyncScope.COMMENTS_TAB }; private static final int NINE = 9; private static final String DOCUMENT_ROUTE_QUESTION="DocRoute"; private static final String ADD_SYNC_CHANGE_QUESTION = "document.question.awardhierarchy.sync"; private static final String DEL_SYNC_CHANGE_QUESTION = "document.question.awardhierarchy.sync"; /** * @see org.kuali.core.web.struts.action.KualiDocumentActionBase#docHandler( * org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward docHandler(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; ActionForward forward; cleanUpUserSession(); forward = handleDocument(mapping, form, request, response, awardForm); AwardDocument awardDocument = (AwardDocument) awardForm.getDocument(); //check to see if this document might be a part of an active award sync(if it is lock it) AwardDocument parentSyncAward = getAwardSyncService().getAwardLockingHierarchyForSync(awardDocument, GlobalVariables.getUserSession().getPrincipalId()); if (parentSyncAward != null) { KNSGlobalVariables.getMessageList().add("error.award.awardhierarchy.sync.locked", parentSyncAward.getDocumentNumber()); awardForm.setViewOnly(true); } handlePlaceHolderDocument(awardForm, awardDocument); awardForm.initializeFormOrDocumentBasedOnCommand(); setBooleanAwardInMultipleNodeHierarchyOnForm (awardDocument.getAward()); setBooleanAwardHasTandMOrIsVersioned(awardDocument.getAward()); setSubAwardDetails(awardDocument.getAward()); return forward; } private void handlePlaceHolderDocument(AwardForm form, AwardDocument awardDocument) { if(awardDocument.isPlaceHolderDocument()) { Long awardId = form.getPlaceHolderAwardId(); //If it is a placeholder document, we want to initialize it with the award that the user is viewing int currentAwardIndex = -1; Award currentAward = null; for(Award award : awardDocument.getAwardList()) { currentAwardIndex++; if(ObjectUtils.equals(award.getAwardId(), awardId)) { currentAward = award; break; } } if(currentAward != null) { awardDocument.getAwardList().remove(currentAwardIndex); awardDocument.getAwardList().add(0, currentAward); form.setViewOnly(true); } } } protected void cleanUpUserSession() { GlobalVariables.getUserSession().removeObject(GlobalVariables.getUserSession().getKualiSessionId() + Constants.TIME_AND_MONEY_DOCUMENT_STRING_FOR_SESSION); } /** * @see org.kuali.kra.web.struts.action.KraTransactionalDocumentActionBase#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm)form; ActionForward actionForward = super.execute(mapping, form, request, response); if (awardForm.isAuditActivated()){ awardForm.setUnitRulesMessages(getUnitRulesMessages(awardForm.getAwardDocument())); } if (KNSGlobalVariables.getAuditErrorMap().isEmpty()) { new AuditActionHelper().auditConditionally((AwardForm) form); } return actionForward; } protected List<String> getUnitRulesMessages(AwardDocument awardDoc) { KrmsRulesExecutionService rulesService = KraServiceLocator.getService(KrmsRulesExecutionService.class); return rulesService.processUnitValidations(awardDoc.getLeadUnitNumber(), awardDoc); } /** * This method populates the AwardHierarchy data * @param form * @throws WorkflowException */ protected void populateAwardHierarchy(ActionForm form) throws WorkflowException { AwardForm awardForm = (AwardForm)form; AwardDocument awardDocument = awardForm.getAwardDocument(); List<String> order = new ArrayList<String>(); AwardHierarchyBean helperBean = awardForm.getAwardHierarchyBean(); AwardHierarchy rootNode = helperBean.getRootNode(); Map<String, AwardHierarchy> awardHierarchyNodes = helperBean.getAwardHierarchy(rootNode, order); Map<String,AwardHierarchyNode> awardHierarchyNodesMap = new HashMap<String, AwardHierarchyNode>(); Award currentAward = awardDocument.getAward(); awardForm.setRootAwardNumber(rootNode.getRootAwardNumber()); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for(String str:order){ AwardHierarchy tempAwardNode = awardHierarchyNodes.get(str); sb1.append(tempAwardNode.getAwardNumber()); sb1.append(KRADConstants.BLANK_SPACE).append("%3A"); if (getVersionHistoryService().findActiveVersion(Award.class, tempAwardNode.getAwardNumber()) != null) { sb2.append(tempAwardNode.getAwardNumber()); sb2.append(KRADConstants.BLANK_SPACE).append("%3A"); } } for(int i = 0; i < helperBean.getMaxAwardNumber(); i++){ AwardHierarchyTempObject temp = awardForm.getAwardHierarchyTempObjects().get(i); temp.setSelectBox1(sb1.toString()); temp.setSelectBox2(sb2.toString()); } } protected TimeAndMoneyExistenceService getTimeAndMoneyExistenceService() { return KraServiceLocator.getService(TimeAndMoneyExistenceService.class); } @Override public ActionForward approve(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; AwardForm awardForm = (AwardForm) form; if(getTimeAndMoneyExistenceService().validateTimeAndMoneyRule(awardForm.getAwardDocument().getAward(), awardForm.getAwardHierarchyBean().getRootNode().getAwardNumber())){ forward = super.approve(mapping, form, request, response); }else{ getTimeAndMoneyExistenceService().addAwardVersionErrorMessage(); forward = mapping.findForward(Constants.MAPPING_AWARD_BASIC); } String routeHeaderId = awardForm.getDocument().getDocumentNumber(); String returnLocation = buildActionUrl(routeHeaderId, Constants.MAPPING_AWARD_ACTIONS_PAGE, "AwardDocument"); ActionForward basicForward = mapping.findForward(KRADConstants.MAPPING_PORTAL); ActionForward holdingPageForward = mapping.findForward(Constants.MAPPING_HOLDING_PAGE); return routeToHoldingPage(basicForward, forward, holdingPageForward, returnLocation); } protected ActionForward submitAward(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC); if(getTimeAndMoneyExistenceService().validateTimeAndMoneyRule(awardForm.getAwardDocument().getAward(), awardForm.getAwardHierarchyBean().getRootNode().getAwardNumber())){ forward = super.route(mapping, form, request, response); populateAwardHierarchy(awardForm); }else{ getTimeAndMoneyExistenceService().addAwardVersionErrorMessage(); } String routeHeaderId = awardForm.getDocument().getDocumentNumber(); String returnLocation = buildActionUrl(routeHeaderId, Constants.MAPPING_AWARD_ACTIONS_PAGE, "AwardDocument"); ActionForward basicForward = mapping.findForward(KRADConstants.MAPPING_PORTAL); ActionForward holdingPageForward = mapping.findForward(Constants.MAPPING_HOLDING_PAGE); return routeToHoldingPage(basicForward, forward, holdingPageForward, returnLocation); } @Override public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC); AwardForm awardForm = (AwardForm) form; awardForm.setAuditActivated(true); Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON); String methodToCall = ((KualiForm) form).getMethodToCall(); ValidationState status = new AuditActionHelper().isValidSubmission(awardForm, true); if (status == ValidationState.WARNING) { if(question == null){ return this.performQuestionWithoutInput(mapping, form, request, response, DOCUMENT_ROUTE_QUESTION, "Validation Warning Exists. Are you sure want to submit to workflow routing.", KRADConstants.CONFIRMATION_QUESTION, methodToCall, ""); } else if(DOCUMENT_ROUTE_QUESTION.equals(question) && ConfirmationQuestion.YES.equals(buttonClicked)) { return submitAward(mapping, form, request, response); } else { return forward; } } if(status == ValidationState.OK){ return submitAward(mapping, form, request, response); } else { GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("datavalidation",KeyConstants.ERROR_WORKFLOW_SUBMISSION, new String[] {}); return forward; } } @Override public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; AwardForm awardForm = (AwardForm) form; if (getTimeAndMoneyExistenceService().validateTimeAndMoneyRule(awardForm.getAwardDocument().getAward(), awardForm.getAwardHierarchyBean().getRootNode().getAwardNumber())) { awardForm.setAuditActivated(true); ValidationState status = new AuditActionHelper().isValidSubmission(awardForm, true); if (status == ValidationState.ERROR) { GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("datavalidation", KeyConstants.ERROR_WORKFLOW_SUBMISSION, new String[] {}); forward = mapping.findForward(Constants.MAPPING_AWARD_BASIC); } else { forward = super.blanketApprove(mapping, form, request, response); } } else { getTimeAndMoneyExistenceService().addAwardVersionErrorMessage(); forward = mapping.findForward(Constants.MAPPING_AWARD_BASIC); } String routeHeaderId = awardForm.getDocument().getDocumentNumber(); String returnLocation = buildActionUrl(routeHeaderId, Constants.MAPPING_AWARD_ACTIONS_PAGE, "AwardDocument"); ActionForward basicForward = mapping.findForward(KRADConstants.MAPPING_PORTAL); ActionForward holdingPageForward = mapping.findForward(Constants.MAPPING_HOLDING_PAGE); return routeToHoldingPage(basicForward, forward, holdingPageForward, returnLocation); } /** * @see org.kuali.kra.web.struts.action.KraTransactionalDocumentActionBase#save(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO: JF Are all of these saves in a single transaction? ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC); AwardForm awardForm = (AwardForm) form; Award award = awardForm.getAwardDocument().getAward(); checkAwardNumber(award); String userId = GlobalVariables.getUserSession().getPrincipalName(); if (award.getAwardApprovedSubawards() == null || award.getAwardApprovedSubawards().isEmpty()) { award.setSubContractIndicator(Constants.NO_FLAG); } else { award.setSubContractIndicator(Constants.YES_FLAG); } if (award.getAwardTransferringSponsors() == null || award.getAwardTransferringSponsors().isEmpty()) { award.setTransferSponsorIndicator(Constants.NO_FLAG); } else { award.setTransferSponsorIndicator(Constants.YES_FLAG); } if (award.getKeywords() == null || award.getKeywords().isEmpty()) { award.setScienceCodeIndicator(Constants.NO_FLAG); } else { award.setScienceCodeIndicator(Constants.YES_FLAG); } forward = super.save(mapping, form, request, response); if (awardForm.getMethodToCall().equals("save") && awardForm.isAuditActivated()) { forward = mapping.findForward(Constants.MAPPING_AWARD_ACTIONS_PAGE); } AwardHierarchyBean bean = awardForm.getAwardHierarchyBean(); if (bean.saveHierarchyChanges()) { List<String> order = new ArrayList<String>(); awardForm.setAwardHierarchyNodes(bean.getAwardHierarchy(bean.getRootNode().getAwardNumber(), order)); } // generate hierarchy sync changes after save so all BOs have ids and parent ids set for (AwardSyncPendingChangeBean pendingChange : awardForm.getAwardSyncBean().getConfirmedPendingChanges()) { // refresh object to make sure all references have been loaded before the sync pendingChange.getObject().refresh(); getAwardSyncCreationService().addAwardSyncChange(award, pendingChange); } // now we need to save the hierarchy changes getBusinessObjectService().save(award.getSyncChanges()); awardForm.getAwardSyncBean().getConfirmedPendingChanges().clear(); /** * deal with the award report tracking generation business. */ getReportTrackingService().generateReportTrackingAndSave(award, false); return forward; } @Override public ActionForward reload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; ActionForward actionForward = super.reload(mapping, form, request, response); getReportTrackingService().refreshReportTracking(awardForm.getAwardDocument().getAward()); return actionForward; } @Override public ActionForward close(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; if (awardForm.getViewFundingSource()) { return mapping.findForward(Constants.MAPPING_CLOSE_PAGE); } else { return super.close(mapping, form, request, response); } } /** * This method returns the award associated with the AwardDocument on the AwardForm * @return */ protected Award getAward(ActionForm form) { return getAwardDocument(form).getAward(); } /** * This method returns the AwardDocument * * @param form * @return */ protected AwardDocument getAwardDocument(ActionForm form) { return ((AwardForm) form).getAwardDocument(); } /** * This method sets an award number on an award if the award number hasn't been initialized yet. * @param award */ protected void checkAwardNumber(Award award) { if (Award.DEFAULT_AWARD_NUMBER.equals(award.getAwardNumber())) { AwardNumberService awardNumberService = getAwardNumberService(); String awardNumber = awardNumberService.getNextAwardNumber(); award.setAwardNumber(awardNumber); } if (Award.DEFAULT_AWARD_NUMBER.equals(award.getAwardAmountInfos().get(0).getAwardNumber())) { award.getAwardAmountInfos().get(0).setAwardNumber(award.getAwardNumber()); } for(AwardApprovedSubaward approvedSubaward : award.getAwardApprovedSubawards()) { if(Award.DEFAULT_AWARD_NUMBER.equals(approvedSubaward.getAwardNumber())) { approvedSubaward.setAwardNumber(award.getAwardNumber()); } } for(AwardComment comment : award.getAwardComments()) { comment.setAward(award); } for(AwardCustomData customData : award.getAwardCustomDataList()) { customData.setAward(award); } } /** * * This method is a helper method to retrieve AwardNumberService. * @return */ protected AwardNumberService getAwardNumberService() { return KraServiceLocator.getService(AwardNumberService.class); } /** * @see org.kuali.kra.web.struts.action.KraTransactionalDocumentActionBase#initialDocumentSave(org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase) * * TODO JF: Handle initial save * * One of these conditions exist when this method is called: 1) This is a new award, created from the "Create Award" portal action. A new root node needs to be created a) prevAwardNumber and prevRootAwardNumber are null b) awardHierarchyBean.rootNodes.size() == 0 2) This is a new award created from a hierarchy action. The node for this award should exist on the hierarchy bean a) prevAwardNumber and prevRootAwardNumber are ? b) awardHierarchyBean.rootNodes.size() == ? */ @Override protected void initialDocumentSave(KualiDocumentFormBase form) throws Exception { AwardForm awardForm = (AwardForm) form; AwardDocument awardDocument = (AwardDocument) awardForm.getDocument(); createInitialAwardUsers(awardForm.getAwardDocument().getAward()); populateStaticCloseoutReports(awardForm); String userId = GlobalVariables.getUserSession().getPrincipalName(); Award award = awardDocument.getAward(); getAwardService().updateAwardSequenceStatus(award, VersionStatus.PENDING); getVersionHistoryService().updateVersionHistory(award, VersionStatus.PENDING, userId); if(!awardForm.getAwardDocument().isDocumentSaveAfterVersioning()) { awardForm.getAwardHierarchyBean().createDefaultAwardHierarchy(); awardForm.getAwardHierarchyBean().saveHierarchyChanges(); } } /** * Create the original set of Award Users for a new Award Document. * The creator the award is assigned to the AWARD_MODIFIER role, if the creator isn't already an AWARD_MODIFIER. * * @param doc */ protected void createInitialAwardUsers(Award award) { String userId = GlobalVariables.getUserSession().getPrincipalId(); KraAuthorizationService kraAuthService = KraServiceLocator.getService(KraAuthorizationService.class); if (!kraAuthService.hasRole(userId, KraAuthorizationConstants.KC_AWARD_NAMESPACE, AwardRoleConstants.AWARD_MODIFIER.getAwardRole())) { kraAuthService.addRole(userId, AwardRoleConstants.AWARD_MODIFIER.getAwardRole(), award); } } /** * * This method populates the initial static AwardCloseout reports upon the creation of an Award. * * @param form */ protected void populateStaticCloseoutReports(AwardForm form){ CloseoutReportTypeValuesFinder closeoutReportTypeValuesFinder = new CloseoutReportTypeValuesFinder(); form.getAwardCloseoutBean().addAwardCloseoutStaticItems(closeoutReportTypeValuesFinder.getKeyValues()); } protected AwardHierarchyService getAwardHierarchyService(){ return KraServiceLocator.getService(AwardHierarchyService.class); } /** * Can the Award be saved? This method is normally overridden by * a subclass in order to invoke business rules to verify that the * Award can be saved. * @param awardForm the Award Form * @return true if the award can be saved; otherwise false */ protected boolean isValidSave(AwardForm awardForm) { AwardDocument awardDocument = (AwardDocument) awardForm.getDocument(); String leadUnitNumber = awardDocument.getLeadUnitNumber(); if (StringUtils.isNotEmpty(leadUnitNumber) && checkNoMoreThanOnePI(awardDocument.getAward())) { String userId = GlobalVariables.getUserSession().getPrincipalId(); UnitAuthorizationService authService = KraServiceLocator.getService(UnitAuthorizationService.class); //List<Unit> userUnits = authService.getUnits(userId, Constants.MODULE_NAMESPACE_AWARD, AwardPermissionConstants.CREATE_AWARD.getAwardPermission()); return authService.hasMatchingQualifiedUnits(userId, Constants.MODULE_NAMESPACE_AWARD, AwardPermissionConstants.MODIFY_AWARD.getAwardPermission(), leadUnitNumber); } return false; } private boolean checkNoMoreThanOnePI(Award award) { int piCount = 0; int counter = 0; ArrayList<String> fields = new ArrayList<String>(); for (AwardPerson p : award.getProjectPersons()) { if (p.isPrincipalInvestigator()) { piCount++; fields.add("projectPersonnelBean.projectPersonnel[" + counter + "].contactRoleCode"); } counter++; } boolean valid = piCount <= 1; if (!valid) { //projectPersonnelBean.contactRoleCode //projectPersonnelBean.projectPersonnel[0].contactRoleCode for (String field : fields) { GlobalVariables.getMessageMap().putError(field, AwardProjectPersonsSaveRule.ERROR_AWARD_PROJECT_PERSON_MULTIPLE_PI_EXISTS); } } return valid; } /** * Use the Kuali Rule Service to apply the rules for the given event. * @param event the event to process * @return true if success; false if there was a validation error */ protected final boolean applyRules(KualiDocumentEvent event) { return getKualiRuleService().applyRules(event); } /** * * This method builds the string for the ActionForward * @param forwardPath * @param docIdRequestParameter * @return */ public String buildForwardStringForActionListCommand(String forwardPath, String docIdRequestParameter){ StringBuilder sb = new StringBuilder(); sb.append(forwardPath); sb.append("?"); sb.append(KRADConstants.PARAMETER_DOC_ID); sb.append("="); sb.append(docIdRequestParameter); return sb.toString(); } /** * * This method gets called upon navigation to Awards tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward home(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; AwardDocument awardDocument = (AwardDocument) awardForm.getDocument(); setBooleanAwardInMultipleNodeHierarchyOnForm (awardDocument.getAward()); setBooleanAwardHasTandMOrIsVersioned(awardDocument.getAward()); AwardAmountInfoService awardAmountInfoService = KraServiceLocator.getService(AwardAmountInfoService.class); int index = awardAmountInfoService.fetchIndexOfAwardAmountInfoWithHighestTransactionId(awardDocument.getAward().getAwardAmountInfos()); return mapping.findForward(Constants.MAPPING_AWARD_HOME_PAGE); } /** * This method... * @param awardDocument * @param awardForm */ @SuppressWarnings("unchecked") public void setBooleanAwardInMultipleNodeHierarchyOnForm (Award award) { Map<String, Object> fieldValues = new HashMap<String, Object>(); String awardNumber = award.getAwardNumber(); fieldValues.put("awardNumber", awardNumber); fieldValues.put("active", Boolean.TRUE); BusinessObjectService businessObjectService = KraServiceLocator.getService(BusinessObjectService.class); List<AwardHierarchy> awardHierarchies = (List) businessObjectService.findMatching(AwardHierarchy.class, fieldValues); if (awardHierarchies.size() == 0) { award.setAwardInMultipleNodeHierarchy(false); }else { Map<String, Object> newFieldValues = new HashMap<String, Object>(); String rootAwardNumber = awardHierarchies.get(0).getRootAwardNumber(); newFieldValues.put("rootAwardNumber", rootAwardNumber); newFieldValues.put("active", Boolean.TRUE); int matchingValues = businessObjectService.countMatching(AwardHierarchy.class, newFieldValues); if (matchingValues > 1) { award.setAwardInMultipleNodeHierarchy(true); }else { award.setAwardInMultipleNodeHierarchy(false); } } } /** * If an Award has associated Time and Money document or been versioned and no previous version has been edited in a Time and Money document, * then we want the money and date fields on Award to be read only. * @param awardDocument * @param awardForm */ public void setBooleanAwardHasTandMOrIsVersioned (Award award) { boolean previousVersionHasBeenEditedInTandMDocument = false; // what we really want to do is check to see if latest version of Awards has a T&M doc associated with it. // If it's versioned, that's OK, we still want to allow editing of the amounts and dates. List<VersionHistory> awardHistory = getVersionHistoryService().findVersionHistory(Award.class, award.getAwardNumber()); if(awardHistory.size() > 1) { if (award.getSequenceNumber() == 1 && award.getAwardAmountInfos().size() > 2) { previousVersionHasBeenEditedInTandMDocument = true; } else if (award.getSequenceNumber() > 1 && award.getAwardAmountInfos().size() > 1) { previousVersionHasBeenEditedInTandMDocument = true; } } award.setAwardHasAssociatedTandMOrIsVersioned(previousVersionHasBeenEditedInTandMDocument); } /** * * This method gets called upon navigation to Contacts tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward contacts(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { SponsorService sponsorService = getSponsorService(); Award award = getAward(form); AwardForm awardForm = (AwardForm) form; award.initCentralAdminContacts(); return mapping.findForward(Constants.MAPPING_AWARD_CONTACTS_PAGE); } /** * * This method gets called upon navigation to Commitments tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward commitments(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { return mapping.findForward(Constants.MAPPING_AWARD_COMMITMENTS_PAGE); } protected void generateDirectFandADistribution(Award award) { if(!(award.getAwardEffectiveDate() == null)) { // delete entries that were added during previous T&M initiations but the doc cancelled. getBusinessObjectService().delete(award.getAwardDirectFandADistributions()); Boolean autoGenerate = getParameterService().getParameterValueAsBoolean(Constants.PARAMETER_MODULE_AWARD, ParameterConstants.DOCUMENT_COMPONENT, KeyConstants.AUTO_GENERATE_TIME_MONEY_FUNDS_DIST_PERIODS); if (autoGenerate) { AwardDirectFandADistributionService awardDirectFandADistributionService = getAwardDirectFandADistributionService(); award.setAwardDirectFandADistributions (awardDirectFandADistributionService. generateDefaultAwardDirectFandADistributionPeriods(award)); } } } @SuppressWarnings({ "deprecation", "unchecked" }) public ActionForward timeAndMoney(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ AwardForm awardForm = (AwardForm) form; AwardDocument awardDocument = awardForm.getAwardDocument(); ActionForward actionForward; //if award document is view only then we don't need to save document before opening T&M document. if ((!awardForm.getEditingMode().containsKey("viewOnly") || awardForm.getEditingMode().containsKey("fullEntry")) && !awardDocument.getDocumentHeader().getWorkflowDocument().isFinal()) { this.save(mapping, form, request, response); } //if T&M document is created, there must be a project start date on the award. timeAndMoneyAwardDateSaveRuleImpl = new TimeAndMoneyAwardDateSaveRuleImpl(); timeAndMoneyAwardDateSaveRuleImpl.enforceAwardStartDatePopulated(awardDocument.getAward()); if(GlobalVariables.getMessageMap().hasNoErrors()){ //AwardForm awardForm = (AwardForm) form; DocumentService documentService = KraServiceLocator.getService(DocumentService.class); boolean firstTimeAndMoneyDocCreation = Boolean.TRUE; TransactionDetail transactionDetail = null; populateAwardHierarchy(form); Award currentAward = awardDocument.getAward(); Map<String, Object> fieldValues = new HashMap<String, Object>(); String rootAwardNumber = awardForm.getAwardHierarchyNodes().get(currentAward.getAwardNumber()).getRootAwardNumber(); fieldValues.put("rootAwardNumber", rootAwardNumber); BusinessObjectService businessObjectService = KraServiceLocator.getService(BusinessObjectService.class); List<TimeAndMoneyDocument> timeAndMoneyDocuments = (List<TimeAndMoneyDocument>)businessObjectService.findMatching(TimeAndMoneyDocument.class, fieldValues); Collections.sort(timeAndMoneyDocuments); Award rootAward = getAwardVersionService().getWorkingAwardVersion(rootAwardNumber); // check for existing finalized T & M document before creating a new one. TimeAndMoneyDocument timeAndMoneyDocument = getLastFinalTandMDocument(timeAndMoneyDocuments); if(timeAndMoneyDocuments.size() > 0 && timeAndMoneyDocument != null) { firstTimeAndMoneyDocCreation = Boolean.FALSE; } if (timeAndMoneyDocument == null) { generateDirectFandADistribution(rootAward); } if(firstTimeAndMoneyDocCreation){ timeAndMoneyDocument = (TimeAndMoneyDocument) documentService.getNewDocument(TimeAndMoneyDocument.class); timeAndMoneyDocument.getDocumentHeader().setDocumentDescription("timeandmoney document"); timeAndMoneyDocument.setRootAwardNumber(rootAwardNumber); timeAndMoneyDocument.setAwardNumber(rootAward.getAwardNumber()); timeAndMoneyDocument.setAward(rootAward); AwardAmountTransaction aat = new AwardAmountTransaction(); aat.setAwardNumber("000000-00000");//need to initialize one element in this collection because the doc is saved on creation. aat.setDocumentNumber(timeAndMoneyDocument.getDocumentNumber()); String defaultTxnTypeStr = getParameterService().getParameterValueAsString(Constants.MODULE_NAMESPACE_TIME_AND_MONEY, ParameterConstants.DOCUMENT_COMPONENT, Constants.DEFAULT_TXN_TYPE_COPIED_AWARD); if(StringUtils.isNotEmpty(defaultTxnTypeStr)) { aat.setTransactionTypeCode(Integer.parseInt(defaultTxnTypeStr)); } aat.setAwardNumber(rootAward.getAwardNumber()); //any code for initial transaction and history. transactionDetail = addTransactionDetails(Constants.AWARD_HIERARCHY_DEFAULT_PARENT_OF_ROOT, rootAward.getAwardNumber(), rootAward.getSequenceNumber(), timeAndMoneyDocument.getDocumentNumber(), INITIAL_TRANSACTION_COMMENT, rootAward); //need this check so we don't add additional AAI object if Award has been copied and then creating first T&M doc. if(rootAward.getAwardAmountInfos().size() < 2) { addNewAwardAmountInfoForInitialTransaction(rootAward, timeAndMoneyDocument.getDocumentNumber()); }else { rootAward.getLastAwardAmountInfo().setTimeAndMoneyDocumentNumber(timeAndMoneyDocument.getDocumentNumber()); getBusinessObjectService().save(rootAward); } timeAndMoneyDocument.getAwardAmountTransactions().add(aat); documentService.saveDocument(timeAndMoneyDocument); getBusinessObjectService().save(transactionDetail); } String routeHeaderId = timeAndMoneyDocument.getDocumentHeader().getWorkflowDocument().getDocumentId(); String forward = buildForwardUrl(routeHeaderId); actionForward = new ActionForward(forward, true); //add this to session and leverage in T&M for return to award action. GlobalVariables.getUserSession().addObject(Constants.AWARD_DOCUMENT_STRING_FOR_SESSION + "-" + timeAndMoneyDocument.getDocumentNumber(), awardDocument.getDocumentNumber()); } else { actionForward = mapping.findForward(Constants.MAPPING_AWARD_BASIC); } return actionForward; } protected TimeAndMoneyDocument getLastFinalTandMDocument(List<TimeAndMoneyDocument> timeAndMoneyDocuments) throws WorkflowException { TimeAndMoneyDocument returnVal = null; DocumentService documentService = KraServiceLocator.getService(DocumentService.class); while(timeAndMoneyDocuments.size() > 0) { TimeAndMoneyDocument docWithWorkFlowData = (TimeAndMoneyDocument) documentService.getByDocumentHeaderId(timeAndMoneyDocuments.get(timeAndMoneyDocuments.size() - 1).getDocumentNumber()); if(docWithWorkFlowData.getDocumentHeader().getWorkflowDocument().isCanceled()) { timeAndMoneyDocuments.remove(timeAndMoneyDocuments.size() - 1); }else { returnVal = docWithWorkFlowData; break; } } return returnVal; } /* * * This method creates a transactionDetail object and adds it to the list for persistence later. * * @param sourceAwardNumber * @param destinationAwardNumber * @param sequenceNumber * @param pendingTransaction * @param currentAwardNumber * @param documentNumber * @param transactionDetailItems */ protected TransactionDetail addTransactionDetails(String sourceAwardNumber, String destinationAwardNumber, Integer sequenceNumber, String documentNumber, String commentsString, Award rootAward){ TransactionDetail transactionDetail = new TransactionDetail(); transactionDetail.setSourceAwardNumber(sourceAwardNumber); transactionDetail.setSequenceNumber(sequenceNumber); transactionDetail.setDestinationAwardNumber(destinationAwardNumber); if(isDirectIndirectViewEnabled()){ transactionDetail.setAnticipatedAmount(rootAward.getAnticipatedTotalDirect().add(rootAward.getAnticipatedTotalIndirect())); transactionDetail.setAnticipatedDirectAmount(rootAward.getAnticipatedTotalDirect()); transactionDetail.setAnticipatedIndirectAmount(rootAward.getAnticipatedTotalIndirect()); transactionDetail.setObligatedAmount(rootAward.getObligatedTotalDirect().add(rootAward.getObligatedTotalIndirect())); transactionDetail.setObligatedDirectAmount(rootAward.getObligatedTotalDirect()); transactionDetail.setObligatedIndirectAmount(rootAward.getObligatedTotalIndirect()); } else { transactionDetail.setAnticipatedAmount(rootAward.getAnticipatedTotal()); transactionDetail.setAnticipatedDirectAmount(rootAward.getAnticipatedTotal()); transactionDetail.setAnticipatedIndirectAmount(new KualiDecimal(0)); transactionDetail.setObligatedAmount(rootAward.getObligatedTotal()); transactionDetail.setObligatedDirectAmount(rootAward.getObligatedTotal()); transactionDetail.setObligatedIndirectAmount(new KualiDecimal(0)); } transactionDetail.setAwardNumber(rootAward.getAwardNumber()); transactionDetail.setTransactionId(new Long(0)); transactionDetail.setTimeAndMoneyDocumentNumber(documentNumber); transactionDetail.setComments(commentsString); transactionDetail.setTransactionDetailType(TransactionDetailType.PRIMARY.toString()); return transactionDetail; } /** * Looks up and returns the ParameterService. * @return the parameter service. */ protected ParameterService getParameterService() { if (this.parameterService == null) { this.parameterService = KraServiceLocator.getService(ParameterService.class); } return this.parameterService; } public boolean isDirectIndirectViewEnabled() { boolean returnValue = false; String directIndirectEnabledValue = getParameterService().getParameterValueAsString(Constants.PARAMETER_MODULE_AWARD, ParameterConstants.DOCUMENT_COMPONENT, "ENABLE_AWD_ANT_OBL_DIRECT_INDIRECT_COST"); if(directIndirectEnabledValue.equals("1")) { returnValue = true; } return returnValue; } /* * add money to amount info Totals, and Distributables. * */ private void addNewAwardAmountInfoForInitialTransaction(Award rootAward, String documentNumber) { AwardAmountInfo rootAwardAmountInfo = rootAward.getLastAwardAmountInfo(); AwardAmountInfo newAwardAmountInfo = new AwardAmountInfo(); newAwardAmountInfo.setAwardNumber(rootAward.getAwardNumber()); newAwardAmountInfo.setSequenceNumber(rootAward.getSequenceNumber()); newAwardAmountInfo.setFinalExpirationDate(rootAwardAmountInfo.getFinalExpirationDate()); newAwardAmountInfo.setCurrentFundEffectiveDate(rootAwardAmountInfo.getCurrentFundEffectiveDate()); newAwardAmountInfo.setObligationExpirationDate(rootAwardAmountInfo.getObligationExpirationDate()); newAwardAmountInfo.setTimeAndMoneyDocumentNumber(documentNumber); newAwardAmountInfo.setTransactionId(null); newAwardAmountInfo.setAward(rootAward); //add transaction amounts to the AmountInfo if(isDirectIndirectViewEnabled()){ newAwardAmountInfo.setAmountObligatedToDate(rootAward.getObligatedTotalDirect().add(rootAward.getObligatedTotalIndirect())); newAwardAmountInfo.setObligatedTotalDirect(rootAward.getObligatedTotalDirect()); newAwardAmountInfo.setObligatedTotalIndirect(rootAward.getObligatedTotalIndirect()); newAwardAmountInfo.setObligatedChange(rootAwardAmountInfo.getObligatedChange()); newAwardAmountInfo.setObligatedChangeDirect(rootAwardAmountInfo.getObligatedTotalDirect()); newAwardAmountInfo.setObligatedChangeIndirect(rootAwardAmountInfo.getObligatedTotalIndirect()); newAwardAmountInfo.setAnticipatedChange(rootAwardAmountInfo.getAnticipatedChange()); newAwardAmountInfo.setAnticipatedTotalAmount(rootAward.getAnticipatedTotalDirect().add(rootAward.getAnticipatedTotalIndirect())); newAwardAmountInfo.setAnticipatedTotalDirect(rootAward.getAnticipatedTotalDirect()); newAwardAmountInfo.setAnticipatedTotalIndirect(rootAward.getAnticipatedTotalIndirect()); newAwardAmountInfo.setAnticipatedChangeDirect(rootAwardAmountInfo.getAnticipatedTotalDirect()); newAwardAmountInfo.setAnticipatedChangeIndirect(rootAwardAmountInfo.getAnticipatedTotalIndirect()); newAwardAmountInfo.setObliDistributableAmount(rootAward.getObligatedTotalDirect().add(rootAward.getObligatedTotalIndirect())); newAwardAmountInfo.setAntDistributableAmount(rootAward.getAnticipatedTotalDirect().add(rootAward.getAnticipatedTotalIndirect())); } else { newAwardAmountInfo.setAmountObligatedToDate(rootAwardAmountInfo.getAmountObligatedToDate()); newAwardAmountInfo.setObligatedTotalDirect(rootAward.getObligatedTotalDirect()); newAwardAmountInfo.setObligatedTotalIndirect(rootAward.getObligatedTotalIndirect()); newAwardAmountInfo.setObligatedChange(rootAwardAmountInfo.getObligatedChange()); newAwardAmountInfo.setObligatedChangeDirect(rootAwardAmountInfo.getObligatedChangeDirect()); newAwardAmountInfo.setObligatedChangeIndirect(rootAwardAmountInfo.getObligatedChangeIndirect()); newAwardAmountInfo.setAnticipatedChange(rootAwardAmountInfo.getAnticipatedChange()); newAwardAmountInfo.setAnticipatedTotalAmount(rootAward.getAnticipatedTotal()); newAwardAmountInfo.setAnticipatedTotalDirect(rootAward.getAnticipatedTotalDirect()); newAwardAmountInfo.setAnticipatedTotalIndirect(rootAward.getAnticipatedTotalIndirect()); newAwardAmountInfo.setAnticipatedChangeDirect(rootAwardAmountInfo.getAnticipatedChangeDirect()); newAwardAmountInfo.setAnticipatedChangeIndirect(rootAwardAmountInfo.getAnticipatedChangeIndirect()); newAwardAmountInfo.setObliDistributableAmount(rootAward.getObligatedTotal()); newAwardAmountInfo.setAntDistributableAmount(rootAward.getAnticipatedTotal()); } newAwardAmountInfo.setOriginatingAwardVersion(rootAward.getSequenceNumber()); rootAward.getAwardAmountInfos().add(newAwardAmountInfo); getBusinessObjectService().save(rootAward); } public List<Award> getAwardVersions(String awardNumber) { BusinessObjectService businessObjectService = KraServiceLocator.getService(BusinessObjectService.class); List<Award> awards = (List<Award>)businessObjectService.findMatchingOrderBy(Award.class, getHashMapToFindActiveAward(awardNumber), "sequenceNumber", true); return awards; } // public Award getWorkingAwardVersion(String goToAwardNumber) { // Award award = null; // award = getPendingAwardVersion(goToAwardNumber); // if (award == null) { // award = getActiveAwardVersion(goToAwardNumber); // } // return award; // } public AwardVersionService getAwardVersionService() { return KraServiceLocator.getService(AwardVersionService.class); } public ActionForward openWindow(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String documentNumber = request.getParameter("awardDocumentNumber"); String awardNumber = request.getParameter("awardNumber"); AwardForm awardForm = (AwardForm)form; DocumentService documentService = KraServiceLocator.getService(DocumentService.class); AwardDocument awardDocument = (AwardDocument)documentService.getByDocumentHeaderId(documentNumber); Award award = getAwardService().getAwardAssociatedWithDocument(awardDocument.getDocumentNumber()); awardForm.setCurrentAwardNumber(awardNumber); awardForm.setCurrentSeqNumber(award.getSequenceNumber().toString()); awardDocument.setAward(award); awardForm.setDocument(awardDocument); populateAwardHierarchy(awardForm); return mapping.findForward("basic"); } private Map<String, String> getHashMapToFindActiveAward(String goToAwardNumber) { Map<String, String> map = new HashMap<String,String>(); map.put("awardNumber", goToAwardNumber); return map; } /** * This method tests if the award is new by checking the size of AwardDirectFandADistributions on the Award. * @param awardForm * @return */ public boolean isNewAward(AwardForm awardForm) { return awardForm.getAwardDocument().getAward().getAwardDirectFandADistributions().size() == 0; } /** * * This method is a helper method to retrieve AwardSponsorTermService. * @return */ protected AwardDirectFandADistributionService getAwardDirectFandADistributionService() { return KraServiceLocator.getService(AwardDirectFandADistributionService.class); } /** * * This method gets called upon navigation to Payment, Reports and Terms tab. * @param mapping * @param form * @param request * @param response * @return */ @SuppressWarnings("all") public ActionForward paymentReportsAndTerms(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; setReportsAndTermsOnAwardForm(awardForm); return mapping.findForward(Constants.MAPPING_AWARD_PAYMENT_REPORTS_AND_TERMS_PAGE); } @SuppressWarnings("unchecked") protected void setReportsAndTermsOnAwardForm(AwardForm awardForm) { AwardSponsorTermService awardSponsorTermService = getAwardSponsorTermService(); List<KeyValue> sponsorTermTypes = awardSponsorTermService.retrieveSponsorTermTypesToAwardFormForPanelHeaderDisplay(); awardForm.getSponsorTermFormHelper().setSponsorTermTypes(sponsorTermTypes); awardForm.getSponsorTermFormHelper().setNewSponsorTerms(awardSponsorTermService.getEmptyNewSponsorTerms(sponsorTermTypes)); AwardReportsService awardReportsService = KraServiceLocator.getService(AwardReportsService.class); Map<String,Object> initializedObjects = awardReportsService.initializeObjectsForReportsAndPayments( awardForm.getAwardDocument().getAward()); awardForm.setReportClasses((List<ConcreteKeyValue>) initializedObjects.get( Constants.REPORT_CLASSES_KEY_FOR_INITIALIZE_OBJECTS)); awardForm.getAwardReportsBean().setNewAwardReportTerms((List<AwardReportTerm>) initializedObjects.get( Constants.NEW_AWARD_REPORT_TERMS_LIST_KEY_FOR_INITIALIZE_OBJECTS)); awardForm.getAwardReportsBean().setNewAwardReportTermRecipients((List<AwardReportTermRecipient>) initializedObjects.get( Constants.NEW_AWARD_REPORT_TERM_RECIPIENTS_LIST_KEY_FOR_INITIALIZE_OBJECTS)); awardForm.setReportClassForPaymentsAndInvoices((ReportClass) initializedObjects.get( Constants.REPORT_CLASS_FOR_PAYMENTS_AND_INVOICES_PANEL)); awardForm.buildReportTrackingBeans(); } /** * * This method is a helper method to retrieve AwardSponsorTermService. * @return */ protected AwardSponsorTermService getAwardSponsorTermService() { return KraServiceLocator.getService(AwardSponsorTermService.class); } /** * * This method gets called upon navigation to Special Review tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward specialReview(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { ((AwardForm) form).getSpecialReviewHelper().prepareView(); return mapping.findForward(Constants.MAPPING_AWARD_SPECIAL_REVIEW_PAGE); } /** * * This method gets called upon navigation to Special Review tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward customData(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; awardForm.getCustomDataHelper().prepareCustomData(); return mapping.findForward(Constants.MAPPING_AWARD_CUSTOM_DATA_PAGE); } /** * * This method gets called upon navigation to Custom Data tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward questions(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { return mapping.findForward(Constants.MAPPING_AWARD_QUESTIONS_PAGE); } /** * * This method gets called upon navigation to Questions tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward permissions(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { ((AwardForm)form).getPermissionsHelper().prepareView(); return mapping.findForward(Constants.MAPPING_AWARD_PERMISSIONS_PAGE); } /** * * This method gets called upon navigation to Permissions tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward notesAndAttachments(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; awardForm.getAwardCommentBean().setAwardCommentScreenDisplayTypesOnForm(); awardForm.getAwardCommentBean().setAwardCommentHistoryFlags(); return mapping.findForward(Constants.MAPPING_AWARD_NOTES_AND_ATTACHMENTS_PAGE); } /** * * This method gets called upon navigation to Medusa tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward medusa(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; if (awardForm.getDocument().getDocumentNumber() == null) { //if we are entering this from the search results loadDocumentInForm(request, awardForm); } awardForm.getMedusaBean().setMedusaViewRadio("0"); awardForm.getMedusaBean().setModuleName("award"); awardForm.getMedusaBean().setModuleIdentifier(awardForm.getAwardDocument().getAward().getAwardId()); awardForm.getMedusaBean().generateParentNodes(); return mapping.findForward(Constants.MAPPING_AWARD_MEDUSA_PAGE); } /** * * This method gets called upon navigation to Award Actions tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward awardActions(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; String command = request.getParameter(KewApiConstants.COMMAND_PARAMETER); if(StringUtils.isNotEmpty(command) && KewApiConstants.DOCSEARCH_COMMAND.equals(command)) { loadDocumentInForm(request, awardForm); WorkflowDocument workflowDoc = awardForm.getAwardDocument().getDocumentHeader().getWorkflowDocument(); if(workflowDoc != null) awardForm.setDocTypeName(workflowDoc.getDocumentTypeName()); request.setAttribute("selectedAwardNumber", awardForm.getAwardDocument().getAward().getAwardNumber()); } populateAwardHierarchy(form); return mapping.findForward(Constants.MAPPING_AWARD_ACTIONS_PAGE); } /** * * This method gets called upon navigation to Awards tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward budgets(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; getAwardBudgetService().populateBudgetLimitSummary(awardForm.getBudgetLimitSummary(), awardForm.getAwardDocument()); return mapping.findForward(Constants.MAPPING_AWARD_BUDGET_VERSIONS_PAGE); } /** * @param mapping * @param form * @param request * @param response * @param awardForm * @return * @throws Exception */ ActionForward handleDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, AwardForm awardForm) throws Exception { ActionForward forward = null; String command = awardForm.getCommand(); if (KewApiConstants.ACTIONLIST_INLINE_COMMAND.equals(command)) { loadDocumentInForm(request, awardForm); String docIdRequestParameter = request.getParameter(KRADConstants.PARAMETER_DOC_ID); ActionForward baseForward = mapping.findForward(Constants.MAPPING_COPY_PROPOSAL_PAGE); forward = new ActionForward(buildForwardStringForActionListCommand( baseForward.getPath(),awardForm.getDocument().getDocumentNumber())); } else if (Constants.MAPPING_AWARD_ACTIONS_PAGE.equals(command)) { loadDocument(awardForm); } else { forward = super.docHandler(mapping, form, request, response); } if (Constants.MAPPING_AWARD_ACTIONS_PAGE.equals(command)) { forward = awardActions(mapping, awardForm, request, response); } return forward; } protected void loadDocument(KualiDocumentFormBase kualiForm) throws WorkflowException { super.loadDocument(kualiForm); Award award = ((AwardForm) kualiForm).getAwardDocument().getAward(); award.setSponsorNihMultiplePi(getSponsorService().isSponsorNihMultiplePi(award)); } /** * * loadDocumentInForm * @param mapping * @param form * @param request * @param response * @return */ protected void loadDocumentInForm(HttpServletRequest request, AwardForm awardForm) throws WorkflowException { String docIdRequestParameter = request.getParameter(KRADConstants.PARAMETER_DOC_ID); AwardDocument retrievedDocument = (AwardDocument) KRADServiceLocatorWeb.getDocumentService().getByDocumentHeaderId(docIdRequestParameter); awardForm.setDocument(retrievedDocument); request.setAttribute(KRADConstants.PARAMETER_DOC_ID, docIdRequestParameter); handlePlaceHolderDocument(awardForm, retrievedDocument); } /** * * @return */ @Override protected DocumentService getDocumentService() { return KRADServiceLocatorWeb.getDocumentService(); } /** * * This method is a helper method to retrieve KualiRuleService. * @return */ protected KualiRuleService getKualiRuleService() { return KraServiceLocator.getService(KualiRuleService.class); } /** * This method sets up a sponsor template synchronization loop. * It is called by the ui when a specific set of scopes need to by synchronized. * If no scopes are in the request, then a full synchronization to the scopes: * * AWARD_PAGE * SPONSOR_CONTACTS_TAB * PAYMENTS_AND_INVOICES_TAB * TERMS_TAB * REPORTS_TAB * COMMENTS_TAB * * is performed. This method generates and stores the list of scopes to sync * and the map to indicate if confirmation is necessary from the user before * a particular scope is synchronized and then forwards to the method the handles * the request loop. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward syncAwardTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ AwardTemplateSyncService awardTemplateSyncService = KraServiceLocator.getService(AwardTemplateSyncService.class); AwardForm awardForm = (AwardForm)form; AwardDocument awardDocument = awardForm.getAwardDocument(); AwardTemplateSyncScope[] scopes; String syncScopes = getSyncScopesString( request ); System.err.println("syncScopes: " + syncScopes); if (awardDocument.getAward().getTemplateCode() == null || awardDocument.getAward().getAwardTemplate() == null) { //return now since there is no template code. GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError( StringUtils.isBlank(syncScopes) ? "document.award.awardTemplate" : String.format("document.award.awardTemplate.%s", StringUtils.substring(syncScopes,1)), KeyConstants.ERROR_NO_SPONSOR_TEMPLATE_FOUND, new String[]{}); awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); return mapping.findForward(Constants.MAPPING_AWARD_BASIC); } Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); if( question != null ) return processSyncAward(mapping, awardForm, request, response); awardForm.setCurrentSyncScopes(null); awardForm.setSyncRequiresConfirmationMap(null); /* * The format for the action string is: * methodToCall.syncAwardTemplate:SCOPE1:...:SCOPEN].anchor... * Where: * [PropertyName|MethodName] means to sync by a property name or a method name. * SCOPE1...SCOPEN : A ':' delimited list of scope names that should be synced. If none are specified then the sync is done for every field and method. * */ if (StringUtils.isNotBlank(syncScopes) && syncScopes.length() > 1 && syncScopes.indexOf(":")>-1) { String[] scopeStrings = StringUtils.split(StringUtils.substringAfter(syncScopes, ":")); scopes = new AwardTemplateSyncScope[scopeStrings.length]; for( int i = 0; i < scopeStrings.length; i++ ) { scopes[i] = Enum.valueOf(AwardTemplateSyncScope.class, scopeStrings[i]); } awardForm.setSyncRequiresConfirmationMap(generateScopeRequiresConfirmationMap( scopes, awardDocument, false, false )); awardForm.setCurrentSyncScopes(scopes); } else { awardForm.setSyncRequiresConfirmationMap(generateScopeRequiresConfirmationMap( DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES, awardDocument, false, false )); awardForm.setCurrentSyncScopes(DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES); } return processSyncAward(mapping,form,request,response); } private Map<AwardTemplateSyncScope, Boolean> generateScopeRequiresConfirmationMap( AwardTemplateSyncScope[] scopes, AwardDocument awardDocument,boolean skipCheck,boolean defaultValue ) { AwardTemplateSyncService awardTemplateSyncService = KraServiceLocator.getService(AwardTemplateSyncService.class); Map< AwardTemplateSyncScope,Boolean> requiresQuestionMap = new HashMap<AwardTemplateSyncScope,Boolean>(); for( AwardTemplateSyncScope scope: scopes ) { if( skipCheck ) { requiresQuestionMap.put(scope, defaultValue); } else { if( awardTemplateSyncService.syncWillAlterData(awardDocument, scope) ) { if( LOG.isDebugEnabled() ) LOG.debug(String.format( "%s:%s", scope, true )); requiresQuestionMap.put(scope, true); } else { if( LOG.isDebugEnabled() ) LOG.warn(String.format( "%s:%s", scope, false )); requiresQuestionMap.put(scope, false); } } } return requiresQuestionMap; } /** * This method sets up a full template sync. This is called on return from a Sponsor Template Lookup. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward fullSyncToAwardTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm)form; AwardDocument awardDocument = awardForm.getAwardDocument(); if( awardDocument.getAward().getTemplateCode() == null ) { //return now since there is no template code. GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("document.award.awardTemplate",KeyConstants.ERROR_NO_TEMPLATE_CODE, new String[] {}); awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); return mapping.findForward(Constants.MAPPING_AWARD_BASIC); // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. } else if (org.kuali.rice.krad.util.ObjectUtils.isNull(awardDocument.getAward().getAwardTemplate())) { awardDocument.getAward().refreshReferenceObject("awardTemplate"); // check again to confirm if the awardTemplate was actually invalid or was it just the OJB lazy loading. if (org.kuali.rice.krad.util.ObjectUtils.isNull(awardDocument.getAward().getAwardTemplate())) { GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("document.award.awardTemplate", KeyConstants.ERROR_INVALID_TEMPLATE_CODE, new String[] {}); awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); return mapping.findForward(Constants.MAPPING_AWARD_BASIC); } // ### Vivantech Fix : #15 / [#80417598] finish. } else { awardDocument.getAward().refreshReferenceObject("awardTemplate"); } Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON); boolean proceedToProcessSyncAward = true; if( question == null ) { //setup before forwarding to the processor. AwardTemplateSyncScope[] scopes; scopes = new AwardTemplateSyncScope[] { AwardTemplateSyncScope.FULL }; HashMap<AwardTemplateSyncScope,Boolean> confirmMap = new HashMap<AwardTemplateSyncScope,Boolean>(); confirmMap.put(AwardTemplateSyncScope.FULL, true); awardForm.setCurrentSyncScopes(scopes); awardForm.setSyncRequiresConfirmationMap(confirmMap); } else if( question!=null && (QUESTION_VERIFY_SYNC+":"+AwardTemplateSyncScope.FULL).equals(question) ) { if( ConfirmationQuestion.YES.equals(buttonClicked) ) { //if the award has a sequence number more than 1, we //only select the template and the user must use the buttons on //each panel to sync. if( awardDocument.getAward().getSequenceNumber() > 1 ) { awardForm.setCurrentSyncScopes(new AwardTemplateSyncScope[] {}); proceedToProcessSyncAward=false; awardForm.setTemplateLookup(false); awardForm.setOldTemplateCode(null); } else { awardForm.setCurrentSyncScopes(DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES); awardForm.setSyncRequiresConfirmationMap(generateScopeRequiresConfirmationMap( DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES, awardDocument, false,false )); } } else { proceedToProcessSyncAward = false; awardDocument.getAward().setTemplateCode(awardForm.getOldTemplateCode()); awardDocument.getAward().refreshReferenceObject("awardTemplate"); awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); } } return proceedToProcessSyncAward?processSyncAward(mapping,form,request,response):mapping.findForward(Constants.MAPPING_AWARD_BASIC); } protected StrutsConfirmation buildAwardSyncParameterizedConfirmationQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionId, String configurationId, String... params) throws Exception { StrutsConfirmation retval = new StrutsConfirmation(); retval.setMapping(mapping); retval.setForm(form); retval.setRequest(request); retval.setResponse(response); retval.setQuestionId(questionId); retval.setQuestionType(CONFIRMATION_QUESTION); String questionText = this.COMFIRMATION_PARAM_STRING; for (int i = 0; i < params.length; i++) { questionText = replace(questionText, "{" + i + "}", params[i]); } retval.setQuestionText(questionText); return retval; } public ActionForward processSyncAward(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ AwardTemplateSyncService awardTemplateSyncService = KraServiceLocator.getService(AwardTemplateSyncService.class); AwardForm awardForm = (AwardForm)form; AwardDocument awardDocument = awardForm.getAwardDocument(); // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. String awardTemplateDescription = ""; if (org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument) && org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument.getAward()) && org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument.getAward().getAwardTemplate()) && org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument.getAward().getAwardTemplate().getDescription())) awardTemplateDescription = awardDocument.getAward().getAwardTemplate().getDescription(); // ### Vivantech Fix : #15 / [#80417598] finish. String question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON); AwardTemplateSyncScope[] scopes = awardForm.getCurrentSyncScopes(); AwardTemplateSyncScope[] scopesList = scopes; // for maintaining the current scopes list ConfigurationService kualiConfiguration = CoreApiServiceLocator.getKualiConfigurationService(); for( int i = 0; i < scopes.length; i++ ) { AwardTemplateSyncScope currentScope = scopes[i]; if (((question == null || !((StringUtils.equals(QUESTION_VERIFY_SYNC + ":" + currentScope, question)))) && awardForm.getSyncRequiresConfirmationMap().get(currentScope)) && !StringUtils.equals(QUESTION_VERIFY_EMPTY_SYNC + ":" + currentScope, question)) { String scopeSyncLabel = ""; StrutsConfirmation confirmationQuestion = new StrutsConfirmation(); if( StringUtils.isNotEmpty(currentScope.getDisplayPropertyName())) { scopeSyncLabel = kualiConfiguration.getPropertyValueAsString(currentScope.getDisplayPropertyName()); } // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. if( StringUtils.equals(scopeSyncLabel, REPORTS_PROPERTY_NAME) || StringUtils.equals(scopeSyncLabel, PAYMENT_INVOICES_PROPERTY_NAME)) { confirmationQuestion = buildAwardSyncParameterizedConfirmationQuestion(mapping, form, request, response, (QUESTION_VERIFY_SYNC+":"+currentScope), currentScope.equals(AwardTemplateSyncScope.FULL)?KeyConstants.QUESTION_SYNC_FULL:KeyConstants.QUESTION_SYNC_PANEL, scopeSyncLabel, awardTemplateDescription, getScopeMessageToAddQuestion(currentScope)); } else { // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. confirmationQuestion = buildParameterizedConfirmationQuestion(mapping, form, request, response, (QUESTION_VERIFY_SYNC+":"+currentScope), currentScope.equals(AwardTemplateSyncScope.FULL)?KeyConstants.QUESTION_SYNC_FULL:KeyConstants.QUESTION_SYNC_PANEL, scopeSyncLabel, awardTemplateDescription, getScopeMessageToAddQuestion(currentScope)); } confirmationQuestion.setCaller("processSyncAward"); awardForm.setCurrentSyncQuestionId( (QUESTION_VERIFY_SYNC+":"+currentScope) ); return (performQuestionWithoutInput( confirmationQuestion,"" )); } else if (( StringUtils.equals(awardForm.getCurrentSyncQuestionId(), question) && ConfirmationQuestion.YES.equals(buttonClicked)) || !awardForm.getSyncRequiresConfirmationMap().get(currentScope)) { if( LOG.isDebugEnabled() ) LOG.debug( "USER ACCEPTED SYNC OR NO CONFIRM REQUIRED FOR:"+currentScope+" CALLING SYNC SERVICE." ); boolean templateHasScopedData = awardTemplateSyncService.templateContainsScopedData(awardDocument, currentScope); boolean scopeRequiresEmptyConfirm = ArrayUtils.contains(DEFAULT_SCOPES_REQUIRE_VERIFY_FOR_EMPTY,currentScope); if( awardDocument.getAward().getSequenceNumber() > 1 && !templateHasScopedData && StringUtils.equals( awardForm.getCurrentSyncQuestionId(), (QUESTION_VERIFY_SYNC+":"+currentScope) ) && scopeRequiresEmptyConfirm ) { //we need to verify since the template has no data. String scopeSyncLabel = ""; if( StringUtils.isNotEmpty(currentScope.getDisplayPropertyName())) scopeSyncLabel = kualiConfiguration.getPropertyValueAsString(currentScope.getDisplayPropertyName()); // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. StrutsConfirmation confirmationQuestion = buildParameterizedConfirmationQuestion(mapping, form, request, response, ( QUESTION_VERIFY_EMPTY_SYNC+":"+currentScope), KeyConstants.QUESTION_SYNC_PANEL_TO_EMPTY, scopeSyncLabel, awardTemplateDescription); awardForm.setCurrentSyncQuestionId((QUESTION_VERIFY_EMPTY_SYNC+":"+currentScope)); confirmationQuestion.setCaller("processSyncAward"); return performQuestionWithoutInput(confirmationQuestion, ""); } else { //anything to do here? } AwardTemplateSyncScope[] s = { currentScope }; awardTemplateSyncService.syncAwardToTemplate(awardDocument, s); scopesList = (AwardTemplateSyncScope[])ArrayUtils.remove(scopesList, 0); // maintaining the current list awardForm.setCurrentSyncScopes(scopesList); } else if ( StringUtils.equals(awardForm.getCurrentSyncQuestionId(),question) && ConfirmationQuestion.NO.equals(buttonClicked)) { if( LOG.isDebugEnabled() ) LOG.debug( "USER DECLINED "+currentScope +", SKIPPING." ); scopesList = (AwardTemplateSyncScope[])ArrayUtils.remove(scopesList, 0); // maintaining the current list awardForm.setCurrentSyncScopes(scopesList); } else { throw new RuntimeException( "Do not know what to do in this case!" ); } } awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); awardForm.setCurrentSyncScopes(null); awardForm.setCurrentSyncQuestionId(null); return mapping.findForward(Constants.MAPPING_AWARD_BASIC); } private String getScopeMessageToAddQuestion( AwardTemplateSyncScope scope ) { ConfigurationService configurationService = CoreApiServiceLocator.getKualiConfigurationService(); String result = configurationService.getPropertyValueAsString("document.question.syncPanel.add.text."+scope); return result==null?"":result; } /** * Parses the method to call attribute to pick off the scopes to sync. * * @param request * @return returns the colon delimited list of scopes. */ protected String getSyncScopesString(HttpServletRequest request) { String syncScopesList = null; String parameterName = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE); if (StringUtils.isNotBlank(parameterName) && parameterName.indexOf(".scopes")!=-1) { syncScopesList = StringUtils.substringBetween(parameterName, ".scopes", ".anchor"); } return syncScopesList; } protected SponsorService getSponsorService() { return KraServiceLocator.getService(SponsorService.class); } @Override protected PessimisticLockService getPessimisticLockService() { return KraServiceLocator.getService(AwardLockService.class); } /** * @return */ protected VersionHistoryService getVersionHistoryService() { return KraServiceLocator.getService(VersionHistoryService.class); } /** * KCAWD-494:If the user selects a sponsor template lookup, set a flag and store the current sponsor template code in the form. The flag and the * current value will be used on the return to check if the template has changed. * * * @see org.kuali.rice.kns.web.struts.action.KualiAction#performLookup(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward performLookup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String parameterName = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE); if( (StringUtils.isNotBlank(parameterName) && parameterName.indexOf(".performLookup")!=-1 && parameterName.contains("templateCode:document.award.templateCode"))) { AwardForm awardForm = (AwardForm)form; awardForm.setTemplateLookup(true); ((AwardForm)form).setOldTemplateCode(((AwardForm)form).getAwardDocument().getAward().getTemplateCode() ); } return super.performLookup(mapping, form, request, response); } /** * * This should be called when an add or delete action is called that might be added to the sync queue. * It checks to ensure that syncMode is already enabled and will return an ActionForward for * the question or for the returnForward specified by the caller. * @param mapping * @param form * @param request * @param response * @param syncType * @param object * @param attrName * @param returnForward * @return * @throws Exception */ protected ActionForward confirmSyncAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, AwardSyncType syncType, PersistableBusinessObject object, String awardAttrName, String attrName, ActionForward returnForward) throws Exception { AwardForm awardForm = (AwardForm) form; if (awardForm.isSyncMode()) { awardForm.getAwardSyncBean().setCurrentForward(returnForward); awardForm.getAwardSyncBean().addPendingChange(syncType, object, awardAttrName, attrName); return syncActionCaller(mapping, form, request, response); } else { return returnForward; } } /** * This should be called when a group add or delete action is called that might be added to the sync queue. * It checks to ensure that syncMode is already enabled and will return an ActionForward for * the question or for the returnForward specified by the caller. * @param mapping * @param form * @param request * @param response * @param pendingChanges * @param returnForward * @return * @throws Exception */ protected ActionForward confirmSyncAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, List<AwardSyncPendingChangeBean> pendingChanges, ActionForward returnForward) throws Exception { AwardForm awardForm = (AwardForm) form; if (awardForm.isSyncMode()) { awardForm.getAwardSyncBean().setCurrentForward(returnForward); awardForm.getAwardSyncBean().getPendingChanges().addAll(pendingChanges); return syncActionCaller(mapping, form, request, response); } else { return returnForward; } } /** * When synchronizing a new addition or deletion call this method. It will confirm the change * and then add the change. * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward syncActionCaller(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; String message = ADD_SYNC_CHANGE_QUESTION; if (awardForm.getAwardSyncBean().getPendingChanges().get(0).getSyncType().equals(AwardSyncType.DELETE_SYNC.getSyncValue())) { message = DEL_SYNC_CHANGE_QUESTION; } //overwrite the method to call to call this instead of the original method which would result //in an error as the action should have already been performed request.setAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE, "methodToCall.syncActionCaller"); ActionForward confirmAction = confirm(buildParameterizedConfirmationQuestion(mapping, form, request, response, "confirmSyncActionKey", message), "confirmSyncAction", "refuseSyncAction"); if (confirmAction != null) { return confirmAction; } else { return awardForm.getAwardSyncBean().getCurrentForward(); } } /** * If the user answers yes to a confirm sync action question call this method. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward confirmSyncAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; awardForm.getAwardSyncBean().confirmPendingChanges(); return null; } /** * If the user answers no to a confirm sync action question call this method. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward refuseSyncAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; awardForm.getAwardSyncBean().getPendingChanges().clear(); return null; } protected AwardSyncCreationService getAwardSyncCreationService() { return KraServiceLocator.getService(AwardSyncCreationService.class); } protected AwardSyncService getAwardSyncService() { return KraServiceLocator.getService(AwardSyncService.class); } protected AwardBudgetService getAwardBudgetService() { if (awardBudgetService == null) { awardBudgetService = KraServiceLocator.getService(AwardBudgetService.class); } return awardBudgetService; } /** * @see org.kuali.kra.web.struts.action.KraTransactionalDocumentActionBase#populateAuthorizationFields(org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase) * If Award Infos or dates have been edited in a T&M document, then we want to suppress the cancel action. */ @SuppressWarnings("unchecked") @Override protected void populateAuthorizationFields(KualiDocumentFormBase formBase) { super.populateAuthorizationFields(formBase); AwardForm awardForm = (AwardForm) formBase; AwardDocument awardDocument = awardForm.getAwardDocument(); Award award = awardDocument.getAward(); Map documentActions = formBase.getDocumentActions(); //if Award version has been edited in T&M doc then we suppress cancel action. //workaround for copied awards. On initial copy the Award has two entries in AAI table and originating award version of first entry is null. if (award.getAwardAmountInfos().size() > 1) { if(!(award.getAwardAmountInfos().size() == 2 && award.getAwardAmountInfos().get(0).getOriginatingAwardVersion() == null) && documentActions.containsKey(KRADConstants.KUALI_ACTION_CAN_CANCEL)) { documentActions.remove(KRADConstants.KUALI_ACTION_CAN_CANCEL); } } } public AwardService getAwardService() { if (awardService == null) { awardService = KraServiceLocator.getService(AwardService.class); } return awardService; } public void setAwardService(AwardService awardService) { this.awardService = awardService; } public ReportTrackingService getReportTrackingService() { if (reportTrackingService == null) { reportTrackingService = KraServiceLocator.getService(ReportTrackingService.class); } return reportTrackingService; } /** * This method will populate the subawards if award is added as a funding source to perticular subaward * @param award */ protected void setSubAwardDetails(Award award){ award.setSubAwardList(getSubAwardService().getLinkedSubAwards(award)); } protected KcNotificationService getNotificationService() { if (notificationService == null) { notificationService = KraServiceLocator.getService(KcNotificationService.class); } return notificationService; } public void setNotificationService(KcNotificationService notificationService) { this.notificationService = notificationService; } protected SubAwardService getSubAwardService() { if (subAwardService == null) { subAwardService = KraServiceLocator.getService(SubAwardService.class); } return subAwardService; } public void setSubAwardService(SubAwardService subAwardService) { this.subAwardService = subAwardService; } public ActionForward superUserActionHelper(SuperUserAction actionName, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC); AwardForm awardForm = (AwardForm) form; Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON); String methodToCall = ((KualiForm) form).getMethodToCall(); awardForm.setAuditActivated(true); ValidationState status = ValidationState.OK; if (!awardForm.getDocument().getDocumentHeader().getWorkflowDocument().isEnroute()) { status = new AuditActionHelper().isValidSubmission(awardForm, true); } if (status == ValidationState.WARNING) { if(question == null){ List<String> selectedActionRequests = awardForm.getSelectedActionRequests(); // Need to add the super user requests to user session because they are wiped out by //the KualiRequestProcessor reset on //clicking yes to the question. Retrieve again during actual routing and add to form. GlobalVariables.getUserSession().addObject(SUPER_USER_ACTION_REQUESTS, selectedActionRequests); try { return this.performQuestionWithoutInput(mapping, form, request, response, DOCUMENT_ROUTE_QUESTION, "Validation Warning Exists. Are you sure want to submit to workflow routing.", KRADConstants.CONFIRMATION_QUESTION, methodToCall, ""); } catch (Exception e) { e.printStackTrace(); } } else if(DOCUMENT_ROUTE_QUESTION.equals(question) && ConfirmationQuestion.YES.equals(buttonClicked)) { awardForm.setSelectedActionRequests((List<String>)GlobalVariables.getUserSession().retrieveObject(SUPER_USER_ACTION_REQUESTS)); GlobalVariables.getUserSession().removeObject(SUPER_USER_ACTION_REQUESTS); switch (actionName) { case SUPER_USER_APPROVE: return super.superUserApprove(mapping, awardForm, request, response); case TAKE_SUPER_USER_ACTIONS: return super.takeSuperUserActions(mapping, awardForm, request, response); } } else { return forward; } } else if(status == ValidationState.OK){ switch (actionName) { case SUPER_USER_APPROVE: return super.superUserApprove(mapping, awardForm, request, response); case TAKE_SUPER_USER_ACTIONS: return super.takeSuperUserActions(mapping, awardForm, request, response); } } else { GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("datavalidation",KeyConstants.ERROR_WORKFLOW_SUBMISSION, new String[] {}); return forward; } return forward; } @Override public ActionForward superUserApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { return superUserActionHelper(SuperUserAction.SUPER_USER_APPROVE, mapping, form, request, response); } @Override public ActionForward takeSuperUserActions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { return superUserActionHelper(SuperUserAction.TAKE_SUPER_USER_ACTIONS, mapping, form, request, response); } }
src/main/java/org/kuali/kra/award/web/struts/action/AwardAction.java
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.award.web.struts.action; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.kra.authorization.KraAuthorizationConstants; import org.kuali.kra.award.*; import org.kuali.kra.award.awardhierarchy.AwardHierarchy; import org.kuali.kra.award.awardhierarchy.AwardHierarchyBean; import org.kuali.kra.award.awardhierarchy.AwardHierarchyService; import org.kuali.kra.award.awardhierarchy.AwardHierarchyTempObject; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncPendingChangeBean; import org.kuali.kra.award.awardhierarchy.sync.AwardSyncType; import org.kuali.kra.award.awardhierarchy.sync.service.AwardSyncCreationService; import org.kuali.kra.award.awardhierarchy.sync.service.AwardSyncService; import org.kuali.kra.award.budget.AwardBudgetService; import org.kuali.kra.award.contacts.AwardPerson; import org.kuali.kra.award.contacts.AwardProjectPersonsSaveRule; import org.kuali.kra.award.customdata.AwardCustomData; import org.kuali.kra.award.document.AwardDocument; import org.kuali.kra.award.home.Award; import org.kuali.kra.award.home.AwardAmountInfo; import org.kuali.kra.award.home.AwardComment; import org.kuali.kra.award.home.AwardService; import org.kuali.kra.award.home.approvedsubawards.AwardApprovedSubaward; import org.kuali.kra.award.paymentreports.ReportClass; import org.kuali.kra.award.paymentreports.awardreports.AwardReportTerm; import org.kuali.kra.award.paymentreports.awardreports.AwardReportTermRecipient; import org.kuali.kra.award.paymentreports.awardreports.reporting.service.ReportTrackingService; import org.kuali.kra.award.paymentreports.closeout.CloseoutReportTypeValuesFinder; import org.kuali.kra.award.timeandmoney.AwardDirectFandADistribution; import org.kuali.kra.award.version.service.AwardVersionService; import org.kuali.kra.bo.versioning.VersionHistory; import org.kuali.kra.bo.versioning.VersionStatus; import org.kuali.kra.budget.web.struts.action.BudgetParentActionBase; import org.kuali.kra.common.notification.service.KcNotificationService; import org.kuali.kra.infrastructure.*; import org.kuali.kra.krms.service.KrmsRulesExecutionService; import org.kuali.kra.service.*; import org.kuali.kra.subaward.service.SubAwardService; import org.kuali.kra.timeandmoney.AwardHierarchyNode; import org.kuali.kra.timeandmoney.document.TimeAndMoneyDocument; import org.kuali.kra.timeandmoney.history.TransactionDetail; import org.kuali.kra.timeandmoney.history.TransactionDetailType; import org.kuali.kra.timeandmoney.rules.TimeAndMoneyAwardDateSaveRuleImpl; import org.kuali.kra.timeandmoney.transactions.AwardAmountTransaction; import org.kuali.kra.web.struts.action.AuditActionHelper; import org.kuali.kra.web.struts.action.AuditActionHelper.ValidationState; import org.kuali.kra.web.struts.action.StrutsConfirmation; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.core.api.util.ConcreteKeyValue; import org.kuali.rice.core.api.util.KeyValue; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.coreservice.framework.parameter.ParameterConstants; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.kew.api.KewApiConstants; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kew.api.exception.WorkflowException; import org.kuali.rice.kns.question.ConfirmationQuestion; import org.kuali.rice.kns.util.KNSGlobalVariables; import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase; import org.kuali.rice.kns.web.struts.form.KualiForm; import org.kuali.rice.krad.bo.PersistableBusinessObject; import org.kuali.rice.krad.rules.rule.event.KualiDocumentEvent; import org.kuali.rice.krad.service.*; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; import static org.apache.commons.lang.StringUtils.replace; import static org.kuali.rice.krad.util.KRADConstants.CONFIRMATION_QUESTION; /** * * This class represents base Action class for all the Award pages. */ public class AwardAction extends BudgetParentActionBase { protected static final String AWARD_ID_PARAMETER_NAME = "awardId"; private static final String INITIAL_TRANSACTION_COMMENT = "Initial Time And Money creation transaction"; private static final String REPORTS_PROPERTY_NAME = "Reports"; private static final String PAYMENT_INVOICES_PROPERTY_NAME = "Payments and Invoices"; private static final String COMFIRMATION_PARAM_STRING = "After Award {0} information is synchronized, make sure that the Award Sponsor Contacts information is also synchronized with the same sponsor template. Failing to do so will result in data inconsistency. Are you sure you want to replace current {0} information with selected {1} template information?"; private static final String SUPER_USER_ACTION_REQUESTS = "superUserActionRequests"; private enum SuperUserAction { SUPER_USER_APPROVE, TAKE_SUPER_USER_ACTIONS } private ParameterService parameterService; private transient AwardBudgetService awardBudgetService; private transient AwardService awardService; private transient ReportTrackingService reportTrackingService; private transient KcNotificationService notificationService; private transient SubAwardService subAwardService; TimeAndMoneyAwardDateSaveRuleImpl timeAndMoneyAwardDateSaveRuleImpl; private static final Log LOG = LogFactory.getLog( AwardAction.class ); //question constants private static final String QUESTION_VERIFY_SYNC="VerifySync"; private static final String QUESTION_VERIFY_EMPTY_SYNC="VerifyEmptySync"; private static final AwardTemplateSyncScope[] DEFAULT_SCOPES_REQUIRE_VERIFY_FOR_EMPTY = new AwardTemplateSyncScope[] { AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB, AwardTemplateSyncScope.SPONSOR_CONTACTS_TAB, AwardTemplateSyncScope.REPORTS_TAB }; private static final AwardTemplateSyncScope[] DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES = new AwardTemplateSyncScope[] { AwardTemplateSyncScope.AWARD_PAGE, AwardTemplateSyncScope.COST_SHARE, AwardTemplateSyncScope.PAYMENTS_AND_INVOICES_TAB, AwardTemplateSyncScope.SPONSOR_CONTACTS_TAB, AwardTemplateSyncScope.TERMS_TAB, AwardTemplateSyncScope.REPORTS_TAB, AwardTemplateSyncScope.COMMENTS_TAB }; private static final int NINE = 9; private static final String DOCUMENT_ROUTE_QUESTION="DocRoute"; private static final String ADD_SYNC_CHANGE_QUESTION = "document.question.awardhierarchy.sync"; private static final String DEL_SYNC_CHANGE_QUESTION = "document.question.awardhierarchy.sync"; /** * @see org.kuali.core.web.struts.action.KualiDocumentActionBase#docHandler( * org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward docHandler(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; ActionForward forward; cleanUpUserSession(); forward = handleDocument(mapping, form, request, response, awardForm); AwardDocument awardDocument = (AwardDocument) awardForm.getDocument(); //check to see if this document might be a part of an active award sync(if it is lock it) AwardDocument parentSyncAward = getAwardSyncService().getAwardLockingHierarchyForSync(awardDocument, GlobalVariables.getUserSession().getPrincipalId()); if (parentSyncAward != null) { KNSGlobalVariables.getMessageList().add("error.award.awardhierarchy.sync.locked", parentSyncAward.getDocumentNumber()); awardForm.setViewOnly(true); } handlePlaceHolderDocument(awardForm, awardDocument); awardForm.initializeFormOrDocumentBasedOnCommand(); setBooleanAwardInMultipleNodeHierarchyOnForm (awardDocument.getAward()); setBooleanAwardHasTandMOrIsVersioned(awardDocument.getAward()); setSubAwardDetails(awardDocument.getAward()); return forward; } private void handlePlaceHolderDocument(AwardForm form, AwardDocument awardDocument) { if(awardDocument.isPlaceHolderDocument()) { Long awardId = form.getPlaceHolderAwardId(); //If it is a placeholder document, we want to initialize it with the award that the user is viewing int currentAwardIndex = -1; Award currentAward = null; for(Award award : awardDocument.getAwardList()) { currentAwardIndex++; if(ObjectUtils.equals(award.getAwardId(), awardId)) { currentAward = award; break; } } if(currentAward != null) { awardDocument.getAwardList().remove(currentAwardIndex); awardDocument.getAwardList().add(0, currentAward); form.setViewOnly(true); } } } protected void cleanUpUserSession() { GlobalVariables.getUserSession().removeObject(GlobalVariables.getUserSession().getKualiSessionId() + Constants.TIME_AND_MONEY_DOCUMENT_STRING_FOR_SESSION); } /** * @see org.kuali.kra.web.struts.action.KraTransactionalDocumentActionBase#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm)form; ActionForward actionForward = super.execute(mapping, form, request, response); if (awardForm.isAuditActivated()){ awardForm.setUnitRulesMessages(getUnitRulesMessages(awardForm.getAwardDocument())); } if (KNSGlobalVariables.getAuditErrorMap().isEmpty()) { new AuditActionHelper().auditConditionally((AwardForm) form); } return actionForward; } protected List<String> getUnitRulesMessages(AwardDocument awardDoc) { KrmsRulesExecutionService rulesService = KraServiceLocator.getService(KrmsRulesExecutionService.class); return rulesService.processUnitValidations(awardDoc.getLeadUnitNumber(), awardDoc); } /** * This method populates the AwardHierarchy data * @param form * @throws WorkflowException */ protected void populateAwardHierarchy(ActionForm form) throws WorkflowException { AwardForm awardForm = (AwardForm)form; AwardDocument awardDocument = awardForm.getAwardDocument(); List<String> order = new ArrayList<String>(); AwardHierarchyBean helperBean = awardForm.getAwardHierarchyBean(); AwardHierarchy rootNode = helperBean.getRootNode(); Map<String, AwardHierarchy> awardHierarchyNodes = helperBean.getAwardHierarchy(rootNode, order); Map<String,AwardHierarchyNode> awardHierarchyNodesMap = new HashMap<String, AwardHierarchyNode>(); Award currentAward = awardDocument.getAward(); awardForm.setRootAwardNumber(rootNode.getRootAwardNumber()); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for(String str:order){ AwardHierarchy tempAwardNode = awardHierarchyNodes.get(str); sb1.append(tempAwardNode.getAwardNumber()); sb1.append(KRADConstants.BLANK_SPACE).append("%3A"); if (getVersionHistoryService().findActiveVersion(Award.class, tempAwardNode.getAwardNumber()) != null) { sb2.append(tempAwardNode.getAwardNumber()); sb2.append(KRADConstants.BLANK_SPACE).append("%3A"); } } for(int i = 0; i < helperBean.getMaxAwardNumber(); i++){ AwardHierarchyTempObject temp = awardForm.getAwardHierarchyTempObjects().get(i); temp.setSelectBox1(sb1.toString()); temp.setSelectBox2(sb2.toString()); } } protected TimeAndMoneyExistenceService getTimeAndMoneyExistenceService() { return KraServiceLocator.getService(TimeAndMoneyExistenceService.class); } @Override public ActionForward approve(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; AwardForm awardForm = (AwardForm) form; if(getTimeAndMoneyExistenceService().validateTimeAndMoneyRule(awardForm.getAwardDocument().getAward(), awardForm.getAwardHierarchyBean().getRootNode().getAwardNumber())){ forward = super.approve(mapping, form, request, response); }else{ getTimeAndMoneyExistenceService().addAwardVersionErrorMessage(); forward = mapping.findForward(Constants.MAPPING_AWARD_BASIC); } String routeHeaderId = awardForm.getDocument().getDocumentNumber(); String returnLocation = buildActionUrl(routeHeaderId, Constants.MAPPING_AWARD_ACTIONS_PAGE, "AwardDocument"); ActionForward basicForward = mapping.findForward(KRADConstants.MAPPING_PORTAL); ActionForward holdingPageForward = mapping.findForward(Constants.MAPPING_HOLDING_PAGE); return routeToHoldingPage(basicForward, forward, holdingPageForward, returnLocation); } protected ActionForward submitAward(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC); if(getTimeAndMoneyExistenceService().validateTimeAndMoneyRule(awardForm.getAwardDocument().getAward(), awardForm.getAwardHierarchyBean().getRootNode().getAwardNumber())){ forward = super.route(mapping, form, request, response); populateAwardHierarchy(awardForm); }else{ getTimeAndMoneyExistenceService().addAwardVersionErrorMessage(); } String routeHeaderId = awardForm.getDocument().getDocumentNumber(); String returnLocation = buildActionUrl(routeHeaderId, Constants.MAPPING_AWARD_ACTIONS_PAGE, "AwardDocument"); ActionForward basicForward = mapping.findForward(KRADConstants.MAPPING_PORTAL); ActionForward holdingPageForward = mapping.findForward(Constants.MAPPING_HOLDING_PAGE); return routeToHoldingPage(basicForward, forward, holdingPageForward, returnLocation); } @Override public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC); AwardForm awardForm = (AwardForm) form; awardForm.setAuditActivated(true); Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON); String methodToCall = ((KualiForm) form).getMethodToCall(); ValidationState status = new AuditActionHelper().isValidSubmission(awardForm, true); if (status == ValidationState.WARNING) { if(question == null){ return this.performQuestionWithoutInput(mapping, form, request, response, DOCUMENT_ROUTE_QUESTION, "Validation Warning Exists. Are you sure want to submit to workflow routing.", KRADConstants.CONFIRMATION_QUESTION, methodToCall, ""); } else if(DOCUMENT_ROUTE_QUESTION.equals(question) && ConfirmationQuestion.YES.equals(buttonClicked)) { return submitAward(mapping, form, request, response); } else { return forward; } } if(status == ValidationState.OK){ return submitAward(mapping, form, request, response); } else { GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("datavalidation",KeyConstants.ERROR_WORKFLOW_SUBMISSION, new String[] {}); return forward; } } @Override public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; AwardForm awardForm = (AwardForm) form; if (getTimeAndMoneyExistenceService().validateTimeAndMoneyRule(awardForm.getAwardDocument().getAward(), awardForm.getAwardHierarchyBean().getRootNode().getAwardNumber())) { awardForm.setAuditActivated(true); ValidationState status = new AuditActionHelper().isValidSubmission(awardForm, true); if (status == ValidationState.ERROR) { GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("datavalidation", KeyConstants.ERROR_WORKFLOW_SUBMISSION, new String[] {}); forward = mapping.findForward(Constants.MAPPING_AWARD_BASIC); } else { forward = super.blanketApprove(mapping, form, request, response); } } else { getTimeAndMoneyExistenceService().addAwardVersionErrorMessage(); forward = mapping.findForward(Constants.MAPPING_AWARD_BASIC); } String routeHeaderId = awardForm.getDocument().getDocumentNumber(); String returnLocation = buildActionUrl(routeHeaderId, Constants.MAPPING_AWARD_ACTIONS_PAGE, "AwardDocument"); ActionForward basicForward = mapping.findForward(KRADConstants.MAPPING_PORTAL); ActionForward holdingPageForward = mapping.findForward(Constants.MAPPING_HOLDING_PAGE); return routeToHoldingPage(basicForward, forward, holdingPageForward, returnLocation); } /** * @see org.kuali.kra.web.struts.action.KraTransactionalDocumentActionBase#save(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO: JF Are all of these saves in a single transaction? ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC); AwardForm awardForm = (AwardForm) form; Award award = awardForm.getAwardDocument().getAward(); checkAwardNumber(award); String userId = GlobalVariables.getUserSession().getPrincipalName(); if (award.getAwardApprovedSubawards() == null || award.getAwardApprovedSubawards().isEmpty()) { award.setSubContractIndicator(Constants.NO_FLAG); } else { award.setSubContractIndicator(Constants.YES_FLAG); } if (award.getAwardTransferringSponsors() == null || award.getAwardTransferringSponsors().isEmpty()) { award.setTransferSponsorIndicator(Constants.NO_FLAG); } else { award.setTransferSponsorIndicator(Constants.YES_FLAG); } if (award.getKeywords() == null || award.getKeywords().isEmpty()) { award.setScienceCodeIndicator(Constants.NO_FLAG); } else { award.setScienceCodeIndicator(Constants.YES_FLAG); } forward = super.save(mapping, form, request, response); if (awardForm.getMethodToCall().equals("save") && awardForm.isAuditActivated()) { forward = mapping.findForward(Constants.MAPPING_AWARD_ACTIONS_PAGE); } AwardHierarchyBean bean = awardForm.getAwardHierarchyBean(); if (bean.saveHierarchyChanges()) { List<String> order = new ArrayList<String>(); awardForm.setAwardHierarchyNodes(bean.getAwardHierarchy(bean.getRootNode().getAwardNumber(), order)); } // generate hierarchy sync changes after save so all BOs have ids and parent ids set for (AwardSyncPendingChangeBean pendingChange : awardForm.getAwardSyncBean().getConfirmedPendingChanges()) { // refresh object to make sure all references have been loaded before the sync pendingChange.getObject().refresh(); getAwardSyncCreationService().addAwardSyncChange(award, pendingChange); } // now we need to save the hierarchy changes getBusinessObjectService().save(award.getSyncChanges()); awardForm.getAwardSyncBean().getConfirmedPendingChanges().clear(); /** * deal with the award report tracking generation business. */ getReportTrackingService().generateReportTrackingAndSave(award, false); return forward; } @Override public ActionForward reload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; ActionForward actionForward = super.reload(mapping, form, request, response); getReportTrackingService().refreshReportTracking(awardForm.getAwardDocument().getAward()); return actionForward; } @Override public ActionForward close(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; if (awardForm.getViewFundingSource()) { return mapping.findForward(Constants.MAPPING_CLOSE_PAGE); } else { return super.close(mapping, form, request, response); } } /** * This method returns the award associated with the AwardDocument on the AwardForm * @return */ protected Award getAward(ActionForm form) { return getAwardDocument(form).getAward(); } /** * This method returns the AwardDocument * * @param form * @return */ protected AwardDocument getAwardDocument(ActionForm form) { return ((AwardForm) form).getAwardDocument(); } /** * This method sets an award number on an award if the award number hasn't been initialized yet. * @param award */ protected void checkAwardNumber(Award award) { if (Award.DEFAULT_AWARD_NUMBER.equals(award.getAwardNumber())) { AwardNumberService awardNumberService = getAwardNumberService(); String awardNumber = awardNumberService.getNextAwardNumber(); award.setAwardNumber(awardNumber); } if (Award.DEFAULT_AWARD_NUMBER.equals(award.getAwardAmountInfos().get(0).getAwardNumber())) { award.getAwardAmountInfos().get(0).setAwardNumber(award.getAwardNumber()); } for(AwardApprovedSubaward approvedSubaward : award.getAwardApprovedSubawards()) { if(Award.DEFAULT_AWARD_NUMBER.equals(approvedSubaward.getAwardNumber())) { approvedSubaward.setAwardNumber(award.getAwardNumber()); } } for(AwardComment comment : award.getAwardComments()) { comment.setAward(award); } for(AwardCustomData customData : award.getAwardCustomDataList()) { customData.setAward(award); } } /** * * This method is a helper method to retrieve AwardNumberService. * @return */ protected AwardNumberService getAwardNumberService() { return KraServiceLocator.getService(AwardNumberService.class); } /** * @see org.kuali.kra.web.struts.action.KraTransactionalDocumentActionBase#initialDocumentSave(org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase) * * TODO JF: Handle initial save * * One of these conditions exist when this method is called: 1) This is a new award, created from the "Create Award" portal action. A new root node needs to be created a) prevAwardNumber and prevRootAwardNumber are null b) awardHierarchyBean.rootNodes.size() == 0 2) This is a new award created from a hierarchy action. The node for this award should exist on the hierarchy bean a) prevAwardNumber and prevRootAwardNumber are ? b) awardHierarchyBean.rootNodes.size() == ? */ @Override protected void initialDocumentSave(KualiDocumentFormBase form) throws Exception { AwardForm awardForm = (AwardForm) form; AwardDocument awardDocument = (AwardDocument) awardForm.getDocument(); createInitialAwardUsers(awardForm.getAwardDocument().getAward()); populateStaticCloseoutReports(awardForm); String userId = GlobalVariables.getUserSession().getPrincipalName(); Award award = awardDocument.getAward(); getAwardService().updateAwardSequenceStatus(award, VersionStatus.PENDING); getVersionHistoryService().updateVersionHistory(award, VersionStatus.PENDING, userId); if(!awardForm.getAwardDocument().isDocumentSaveAfterVersioning()) { awardForm.getAwardHierarchyBean().createDefaultAwardHierarchy(); awardForm.getAwardHierarchyBean().saveHierarchyChanges(); } } /** * Create the original set of Award Users for a new Award Document. * The creator the award is assigned to the AWARD_MODIFIER role, if the creator isn't already an AWARD_MODIFIER. * * @param doc */ protected void createInitialAwardUsers(Award award) { String userId = GlobalVariables.getUserSession().getPrincipalId(); KraAuthorizationService kraAuthService = KraServiceLocator.getService(KraAuthorizationService.class); if (!kraAuthService.hasRole(userId, KraAuthorizationConstants.KC_AWARD_NAMESPACE, AwardRoleConstants.AWARD_MODIFIER.getAwardRole())) { kraAuthService.addRole(userId, AwardRoleConstants.AWARD_MODIFIER.getAwardRole(), award); } } /** * * This method populates the initial static AwardCloseout reports upon the creation of an Award. * * @param form */ protected void populateStaticCloseoutReports(AwardForm form){ CloseoutReportTypeValuesFinder closeoutReportTypeValuesFinder = new CloseoutReportTypeValuesFinder(); form.getAwardCloseoutBean().addAwardCloseoutStaticItems(closeoutReportTypeValuesFinder.getKeyValues()); } protected AwardHierarchyService getAwardHierarchyService(){ return KraServiceLocator.getService(AwardHierarchyService.class); } /** * Can the Award be saved? This method is normally overridden by * a subclass in order to invoke business rules to verify that the * Award can be saved. * @param awardForm the Award Form * @return true if the award can be saved; otherwise false */ protected boolean isValidSave(AwardForm awardForm) { AwardDocument awardDocument = (AwardDocument) awardForm.getDocument(); String leadUnitNumber = awardDocument.getLeadUnitNumber(); if (StringUtils.isNotEmpty(leadUnitNumber) && checkNoMoreThanOnePI(awardDocument.getAward())) { String userId = GlobalVariables.getUserSession().getPrincipalId(); UnitAuthorizationService authService = KraServiceLocator.getService(UnitAuthorizationService.class); //List<Unit> userUnits = authService.getUnits(userId, Constants.MODULE_NAMESPACE_AWARD, AwardPermissionConstants.CREATE_AWARD.getAwardPermission()); return authService.hasMatchingQualifiedUnits(userId, Constants.MODULE_NAMESPACE_AWARD, AwardPermissionConstants.MODIFY_AWARD.getAwardPermission(), leadUnitNumber); } return false; } private boolean checkNoMoreThanOnePI(Award award) { int piCount = 0; int counter = 0; ArrayList<String> fields = new ArrayList<String>(); for (AwardPerson p : award.getProjectPersons()) { if (p.isPrincipalInvestigator()) { piCount++; fields.add("projectPersonnelBean.projectPersonnel[" + counter + "].contactRoleCode"); } counter++; } boolean valid = piCount <= 1; if (!valid) { //projectPersonnelBean.contactRoleCode //projectPersonnelBean.projectPersonnel[0].contactRoleCode for (String field : fields) { GlobalVariables.getMessageMap().putError(field, AwardProjectPersonsSaveRule.ERROR_AWARD_PROJECT_PERSON_MULTIPLE_PI_EXISTS); } } return valid; } /** * Use the Kuali Rule Service to apply the rules for the given event. * @param event the event to process * @return true if success; false if there was a validation error */ protected final boolean applyRules(KualiDocumentEvent event) { return getKualiRuleService().applyRules(event); } /** * * This method builds the string for the ActionForward * @param forwardPath * @param docIdRequestParameter * @return */ public String buildForwardStringForActionListCommand(String forwardPath, String docIdRequestParameter){ StringBuilder sb = new StringBuilder(); sb.append(forwardPath); sb.append("?"); sb.append(KRADConstants.PARAMETER_DOC_ID); sb.append("="); sb.append(docIdRequestParameter); return sb.toString(); } /** * * This method gets called upon navigation to Awards tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward home(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; AwardDocument awardDocument = (AwardDocument) awardForm.getDocument(); setBooleanAwardInMultipleNodeHierarchyOnForm (awardDocument.getAward()); setBooleanAwardHasTandMOrIsVersioned(awardDocument.getAward()); AwardAmountInfoService awardAmountInfoService = KraServiceLocator.getService(AwardAmountInfoService.class); int index = awardAmountInfoService.fetchIndexOfAwardAmountInfoWithHighestTransactionId(awardDocument.getAward().getAwardAmountInfos()); return mapping.findForward(Constants.MAPPING_AWARD_HOME_PAGE); } /** * This method... * @param awardDocument * @param awardForm */ @SuppressWarnings("unchecked") public void setBooleanAwardInMultipleNodeHierarchyOnForm (Award award) { Map<String, Object> fieldValues = new HashMap<String, Object>(); String awardNumber = award.getAwardNumber(); fieldValues.put("awardNumber", awardNumber); fieldValues.put("active", Boolean.TRUE); BusinessObjectService businessObjectService = KraServiceLocator.getService(BusinessObjectService.class); List<AwardHierarchy> awardHierarchies = (List) businessObjectService.findMatching(AwardHierarchy.class, fieldValues); if (awardHierarchies.size() == 0) { award.setAwardInMultipleNodeHierarchy(false); }else { Map<String, Object> newFieldValues = new HashMap<String, Object>(); String rootAwardNumber = awardHierarchies.get(0).getRootAwardNumber(); newFieldValues.put("rootAwardNumber", rootAwardNumber); newFieldValues.put("active", Boolean.TRUE); int matchingValues = businessObjectService.countMatching(AwardHierarchy.class, newFieldValues); if (matchingValues > 1) { award.setAwardInMultipleNodeHierarchy(true); }else { award.setAwardInMultipleNodeHierarchy(false); } } } /** * If an Award has associated Time and Money document or been versioned and no previous version has been edited in a Time and Money document, * then we want the money and date fields on Award to be read only. * @param awardDocument * @param awardForm */ public void setBooleanAwardHasTandMOrIsVersioned (Award award) { boolean previousVersionHasBeenEditedInTandMDocument = false; // what we really want to do is check to see if latest version of Awards has a T&M doc associated with it. // If it's versioned, that's OK, we still want to allow editing of the amounts and dates. List<VersionHistory> awardHistory = getVersionHistoryService().findVersionHistory(Award.class, award.getAwardNumber()); if(awardHistory.size() > 1) { if (award.getSequenceNumber() == 1 && award.getAwardAmountInfos().size() > 2) { previousVersionHasBeenEditedInTandMDocument = true; } else if (award.getSequenceNumber() > 1 && award.getAwardAmountInfos().size() > 1) { previousVersionHasBeenEditedInTandMDocument = true; } } award.setAwardHasAssociatedTandMOrIsVersioned(previousVersionHasBeenEditedInTandMDocument); } /** * * This method gets called upon navigation to Contacts tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward contacts(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { SponsorService sponsorService = getSponsorService(); Award award = getAward(form); AwardForm awardForm = (AwardForm) form; award.initCentralAdminContacts(); return mapping.findForward(Constants.MAPPING_AWARD_CONTACTS_PAGE); } /** * * This method gets called upon navigation to Commitments tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward commitments(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { return mapping.findForward(Constants.MAPPING_AWARD_COMMITMENTS_PAGE); } protected void generateDirectFandADistribution(Award award) { if(!(award.getAwardEffectiveDate() == null)) { // delete entries that were added during previous T&M initiations but the doc cancelled. getBusinessObjectService().delete(award.getAwardDirectFandADistributions()); Boolean autoGenerate = getParameterService().getParameterValueAsBoolean(Constants.PARAMETER_MODULE_AWARD, ParameterConstants.DOCUMENT_COMPONENT, KeyConstants.AUTO_GENERATE_TIME_MONEY_FUNDS_DIST_PERIODS); if (autoGenerate) { AwardDirectFandADistributionService awardDirectFandADistributionService = getAwardDirectFandADistributionService(); award.setAwardDirectFandADistributions (awardDirectFandADistributionService. generateDefaultAwardDirectFandADistributionPeriods(award)); } } } @SuppressWarnings({ "deprecation", "unchecked" }) public ActionForward timeAndMoney(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ AwardForm awardForm = (AwardForm) form; AwardDocument awardDocument = awardForm.getAwardDocument(); ActionForward actionForward; //if award document is view only then we don't need to save document before opening T&M document. if ((!awardForm.getEditingMode().containsKey("viewOnly") || awardForm.getEditingMode().containsKey("fullEntry")) && !awardDocument.getDocumentHeader().getWorkflowDocument().isFinal()) { this.save(mapping, form, request, response); } //if T&M document is created, there must be a project start date on the award. timeAndMoneyAwardDateSaveRuleImpl = new TimeAndMoneyAwardDateSaveRuleImpl(); timeAndMoneyAwardDateSaveRuleImpl.enforceAwardStartDatePopulated(awardDocument.getAward()); if(GlobalVariables.getMessageMap().hasNoErrors()){ //AwardForm awardForm = (AwardForm) form; DocumentService documentService = KraServiceLocator.getService(DocumentService.class); boolean firstTimeAndMoneyDocCreation = Boolean.TRUE; TransactionDetail transactionDetail = null; populateAwardHierarchy(form); Award currentAward = awardDocument.getAward(); Map<String, Object> fieldValues = new HashMap<String, Object>(); String rootAwardNumber = awardForm.getAwardHierarchyNodes().get(currentAward.getAwardNumber()).getRootAwardNumber(); fieldValues.put("rootAwardNumber", rootAwardNumber); BusinessObjectService businessObjectService = KraServiceLocator.getService(BusinessObjectService.class); List<TimeAndMoneyDocument> timeAndMoneyDocuments = (List<TimeAndMoneyDocument>)businessObjectService.findMatching(TimeAndMoneyDocument.class, fieldValues); Collections.sort(timeAndMoneyDocuments); Award rootAward = getAwardVersionService().getWorkingAwardVersion(rootAwardNumber); // check for existing finalized T & M document before creating a new one. TimeAndMoneyDocument timeAndMoneyDocument = getLastFinalTandMDocument(timeAndMoneyDocuments); if(timeAndMoneyDocuments.size() > 0 && timeAndMoneyDocument != null) { firstTimeAndMoneyDocCreation = Boolean.FALSE; } if (timeAndMoneyDocument == null) { generateDirectFandADistribution(rootAward); } if(firstTimeAndMoneyDocCreation){ timeAndMoneyDocument = (TimeAndMoneyDocument) documentService.getNewDocument(TimeAndMoneyDocument.class); timeAndMoneyDocument.getDocumentHeader().setDocumentDescription("timeandmoney document"); timeAndMoneyDocument.setRootAwardNumber(rootAwardNumber); timeAndMoneyDocument.setAwardNumber(rootAward.getAwardNumber()); timeAndMoneyDocument.setAward(rootAward); AwardAmountTransaction aat = new AwardAmountTransaction(); aat.setAwardNumber("000000-00000");//need to initialize one element in this collection because the doc is saved on creation. aat.setDocumentNumber(timeAndMoneyDocument.getDocumentNumber()); String defaultTxnTypeStr = getParameterService().getParameterValueAsString(Constants.MODULE_NAMESPACE_TIME_AND_MONEY, ParameterConstants.DOCUMENT_COMPONENT, Constants.DEFAULT_TXN_TYPE_COPIED_AWARD); if(StringUtils.isNotEmpty(defaultTxnTypeStr)) { aat.setTransactionTypeCode(Integer.parseInt(defaultTxnTypeStr)); } aat.setAwardNumber(rootAward.getAwardNumber()); //any code for initial transaction and history. transactionDetail = addTransactionDetails(Constants.AWARD_HIERARCHY_DEFAULT_PARENT_OF_ROOT, rootAward.getAwardNumber(), rootAward.getSequenceNumber(), timeAndMoneyDocument.getDocumentNumber(), INITIAL_TRANSACTION_COMMENT, rootAward); //need this check so we don't add additional AAI object if Award has been copied and then creating first T&M doc. if(rootAward.getAwardAmountInfos().size() < 2) { addNewAwardAmountInfoForInitialTransaction(rootAward, timeAndMoneyDocument.getDocumentNumber()); }else { rootAward.getLastAwardAmountInfo().setTimeAndMoneyDocumentNumber(timeAndMoneyDocument.getDocumentNumber()); getBusinessObjectService().save(rootAward); } timeAndMoneyDocument.getAwardAmountTransactions().add(aat); documentService.saveDocument(timeAndMoneyDocument); getBusinessObjectService().save(transactionDetail); } String routeHeaderId = timeAndMoneyDocument.getDocumentHeader().getWorkflowDocument().getDocumentId(); String forward = buildForwardUrl(routeHeaderId); actionForward = new ActionForward(forward, true); //add this to session and leverage in T&M for return to award action. GlobalVariables.getUserSession().addObject(Constants.AWARD_DOCUMENT_STRING_FOR_SESSION + "-" + timeAndMoneyDocument.getDocumentNumber(), awardDocument.getDocumentNumber()); } else { actionForward = mapping.findForward(Constants.MAPPING_AWARD_BASIC); } return actionForward; } protected TimeAndMoneyDocument getLastFinalTandMDocument(List<TimeAndMoneyDocument> timeAndMoneyDocuments) throws WorkflowException { TimeAndMoneyDocument returnVal = null; DocumentService documentService = KraServiceLocator.getService(DocumentService.class); while(timeAndMoneyDocuments.size() > 0) { TimeAndMoneyDocument docWithWorkFlowData = (TimeAndMoneyDocument) documentService.getByDocumentHeaderId(timeAndMoneyDocuments.get(timeAndMoneyDocuments.size() - 1).getDocumentNumber()); if(docWithWorkFlowData.getDocumentHeader().getWorkflowDocument().isCanceled()) { timeAndMoneyDocuments.remove(timeAndMoneyDocuments.size() - 1); }else { returnVal = docWithWorkFlowData; break; } } return returnVal; } /* * * This method creates a transactionDetail object and adds it to the list for persistence later. * * @param sourceAwardNumber * @param destinationAwardNumber * @param sequenceNumber * @param pendingTransaction * @param currentAwardNumber * @param documentNumber * @param transactionDetailItems */ protected TransactionDetail addTransactionDetails(String sourceAwardNumber, String destinationAwardNumber, Integer sequenceNumber, String documentNumber, String commentsString, Award rootAward){ TransactionDetail transactionDetail = new TransactionDetail(); transactionDetail.setSourceAwardNumber(sourceAwardNumber); transactionDetail.setSequenceNumber(sequenceNumber); transactionDetail.setDestinationAwardNumber(destinationAwardNumber); if(isDirectIndirectViewEnabled()){ transactionDetail.setAnticipatedAmount(rootAward.getAnticipatedTotalDirect().add(rootAward.getAnticipatedTotalIndirect())); transactionDetail.setAnticipatedDirectAmount(rootAward.getAnticipatedTotalDirect()); transactionDetail.setAnticipatedIndirectAmount(rootAward.getAnticipatedTotalIndirect()); transactionDetail.setObligatedAmount(rootAward.getObligatedTotalDirect().add(rootAward.getObligatedTotalIndirect())); transactionDetail.setObligatedDirectAmount(rootAward.getObligatedTotalDirect()); transactionDetail.setObligatedIndirectAmount(rootAward.getObligatedTotalIndirect()); } else { transactionDetail.setAnticipatedAmount(rootAward.getAnticipatedTotal()); transactionDetail.setAnticipatedDirectAmount(rootAward.getAnticipatedTotal()); transactionDetail.setAnticipatedIndirectAmount(new KualiDecimal(0)); transactionDetail.setObligatedAmount(rootAward.getObligatedTotal()); transactionDetail.setObligatedDirectAmount(rootAward.getObligatedTotal()); transactionDetail.setObligatedIndirectAmount(new KualiDecimal(0)); } transactionDetail.setAwardNumber(rootAward.getAwardNumber()); transactionDetail.setTransactionId(new Long(0)); transactionDetail.setTimeAndMoneyDocumentNumber(documentNumber); transactionDetail.setComments(commentsString); transactionDetail.setTransactionDetailType(TransactionDetailType.PRIMARY.toString()); return transactionDetail; } /** * Looks up and returns the ParameterService. * @return the parameter service. */ protected ParameterService getParameterService() { if (this.parameterService == null) { this.parameterService = KraServiceLocator.getService(ParameterService.class); } return this.parameterService; } public boolean isDirectIndirectViewEnabled() { boolean returnValue = false; String directIndirectEnabledValue = getParameterService().getParameterValueAsString(Constants.PARAMETER_MODULE_AWARD, ParameterConstants.DOCUMENT_COMPONENT, "ENABLE_AWD_ANT_OBL_DIRECT_INDIRECT_COST"); if(directIndirectEnabledValue.equals("1")) { returnValue = true; } return returnValue; } /* * add money to amount info Totals, and Distributables. * */ private void addNewAwardAmountInfoForInitialTransaction(Award rootAward, String documentNumber) { AwardAmountInfo rootAwardAmountInfo = rootAward.getLastAwardAmountInfo(); AwardAmountInfo newAwardAmountInfo = new AwardAmountInfo(); newAwardAmountInfo.setAwardNumber(rootAward.getAwardNumber()); newAwardAmountInfo.setSequenceNumber(rootAward.getSequenceNumber()); newAwardAmountInfo.setFinalExpirationDate(rootAwardAmountInfo.getFinalExpirationDate()); newAwardAmountInfo.setCurrentFundEffectiveDate(rootAwardAmountInfo.getCurrentFundEffectiveDate()); newAwardAmountInfo.setObligationExpirationDate(rootAwardAmountInfo.getObligationExpirationDate()); newAwardAmountInfo.setTimeAndMoneyDocumentNumber(documentNumber); newAwardAmountInfo.setTransactionId(null); newAwardAmountInfo.setAward(rootAward); //add transaction amounts to the AmountInfo if(isDirectIndirectViewEnabled()){ newAwardAmountInfo.setAmountObligatedToDate(rootAward.getObligatedTotalDirect().add(rootAward.getObligatedTotalIndirect())); newAwardAmountInfo.setObligatedTotalDirect(rootAward.getObligatedTotalDirect()); newAwardAmountInfo.setObligatedTotalIndirect(rootAward.getObligatedTotalIndirect()); newAwardAmountInfo.setObligatedChange(rootAwardAmountInfo.getObligatedChange()); newAwardAmountInfo.setObligatedChangeDirect(rootAwardAmountInfo.getObligatedTotalDirect()); newAwardAmountInfo.setObligatedChangeIndirect(rootAwardAmountInfo.getObligatedTotalIndirect()); newAwardAmountInfo.setAnticipatedChange(rootAwardAmountInfo.getAnticipatedChange()); newAwardAmountInfo.setAnticipatedTotalAmount(rootAward.getAnticipatedTotalDirect().add(rootAward.getAnticipatedTotalIndirect())); newAwardAmountInfo.setAnticipatedTotalDirect(rootAward.getAnticipatedTotalDirect()); newAwardAmountInfo.setAnticipatedTotalIndirect(rootAward.getAnticipatedTotalIndirect()); newAwardAmountInfo.setAnticipatedChangeDirect(rootAwardAmountInfo.getAnticipatedTotalDirect()); newAwardAmountInfo.setAnticipatedChangeIndirect(rootAwardAmountInfo.getAnticipatedTotalIndirect()); newAwardAmountInfo.setObliDistributableAmount(rootAward.getObligatedTotalDirect().add(rootAward.getObligatedTotalIndirect())); newAwardAmountInfo.setAntDistributableAmount(rootAward.getAnticipatedTotalDirect().add(rootAward.getAnticipatedTotalIndirect())); } else { newAwardAmountInfo.setAmountObligatedToDate(rootAwardAmountInfo.getAmountObligatedToDate()); newAwardAmountInfo.setObligatedTotalDirect(rootAward.getObligatedTotalDirect()); newAwardAmountInfo.setObligatedTotalIndirect(rootAward.getObligatedTotalIndirect()); newAwardAmountInfo.setObligatedChange(rootAwardAmountInfo.getObligatedChange()); newAwardAmountInfo.setObligatedChangeDirect(rootAwardAmountInfo.getObligatedChangeDirect()); newAwardAmountInfo.setObligatedChangeIndirect(rootAwardAmountInfo.getObligatedChangeIndirect()); newAwardAmountInfo.setAnticipatedChange(rootAwardAmountInfo.getAnticipatedChange()); newAwardAmountInfo.setAnticipatedTotalAmount(rootAward.getAnticipatedTotal()); newAwardAmountInfo.setAnticipatedTotalDirect(rootAward.getAnticipatedTotalDirect()); newAwardAmountInfo.setAnticipatedTotalIndirect(rootAward.getAnticipatedTotalIndirect()); newAwardAmountInfo.setAnticipatedChangeDirect(rootAwardAmountInfo.getAnticipatedChangeDirect()); newAwardAmountInfo.setAnticipatedChangeIndirect(rootAwardAmountInfo.getAnticipatedChangeIndirect()); newAwardAmountInfo.setObliDistributableAmount(rootAward.getObligatedTotal()); newAwardAmountInfo.setAntDistributableAmount(rootAward.getAnticipatedTotal()); } newAwardAmountInfo.setOriginatingAwardVersion(rootAward.getSequenceNumber()); rootAward.getAwardAmountInfos().add(newAwardAmountInfo); getBusinessObjectService().save(rootAward); } public List<Award> getAwardVersions(String awardNumber) { BusinessObjectService businessObjectService = KraServiceLocator.getService(BusinessObjectService.class); List<Award> awards = (List<Award>)businessObjectService.findMatchingOrderBy(Award.class, getHashMapToFindActiveAward(awardNumber), "sequenceNumber", true); return awards; } // public Award getWorkingAwardVersion(String goToAwardNumber) { // Award award = null; // award = getPendingAwardVersion(goToAwardNumber); // if (award == null) { // award = getActiveAwardVersion(goToAwardNumber); // } // return award; // } public AwardVersionService getAwardVersionService() { return KraServiceLocator.getService(AwardVersionService.class); } public ActionForward openWindow(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String documentNumber = request.getParameter("awardDocumentNumber"); String awardNumber = request.getParameter("awardNumber"); AwardForm awardForm = (AwardForm)form; DocumentService documentService = KraServiceLocator.getService(DocumentService.class); AwardDocument awardDocument = (AwardDocument)documentService.getByDocumentHeaderId(documentNumber); Award award = getAwardService().getAwardAssociatedWithDocument(awardDocument.getDocumentNumber()); awardForm.setCurrentAwardNumber(awardNumber); awardForm.setCurrentSeqNumber(award.getSequenceNumber().toString()); awardDocument.setAward(award); awardForm.setDocument(awardDocument); populateAwardHierarchy(awardForm); return mapping.findForward("basic"); } private Map<String, String> getHashMapToFindActiveAward(String goToAwardNumber) { Map<String, String> map = new HashMap<String,String>(); map.put("awardNumber", goToAwardNumber); return map; } /** * This method tests if the award is new by checking the size of AwardDirectFandADistributions on the Award. * @param awardForm * @return */ public boolean isNewAward(AwardForm awardForm) { return awardForm.getAwardDocument().getAward().getAwardDirectFandADistributions().size() == 0; } /** * * This method is a helper method to retrieve AwardSponsorTermService. * @return */ protected AwardDirectFandADistributionService getAwardDirectFandADistributionService() { return KraServiceLocator.getService(AwardDirectFandADistributionService.class); } /** * * This method gets called upon navigation to Payment, Reports and Terms tab. * @param mapping * @param form * @param request * @param response * @return */ @SuppressWarnings("all") public ActionForward paymentReportsAndTerms(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; setReportsAndTermsOnAwardForm(awardForm); return mapping.findForward(Constants.MAPPING_AWARD_PAYMENT_REPORTS_AND_TERMS_PAGE); } @SuppressWarnings("unchecked") protected void setReportsAndTermsOnAwardForm(AwardForm awardForm) { AwardSponsorTermService awardSponsorTermService = getAwardSponsorTermService(); List<KeyValue> sponsorTermTypes = awardSponsorTermService.retrieveSponsorTermTypesToAwardFormForPanelHeaderDisplay(); awardForm.getSponsorTermFormHelper().setSponsorTermTypes(sponsorTermTypes); awardForm.getSponsorTermFormHelper().setNewSponsorTerms(awardSponsorTermService.getEmptyNewSponsorTerms(sponsorTermTypes)); AwardReportsService awardReportsService = KraServiceLocator.getService(AwardReportsService.class); Map<String,Object> initializedObjects = awardReportsService.initializeObjectsForReportsAndPayments( awardForm.getAwardDocument().getAward()); awardForm.setReportClasses((List<ConcreteKeyValue>) initializedObjects.get( Constants.REPORT_CLASSES_KEY_FOR_INITIALIZE_OBJECTS)); awardForm.getAwardReportsBean().setNewAwardReportTerms((List<AwardReportTerm>) initializedObjects.get( Constants.NEW_AWARD_REPORT_TERMS_LIST_KEY_FOR_INITIALIZE_OBJECTS)); awardForm.getAwardReportsBean().setNewAwardReportTermRecipients((List<AwardReportTermRecipient>) initializedObjects.get( Constants.NEW_AWARD_REPORT_TERM_RECIPIENTS_LIST_KEY_FOR_INITIALIZE_OBJECTS)); awardForm.setReportClassForPaymentsAndInvoices((ReportClass) initializedObjects.get( Constants.REPORT_CLASS_FOR_PAYMENTS_AND_INVOICES_PANEL)); awardForm.buildReportTrackingBeans(); } /** * * This method is a helper method to retrieve AwardSponsorTermService. * @return */ protected AwardSponsorTermService getAwardSponsorTermService() { return KraServiceLocator.getService(AwardSponsorTermService.class); } /** * * This method gets called upon navigation to Special Review tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward specialReview(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { ((AwardForm) form).getSpecialReviewHelper().prepareView(); return mapping.findForward(Constants.MAPPING_AWARD_SPECIAL_REVIEW_PAGE); } /** * * This method gets called upon navigation to Special Review tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward customData(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; awardForm.getCustomDataHelper().prepareCustomData(); return mapping.findForward(Constants.MAPPING_AWARD_CUSTOM_DATA_PAGE); } /** * * This method gets called upon navigation to Custom Data tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward questions(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { return mapping.findForward(Constants.MAPPING_AWARD_QUESTIONS_PAGE); } /** * * This method gets called upon navigation to Questions tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward permissions(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { ((AwardForm)form).getPermissionsHelper().prepareView(); return mapping.findForward(Constants.MAPPING_AWARD_PERMISSIONS_PAGE); } /** * * This method gets called upon navigation to Permissions tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward notesAndAttachments(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; awardForm.getAwardCommentBean().setAwardCommentScreenDisplayTypesOnForm(); awardForm.getAwardCommentBean().setAwardCommentHistoryFlags(); return mapping.findForward(Constants.MAPPING_AWARD_NOTES_AND_ATTACHMENTS_PAGE); } /** * * This method gets called upon navigation to Medusa tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward medusa(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; if (awardForm.getDocument().getDocumentNumber() == null) { //if we are entering this from the search results loadDocumentInForm(request, awardForm); } awardForm.getMedusaBean().setMedusaViewRadio("0"); awardForm.getMedusaBean().setModuleName("award"); awardForm.getMedusaBean().setModuleIdentifier(awardForm.getAwardDocument().getAward().getAwardId()); awardForm.getMedusaBean().generateParentNodes(); return mapping.findForward(Constants.MAPPING_AWARD_MEDUSA_PAGE); } /** * * This method gets called upon navigation to Award Actions tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward awardActions(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; String command = request.getParameter(KewApiConstants.COMMAND_PARAMETER); if(StringUtils.isNotEmpty(command) && KewApiConstants.DOCSEARCH_COMMAND.equals(command)) { loadDocumentInForm(request, awardForm); WorkflowDocument workflowDoc = awardForm.getAwardDocument().getDocumentHeader().getWorkflowDocument(); if(workflowDoc != null) awardForm.setDocTypeName(workflowDoc.getDocumentTypeName()); request.setAttribute("selectedAwardNumber", awardForm.getAwardDocument().getAward().getAwardNumber()); } populateAwardHierarchy(form); return mapping.findForward(Constants.MAPPING_AWARD_ACTIONS_PAGE); } /** * * This method gets called upon navigation to Awards tab. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward budgets(ActionMapping mapping, ActionForm form , HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; getAwardBudgetService().populateBudgetLimitSummary(awardForm.getBudgetLimitSummary(), awardForm.getAwardDocument()); return mapping.findForward(Constants.MAPPING_AWARD_BUDGET_VERSIONS_PAGE); } /** * @param mapping * @param form * @param request * @param response * @param awardForm * @return * @throws Exception */ ActionForward handleDocument(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, AwardForm awardForm) throws Exception { ActionForward forward = null; String command = awardForm.getCommand(); if (KewApiConstants.ACTIONLIST_INLINE_COMMAND.equals(command)) { loadDocumentInForm(request, awardForm); String docIdRequestParameter = request.getParameter(KRADConstants.PARAMETER_DOC_ID); ActionForward baseForward = mapping.findForward(Constants.MAPPING_COPY_PROPOSAL_PAGE); forward = new ActionForward(buildForwardStringForActionListCommand( baseForward.getPath(),awardForm.getDocument().getDocumentNumber())); } else if (Constants.MAPPING_AWARD_ACTIONS_PAGE.equals(command)) { loadDocument(awardForm); } else { forward = super.docHandler(mapping, form, request, response); } if (Constants.MAPPING_AWARD_ACTIONS_PAGE.equals(command)) { forward = awardActions(mapping, awardForm, request, response); } return forward; } protected void loadDocument(KualiDocumentFormBase kualiForm) throws WorkflowException { super.loadDocument(kualiForm); Award award = ((AwardForm) kualiForm).getAwardDocument().getAward(); award.setSponsorNihMultiplePi(getSponsorService().isSponsorNihMultiplePi(award)); } /** * * loadDocumentInForm * @param mapping * @param form * @param request * @param response * @return */ protected void loadDocumentInForm(HttpServletRequest request, AwardForm awardForm) throws WorkflowException { String docIdRequestParameter = request.getParameter(KRADConstants.PARAMETER_DOC_ID); AwardDocument retrievedDocument = (AwardDocument) KRADServiceLocatorWeb.getDocumentService().getByDocumentHeaderId(docIdRequestParameter); awardForm.setDocument(retrievedDocument); request.setAttribute(KRADConstants.PARAMETER_DOC_ID, docIdRequestParameter); handlePlaceHolderDocument(awardForm, retrievedDocument); } /** * * @return */ @Override protected DocumentService getDocumentService() { return KRADServiceLocatorWeb.getDocumentService(); } /** * * This method is a helper method to retrieve KualiRuleService. * @return */ protected KualiRuleService getKualiRuleService() { return KraServiceLocator.getService(KualiRuleService.class); } /** * This method sets up a sponsor template synchronization loop. * It is called by the ui when a specific set of scopes need to by synchronized. * If no scopes are in the request, then a full synchronization to the scopes: * * AWARD_PAGE * SPONSOR_CONTACTS_TAB * PAYMENTS_AND_INVOICES_TAB * TERMS_TAB * REPORTS_TAB * COMMENTS_TAB * * is performed. This method generates and stores the list of scopes to sync * and the map to indicate if confirmation is necessary from the user before * a particular scope is synchronized and then forwards to the method the handles * the request loop. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward syncAwardTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ AwardTemplateSyncService awardTemplateSyncService = KraServiceLocator.getService(AwardTemplateSyncService.class); AwardForm awardForm = (AwardForm)form; AwardDocument awardDocument = awardForm.getAwardDocument(); AwardTemplateSyncScope[] scopes; String syncScopes = getSyncScopesString( request ); System.err.println("syncScopes: " + syncScopes); if (awardDocument.getAward().getTemplateCode() == null || awardDocument.getAward().getAwardTemplate() == null) { //return now since there is no template code. GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError( StringUtils.isBlank(syncScopes) ? "document.award.awardTemplate" : String.format("document.award.awardTemplate.%s", StringUtils.substring(syncScopes,1)), KeyConstants.ERROR_NO_SPONSOR_TEMPLATE_FOUND, new String[]{}); awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); return mapping.findForward(Constants.MAPPING_AWARD_BASIC); } Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); if( question != null ) return processSyncAward(mapping, awardForm, request, response); awardForm.setCurrentSyncScopes(null); awardForm.setSyncRequiresConfirmationMap(null); /* * The format for the action string is: * methodToCall.syncAwardTemplate:SCOPE1:...:SCOPEN].anchor... * Where: * [PropertyName|MethodName] means to sync by a property name or a method name. * SCOPE1...SCOPEN : A ':' delimited list of scope names that should be synced. If none are specified then the sync is done for every field and method. * */ if (StringUtils.isNotBlank(syncScopes) && syncScopes.length() > 1 && syncScopes.indexOf(":")>-1) { String[] scopeStrings = StringUtils.split(StringUtils.substringAfter(syncScopes, ":")); scopes = new AwardTemplateSyncScope[scopeStrings.length]; for( int i = 0; i < scopeStrings.length; i++ ) { scopes[i] = Enum.valueOf(AwardTemplateSyncScope.class, scopeStrings[i]); } awardForm.setSyncRequiresConfirmationMap(generateScopeRequiresConfirmationMap( scopes, awardDocument, false, false )); awardForm.setCurrentSyncScopes(scopes); } else { awardForm.setSyncRequiresConfirmationMap(generateScopeRequiresConfirmationMap( DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES, awardDocument, false, false )); awardForm.setCurrentSyncScopes(DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES); } return processSyncAward(mapping,form,request,response); } private Map<AwardTemplateSyncScope, Boolean> generateScopeRequiresConfirmationMap( AwardTemplateSyncScope[] scopes, AwardDocument awardDocument,boolean skipCheck,boolean defaultValue ) { AwardTemplateSyncService awardTemplateSyncService = KraServiceLocator.getService(AwardTemplateSyncService.class); Map< AwardTemplateSyncScope,Boolean> requiresQuestionMap = new HashMap<AwardTemplateSyncScope,Boolean>(); for( AwardTemplateSyncScope scope: scopes ) { if( skipCheck ) { requiresQuestionMap.put(scope, defaultValue); } else { if( awardTemplateSyncService.syncWillAlterData(awardDocument, scope) ) { if( LOG.isDebugEnabled() ) LOG.debug(String.format( "%s:%s", scope, true )); requiresQuestionMap.put(scope, true); } else { if( LOG.isDebugEnabled() ) LOG.warn(String.format( "%s:%s", scope, false )); requiresQuestionMap.put(scope, false); } } } return requiresQuestionMap; } /** * This method sets up a full template sync. This is called on return from a Sponsor Template Lookup. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward fullSyncToAwardTemplate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm)form; AwardDocument awardDocument = awardForm.getAwardDocument(); if( awardDocument.getAward().getTemplateCode() == null ) { //return now since there is no template code. GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("document.award.awardTemplate",KeyConstants.ERROR_NO_TEMPLATE_CODE, new String[] {}); awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); return mapping.findForward(Constants.MAPPING_AWARD_BASIC); // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. } else if (org.kuali.rice.krad.util.ObjectUtils.isNull(awardDocument.getAward().getAwardTemplate())) { awardDocument.getAward().refreshReferenceObject("awardTemplate"); // check again to confirm if the awardTemplate was actually invalid or was it just the OJB lazy loading. if (org.kuali.rice.krad.util.ObjectUtils.isNull(awardDocument.getAward().getAwardTemplate())) { GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("document.award.awardTemplate", KeyConstants.ERROR_INVALID_TEMPLATE_CODE, new String[] {}); awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); return mapping.findForward(Constants.MAPPING_AWARD_BASIC); } // ### Vivantech Fix : #15 / [#80417598] finish. } else { awardDocument.getAward().refreshReferenceObject("awardTemplate"); } Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON); boolean proceedToProcessSyncAward = true; if( question == null ) { //setup before forwarding to the processor. AwardTemplateSyncScope[] scopes; scopes = new AwardTemplateSyncScope[] { AwardTemplateSyncScope.FULL }; HashMap<AwardTemplateSyncScope,Boolean> confirmMap = new HashMap<AwardTemplateSyncScope,Boolean>(); confirmMap.put(AwardTemplateSyncScope.FULL, true); awardForm.setCurrentSyncScopes(scopes); awardForm.setSyncRequiresConfirmationMap(confirmMap); } else if( question!=null && (QUESTION_VERIFY_SYNC+":"+AwardTemplateSyncScope.FULL).equals(question) ) { if( ConfirmationQuestion.YES.equals(buttonClicked) ) { //if the award has a sequence number more than 1, we //only select the template and the user must use the buttons on //each panel to sync. if( awardDocument.getAward().getSequenceNumber() > 1 ) { awardForm.setCurrentSyncScopes(new AwardTemplateSyncScope[] {}); proceedToProcessSyncAward=false; awardForm.setTemplateLookup(false); awardForm.setOldTemplateCode(null); } else { awardForm.setCurrentSyncScopes(DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES); awardForm.setSyncRequiresConfirmationMap(generateScopeRequiresConfirmationMap( DEFAULT_AWARD_TEMPLATE_SYNC_SCOPES, awardDocument, false,false )); } } else { proceedToProcessSyncAward = false; awardDocument.getAward().setTemplateCode(awardForm.getOldTemplateCode()); awardDocument.getAward().refreshReferenceObject("awardTemplate"); awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); } } return proceedToProcessSyncAward?processSyncAward(mapping,form,request,response):mapping.findForward(Constants.MAPPING_AWARD_BASIC); } protected StrutsConfirmation buildAwardSyncParameterizedConfirmationQuestion(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String questionId, String configurationId, String... params) throws Exception { StrutsConfirmation retval = new StrutsConfirmation(); retval.setMapping(mapping); retval.setForm(form); retval.setRequest(request); retval.setResponse(response); retval.setQuestionId(questionId); retval.setQuestionType(CONFIRMATION_QUESTION); String questionText = this.COMFIRMATION_PARAM_STRING; for (int i = 0; i < params.length; i++) { questionText = replace(questionText, "{" + i + "}", params[i]); } retval.setQuestionText(questionText); return retval; } public ActionForward processSyncAward(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ AwardTemplateSyncService awardTemplateSyncService = KraServiceLocator.getService(AwardTemplateSyncService.class); AwardForm awardForm = (AwardForm)form; AwardDocument awardDocument = awardForm.getAwardDocument(); String awardTemplateDescription = ""; if (org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument) && org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument.getAward()) && org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument.getAward().getAwardTemplate()) && org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument.getAward().getAwardTemplate().getDescription())) awardTemplateDescription = awardDocument.getAward().getAwardTemplate().getDescription(); String question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON); AwardTemplateSyncScope[] scopes = awardForm.getCurrentSyncScopes(); AwardTemplateSyncScope[] scopesList = scopes; // for maintaining the current scopes list ConfigurationService kualiConfiguration = CoreApiServiceLocator.getKualiConfigurationService(); for( int i = 0; i < scopes.length; i++ ) { AwardTemplateSyncScope currentScope = scopes[i]; if (((question == null || !((StringUtils.equals(QUESTION_VERIFY_SYNC + ":" + currentScope, question)))) && awardForm.getSyncRequiresConfirmationMap().get(currentScope)) && !StringUtils.equals(QUESTION_VERIFY_EMPTY_SYNC + ":" + currentScope, question)) { String scopeSyncLabel = ""; StrutsConfirmation confirmationQuestion = new StrutsConfirmation(); if( StringUtils.isNotEmpty(currentScope.getDisplayPropertyName())) { scopeSyncLabel = kualiConfiguration.getPropertyValueAsString(currentScope.getDisplayPropertyName()); } if( StringUtils.equals(scopeSyncLabel, REPORTS_PROPERTY_NAME) || StringUtils.equals(scopeSyncLabel, PAYMENT_INVOICES_PROPERTY_NAME)) { confirmationQuestion = buildAwardSyncParameterizedConfirmationQuestion(mapping, form, request, response, (QUESTION_VERIFY_SYNC+":"+currentScope), currentScope.equals(AwardTemplateSyncScope.FULL)?KeyConstants.QUESTION_SYNC_FULL:KeyConstants.QUESTION_SYNC_PANEL, scopeSyncLabel, awardTemplateDescription, getScopeMessageToAddQuestion(currentScope)); } else { confirmationQuestion = buildParameterizedConfirmationQuestion(mapping, form, request, response, (QUESTION_VERIFY_SYNC+":"+currentScope), currentScope.equals(AwardTemplateSyncScope.FULL)?KeyConstants.QUESTION_SYNC_FULL:KeyConstants.QUESTION_SYNC_PANEL, scopeSyncLabel, awardTemplateDescription, getScopeMessageToAddQuestion(currentScope)); } confirmationQuestion.setCaller("processSyncAward"); awardForm.setCurrentSyncQuestionId( (QUESTION_VERIFY_SYNC+":"+currentScope) ); return (performQuestionWithoutInput( confirmationQuestion,"" )); } else if (( StringUtils.equals(awardForm.getCurrentSyncQuestionId(), question) && ConfirmationQuestion.YES.equals(buttonClicked)) || !awardForm.getSyncRequiresConfirmationMap().get(currentScope)) { if( LOG.isDebugEnabled() ) LOG.debug( "USER ACCEPTED SYNC OR NO CONFIRM REQUIRED FOR:"+currentScope+" CALLING SYNC SERVICE." ); boolean templateHasScopedData = awardTemplateSyncService.templateContainsScopedData(awardDocument, currentScope); boolean scopeRequiresEmptyConfirm = ArrayUtils.contains(DEFAULT_SCOPES_REQUIRE_VERIFY_FOR_EMPTY,currentScope); if( awardDocument.getAward().getSequenceNumber() > 1 && !templateHasScopedData && StringUtils.equals( awardForm.getCurrentSyncQuestionId(), (QUESTION_VERIFY_SYNC+":"+currentScope) ) && scopeRequiresEmptyConfirm ) { //we need to verify since the template has no data. String scopeSyncLabel = ""; if( StringUtils.isNotEmpty(currentScope.getDisplayPropertyName())) scopeSyncLabel = kualiConfiguration.getPropertyValueAsString(currentScope.getDisplayPropertyName()); StrutsConfirmation confirmationQuestion = buildParameterizedConfirmationQuestion(mapping, form, request, response, ( QUESTION_VERIFY_EMPTY_SYNC+":"+currentScope), KeyConstants.QUESTION_SYNC_PANEL_TO_EMPTY, scopeSyncLabel, awardDocument.getAward().getAwardTemplate().getDescription()); awardForm.setCurrentSyncQuestionId((QUESTION_VERIFY_EMPTY_SYNC+":"+currentScope)); confirmationQuestion.setCaller("processSyncAward"); return performQuestionWithoutInput(confirmationQuestion, ""); } else { //anything to do here? } AwardTemplateSyncScope[] s = { currentScope }; awardTemplateSyncService.syncAwardToTemplate(awardDocument, s); scopesList = (AwardTemplateSyncScope[])ArrayUtils.remove(scopesList, 0); // maintaining the current list awardForm.setCurrentSyncScopes(scopesList); } else if ( StringUtils.equals(awardForm.getCurrentSyncQuestionId(),question) && ConfirmationQuestion.NO.equals(buttonClicked)) { if( LOG.isDebugEnabled() ) LOG.debug( "USER DECLINED "+currentScope +", SKIPPING." ); scopesList = (AwardTemplateSyncScope[])ArrayUtils.remove(scopesList, 0); // maintaining the current list awardForm.setCurrentSyncScopes(scopesList); } else { throw new RuntimeException( "Do not know what to do in this case!" ); } } awardForm.setOldTemplateCode(null); awardForm.setTemplateLookup(false); awardForm.setCurrentSyncScopes(null); awardForm.setCurrentSyncQuestionId(null); return mapping.findForward(Constants.MAPPING_AWARD_BASIC); } private String getScopeMessageToAddQuestion( AwardTemplateSyncScope scope ) { ConfigurationService configurationService = CoreApiServiceLocator.getKualiConfigurationService(); String result = configurationService.getPropertyValueAsString("document.question.syncPanel.add.text."+scope); return result==null?"":result; } /** * Parses the method to call attribute to pick off the scopes to sync. * * @param request * @return returns the colon delimited list of scopes. */ protected String getSyncScopesString(HttpServletRequest request) { String syncScopesList = null; String parameterName = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE); if (StringUtils.isNotBlank(parameterName) && parameterName.indexOf(".scopes")!=-1) { syncScopesList = StringUtils.substringBetween(parameterName, ".scopes", ".anchor"); } return syncScopesList; } protected SponsorService getSponsorService() { return KraServiceLocator.getService(SponsorService.class); } @Override protected PessimisticLockService getPessimisticLockService() { return KraServiceLocator.getService(AwardLockService.class); } /** * @return */ protected VersionHistoryService getVersionHistoryService() { return KraServiceLocator.getService(VersionHistoryService.class); } /** * KCAWD-494:If the user selects a sponsor template lookup, set a flag and store the current sponsor template code in the form. The flag and the * current value will be used on the return to check if the template has changed. * * * @see org.kuali.rice.kns.web.struts.action.KualiAction#performLookup(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward performLookup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String parameterName = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE); if( (StringUtils.isNotBlank(parameterName) && parameterName.indexOf(".performLookup")!=-1 && parameterName.contains("templateCode:document.award.templateCode"))) { AwardForm awardForm = (AwardForm)form; awardForm.setTemplateLookup(true); ((AwardForm)form).setOldTemplateCode(((AwardForm)form).getAwardDocument().getAward().getTemplateCode() ); } return super.performLookup(mapping, form, request, response); } /** * * This should be called when an add or delete action is called that might be added to the sync queue. * It checks to ensure that syncMode is already enabled and will return an ActionForward for * the question or for the returnForward specified by the caller. * @param mapping * @param form * @param request * @param response * @param syncType * @param object * @param attrName * @param returnForward * @return * @throws Exception */ protected ActionForward confirmSyncAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, AwardSyncType syncType, PersistableBusinessObject object, String awardAttrName, String attrName, ActionForward returnForward) throws Exception { AwardForm awardForm = (AwardForm) form; if (awardForm.isSyncMode()) { awardForm.getAwardSyncBean().setCurrentForward(returnForward); awardForm.getAwardSyncBean().addPendingChange(syncType, object, awardAttrName, attrName); return syncActionCaller(mapping, form, request, response); } else { return returnForward; } } /** * This should be called when a group add or delete action is called that might be added to the sync queue. * It checks to ensure that syncMode is already enabled and will return an ActionForward for * the question or for the returnForward specified by the caller. * @param mapping * @param form * @param request * @param response * @param pendingChanges * @param returnForward * @return * @throws Exception */ protected ActionForward confirmSyncAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, List<AwardSyncPendingChangeBean> pendingChanges, ActionForward returnForward) throws Exception { AwardForm awardForm = (AwardForm) form; if (awardForm.isSyncMode()) { awardForm.getAwardSyncBean().setCurrentForward(returnForward); awardForm.getAwardSyncBean().getPendingChanges().addAll(pendingChanges); return syncActionCaller(mapping, form, request, response); } else { return returnForward; } } /** * When synchronizing a new addition or deletion call this method. It will confirm the change * and then add the change. * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward syncActionCaller(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AwardForm awardForm = (AwardForm) form; String message = ADD_SYNC_CHANGE_QUESTION; if (awardForm.getAwardSyncBean().getPendingChanges().get(0).getSyncType().equals(AwardSyncType.DELETE_SYNC.getSyncValue())) { message = DEL_SYNC_CHANGE_QUESTION; } //overwrite the method to call to call this instead of the original method which would result //in an error as the action should have already been performed request.setAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE, "methodToCall.syncActionCaller"); ActionForward confirmAction = confirm(buildParameterizedConfirmationQuestion(mapping, form, request, response, "confirmSyncActionKey", message), "confirmSyncAction", "refuseSyncAction"); if (confirmAction != null) { return confirmAction; } else { return awardForm.getAwardSyncBean().getCurrentForward(); } } /** * If the user answers yes to a confirm sync action question call this method. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward confirmSyncAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; awardForm.getAwardSyncBean().confirmPendingChanges(); return null; } /** * If the user answers no to a confirm sync action question call this method. * @param mapping * @param form * @param request * @param response * @return */ public ActionForward refuseSyncAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { AwardForm awardForm = (AwardForm) form; awardForm.getAwardSyncBean().getPendingChanges().clear(); return null; } protected AwardSyncCreationService getAwardSyncCreationService() { return KraServiceLocator.getService(AwardSyncCreationService.class); } protected AwardSyncService getAwardSyncService() { return KraServiceLocator.getService(AwardSyncService.class); } protected AwardBudgetService getAwardBudgetService() { if (awardBudgetService == null) { awardBudgetService = KraServiceLocator.getService(AwardBudgetService.class); } return awardBudgetService; } /** * @see org.kuali.kra.web.struts.action.KraTransactionalDocumentActionBase#populateAuthorizationFields(org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase) * If Award Infos or dates have been edited in a T&M document, then we want to suppress the cancel action. */ @SuppressWarnings("unchecked") @Override protected void populateAuthorizationFields(KualiDocumentFormBase formBase) { super.populateAuthorizationFields(formBase); AwardForm awardForm = (AwardForm) formBase; AwardDocument awardDocument = awardForm.getAwardDocument(); Award award = awardDocument.getAward(); Map documentActions = formBase.getDocumentActions(); //if Award version has been edited in T&M doc then we suppress cancel action. //workaround for copied awards. On initial copy the Award has two entries in AAI table and originating award version of first entry is null. if (award.getAwardAmountInfos().size() > 1) { if(!(award.getAwardAmountInfos().size() == 2 && award.getAwardAmountInfos().get(0).getOriginatingAwardVersion() == null) && documentActions.containsKey(KRADConstants.KUALI_ACTION_CAN_CANCEL)) { documentActions.remove(KRADConstants.KUALI_ACTION_CAN_CANCEL); } } } public AwardService getAwardService() { if (awardService == null) { awardService = KraServiceLocator.getService(AwardService.class); } return awardService; } public void setAwardService(AwardService awardService) { this.awardService = awardService; } public ReportTrackingService getReportTrackingService() { if (reportTrackingService == null) { reportTrackingService = KraServiceLocator.getService(ReportTrackingService.class); } return reportTrackingService; } /** * This method will populate the subawards if award is added as a funding source to perticular subaward * @param award */ protected void setSubAwardDetails(Award award){ award.setSubAwardList(getSubAwardService().getLinkedSubAwards(award)); } protected KcNotificationService getNotificationService() { if (notificationService == null) { notificationService = KraServiceLocator.getService(KcNotificationService.class); } return notificationService; } public void setNotificationService(KcNotificationService notificationService) { this.notificationService = notificationService; } protected SubAwardService getSubAwardService() { if (subAwardService == null) { subAwardService = KraServiceLocator.getService(SubAwardService.class); } return subAwardService; } public void setSubAwardService(SubAwardService subAwardService) { this.subAwardService = subAwardService; } public ActionForward superUserActionHelper(SuperUserAction actionName, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC); AwardForm awardForm = (AwardForm) form; Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON); String methodToCall = ((KualiForm) form).getMethodToCall(); awardForm.setAuditActivated(true); ValidationState status = ValidationState.OK; if (!awardForm.getDocument().getDocumentHeader().getWorkflowDocument().isEnroute()) { status = new AuditActionHelper().isValidSubmission(awardForm, true); } if (status == ValidationState.WARNING) { if(question == null){ List<String> selectedActionRequests = awardForm.getSelectedActionRequests(); // Need to add the super user requests to user session because they are wiped out by //the KualiRequestProcessor reset on //clicking yes to the question. Retrieve again during actual routing and add to form. GlobalVariables.getUserSession().addObject(SUPER_USER_ACTION_REQUESTS, selectedActionRequests); try { return this.performQuestionWithoutInput(mapping, form, request, response, DOCUMENT_ROUTE_QUESTION, "Validation Warning Exists. Are you sure want to submit to workflow routing.", KRADConstants.CONFIRMATION_QUESTION, methodToCall, ""); } catch (Exception e) { e.printStackTrace(); } } else if(DOCUMENT_ROUTE_QUESTION.equals(question) && ConfirmationQuestion.YES.equals(buttonClicked)) { awardForm.setSelectedActionRequests((List<String>)GlobalVariables.getUserSession().retrieveObject(SUPER_USER_ACTION_REQUESTS)); GlobalVariables.getUserSession().removeObject(SUPER_USER_ACTION_REQUESTS); switch (actionName) { case SUPER_USER_APPROVE: return super.superUserApprove(mapping, awardForm, request, response); case TAKE_SUPER_USER_ACTIONS: return super.takeSuperUserActions(mapping, awardForm, request, response); } } else { return forward; } } else if(status == ValidationState.OK){ switch (actionName) { case SUPER_USER_APPROVE: return super.superUserApprove(mapping, awardForm, request, response); case TAKE_SUPER_USER_ACTIONS: return super.takeSuperUserActions(mapping, awardForm, request, response); } } else { GlobalVariables.getMessageMap().clearErrorMessages(); GlobalVariables.getMessageMap().putError("datavalidation",KeyConstants.ERROR_WORKFLOW_SUBMISSION, new String[] {}); return forward; } return forward; } @Override public ActionForward superUserApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { return superUserActionHelper(SuperUserAction.SUPER_USER_APPROVE, mapping, form, request, response); } @Override public ActionForward takeSuperUserActions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { return superUserActionHelper(SuperUserAction.TAKE_SUPER_USER_ACTIONS, mapping, form, request, response); } }
Issue #101 / [#92147692] Adding comments to the code and fixing file version in KC-fixes and EKC.
src/main/java/org/kuali/kra/award/web/struts/action/AwardAction.java
Issue #101 / [#92147692] Adding comments to the code and fixing file version in KC-fixes and EKC.
<ide><path>rc/main/java/org/kuali/kra/award/web/struts/action/AwardAction.java <ide> AwardTemplateSyncService awardTemplateSyncService = KraServiceLocator.getService(AwardTemplateSyncService.class); <ide> AwardForm awardForm = (AwardForm)form; <ide> AwardDocument awardDocument = awardForm.getAwardDocument(); <add> <add> // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. <ide> String awardTemplateDescription = ""; <ide> if (org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument) && org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument.getAward()) && org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument.getAward().getAwardTemplate()) && org.kuali.rice.krad.util.ObjectUtils.isNotNull(awardDocument.getAward().getAwardTemplate().getDescription())) <ide> awardTemplateDescription = awardDocument.getAward().getAwardTemplate().getDescription(); <add> // ### Vivantech Fix : #15 / [#80417598] finish. <add> <ide> String question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME); <ide> Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON); <ide> AwardTemplateSyncScope[] scopes = awardForm.getCurrentSyncScopes(); <ide> if( StringUtils.isNotEmpty(currentScope.getDisplayPropertyName())) { <ide> scopeSyncLabel = kualiConfiguration.getPropertyValueAsString(currentScope.getDisplayPropertyName()); <ide> } <add> // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. <ide> if( StringUtils.equals(scopeSyncLabel, REPORTS_PROPERTY_NAME) || StringUtils.equals(scopeSyncLabel, PAYMENT_INVOICES_PROPERTY_NAME)) { <ide> confirmationQuestion = buildAwardSyncParameterizedConfirmationQuestion(mapping, form, request, response, (QUESTION_VERIFY_SYNC+":"+currentScope), <ide> currentScope.equals(AwardTemplateSyncScope.FULL)?KeyConstants.QUESTION_SYNC_FULL:KeyConstants.QUESTION_SYNC_PANEL, <ide> scopeSyncLabel, awardTemplateDescription, getScopeMessageToAddQuestion(currentScope)); <ide> } else { <add> // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. <ide> confirmationQuestion = buildParameterizedConfirmationQuestion(mapping, form, request, response, (QUESTION_VERIFY_SYNC+":"+currentScope), <ide> currentScope.equals(AwardTemplateSyncScope.FULL)?KeyConstants.QUESTION_SYNC_FULL:KeyConstants.QUESTION_SYNC_PANEL, <ide> scopeSyncLabel, awardTemplateDescription, getScopeMessageToAddQuestion(currentScope)); <ide> if( StringUtils.isNotEmpty(currentScope.getDisplayPropertyName())) <ide> scopeSyncLabel = kualiConfiguration.getPropertyValueAsString(currentScope.getDisplayPropertyName()); <ide> <add> // ### Vivantech Fix : #15 / [#80417598] Adding validation for invalid Award Template. <ide> StrutsConfirmation confirmationQuestion = buildParameterizedConfirmationQuestion(mapping, form, request, response, ( <ide> QUESTION_VERIFY_EMPTY_SYNC+":"+currentScope), KeyConstants.QUESTION_SYNC_PANEL_TO_EMPTY, <del> scopeSyncLabel, awardDocument.getAward().getAwardTemplate().getDescription()); <add> scopeSyncLabel, awardTemplateDescription); <ide> awardForm.setCurrentSyncQuestionId((QUESTION_VERIFY_EMPTY_SYNC+":"+currentScope)); <ide> confirmationQuestion.setCaller("processSyncAward"); <ide> return performQuestionWithoutInput(confirmationQuestion, "");
Java
apache-2.0
403703e503ef48762887cf09cecde57afbe67c21
0
cloudeventbus/cloudeventbus
/* * Copyright (c) 2012 Mike Heath. 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 cloudeventbus.server; import cloudeventbus.Subject; import cloudeventbus.codec.AuthenticationRequestFrame; import cloudeventbus.codec.AuthenticationResponseFrame; import cloudeventbus.codec.DecodingException; import cloudeventbus.codec.ErrorFrame; import cloudeventbus.codec.Frame; import cloudeventbus.codec.GreetingFrame; import cloudeventbus.codec.PingFrame; import cloudeventbus.codec.PongFrame; import cloudeventbus.codec.PublishFrame; import cloudeventbus.codec.SendFrame; import cloudeventbus.codec.ServerReadyFrame; import cloudeventbus.codec.SubscribeFrame; import cloudeventbus.codec.UnsubscribeFrame; import cloudeventbus.hub.Hub; import cloudeventbus.hub.SubscriptionHandle; import cloudeventbus.pki.CertificateChain; import cloudeventbus.pki.CertificateUtils; import cloudeventbus.pki.InvalidSignatureException; import cloudeventbus.pki.TrustStore; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundMessageHandlerAdapter; import io.netty.handler.codec.DecoderException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * @author Mike Heath <[email protected]> */ // TODO Send ping frame very 30 seconds. Close socket after 1 minute of inactivity. public class ServerHandler extends ChannelInboundMessageHandlerAdapter<Frame> { private static final Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class); private static final int SUPPORTED_VERSION = 1; private final String agentString; private final Hub<PublishFrame> hub; private final TrustStore trustStore; private byte[] challenge; private boolean serverReady = false; private CertificateChain clientCertificates; private String clientAgent; private NettyHandler handler; private final Map<Subject, SubscriptionHandle> subscriptionHandles = new HashMap<>(); public ServerHandler(String agentString, Hub<PublishFrame> hub, TrustStore trustStore) { this.agentString = agentString; this.hub = hub; this.trustStore = trustStore; } @Override public void messageReceived(ChannelHandlerContext ctx, Frame frame) throws Exception { // TODO Added toString method to frames for debugging purposes. LOGGER.debug("Received frame: {}", frame); if (frame instanceof AuthenticationResponseFrame) { AuthenticationResponseFrame authenticationResponse = (AuthenticationResponseFrame) frame; final CertificateChain certificates = authenticationResponse.getCertificates(); trustStore.validateCertificateChain(certificates); this.clientCertificates = certificates; CertificateUtils.validateSignature( certificates.getLast().getPublicKey(), challenge, authenticationResponse.getSalt(), authenticationResponse.getDigitalSignature()); serverReady = true; ctx.write(ServerReadyFrame.SERVER_READY); } else if (frame instanceof GreetingFrame) { final GreetingFrame greetingFrame = (GreetingFrame) frame; clientAgent = greetingFrame.getAgent(); if (greetingFrame.getVersion() != SUPPORTED_VERSION) { throw new InvalidProtocolVersionException("This server doesn't support protocol version " + greetingFrame.getVersion()); } } else if (frame instanceof AuthenticationRequestFrame) { // TODO Implement support for the client request authentication throw new CloudEventBusServerException("Client to server authentication not yet supported"); } // The server has to be "ready" to process frames below this point. else if (!serverReady) { throw new ServerNotReadyException("This server requires authentication."); } else if (frame instanceof PublishFrame) { final PublishFrame publishFrame = (PublishFrame) frame; hub.publish(publishFrame.getSubject(), publishFrame.getReplySubject(), publishFrame.getBody()); } else if (frame instanceof SendFrame) { final SendFrame sendFrame = (SendFrame) frame; if (!hub.send(sendFrame.getSubject(), sendFrame.getReplySubject(), sendFrame.getBody())) { // If we can't send the message locally, try sending it to a peer server. // TODO Figure out peer servers. throw new UnsupportedOperationException("We need to figure out peer servers and how to do a SEND with them."); } } else if (frame instanceof SubscribeFrame) { final SubscribeFrame subscribeFrame = (SubscribeFrame) frame; final Subject subject = subscribeFrame.getSubject(); if (subscriptionHandles.containsKey(subject)) { throw new DuplicateSubscriptionException("Already subscribed to subject " + subject); } hub.subscribe(subject, handler); } else if (frame instanceof UnsubscribeFrame) { final UnsubscribeFrame unsubscribeFrame = (UnsubscribeFrame) frame; final Subject subject = unsubscribeFrame.getSubject(); final SubscriptionHandle subscriptionHandle = subscriptionHandles.get(subject); if (subscriptionHandle == null) { throw new NotSubscribedException("Not subscribed to subject " + subject); } subscriptionHandle.remove(); } else if (frame instanceof PingFrame) { ctx.write(PongFrame.PONG); } else { throw new CloudEventBusServerException("Unable to handle frame of type " + frame.getClass().getName()); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.write(new GreetingFrame(SUPPORTED_VERSION, agentString)); if (trustStore == null) { serverReady = true; ctx.write(ServerReadyFrame.SERVER_READY); } else { challenge = CertificateUtils.generateChallenge(); ctx.write(new AuthenticationRequestFrame(challenge)); } handler = new NettyHandler(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { // Cleanup subscripts in hub for (SubscriptionHandle handle : subscriptionHandles.values()) { handle.remove(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // TODO Experiment with using a marker to identify the remote agent. LOGGER.error((clientAgent == null ? "" : clientAgent + " ") + cause.getMessage(), cause); if (cause instanceof DecoderException) { cause = cause.getCause(); } //TODO Move error code to CloudEventBus exception final ErrorFrame.Code errorCode; if (cause instanceof DecodingException) { errorCode = ErrorFrame.Code.MALFORMED_REQUEST; } else if (cause instanceof InvalidSignatureException) { errorCode = ErrorFrame.Code.INVALID_SIGNATURE; } else if (cause instanceof ServerNotReadyException) { errorCode = ErrorFrame.Code.SERVER_NOT_READY; } else if (cause instanceof InvalidProtocolVersionException) { errorCode = ErrorFrame.Code.UNSUPPORTED_PROTOCOL_VERSION; } else if (cause instanceof DuplicateSubscriptionException) { errorCode = ErrorFrame.Code.DUPLICATE_SUBSCRIPTION; } else if (cause instanceof NotSubscribedException) { errorCode = ErrorFrame.Code.NOT_SUBSCRIBED; } else { errorCode = ErrorFrame.Code.SERVER_ERROR; } final ErrorFrame errorFrame = new ErrorFrame(errorCode, cause.getMessage()); ctx.write(errorFrame).addListener(ChannelFutureListener.CLOSE); } }
server-core/src/main/java/cloudeventbus/server/ServerHandler.java
/* * Copyright (c) 2012 Mike Heath. 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 cloudeventbus.server; import cloudeventbus.Subject; import cloudeventbus.codec.AuthenticationRequestFrame; import cloudeventbus.codec.AuthenticationResponseFrame; import cloudeventbus.codec.DecodingException; import cloudeventbus.codec.ErrorFrame; import cloudeventbus.codec.Frame; import cloudeventbus.codec.GreetingFrame; import cloudeventbus.codec.PingFrame; import cloudeventbus.codec.PongFrame; import cloudeventbus.codec.PublishFrame; import cloudeventbus.codec.SendFrame; import cloudeventbus.codec.ServerReadyFrame; import cloudeventbus.codec.SubscribeFrame; import cloudeventbus.codec.UnsubscribeFrame; import cloudeventbus.hub.Hub; import cloudeventbus.hub.SubscriptionHandle; import cloudeventbus.pki.CertificateChain; import cloudeventbus.pki.CertificateUtils; import cloudeventbus.pki.InvalidSignatureException; import cloudeventbus.pki.TrustStore; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundMessageHandlerAdapter; import io.netty.handler.codec.DecoderException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * @author Mike Heath <[email protected]> */ // TODO Send ping frame very 30 seconds. Close socket after 1 minute of inactivity. public class ServerHandler extends ChannelInboundMessageHandlerAdapter<Frame> { private static final Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class); private static final int SUPPORTED_VERSION = 1; private final String agentString; private final Hub<PublishFrame> hub; // TODO How to publish to WebSocket hub, etc. private final TrustStore trustStore; private byte[] challenge; private boolean serverReady = false; private CertificateChain clientCertificates; private String clientAgent; private NettyHandler handler; private final Map<Subject, SubscriptionHandle> subscriptionHandles = new HashMap<>(); public ServerHandler(String agentString, Hub<PublishFrame> hub, TrustStore trustStore) { this.agentString = agentString; this.hub = hub; this.trustStore = trustStore; } @Override public void messageReceived(ChannelHandlerContext ctx, Frame frame) throws Exception { // TODO Added toString method to frames for debugging purposes. LOGGER.debug("Received frame: {}", frame); if (frame instanceof AuthenticationResponseFrame) { AuthenticationResponseFrame authenticationResponse = (AuthenticationResponseFrame) frame; final CertificateChain certificates = authenticationResponse.getCertificates(); trustStore.validateCertificateChain(certificates); this.clientCertificates = certificates; CertificateUtils.validateSignature( certificates.getLast().getPublicKey(), challenge, authenticationResponse.getSalt(), authenticationResponse.getDigitalSignature()); serverReady = true; ctx.write(ServerReadyFrame.SERVER_READY); } else if (frame instanceof GreetingFrame) { final GreetingFrame greetingFrame = (GreetingFrame) frame; clientAgent = greetingFrame.getAgent(); if (greetingFrame.getVersion() != SUPPORTED_VERSION) { throw new InvalidProtocolVersionException("This server doesn't support protocol version " + greetingFrame.getVersion()); } } else if (frame instanceof AuthenticationRequestFrame) { // TODO Implement support for the client request authentication throw new CloudEventBusServerException("Client to server authentication not yet supported"); } // The server has to be "ready" to process frames below this point. else if (!serverReady) { throw new ServerNotReadyException("This server requires authentication."); } else if (frame instanceof PublishFrame) { final PublishFrame publishFrame = (PublishFrame) frame; hub.publish(publishFrame.getSubject(), publishFrame.getReplySubject(), publishFrame.getBody()); } else if (frame instanceof SendFrame) { final SendFrame sendFrame = (SendFrame) frame; if (!hub.send(sendFrame.getSubject(), sendFrame.getReplySubject(), sendFrame.getBody())) { // If we can't send the message locally, try sending it to a peer server. // TODO Figure out peer servers. throw new UnsupportedOperationException("We need to figure out peer servers and how to do a SEND with them."); } } else if (frame instanceof SubscribeFrame) { final SubscribeFrame subscribeFrame = (SubscribeFrame) frame; final Subject subject = subscribeFrame.getSubject(); if (subscriptionHandles.containsKey(subject)) { throw new DuplicateSubscriptionException("Already subscribed to subject " + subject); } hub.subscribe(subject, handler); } else if (frame instanceof UnsubscribeFrame) { final UnsubscribeFrame unsubscribeFrame = (UnsubscribeFrame) frame; final Subject subject = unsubscribeFrame.getSubject(); final SubscriptionHandle subscriptionHandle = subscriptionHandles.get(subject); if (subscriptionHandle == null) { throw new NotSubscribedException("Not subscribed to subject " + subject); } subscriptionHandle.remove(); } else if (frame instanceof PingFrame) { ctx.write(PongFrame.PONG); } else { throw new CloudEventBusServerException("Unable to handle frame of type " + frame.getClass().getName()); } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.write(new GreetingFrame(SUPPORTED_VERSION, agentString)); if (trustStore == null) { serverReady = true; ctx.write(ServerReadyFrame.SERVER_READY); } else { challenge = CertificateUtils.generateChallenge(); ctx.write(new AuthenticationRequestFrame(challenge)); } handler = new NettyHandler(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { // Cleanup subscripts in hub for (SubscriptionHandle handle : subscriptionHandles.values()) { handle.remove(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // TODO Experiment with using a marker to identify the remote agent. LOGGER.error((clientAgent == null ? "" : clientAgent + " ") + cause.getMessage(), cause); if (cause instanceof DecoderException) { cause = cause.getCause(); } //TODO Move error code to CloudEventBus exception final ErrorFrame.Code errorCode; if (cause instanceof DecodingException) { errorCode = ErrorFrame.Code.MALFORMED_REQUEST; } else if (cause instanceof InvalidSignatureException) { errorCode = ErrorFrame.Code.INVALID_SIGNATURE; } else if (cause instanceof ServerNotReadyException) { errorCode = ErrorFrame.Code.SERVER_NOT_READY; } else if (cause instanceof InvalidProtocolVersionException) { errorCode = ErrorFrame.Code.UNSUPPORTED_PROTOCOL_VERSION; } else if (cause instanceof DuplicateSubscriptionException) { errorCode = ErrorFrame.Code.DUPLICATE_SUBSCRIPTION; } else if (cause instanceof NotSubscribedException) { errorCode = ErrorFrame.Code.NOT_SUBSCRIBED; } else { errorCode = ErrorFrame.Code.SERVER_ERROR; } final ErrorFrame errorFrame = new ErrorFrame(errorCode, cause.getMessage()); ctx.write(errorFrame).addListener(ChannelFutureListener.CLOSE); } }
Removed TODO item.
server-core/src/main/java/cloudeventbus/server/ServerHandler.java
Removed TODO item.
<ide><path>erver-core/src/main/java/cloudeventbus/server/ServerHandler.java <ide> private static final int SUPPORTED_VERSION = 1; <ide> <ide> private final String agentString; <del> private final Hub<PublishFrame> hub; // TODO How to publish to WebSocket hub, etc. <add> private final Hub<PublishFrame> hub; <ide> private final TrustStore trustStore; <ide> <ide> private byte[] challenge;
Java
lgpl-2.1
fcad4fd980273159c7782a4a1c16a7250d644a01
0
pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform
package org.xwiki.platform; import junit.framework.TestCase; import org.xwiki.platform.patchservice.api.RWOperation; import org.xwiki.platform.patchservice.impl.OperationFactoryImpl; import com.xpn.xwiki.XWikiException; public class CheckAllOperationsImplementedTest extends TestCase { public void testAllOperationsImplemented() throws XWikiException { assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CONTENT_INSERT)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CONTENT_DELETE)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_PROPERTY_SET)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CLASS_PROPERTY_ADD)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CLASS_PROPERTY_CHANGE)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CLASS_PROPERTY_DELETE)); assertNotNull(OperationFactoryImpl.getInstance() .newOperation(RWOperation.TYPE_OBJECT_ADD)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_DELETE)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_PROPERTY_SET)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_PROPERTY_INSERT_AT)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_PROPERTY_DELETE_AT)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_ATTACHMENT_ADD)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_ATTACHMENT_SET)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_ATTACHMENT_DELETE)); } /* Uncomment to get a sample of the XML output.when running tests. */ // public void testXmlOutput() throws Exception // { // Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); // Element root = doc.createElement("patch"); // doc.appendChild(root); // root.appendChild(doc.createTextNode("\n")); // // RWOperation operation = // OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_INSERT); // operation.insert(" as/<>\"'&d ", new PositionImpl(2, 3, " \"'<>befo&amp;re", "after ")); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_DELETE); // operation.delete("Here ", new PositionImpl(0, 0)); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_PROPERTY_SET); // operation.setProperty("prop", "val"); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // BaseClass b = new BaseClass(); // b.addBooleanField("field", "The field", "yesno"); // operation = getOperation((PropertyClass) b.get("field"), true); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = getOperation((PropertyClass) b.get("field"), false); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation( // RWOperation.TYPE_CLASS_PROPERTY_DELETE); // operation.deleteType("XWiki.Class", "prop1"); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_ADD); // operation.addObject("XWiki.Class"); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_DELETE); // operation.deleteObject("XWiki.Class", 2); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_PROPERTY_SET); // operation.setObjectProperty("XWiki.Class", 2, "propertyName", "value"); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation( // RWOperation.TYPE_OBJECT_PROPERTY_INSERT_AT); // operation.insertInProperty("XWiki.Class", 0, "property", "inserted text", // new PositionImpl(2, 0)); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation( // RWOperation.TYPE_OBJECT_PROPERTY_DELETE_AT); // operation.deleteFromProperty("XWiki.Class", 0, "property", "deleted text", // new PositionImpl(2, 0)); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_ADD); // operation.addAttachment(new ByteArrayInputStream("hello".getBytes()), "file", "XWiki.Me"); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_SET); // operation.setAttachment(new ByteArrayInputStream("hello".getBytes()), "file", "XWiki.Me"); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // operation = // OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_DELETE); // operation.deleteAttachment("file"); // root.appendChild(operation.toXml(doc)); // root.appendChild(doc.createTextNode("\n")); // // DOMImplementationLS ls = (DOMImplementationLS) doc.getImplementation(); // System.out.println(ls.createLSSerializer().writeToString(doc)); // } // // private RWOperation getOperation(PropertyClass property, boolean create) // throws XWikiException // { // String type = property.getClass().getCanonicalName(); // Map config = new HashMap(); // for (Iterator it2 = property.getFieldList().iterator(); it2.hasNext();) { // BaseProperty pr = (BaseProperty) it2.next(); // config.put(pr.getName(), pr.getValue()); // } // RWOperation operation = // OperationFactoryImpl.getInstance().newOperation( // create ? RWOperation.TYPE_CLASS_PROPERTY_ADD // : RWOperation.TYPE_CLASS_PROPERTY_CHANGE); // if (create) { // operation.createType("XWiki.Class", property.getName(), type, config); // } else { // operation.modifyType("XWiki.Class", property.getName(), config); // } // return operation; // } }
xwiki-patchservice/src/test/java/org/xwiki/platform/CheckAllOperationsImplementedTest.java
package org.xwiki.platform; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.xml.parsers.DocumentBuilderFactory; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.ls.DOMImplementationLS; import org.xwiki.platform.patchservice.api.RWOperation; import org.xwiki.platform.patchservice.impl.OperationFactoryImpl; import org.xwiki.platform.patchservice.impl.PositionImpl; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.objects.classes.PropertyClass; public class CheckAllOperationsImplementedTest extends TestCase { public void testAllOperationsImplemented() throws XWikiException { assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CONTENT_INSERT)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CONTENT_DELETE)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_PROPERTY_SET)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CLASS_PROPERTY_ADD)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CLASS_PROPERTY_CHANGE)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CLASS_PROPERTY_DELETE)); assertNotNull(OperationFactoryImpl.getInstance() .newOperation(RWOperation.TYPE_OBJECT_ADD)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_DELETE)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_PROPERTY_SET)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_PROPERTY_INSERT_AT)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_PROPERTY_DELETE_AT)); assertNotNull(OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_ATTACHMENT_ADD)); // assertNotNull(OperationFactoryImpl.getInstance().newOperation( // RWOperation.TYPE_ATTACHMENT_SET)); // assertNotNull(OperationFactoryImpl.getInstance().newOperation( // RWOperation.TYPE_ATTACHMENT_DELETE)); } public void testXmlOutput() throws Exception { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = doc.createElement("patch"); doc.appendChild(root); root.appendChild(doc.createTextNode("\n")); RWOperation operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_INSERT); operation.insert(" as/<>\"'&d ", new PositionImpl(2, 3, " \"'<>befo&amp;re", "after ")); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_DELETE); operation.delete("Here ", new PositionImpl(0, 0)); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_PROPERTY_SET); operation.setProperty("prop", "val"); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); BaseClass b = new BaseClass(); b.addBooleanField("field", "The field", "yesno"); operation = getOperation((PropertyClass) b.get("field"), true); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = getOperation((PropertyClass) b.get("field"), false); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_CLASS_PROPERTY_DELETE); operation.deleteType("XWiki.Class", "prop1"); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_ADD); operation.addObject("XWiki.Class"); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_DELETE); operation.deleteObject("XWiki.Class", 2); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_PROPERTY_SET); operation.setObjectProperty("XWiki.Class", 2, "propertyName", "value"); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_PROPERTY_INSERT_AT); operation.insertInProperty("XWiki.Class", 0, "property", "inserted text", new PositionImpl(2, 0)); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = OperationFactoryImpl.getInstance().newOperation( RWOperation.TYPE_OBJECT_PROPERTY_DELETE_AT); operation.deleteFromProperty("XWiki.Class", 0, "property", "deleted text", new PositionImpl(2, 0)); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_ADD); operation.addAttachment(new ByteArrayInputStream("hello".getBytes()), "file", "XWiki.Me"); root.appendChild(operation.toXml(doc)); root.appendChild(doc.createTextNode("\n")); DOMImplementationLS ls = (DOMImplementationLS) doc.getImplementation(); System.out.println(ls.createLSSerializer().writeToString(doc)); } private RWOperation getOperation(PropertyClass property, boolean create) throws XWikiException { String type = property.getClass().getCanonicalName(); Map config = new HashMap(); for (Iterator it2 = property.getFieldList().iterator(); it2.hasNext();) { BaseProperty pr = (BaseProperty) it2.next(); config.put(pr.getName(), pr.getValue()); } RWOperation operation = OperationFactoryImpl.getInstance().newOperation( create ? RWOperation.TYPE_CLASS_PROPERTY_ADD : RWOperation.TYPE_CLASS_PROPERTY_CHANGE); if (create) { operation.createType("XWiki.Class", property.getName(), type, config); } else { operation.modifyType("XWiki.Class", property.getName(), config); } return operation; } }
XWIKI-1977: Create a patchservice data model Tests cleanup. git-svn-id: cfa2b40e478804c47c05d0f328c574ec5aa2b82e@6618 f329d543-caf0-0310-9063-dda96c69346f
xwiki-patchservice/src/test/java/org/xwiki/platform/CheckAllOperationsImplementedTest.java
XWIKI-1977: Create a patchservice data model Tests cleanup.
<ide><path>wiki-patchservice/src/test/java/org/xwiki/platform/CheckAllOperationsImplementedTest.java <ide> package org.xwiki.platform; <del> <del>import java.io.ByteArrayInputStream; <del>import java.util.HashMap; <del>import java.util.Iterator; <del>import java.util.Map; <del> <del>import javax.xml.parsers.DocumentBuilderFactory; <ide> <ide> import junit.framework.TestCase; <ide> <del>import org.w3c.dom.Document; <del>import org.w3c.dom.Element; <del>import org.w3c.dom.ls.DOMImplementationLS; <ide> import org.xwiki.platform.patchservice.api.RWOperation; <ide> import org.xwiki.platform.patchservice.impl.OperationFactoryImpl; <del>import org.xwiki.platform.patchservice.impl.PositionImpl; <ide> <ide> import com.xpn.xwiki.XWikiException; <del>import com.xpn.xwiki.objects.BaseProperty; <del>import com.xpn.xwiki.objects.classes.BaseClass; <del>import com.xpn.xwiki.objects.classes.PropertyClass; <ide> <ide> public class CheckAllOperationsImplementedTest extends TestCase <ide> { <ide> RWOperation.TYPE_OBJECT_PROPERTY_DELETE_AT)); <ide> assertNotNull(OperationFactoryImpl.getInstance().newOperation( <ide> RWOperation.TYPE_ATTACHMENT_ADD)); <del> // assertNotNull(OperationFactoryImpl.getInstance().newOperation( <del> // RWOperation.TYPE_ATTACHMENT_SET)); <del> // assertNotNull(OperationFactoryImpl.getInstance().newOperation( <del> // RWOperation.TYPE_ATTACHMENT_DELETE)); <add> assertNotNull(OperationFactoryImpl.getInstance().newOperation( <add> RWOperation.TYPE_ATTACHMENT_SET)); <add> assertNotNull(OperationFactoryImpl.getInstance().newOperation( <add> RWOperation.TYPE_ATTACHMENT_DELETE)); <ide> } <ide> <del> public void testXmlOutput() throws Exception <del> { <del> Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); <del> Element root = doc.createElement("patch"); <del> doc.appendChild(root); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> RWOperation operation = <del> OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_INSERT); <del> operation.insert(" as/<>\"'&d ", new PositionImpl(2, 3, " \"'<>befo&amp;re", "after ")); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = <del> OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_DELETE); <del> operation.delete("Here ", new PositionImpl(0, 0)); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = <del> OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_PROPERTY_SET); <del> operation.setProperty("prop", "val"); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> BaseClass b = new BaseClass(); <del> b.addBooleanField("field", "The field", "yesno"); <del> operation = getOperation((PropertyClass) b.get("field"), true); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = getOperation((PropertyClass) b.get("field"), false); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = <del> OperationFactoryImpl.getInstance().newOperation( <del> RWOperation.TYPE_CLASS_PROPERTY_DELETE); <del> operation.deleteType("XWiki.Class", "prop1"); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_ADD); <del> operation.addObject("XWiki.Class"); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = <del> OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_DELETE); <del> operation.deleteObject("XWiki.Class", 2); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = <del> OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_PROPERTY_SET); <del> operation.setObjectProperty("XWiki.Class", 2, "propertyName", "value"); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = <del> OperationFactoryImpl.getInstance().newOperation( <del> RWOperation.TYPE_OBJECT_PROPERTY_INSERT_AT); <del> operation.insertInProperty("XWiki.Class", 0, "property", "inserted text", <del> new PositionImpl(2, 0)); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = <del> OperationFactoryImpl.getInstance().newOperation( <del> RWOperation.TYPE_OBJECT_PROPERTY_DELETE_AT); <del> operation.deleteFromProperty("XWiki.Class", 0, "property", "deleted text", <del> new PositionImpl(2, 0)); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> operation = <del> OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_ADD); <del> operation.addAttachment(new ByteArrayInputStream("hello".getBytes()), "file", "XWiki.Me"); <del> root.appendChild(operation.toXml(doc)); <del> root.appendChild(doc.createTextNode("\n")); <del> <del> DOMImplementationLS ls = (DOMImplementationLS) doc.getImplementation(); <del> System.out.println(ls.createLSSerializer().writeToString(doc)); <del> } <del> <del> private RWOperation getOperation(PropertyClass property, boolean create) <del> throws XWikiException <del> { <del> String type = property.getClass().getCanonicalName(); <del> Map config = new HashMap(); <del> for (Iterator it2 = property.getFieldList().iterator(); it2.hasNext();) { <del> BaseProperty pr = (BaseProperty) it2.next(); <del> config.put(pr.getName(), pr.getValue()); <del> } <del> RWOperation operation = <del> OperationFactoryImpl.getInstance().newOperation( <del> create ? RWOperation.TYPE_CLASS_PROPERTY_ADD <del> : RWOperation.TYPE_CLASS_PROPERTY_CHANGE); <del> if (create) { <del> operation.createType("XWiki.Class", property.getName(), type, config); <del> } else { <del> operation.modifyType("XWiki.Class", property.getName(), config); <del> } <del> return operation; <del> } <add> /* Uncomment to get a sample of the XML output.when running tests. */ <add>// public void testXmlOutput() throws Exception <add>// { <add>// Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); <add>// Element root = doc.createElement("patch"); <add>// doc.appendChild(root); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// RWOperation operation = <add>// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_INSERT); <add>// operation.insert(" as/<>\"'&d ", new PositionImpl(2, 3, " \"'<>befo&amp;re", "after ")); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_CONTENT_DELETE); <add>// operation.delete("Here ", new PositionImpl(0, 0)); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_PROPERTY_SET); <add>// operation.setProperty("prop", "val"); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// BaseClass b = new BaseClass(); <add>// b.addBooleanField("field", "The field", "yesno"); <add>// operation = getOperation((PropertyClass) b.get("field"), true); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = getOperation((PropertyClass) b.get("field"), false); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation( <add>// RWOperation.TYPE_CLASS_PROPERTY_DELETE); <add>// operation.deleteType("XWiki.Class", "prop1"); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_ADD); <add>// operation.addObject("XWiki.Class"); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_DELETE); <add>// operation.deleteObject("XWiki.Class", 2); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_OBJECT_PROPERTY_SET); <add>// operation.setObjectProperty("XWiki.Class", 2, "propertyName", "value"); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation( <add>// RWOperation.TYPE_OBJECT_PROPERTY_INSERT_AT); <add>// operation.insertInProperty("XWiki.Class", 0, "property", "inserted text", <add>// new PositionImpl(2, 0)); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation( <add>// RWOperation.TYPE_OBJECT_PROPERTY_DELETE_AT); <add>// operation.deleteFromProperty("XWiki.Class", 0, "property", "deleted text", <add>// new PositionImpl(2, 0)); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_ADD); <add>// operation.addAttachment(new ByteArrayInputStream("hello".getBytes()), "file", "XWiki.Me"); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_SET); <add>// operation.setAttachment(new ByteArrayInputStream("hello".getBytes()), "file", "XWiki.Me"); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// operation = <add>// OperationFactoryImpl.getInstance().newOperation(RWOperation.TYPE_ATTACHMENT_DELETE); <add>// operation.deleteAttachment("file"); <add>// root.appendChild(operation.toXml(doc)); <add>// root.appendChild(doc.createTextNode("\n")); <add>// <add>// DOMImplementationLS ls = (DOMImplementationLS) doc.getImplementation(); <add>// System.out.println(ls.createLSSerializer().writeToString(doc)); <add>// } <add>// <add>// private RWOperation getOperation(PropertyClass property, boolean create) <add>// throws XWikiException <add>// { <add>// String type = property.getClass().getCanonicalName(); <add>// Map config = new HashMap(); <add>// for (Iterator it2 = property.getFieldList().iterator(); it2.hasNext();) { <add>// BaseProperty pr = (BaseProperty) it2.next(); <add>// config.put(pr.getName(), pr.getValue()); <add>// } <add>// RWOperation operation = <add>// OperationFactoryImpl.getInstance().newOperation( <add>// create ? RWOperation.TYPE_CLASS_PROPERTY_ADD <add>// : RWOperation.TYPE_CLASS_PROPERTY_CHANGE); <add>// if (create) { <add>// operation.createType("XWiki.Class", property.getName(), type, config); <add>// } else { <add>// operation.modifyType("XWiki.Class", property.getName(), config); <add>// } <add>// return operation; <add>// } <ide> }
Java
apache-2.0
d2b2ff6960e3b82d31c4f6b65a4f72ed65a9c355
0
davidmoten/pulley
package pulley.streams; import static pulley.Stream.stream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import pulley.A0; import pulley.Cons; import pulley.Factory; import pulley.Promise; import pulley.Promises; import pulley.Scheduler; import pulley.Schedulers; import pulley.Stream; import pulley.Util; import pulley.util.Optional; public class Merge { public static <T> Stream<T> create(final List<Stream<T>> list) { return stream(factory(list)); } public static <T> Stream<T> create(final Stream<Stream<T>> streams) { return Util.notImplemented(); } private static <T> Factory<Promise<Optional<Cons<T>>>> factory(final List<Stream<T>> streams) { return new Factory<Promise<Optional<Cons<T>>>>() { @Override public Promise<Optional<Cons<T>>> create() { List<Promise<Optional<Cons<T>>>> promises = new ArrayList<Promise<Optional<Cons<T>>>>( streams.size()); for (Stream<T> stream : streams) { promises.add(stream.factory().create()); } return new MergePromise<T>(promises); } }; } private static class MergePromise<T> implements Promise<Optional<Cons<T>>> { private final List<Promise<Optional<Cons<T>>>> promises; MergePromise(List<Promise<Optional<Cons<T>>>> promises) { this.promises = promises; } @Override public Optional<Cons<T>> get() { // blocking !!!! final List<Promise<Optional<Cons<T>>>> promises2 = new ArrayList<Promise<Optional<Cons<T>>>>( promises); final AtomicBoolean found = new AtomicBoolean(false); final AtomicReference<Optional<Cons<T>>> value = new AtomicReference<Optional<Cons<T>>>(); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger countTerminated = new AtomicInteger(0); for (int i = 0; i < promises.size(); i++) { final int index = i; Promise<Optional<Cons<T>>> p = promises.get(index); p.scheduler().schedule(new A0() { @Override public void call() { if (!found.get()) { promises2.set(index, Promises.cache(promises2.get(index))); Optional<Cons<T>> t = promises2.get(index).get(); if (t.isPresent() && found.compareAndSet(false, true)) { value.set(t); promises2.set(index, t.get().tail()); latch.countDown(); } else if (!t.isPresent()) { promises2.set(index, null); if (countTerminated.incrementAndGet() == promises.size()) { latch.countDown(); } } } } }); } try { latch.await(); if (countTerminated.get() == promises.size()) return Optional.absent(); else return Optional.of(Cons.cons(value.get().get().head(), new MergePromise<T>( removeNulls(promises2)))); } catch (InterruptedException e) { throw new RuntimeException(e); } } private static <T> List<T> removeNulls(List<T> list) { List<T> list2 = new ArrayList<T>(); for (T t : list) if (t != null) list2.add(t); return list2; } @Override public A0 closeAction() { return new A0() { @Override public void call() { for (Promise<Optional<Cons<T>>> promise : promises) promise.closeAction().call(); } }; } @Override public Scheduler scheduler() { return Schedulers.immediate(); } } }
src/main/java/pulley/streams/Merge.java
package pulley.streams; import static pulley.Stream.stream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import pulley.A0; import pulley.Cons; import pulley.Factory; import pulley.Promise; import pulley.Promises; import pulley.Scheduler; import pulley.Schedulers; import pulley.Stream; import pulley.Util; import pulley.util.Optional; public class Merge { public static <T> Stream<T> create(final List<Stream<T>> list) { return stream(factory(list)); } public static <T> Stream<T> create(final Stream<Stream<T>> streams) { return Util.notImplemented(); } private static <T> Factory<Promise<Optional<Cons<T>>>> factory(final List<Stream<T>> streams) { return new Factory<Promise<Optional<Cons<T>>>>() { @Override public Promise<Optional<Cons<T>>> create() { List<Promise<Optional<Cons<T>>>> promises = new ArrayList<Promise<Optional<Cons<T>>>>( streams.size()); for (Stream<T> stream : streams) { promises.add(stream.factory().create()); } return new MergePromise<T>(promises); } }; } private static class MergePromise<T> implements Promise<Optional<Cons<T>>> { private final List<Promise<Optional<Cons<T>>>> promises; MergePromise(List<Promise<Optional<Cons<T>>>> promises) { this.promises = promises; } @Override public Optional<Cons<T>> get() { // blocking !!!! final List<Promise<Optional<Cons<T>>>> promises2 = new ArrayList<Promise<Optional<Cons<T>>>>( promises); final AtomicBoolean found = new AtomicBoolean(false); final AtomicReference<Optional<Cons<T>>> value = new AtomicReference<Optional<Cons<T>>>(); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger countTerminated = new AtomicInteger(0); for (int i = 0; i < promises.size(); i++) { final int index = i; promises.get(index).scheduler().schedule(new A0() { @Override public void call() { if (!found.get()) { promises2.set(index, Promises.cache(promises2.get(index))); Optional<Cons<T>> t = promises2.get(index).get(); if (t.isPresent() && found.compareAndSet(false, true)) { value.set(t); promises2.set(index, t.get().tail()); latch.countDown(); } else if (!t.isPresent()) { if (countTerminated.incrementAndGet() == promises.size()) { latch.countDown(); } } } } }); } try { latch.await(); if (countTerminated.get() == promises.size()) return Optional.absent(); else return Optional.of(Cons.cons(value.get().get().head(), new MergePromise<T>( promises2))); } catch (InterruptedException e) { throw new RuntimeException(e); } } @Override public A0 closeAction() { return new A0() { @Override public void call() { for (Promise<Optional<Cons<T>>> promise : promises) promise.closeAction().call(); } }; } @Override public Scheduler scheduler() { return Schedulers.immediate(); } } }
remove merged streams as they complete
src/main/java/pulley/streams/Merge.java
remove merged streams as they complete
<ide><path>rc/main/java/pulley/streams/Merge.java <ide> <ide> for (int i = 0; i < promises.size(); i++) { <ide> final int index = i; <del> promises.get(index).scheduler().schedule(new A0() { <add> Promise<Optional<Cons<T>>> p = promises.get(index); <add> p.scheduler().schedule(new A0() { <ide> @Override <ide> public void call() { <ide> if (!found.get()) { <ide> promises2.set(index, t.get().tail()); <ide> latch.countDown(); <ide> } else if (!t.isPresent()) { <add> promises2.set(index, null); <ide> if (countTerminated.incrementAndGet() == promises.size()) { <ide> latch.countDown(); <ide> } <ide> return Optional.absent(); <ide> else <ide> return Optional.of(Cons.cons(value.get().get().head(), new MergePromise<T>( <del> promises2))); <add> removeNulls(promises2)))); <ide> } catch (InterruptedException e) { <ide> throw new RuntimeException(e); <ide> } <add> } <add> <add> private static <T> List<T> removeNulls(List<T> list) { <add> List<T> list2 = new ArrayList<T>(); <add> for (T t : list) <add> if (t != null) <add> list2.add(t); <add> return list2; <ide> } <ide> <ide> @Override
Java
apache-2.0
a0f4be4cbcfbeb9a7facc6b03c4c5d5414c2d10c
0
oalles/camel,lburgazzoli/camel,tdiesler/camel,josefkarasek/camel,veithen/camel,curso007/camel,woj-i/camel,trohovsky/camel,skinzer/camel,onders86/camel,nicolaferraro/camel,sebi-hgdata/camel,aaronwalker/camel,iweiss/camel,sebi-hgdata/camel,driseley/camel,josefkarasek/camel,royopa/camel,tlehoux/camel,YoshikiHigo/camel,grange74/camel,hqstevenson/camel,bgaudaen/camel,lburgazzoli/apache-camel,dvankleef/camel,NetNow/camel,driseley/camel,allancth/camel,NetNow/camel,CodeSmell/camel,joakibj/camel,jkorab/camel,lowwool/camel,anoordover/camel,bfitzpat/camel,chirino/camel,satishgummadelli/camel,rparree/camel,akhettar/camel,royopa/camel,stravag/camel,prashant2402/camel,MrCoder/camel,pkletsko/camel,bgaudaen/camel,atoulme/camel,davidkarlsen/camel,driseley/camel,jlpedrosa/camel,sverkera/camel,Thopap/camel,pkletsko/camel,grgrzybek/camel,pax95/camel,mike-kukla/camel,ge0ffrey/camel,jlpedrosa/camel,arnaud-deprez/camel,jamesnetherton/camel,yury-vashchyla/camel,mcollovati/camel,apache/camel,RohanHart/camel,isavin/camel,kevinearls/camel,askannon/camel,edigrid/camel,haku/camel,gilfernandes/camel,koscejev/camel,dkhanolkar/camel,ekprayas/camel,neoramon/camel,yury-vashchyla/camel,oalles/camel,mnki/camel,curso007/camel,CodeSmell/camel,acartapanis/camel,dmvolod/camel,tarilabs/camel,snurmine/camel,borcsokj/camel,tlehoux/camel,jkorab/camel,FingolfinTEK/camel,partis/camel,davidwilliams1978/camel,dpocock/camel,satishgummadelli/camel,gilfernandes/camel,DariusX/camel,w4tson/camel,mnki/camel,skinzer/camel,aaronwalker/camel,jameszkw/camel,davidwilliams1978/camel,dsimansk/camel,stalet/camel,mohanaraosv/camel,ssharma/camel,prashant2402/camel,pplatek/camel,bfitzpat/camel,jarst/camel,MrCoder/camel,mzapletal/camel,davidwilliams1978/camel,chanakaudaya/camel,tadayosi/camel,tarilabs/camel,noelo/camel,neoramon/camel,sabre1041/camel,jamesnetherton/camel,isavin/camel,eformat/camel,drsquidop/camel,ssharma/camel,bdecoste/camel,dpocock/camel,atoulme/camel,tarilabs/camel,YoshikiHigo/camel,borcsokj/camel,mike-kukla/camel,bfitzpat/camel,anoordover/camel,grgrzybek/camel,nicolaferraro/camel,jamesnetherton/camel,kevinearls/camel,yuruki/camel,bdecoste/camel,hqstevenson/camel,isururanawaka/camel,logzio/camel,tdiesler/camel,mgyongyosi/camel,tdiesler/camel,allancth/camel,scranton/camel,onders86/camel,oscerd/camel,aaronwalker/camel,ullgren/camel,logzio/camel,gilfernandes/camel,MohammedHammam/camel,maschmid/camel,mike-kukla/camel,partis/camel,snadakuduru/camel,MohammedHammam/camel,ge0ffrey/camel,manuelh9r/camel,brreitme/camel,brreitme/camel,stalet/camel,lburgazzoli/apache-camel,jameszkw/camel,igarashitm/camel,ssharma/camel,ramonmaruko/camel,tlehoux/camel,nboukhed/camel,ramonmaruko/camel,tlehoux/camel,lburgazzoli/camel,NickCis/camel,atoulme/camel,jamesnetherton/camel,dvankleef/camel,logzio/camel,jpav/camel,YMartsynkevych/camel,noelo/camel,sebi-hgdata/camel,ullgren/camel,davidkarlsen/camel,kevinearls/camel,dvankleef/camel,igarashitm/camel,akhettar/camel,borcsokj/camel,bfitzpat/camel,neoramon/camel,apache/camel,apache/camel,hqstevenson/camel,jonmcewen/camel,davidwilliams1978/camel,bdecoste/camel,zregvart/camel,mohanaraosv/camel,bdecoste/camel,objectiser/camel,neoramon/camel,adessaigne/camel,pmoerenhout/camel,lburgazzoli/camel,punkhorn/camel-upstream,lasombra/camel,aaronwalker/camel,engagepoint/camel,yuruki/camel,noelo/camel,sebi-hgdata/camel,logzio/camel,isururanawaka/camel,CodeSmell/camel,isavin/camel,mohanaraosv/camel,yogamaha/camel,gyc567/camel,eformat/camel,grgrzybek/camel,Fabryprog/camel,borcsokj/camel,YMartsynkevych/camel,qst-jdc-labs/camel,christophd/camel,tkopczynski/camel,anton-k11/camel,woj-i/camel,haku/camel,jlpedrosa/camel,yogamaha/camel,arnaud-deprez/camel,tdiesler/camel,jarst/camel,sabre1041/camel,davidkarlsen/camel,salikjan/camel,ullgren/camel,sebi-hgdata/camel,ramonmaruko/camel,jonmcewen/camel,tdiesler/camel,allancth/camel,grange74/camel,YMartsynkevych/camel,lburgazzoli/apache-camel,jpav/camel,prashant2402/camel,prashant2402/camel,dkhanolkar/camel,noelo/camel,maschmid/camel,joakibj/camel,Thopap/camel,bhaveshdt/camel,chanakaudaya/camel,rparree/camel,ekprayas/camel,tadayosi/camel,MrCoder/camel,objectiser/camel,pmoerenhout/camel,joakibj/camel,FingolfinTEK/camel,atoulme/camel,tadayosi/camel,bdecoste/camel,anoordover/camel,nikvaessen/camel,pkletsko/camel,chirino/camel,logzio/camel,maschmid/camel,duro1/camel,dmvolod/camel,YoshikiHigo/camel,ramonmaruko/camel,jlpedrosa/camel,CandleCandle/camel,jonmcewen/camel,jmandawg/camel,gnodet/camel,jarst/camel,ge0ffrey/camel,acartapanis/camel,pplatek/camel,isururanawaka/camel,igarashitm/camel,jpav/camel,RohanHart/camel,NickCis/camel,kevinearls/camel,jonmcewen/camel,engagepoint/camel,engagepoint/camel,tlehoux/camel,nboukhed/camel,pmoerenhout/camel,jollygeorge/camel,mgyongyosi/camel,josefkarasek/camel,yuruki/camel,ssharma/camel,alvinkwekel/camel,YMartsynkevych/camel,iweiss/camel,JYBESSON/camel,gyc567/camel,NetNow/camel,curso007/camel,trohovsky/camel,DariusX/camel,oscerd/camel,snurmine/camel,tdiesler/camel,snurmine/camel,objectiser/camel,duro1/camel,Thopap/camel,maschmid/camel,NickCis/camel,NetNow/camel,qst-jdc-labs/camel,rmarting/camel,Fabryprog/camel,sirlatrom/camel,pkletsko/camel,dkhanolkar/camel,johnpoth/camel,jlpedrosa/camel,jarst/camel,pax95/camel,gautric/camel,edigrid/camel,ullgren/camel,engagepoint/camel,yury-vashchyla/camel,iweiss/camel,duro1/camel,erwelch/camel,brreitme/camel,chirino/camel,woj-i/camel,haku/camel,acartapanis/camel,jollygeorge/camel,pax95/camel,acartapanis/camel,coderczp/camel,lburgazzoli/apache-camel,maschmid/camel,isavin/camel,ekprayas/camel,qst-jdc-labs/camel,jkorab/camel,christophd/camel,adessaigne/camel,yogamaha/camel,stalet/camel,anton-k11/camel,oalles/camel,anoordover/camel,FingolfinTEK/camel,dsimansk/camel,isavin/camel,skinzer/camel,JYBESSON/camel,DariusX/camel,gnodet/camel,pplatek/camel,coderczp/camel,acartapanis/camel,stravag/camel,tadayosi/camel,CandleCandle/camel,zregvart/camel,mzapletal/camel,bfitzpat/camel,johnpoth/camel,bgaudaen/camel,MrCoder/camel,onders86/camel,ssharma/camel,dmvolod/camel,curso007/camel,aaronwalker/camel,scranton/camel,snurmine/camel,snadakuduru/camel,anton-k11/camel,YoshikiHigo/camel,akhettar/camel,FingolfinTEK/camel,jmandawg/camel,drsquidop/camel,woj-i/camel,veithen/camel,gyc567/camel,ge0ffrey/camel,gyc567/camel,arnaud-deprez/camel,drsquidop/camel,nboukhed/camel,driseley/camel,partis/camel,royopa/camel,chanakaudaya/camel,yuruki/camel,snadakuduru/camel,scranton/camel,ssharma/camel,coderczp/camel,borcsokj/camel,cunningt/camel,FingolfinTEK/camel,nikvaessen/camel,sirlatrom/camel,arnaud-deprez/camel,cunningt/camel,lasombra/camel,CandleCandle/camel,anton-k11/camel,nboukhed/camel,CodeSmell/camel,lowwool/camel,satishgummadelli/camel,igarashitm/camel,isururanawaka/camel,RohanHart/camel,mnki/camel,koscejev/camel,skinzer/camel,cunningt/camel,duro1/camel,coderczp/camel,scranton/camel,gnodet/camel,JYBESSON/camel,noelo/camel,akhettar/camel,oalles/camel,objectiser/camel,josefkarasek/camel,jameszkw/camel,veithen/camel,dpocock/camel,stalet/camel,sverkera/camel,haku/camel,mcollovati/camel,sverkera/camel,mgyongyosi/camel,satishgummadelli/camel,prashant2402/camel,josefkarasek/camel,adessaigne/camel,gnodet/camel,isavin/camel,askannon/camel,mgyongyosi/camel,ekprayas/camel,koscejev/camel,NickCis/camel,cunningt/camel,bgaudaen/camel,pplatek/camel,jpav/camel,johnpoth/camel,jpav/camel,brreitme/camel,bgaudaen/camel,anton-k11/camel,chirino/camel,johnpoth/camel,jkorab/camel,MrCoder/camel,mnki/camel,tarilabs/camel,joakibj/camel,w4tson/camel,rparree/camel,allancth/camel,logzio/camel,apache/camel,MrCoder/camel,MohammedHammam/camel,jollygeorge/camel,tkopczynski/camel,akhettar/camel,JYBESSON/camel,koscejev/camel,snadakuduru/camel,chanakaudaya/camel,allancth/camel,pax95/camel,qst-jdc-labs/camel,coderczp/camel,dpocock/camel,stravag/camel,jpav/camel,askannon/camel,w4tson/camel,eformat/camel,drsquidop/camel,royopa/camel,hqstevenson/camel,grgrzybek/camel,pmoerenhout/camel,adessaigne/camel,dvankleef/camel,chirino/camel,dmvolod/camel,oalles/camel,akhettar/camel,noelo/camel,brreitme/camel,jarst/camel,haku/camel,askannon/camel,acartapanis/camel,jollygeorge/camel,sabre1041/camel,tarilabs/camel,mnki/camel,edigrid/camel,lburgazzoli/apache-camel,qst-jdc-labs/camel,hqstevenson/camel,askannon/camel,engagepoint/camel,eformat/camel,brreitme/camel,satishgummadelli/camel,nicolaferraro/camel,grange74/camel,dkhanolkar/camel,jlpedrosa/camel,jamesnetherton/camel,pplatek/camel,lowwool/camel,tkopczynski/camel,jollygeorge/camel,logzio/camel,stalet/camel,punkhorn/camel-upstream,ge0ffrey/camel,yogamaha/camel,w4tson/camel,FingolfinTEK/camel,DariusX/camel,apache/camel,kevinearls/camel,mgyongyosi/camel,nikvaessen/camel,CandleCandle/camel,iweiss/camel,lburgazzoli/camel,lburgazzoli/apache-camel,RohanHart/camel,NetNow/camel,edigrid/camel,scranton/camel,jollygeorge/camel,davidkarlsen/camel,gautric/camel,Thopap/camel,mike-kukla/camel,arnaud-deprez/camel,sirlatrom/camel,eformat/camel,lowwool/camel,oscerd/camel,tadayosi/camel,MohammedHammam/camel,curso007/camel,joakibj/camel,oscerd/camel,erwelch/camel,stravag/camel,jmandawg/camel,neoramon/camel,mzapletal/camel,koscejev/camel,erwelch/camel,anoordover/camel,sabre1041/camel,bdecoste/camel,rparree/camel,alvinkwekel/camel,yury-vashchyla/camel,grgrzybek/camel,mohanaraosv/camel,pmoerenhout/camel,rmarting/camel,manuelh9r/camel,zregvart/camel,tkopczynski/camel,pplatek/camel,yuruki/camel,pax95/camel,jarst/camel,mzapletal/camel,NickCis/camel,rmarting/camel,scranton/camel,gilfernandes/camel,edigrid/camel,bhaveshdt/camel,atoulme/camel,oscerd/camel,ramonmaruko/camel,jkorab/camel,manuelh9r/camel,christophd/camel,dpocock/camel,johnpoth/camel,duro1/camel,tkopczynski/camel,lowwool/camel,rparree/camel,YMartsynkevych/camel,punkhorn/camel-upstream,cunningt/camel,yogamaha/camel,jmandawg/camel,lburgazzoli/camel,sverkera/camel,cunningt/camel,gautric/camel,chanakaudaya/camel,NetNow/camel,ekprayas/camel,punkhorn/camel-upstream,veithen/camel,bfitzpat/camel,ge0ffrey/camel,royopa/camel,YMartsynkevych/camel,gilfernandes/camel,rparree/camel,yogamaha/camel,lburgazzoli/camel,edigrid/camel,bhaveshdt/camel,onders86/camel,christophd/camel,lasombra/camel,NickCis/camel,erwelch/camel,tlehoux/camel,partis/camel,askannon/camel,jonmcewen/camel,dvankleef/camel,drsquidop/camel,josefkarasek/camel,mzapletal/camel,veithen/camel,sverkera/camel,royopa/camel,Thopap/camel,anton-k11/camel,jmandawg/camel,snadakuduru/camel,jamesnetherton/camel,dmvolod/camel,adessaigne/camel,sirlatrom/camel,gilfernandes/camel,dpocock/camel,sabre1041/camel,chirino/camel,yury-vashchyla/camel,jmandawg/camel,lasombra/camel,gyc567/camel,MohammedHammam/camel,YoshikiHigo/camel,nikhilvibhav/camel,oalles/camel,partis/camel,isururanawaka/camel,CandleCandle/camel,woj-i/camel,johnpoth/camel,gnodet/camel,Fabryprog/camel,igarashitm/camel,Fabryprog/camel,dmvolod/camel,pplatek/camel,pkletsko/camel,lasombra/camel,rmarting/camel,duro1/camel,sirlatrom/camel,RohanHart/camel,bhaveshdt/camel,mohanaraosv/camel,adessaigne/camel,dvankleef/camel,dsimansk/camel,yuruki/camel,dkhanolkar/camel,dsimansk/camel,JYBESSON/camel,snurmine/camel,ramonmaruko/camel,onders86/camel,oscerd/camel,erwelch/camel,chanakaudaya/camel,w4tson/camel,skinzer/camel,sebi-hgdata/camel,neoramon/camel,YoshikiHigo/camel,dsimansk/camel,bhaveshdt/camel,nikvaessen/camel,tarilabs/camel,zregvart/camel,isururanawaka/camel,coderczp/camel,anoordover/camel,iweiss/camel,manuelh9r/camel,jameszkw/camel,MohammedHammam/camel,iweiss/camel,manuelh9r/camel,gautric/camel,driseley/camel,snurmine/camel,lasombra/camel,jameszkw/camel,sverkera/camel,erwelch/camel,lowwool/camel,grange74/camel,atoulme/camel,stravag/camel,mgyongyosi/camel,arnaud-deprez/camel,pax95/camel,Thopap/camel,drsquidop/camel,sirlatrom/camel,nikhilvibhav/camel,trohovsky/camel,grange74/camel,veithen/camel,nboukhed/camel,nikvaessen/camel,borcsokj/camel,nboukhed/camel,joakibj/camel,hqstevenson/camel,salikjan/camel,kevinearls/camel,tadayosi/camel,davidwilliams1978/camel,yury-vashchyla/camel,jonmcewen/camel,christophd/camel,maschmid/camel,pkletsko/camel,grgrzybek/camel,mnki/camel,jkorab/camel,partis/camel,mcollovati/camel,bhaveshdt/camel,igarashitm/camel,mohanaraosv/camel,nikhilvibhav/camel,alvinkwekel/camel,driseley/camel,onders86/camel,dkhanolkar/camel,bgaudaen/camel,mcollovati/camel,nicolaferraro/camel,w4tson/camel,jameszkw/camel,nikhilvibhav/camel,trohovsky/camel,sabre1041/camel,mike-kukla/camel,trohovsky/camel,CandleCandle/camel,ekprayas/camel,tkopczynski/camel,gautric/camel,satishgummadelli/camel,koscejev/camel,trohovsky/camel,stravag/camel,prashant2402/camel,rmarting/camel,woj-i/camel,davidwilliams1978/camel,nikvaessen/camel,allancth/camel,christophd/camel,rmarting/camel,manuelh9r/camel,curso007/camel,gautric/camel,pmoerenhout/camel,mike-kukla/camel,eformat/camel,snadakuduru/camel,dsimansk/camel,alvinkwekel/camel,aaronwalker/camel,qst-jdc-labs/camel,grange74/camel,RohanHart/camel,JYBESSON/camel,stalet/camel,gyc567/camel,haku/camel,mzapletal/camel,apache/camel,skinzer/camel
/** * 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.camel.component.jms; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import org.apache.camel.AsyncCallback; import org.apache.camel.Exchange; import org.apache.camel.FailedToCreateProducerException; import org.apache.camel.RuntimeExchangeException; import org.apache.camel.component.jms.JmsConfiguration.CamelJmsTemplate; import org.apache.camel.component.jms.reply.ReplyManager; import org.apache.camel.component.jms.reply.UseMessageIdAsCorrelationIdMessageSentCallback; import org.apache.camel.impl.DefaultAsyncProducer; import org.apache.camel.spi.UuidGenerator; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ValueHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.jms.core.JmsOperations; import org.springframework.jms.core.MessageCreator; /** * @version $Revision$ */ public class JmsProducer extends DefaultAsyncProducer { private static final transient Log LOG = LogFactory.getLog(JmsProducer.class); private final JmsEndpoint endpoint; private final AtomicBoolean started = new AtomicBoolean(false); private JmsOperations inOnlyTemplate; private JmsOperations inOutTemplate; private UuidGenerator uuidGenerator; private ReplyManager replyManager; public JmsProducer(JmsEndpoint endpoint) { super(endpoint); this.endpoint = endpoint; } protected void initReplyManager() { if (!started.get()) { synchronized (this) { if (started.get()) { return; } try { if (endpoint.getReplyTo() != null) { replyManager = endpoint.getReplyManager(endpoint.getReplyTo()); if (LOG.isInfoEnabled()) { LOG.info("Using JmsReplyManager: " + replyManager + " to process replies from: " + endpoint.getReplyTo() + " queue with " + endpoint.getConcurrentConsumers() + " concurrent consumers."); } } else { replyManager = endpoint.getReplyManager(); if (LOG.isInfoEnabled()) { LOG.info("Using JmsReplyManager: " + replyManager + " to process replies from temporary queue with " + endpoint.getConcurrentConsumers() + " concurrent consumers."); } } } catch (Exception e) { throw new FailedToCreateProducerException(endpoint, e); } started.set(true); } } } public boolean process(Exchange exchange, AsyncCallback callback) { // deny processing if we are not started if (!isRunAllowed()) { if (exchange.getException() == null) { exchange.setException(new RejectedExecutionException()); } // we cannot process so invoke callback callback.done(true); return true; } if (!endpoint.isDisableReplyTo() && exchange.getPattern().isOutCapable()) { // in out requires a bit more work than in only return processInOut(exchange, callback); } else { // in only return processInOnly(exchange, callback); } } protected boolean processInOut(final Exchange exchange, final AsyncCallback callback) { final org.apache.camel.Message in = exchange.getIn(); String destinationName = in.getHeader(JmsConstants.JMS_DESTINATION_NAME, String.class); // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION_NAME); if (destinationName == null) { destinationName = endpoint.getDestinationName(); } Destination destination = in.getHeader(JmsConstants.JMS_DESTINATION, Destination.class); // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION); if (destination == null) { destination = endpoint.getDestination(); } if (destination != null) { // prefer to use destination over destination name destinationName = null; } initReplyManager(); // note due to JMS transaction semantics we cannot use a single transaction // for sending the request and receiving the response final Destination replyTo = replyManager.getReplyTo(); if (replyTo == null) { throw new RuntimeExchangeException("Failed to resolve replyTo destination", exchange); } // when using message id as correlation id, we need at first to use a provisional correlation id // which we then update to the real JMSMessageID when the message has been sent // this is done with the help of the MessageSentCallback final boolean msgIdAsCorrId = endpoint.getConfiguration().isUseMessageIDAsCorrelationID(); final String provisionalCorrelationId = msgIdAsCorrId ? getUuidGenerator().generateUuid() : null; MessageSentCallback messageSentCallback = null; if (msgIdAsCorrId) { messageSentCallback = new UseMessageIdAsCorrelationIdMessageSentCallback(replyManager, provisionalCorrelationId, endpoint.getRequestTimeout()); } final ValueHolder<MessageSentCallback> sentCallback = new ValueHolder<MessageSentCallback>(messageSentCallback); final String originalCorrelationId = in.getHeader("JMSCorrelationID", String.class); if (originalCorrelationId == null && !msgIdAsCorrId) { in.setHeader("JMSCorrelationID", getUuidGenerator().generateUuid()); } MessageCreator messageCreator = new MessageCreator() { public Message createMessage(Session session) throws JMSException { Message message = endpoint.getBinding().makeJmsMessage(exchange, in, session, null); message.setJMSReplyTo(replyTo); replyManager.setReplyToSelectorHeader(in, message); String correlationId = determineCorrelationId(message, provisionalCorrelationId); replyManager.registerReply(replyManager, exchange, callback, originalCorrelationId, correlationId, endpoint.getRequestTimeout()); return message; } }; doSend(true, destinationName, destination, messageCreator, sentCallback.get()); // after sending then set the OUT message id to the JMSMessageID so its identical setMessageId(exchange); // continue routing asynchronously (reply will be processed async when its received) return false; } /** * Strategy to determine which correlation id to use among <tt>JMSMessageID</tt> and <tt>JMSCorrelationID</tt>. * * @param message the JMS message * @param provisionalCorrelationId an optional provisional correlation id, which is preferred to be used * @return the correlation id to use * @throws JMSException can be thrown */ protected String determineCorrelationId(Message message, String provisionalCorrelationId) throws JMSException { if (provisionalCorrelationId != null) { return provisionalCorrelationId; } final String messageId = message.getJMSMessageID(); final String correlationId = message.getJMSCorrelationID(); if (endpoint.getConfiguration().isUseMessageIDAsCorrelationID()) { return messageId; } else if (ObjectHelper.isEmpty(correlationId)) { // correlation id is empty so fallback to message id return messageId; } else { return correlationId; } } protected boolean processInOnly(final Exchange exchange, final AsyncCallback callback) { final org.apache.camel.Message in = exchange.getIn(); String destinationName = in.getHeader(JmsConstants.JMS_DESTINATION_NAME, String.class); if (destinationName != null) { // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION_NAME); } if (destinationName == null) { destinationName = endpoint.getDestinationName(); } Destination destination = in.getHeader(JmsConstants.JMS_DESTINATION, Destination.class); if (destination != null) { // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION); } if (destination == null) { destination = endpoint.getDestination(); } if (destination != null) { // prefer to use destination over destination name destinationName = null; } // we must honor these special flags to preserve QoS if (!endpoint.isPreserveMessageQos() && !endpoint.isExplicitQosEnabled()) { Object replyTo = exchange.getIn().getHeader("JMSReplyTo"); if (replyTo != null) { // we are routing an existing JmsMessage, origin from another JMS endpoint // then we need to remove the existing JMSReplyTo // as we are not out capable and thus do not expect a reply, and therefore // the consumer of this message we send should not return a reply String to = destinationName != null ? destinationName : "" + destination; LOG.warn("Disabling JMSReplyTo as this Exchange is not OUT capable with JMSReplyTo: " + replyTo + " for destination: " + to + ". Use preserveMessageQos=true to force Camel to keep the JMSReplyTo." + " Exchange: " + exchange); exchange.getIn().setHeader("JMSReplyTo", null); } } MessageCreator messageCreator = new MessageCreator() { public Message createMessage(Session session) throws JMSException { Message answer = endpoint.getBinding().makeJmsMessage(exchange, in, session, null); // if the binding did not create the reply to then we have to try to create it here String replyTo = exchange.getIn().getHeader("JMSReplyTo", String.class); if (replyTo != null && answer.getJMSReplyTo() == null) { Destination destination = null; // try using destination resolver to lookup the destination if (endpoint.getDestinationResolver() != null) { destination = endpoint.getDestinationResolver().resolveDestinationName(session, replyTo, endpoint.isPubSubDomain()); } if (destination == null) { // okay then fallback and create the queue if (endpoint.isPubSubDomain()) { if (LOG.isDebugEnabled()) { LOG.debug("Creating JMSReplyTo topic: " + replyTo); } destination = session.createTopic(replyTo); } else { if (LOG.isDebugEnabled()) { LOG.debug("Creating JMSReplyTo queue: " + replyTo); } destination = session.createQueue(replyTo); } } if (destination != null) { if (LOG.isDebugEnabled()) { LOG.debug("Using JMSReplyTo destination: " + destination); } answer.setJMSReplyTo(destination); } } return answer; } }; doSend(false, destinationName, destination, messageCreator, null); // after sending then set the OUT message id to the JMSMessageID so its identical setMessageId(exchange); // we are synchronous so return true callback.done(true); return true; } /** * Sends the message using the JmsTemplate. * * @param inOut use inOut or inOnly template * @param destinationName the destination name * @param destination the destination (if no name provided) * @param messageCreator the creator to create the {@link Message} to send * @param callback optional callback for inOut messages */ protected void doSend(boolean inOut, String destinationName, Destination destination, MessageCreator messageCreator, MessageSentCallback callback) { CamelJmsTemplate template = (CamelJmsTemplate) (inOut ? getInOutTemplate() : getInOnlyTemplate()); if (LOG.isTraceEnabled()) { LOG.trace("Using " + (inOut ? "inOut" : "inOnly") + " jms template"); } // destination should be preferred if (destination != null) { if (inOut) { if (template != null) { template.send(destination, messageCreator, callback); } } else { if (template != null) { template.send(destination, messageCreator); } } } else if (destinationName != null) { if (inOut) { if (template != null) { template.send(destinationName, messageCreator, callback); } } else { if (template != null) { template.send(destinationName, messageCreator); } } } else { throw new IllegalArgumentException("Neither destination nor destinationName is specified on this endpoint: " + endpoint); } } protected void setMessageId(Exchange exchange) { if (exchange.hasOut()) { JmsMessage out = (JmsMessage) exchange.getOut(); try { if (out != null && out.getJmsMessage() != null) { out.setMessageId(out.getJmsMessage().getJMSMessageID()); } } catch (JMSException e) { LOG.warn("Unable to retrieve JMSMessageID from outgoing " + "JMS Message and set it into Camel's MessageId", e); } } } public JmsOperations getInOnlyTemplate() { if (inOnlyTemplate == null) { inOnlyTemplate = endpoint.createInOnlyTemplate(); } return inOnlyTemplate; } public void setInOnlyTemplate(JmsOperations inOnlyTemplate) { this.inOnlyTemplate = inOnlyTemplate; } public JmsOperations getInOutTemplate() { if (inOutTemplate == null) { inOutTemplate = endpoint.createInOutTemplate(); } return inOutTemplate; } public void setInOutTemplate(JmsOperations inOutTemplate) { this.inOutTemplate = inOutTemplate; } public UuidGenerator getUuidGenerator() { return uuidGenerator; } public void setUuidGenerator(UuidGenerator uuidGenerator) { this.uuidGenerator = uuidGenerator; } protected void doStart() throws Exception { super.doStart(); if (uuidGenerator == null) { // use the generator configured on the camel context uuidGenerator = getEndpoint().getCamelContext().getUuidGenerator(); } } protected void doStop() throws Exception { super.doStop(); } }
components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.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.camel.component.jms; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import org.apache.camel.AsyncCallback; import org.apache.camel.Exchange; import org.apache.camel.FailedToCreateProducerException; import org.apache.camel.RuntimeExchangeException; import org.apache.camel.component.jms.JmsConfiguration.CamelJmsTemplate; import org.apache.camel.component.jms.reply.ReplyManager; import org.apache.camel.component.jms.reply.UseMessageIdAsCorrelationIdMessageSentCallback; import org.apache.camel.impl.DefaultAsyncProducer; import org.apache.camel.spi.UuidGenerator; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ValueHolder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.jms.core.JmsOperations; import org.springframework.jms.core.MessageCreator; /** * @version $Revision$ */ public class JmsProducer extends DefaultAsyncProducer { private static final transient Log LOG = LogFactory.getLog(JmsProducer.class); private final JmsEndpoint endpoint; private final AtomicBoolean started = new AtomicBoolean(false); private JmsOperations inOnlyTemplate; private JmsOperations inOutTemplate; private UuidGenerator uuidGenerator; private ReplyManager replyManager; public JmsProducer(JmsEndpoint endpoint) { super(endpoint); this.endpoint = endpoint; } protected void initReplyManager() { if (!started.get()) { synchronized (this) { if (started.get()) { return; } try { if (endpoint.getReplyTo() != null) { replyManager = endpoint.getReplyManager(endpoint.getReplyTo()); if (LOG.isInfoEnabled()) { LOG.info("Using JmsReplyManager: " + replyManager + " to process replies from: " + endpoint.getReplyTo() + " queue with " + endpoint.getConcurrentConsumers() + " concurrent consumers."); } } else { replyManager = endpoint.getReplyManager(); if (LOG.isInfoEnabled()) { LOG.info("Using JmsReplyManager: " + replyManager + " to process replies from temporary queue with " + endpoint.getConcurrentConsumers() + " concurrent consumers."); } } } catch (Exception e) { throw new FailedToCreateProducerException(endpoint, e); } started.set(true); } } } public boolean process(Exchange exchange, AsyncCallback callback) { if (!endpoint.isDisableReplyTo() && exchange.getPattern().isOutCapable()) { // in out requires a bit more work than in only return processInOut(exchange, callback); } else { // in only return processInOnly(exchange, callback); } } protected boolean processInOut(final Exchange exchange, final AsyncCallback callback) { final org.apache.camel.Message in = exchange.getIn(); String destinationName = in.getHeader(JmsConstants.JMS_DESTINATION_NAME, String.class); // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION_NAME); if (destinationName == null) { destinationName = endpoint.getDestinationName(); } Destination destination = in.getHeader(JmsConstants.JMS_DESTINATION, Destination.class); // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION); if (destination == null) { destination = endpoint.getDestination(); } if (destination != null) { // prefer to use destination over destination name destinationName = null; } initReplyManager(); // note due to JMS transaction semantics we cannot use a single transaction // for sending the request and receiving the response final Destination replyTo = replyManager.getReplyTo(); if (replyTo == null) { throw new RuntimeExchangeException("Failed to resolve replyTo destination", exchange); } // when using message id as correlation id, we need at first to use a provisional correlation id // which we then update to the real JMSMessageID when the message has been sent // this is done with the help of the MessageSentCallback final boolean msgIdAsCorrId = endpoint.getConfiguration().isUseMessageIDAsCorrelationID(); final String provisionalCorrelationId = msgIdAsCorrId ? getUuidGenerator().generateUuid() : null; MessageSentCallback messageSentCallback = null; if (msgIdAsCorrId) { messageSentCallback = new UseMessageIdAsCorrelationIdMessageSentCallback(replyManager, provisionalCorrelationId, endpoint.getRequestTimeout()); } final ValueHolder<MessageSentCallback> sentCallback = new ValueHolder<MessageSentCallback>(messageSentCallback); final String originalCorrelationId = in.getHeader("JMSCorrelationID", String.class); if (originalCorrelationId == null && !msgIdAsCorrId) { in.setHeader("JMSCorrelationID", getUuidGenerator().generateUuid()); } MessageCreator messageCreator = new MessageCreator() { public Message createMessage(Session session) throws JMSException { Message message = endpoint.getBinding().makeJmsMessage(exchange, in, session, null); message.setJMSReplyTo(replyTo); replyManager.setReplyToSelectorHeader(in, message); String correlationId = determineCorrelationId(message, provisionalCorrelationId); replyManager.registerReply(replyManager, exchange, callback, originalCorrelationId, correlationId, endpoint.getRequestTimeout()); return message; } }; doSend(true, destinationName, destination, messageCreator, sentCallback.get()); // after sending then set the OUT message id to the JMSMessageID so its identical setMessageId(exchange); // continue routing asynchronously (reply will be processed async when its received) return false; } /** * Strategy to determine which correlation id to use among <tt>JMSMessageID</tt> and <tt>JMSCorrelationID</tt>. * * @param message the JMS message * @param provisionalCorrelationId an optional provisional correlation id, which is preferred to be used * @return the correlation id to use * @throws JMSException can be thrown */ protected String determineCorrelationId(Message message, String provisionalCorrelationId) throws JMSException { if (provisionalCorrelationId != null) { return provisionalCorrelationId; } final String messageId = message.getJMSMessageID(); final String correlationId = message.getJMSCorrelationID(); if (endpoint.getConfiguration().isUseMessageIDAsCorrelationID()) { return messageId; } else if (ObjectHelper.isEmpty(correlationId)) { // correlation id is empty so fallback to message id return messageId; } else { return correlationId; } } protected boolean processInOnly(final Exchange exchange, final AsyncCallback callback) { final org.apache.camel.Message in = exchange.getIn(); String destinationName = in.getHeader(JmsConstants.JMS_DESTINATION_NAME, String.class); if (destinationName != null) { // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION_NAME); } if (destinationName == null) { destinationName = endpoint.getDestinationName(); } Destination destination = in.getHeader(JmsConstants.JMS_DESTINATION, Destination.class); if (destination != null) { // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION); } if (destination == null) { destination = endpoint.getDestination(); } if (destination != null) { // prefer to use destination over destination name destinationName = null; } // we must honor these special flags to preserve QoS if (!endpoint.isPreserveMessageQos() && !endpoint.isExplicitQosEnabled()) { Object replyTo = exchange.getIn().getHeader("JMSReplyTo"); if (replyTo != null) { // we are routing an existing JmsMessage, origin from another JMS endpoint // then we need to remove the existing JMSReplyTo // as we are not out capable and thus do not expect a reply, and therefore // the consumer of this message we send should not return a reply String to = destinationName != null ? destinationName : "" + destination; LOG.warn("Disabling JMSReplyTo as this Exchange is not OUT capable with JMSReplyTo: " + replyTo + " for destination: " + to + ". Use preserveMessageQos=true to force Camel to keep the JMSReplyTo." + " Exchange: " + exchange); exchange.getIn().setHeader("JMSReplyTo", null); } } MessageCreator messageCreator = new MessageCreator() { public Message createMessage(Session session) throws JMSException { Message answer = endpoint.getBinding().makeJmsMessage(exchange, in, session, null); // if the binding did not create the reply to then we have to try to create it here String replyTo = exchange.getIn().getHeader("JMSReplyTo", String.class); if (replyTo != null && answer.getJMSReplyTo() == null) { Destination destination = null; // try using destination resolver to lookup the destination if (endpoint.getDestinationResolver() != null) { destination = endpoint.getDestinationResolver().resolveDestinationName(session, replyTo, endpoint.isPubSubDomain()); } if (destination == null) { // okay then fallback and create the queue if (endpoint.isPubSubDomain()) { if (LOG.isDebugEnabled()) { LOG.debug("Creating JMSReplyTo topic: " + replyTo); } destination = session.createTopic(replyTo); } else { if (LOG.isDebugEnabled()) { LOG.debug("Creating JMSReplyTo queue: " + replyTo); } destination = session.createQueue(replyTo); } } if (destination != null) { if (LOG.isDebugEnabled()) { LOG.debug("Using JMSReplyTo destination: " + destination); } answer.setJMSReplyTo(destination); } } return answer; } }; doSend(false, destinationName, destination, messageCreator, null); // after sending then set the OUT message id to the JMSMessageID so its identical setMessageId(exchange); // we are synchronous so return true callback.done(true); return true; } /** * Sends the message using the JmsTemplate. * * @param inOut use inOut or inOnly template * @param destinationName the destination name * @param destination the destination (if no name provided) * @param messageCreator the creator to create the {@link Message} to send * @param callback optional callback for inOut messages */ protected void doSend(boolean inOut, String destinationName, Destination destination, MessageCreator messageCreator, MessageSentCallback callback) { CamelJmsTemplate template = (CamelJmsTemplate) (inOut ? getInOutTemplate() : getInOnlyTemplate()); if (LOG.isTraceEnabled()) { LOG.trace("Using " + (inOut ? "inOut" : "inOnly") + " jms template"); } // destination should be preferred if (destination != null) { if (inOut) { if (template != null) { template.send(destination, messageCreator, callback); } } else { if (template != null) { template.send(destination, messageCreator); } } } else if (destinationName != null) { if (inOut) { if (template != null) { template.send(destinationName, messageCreator, callback); } } else { if (template != null) { template.send(destinationName, messageCreator); } } } else { throw new IllegalArgumentException("Neither destination nor destinationName is specified on this endpoint: " + endpoint); } } protected void setMessageId(Exchange exchange) { if (exchange.hasOut()) { JmsMessage out = (JmsMessage) exchange.getOut(); try { if (out != null && out.getJmsMessage() != null) { out.setMessageId(out.getJmsMessage().getJMSMessageID()); } } catch (JMSException e) { LOG.warn("Unable to retrieve JMSMessageID from outgoing " + "JMS Message and set it into Camel's MessageId", e); } } } public JmsOperations getInOnlyTemplate() { if (inOnlyTemplate == null) { inOnlyTemplate = endpoint.createInOnlyTemplate(); } return inOnlyTemplate; } public void setInOnlyTemplate(JmsOperations inOnlyTemplate) { this.inOnlyTemplate = inOnlyTemplate; } public JmsOperations getInOutTemplate() { if (inOutTemplate == null) { inOutTemplate = endpoint.createInOutTemplate(); } return inOutTemplate; } public void setInOutTemplate(JmsOperations inOutTemplate) { this.inOutTemplate = inOutTemplate; } public UuidGenerator getUuidGenerator() { return uuidGenerator; } public void setUuidGenerator(UuidGenerator uuidGenerator) { this.uuidGenerator = uuidGenerator; } protected void doStart() throws Exception { super.doStart(); if (uuidGenerator == null) { // use the generator configured on the camel context uuidGenerator = getEndpoint().getCamelContext().getUuidGenerator(); } } protected void doStop() throws Exception { super.doStop(); } }
CAMEL-3328: jms producer should be started before it can be used. git-svn-id: 11f3c9e1d08a13a4be44fe98a6d63a9c00f6ab23@1034004 13f79535-47bb-0310-9956-ffa450edef68
components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java
CAMEL-3328: jms producer should be started before it can be used.
<ide><path>omponents/camel-jms/src/main/java/org/apache/camel/component/jms/JmsProducer.java <ide> */ <ide> package org.apache.camel.component.jms; <ide> <add>import java.util.concurrent.RejectedExecutionException; <ide> import java.util.concurrent.atomic.AtomicBoolean; <ide> import javax.jms.Destination; <ide> import javax.jms.JMSException; <ide> } <ide> <ide> public boolean process(Exchange exchange, AsyncCallback callback) { <add> // deny processing if we are not started <add> if (!isRunAllowed()) { <add> if (exchange.getException() == null) { <add> exchange.setException(new RejectedExecutionException()); <add> } <add> // we cannot process so invoke callback <add> callback.done(true); <add> return true; <add> } <add> <ide> if (!endpoint.isDisableReplyTo() && exchange.getPattern().isOutCapable()) { <ide> // in out requires a bit more work than in only <ide> return processInOut(exchange, callback);
JavaScript
apache-2.0
033dc2cba6d72aac29ce8fc30efc496959936db0
0
matrix-org/matrix-appservice-irc,matrix-org/matrix-appservice-irc,matrix-org/matrix-appservice-irc
/*eslint no-invalid-this: 0*/ // eslint doesn't understand Promise.coroutine wrapping "use strict"; var Promise = require("bluebird"); var log = require("../logging").get("PublicitySyncer"); // This class keeps the +s state of every channel bridged synced with the RoomVisibility // of any rooms that are connected to the channels, regardless of the number of hops // required to traverse the mapping graph (rooms to channels). // // NB: This is only in the direction I->M // // +s = 'private' // -s = 'public' // Modes received, but +s missing = 'public' function PublicitySyncer(ircBridge) { this.ircBridge = ircBridge; // Cache the mode of each channel, the visibility of each room and the // known mappings between them. When any of these change, any inconsistencies // should be resolved by keeping the matrix side as private as necessary this._visibilityMap = { mappings: { //room_id: ['server #channel1', 'server channel2',...] }, channelIsSecret: { // '$server $channel': true | false }, roomVisibilities: { // room_id: "private" | "public" } } } // This is used so that any updates to the visibility map will cause the syncer to // reset a timer and begin counting down again to the eventual call to solve any // inconsistencies in the visibility map. var solveVisibilityTimeoutId = null; PublicitySyncer.prototype.updateVisibilityMap = function(isMode, key, value) { let hasChanged = false; if (isMode) { if (typeof value !== 'boolean') { throw new Error('+s state must be indicated with a boolean'); } if (this._visibilityMap.channelIsSecret[key] !== value) { this._visibilityMap.channelIsSecret[key] = value; hasChanged = true; } } else { if (typeof value !== 'string' || (value !== "private" && value !== "public")) { throw new Error('Room visibility must = "private" | "public"'); } if (this._visibilityMap.roomVisibilities[key] !== value) { this._visibilityMap.roomVisibilities[key] = value; hasChanged = true; } } if (hasChanged) { clearTimeout(solveVisibilityTimeoutId); solveVisibilityTimeoutId = setTimeout(() => { this._solveVisibility().catch((err) => { log.error("Failed to sync publicity: " + err.message); }); }, 10000); return Promise.resolve(); } return Promise.resolve(); } /* Solve any inconsistencies between the currently known state of channels '+s' modes and rooms 'visibility' states. This does full graph traversal to prevent any +s channels ever escaping into a 'public' room. This function errs on the side of caution by assuming an unknown channel state is '+s'. This just means that if the modes of a channel are not received yet (e.g when no virtual user is in said channel) then the room is assumed secret (+s). The bare minimum is done to make sure no private channels are leaked into public matrix channels. If ANY +s channel is somehow being bridged into a room, that room is updated to private. If ALL channels somehow being bridged into a room are NOT +s, that room is allowed to be public. */ PublicitySyncer.prototype._solveVisibility = Promise.coroutine(function*() { // For each room, do a big OR on all of the channels that are linked in any way this._visibilityMap.mappings = yield this.ircBridge.getStore().getAllChannelMappings(); let roomIds = Object.keys(this._visibilityMap.mappings); let shouldBePrivate = (roomId, checkedChannels) => { // If any channel connected to this room is +s, stop early and call it private // List first connected let channels = this._visibilityMap.mappings[roomId]; // = ['localhost #channel1', 'localhost #channel2', ... ] // No channels mapped to this roomId if (!channels) { return false; } // Filter out already checked channels channels = channels.filter((c) => checkedChannels.indexOf(c) === -1); let anyAreSecret = channels.some((channel) => { let channelIsSecret = this._visibilityMap.channelIsSecret[channel]; // If a channel mode is unknown, assume it is secret if (typeof channelIsSecret === 'undefined') { log.info('Assuming channel ' + channel + ' is secret'); channelIsSecret = true; } return channelIsSecret; }); if (anyAreSecret) { return true; } // Otherwise, recurse with the rooms connected to each channel // So get all the roomIds that this channel is mapped to and return whether any // are mapped to channels that are secret return channels.map((channel) => { return Object.keys(this._visibilityMap.mappings).filter((roomId2) => { return this._visibilityMap.mappings[roomId2].indexOf(channel) !== -1; }); }).some((roomIds2) => { return roomIds2.some((roomId2) => { return shouldBePrivate(roomId2, checkedChannels.concat(channels)); }); }); } let roomCorrectVisibilities = roomIds.map( (roomId) => { return shouldBePrivate(roomId, []) ? 'private' : 'public'; } ); let cli = this.ircBridge._bridge.getBot().client; // Update rooms to correct visibilities let promises = roomIds.map((roomId, index) => { let currentState = this._visibilityMap.roomVisibilities[roomId]; let correctState = roomCorrectVisibilities[index]; if (currentState !== correctState) { return cli.setRoomDirectoryVisibility(roomId, correctState).then( () => { // Update cache this._visibilityMap.roomVisibilities[roomId] = correctState; } ).catch((e) => { log.error(`Failed to setRoomDirectoryVisibility (${e.message})`); }); } }); return Promise.all(promises); }); module.exports = PublicitySyncer;
lib/bridge/PublicitySyncer.js
/*eslint no-invalid-this: 0*/ // eslint doesn't understand Promise.coroutine wrapping "use strict"; var Promise = require("bluebird"); var log = require("../logging").get("PublicitySyncer"); // This class keeps the +s state of every channel bridged synced with the RoomVisibility // of any rooms that are connected to the channels, regardless of the number of hops // required to traverse the mapping graph (rooms to channels). // // NB: This is only in the direction I->M // // +s = 'private' // -s = 'public' // Modes received, but +s missing = 'public' function PublicitySyncer(ircBridge) { this.ircBridge = ircBridge; // Cache the mode of each channel, the visibility of each room and the // known mappings between them. When any of these change, any inconsistencies // should be resolved by keeping the matrix side as private as necessary this._visibilityMap = { mappings: { //room_id: ['server #channel1', 'server channel2',...] }, channelIsSecret: { // '$server $channel': true | false }, roomVisibilities: { // room_id: "private" | "public" } } } // This is used so that any updates to the visibility map will cause the syncer to // reset a timer and begin counting down again to the eventual call to solve any // inconsistencies in the visibility map. var solveVisibilityTimeoutId = null; PublicitySyncer.prototype.updateVisibilityMap = function(isMode, key, value) { let hasChanged = false; if (isMode) { if (typeof value !== 'boolean') { throw new Error('+s state must be indicated with a boolean'); } if (this._visibilityMap.channelIsSecret[key] !== value) { this._visibilityMap.channelIsSecret[key] = value; hasChanged = true; } } else { if (typeof value !== 'string' || (value !== "private" && value !== "public")) { throw new Error('Room visibility must = "private" | "public"'); } if (this._visibilityMap.roomVisibilities[key] !== value) { this._visibilityMap.roomVisibilities[key] = value; hasChanged = true; } } if (hasChanged) { clearTimeout(solveVisibilityTimeoutId); log.info('Solving in 10s'); solveVisibilityTimeoutId = setTimeout(() => { this._solveVisibility().catch((err) => { log.error(err.message); }); }, 10000); return Promise.resolve(); } return Promise.resolve(); } /* Solve any inconsistencies between the currently known state of channels '+s' modes and rooms 'visibility' states. This does full graph traversal to prevent any +s channels ever escaping into a 'public' room. This function errs on the side of caution by assuming an unknown channel state is '+s'. This just means that if the modes of a channel are not received yet (e.g when no virtual user is in said channel) then the room is assumed secret (+s). The bare minimum is done to make sure no private channels are leaked into public matrix channels. If ANY +s channel is somehow being bridged into a room, that room is updated to private. If ALL channels somehow being bridged into a room, that room is allowed to be public. */ PublicitySyncer.prototype._solveVisibility = Promise.coroutine(function*() { // For each room, do a big OR on all of the channels that are linked in any way this._visibilityMap.mappings = yield this.ircBridge.getStore().getAllChannelMappings(); let roomIds = Object.keys(this._visibilityMap.mappings); let shouldBePrivate = (roomId, checkedChannels) => { // If any channel connected to this room is +s, stop early and call it private // List first connected let channels = this._visibilityMap.mappings[roomId]; // = ['localhost #channel1', 'localhost #channel2', ... ] // No channels mapped to this roomId if (!channels) { return false; } // Filter out already checked channels channels = channels.filter((c) => checkedChannels.indexOf(c) === -1); let anyAreSecret = channels.some((channel) => { let channelIsSecret = this._visibilityMap.channelIsSecret[channel]; // If a channel mode is unknown, assume it is secret if (typeof channelIsSecret === 'undefined') { log.info('Assuming channel ' + channel + ' is secret'); channelIsSecret = true; } return channelIsSecret; }); if (anyAreSecret) { return true; } // Otherwise, recurse with the rooms connected to each channel // So get all the roomIds that this channel is mapped to and return whether any // are mapped to channels that are secret return channels.map((channel) => { return Object.keys(this._visibilityMap.mappings).filter((roomId2) => { return this._visibilityMap.mappings[roomId2].indexOf(channel) !== -1; }); }).some((roomIds2) => { return roomIds2.some((roomId2) => { return shouldBePrivate(roomId2, checkedChannels.concat(channels)); }); }); } let roomCorrectVisibilities = roomIds.map( (roomId) => { return shouldBePrivate(roomId, []); } ).map((b) => b ? 'private' : 'public'); let cli = this.ircBridge._bridge.getBot().client; // Update rooms to correct visibilities let promises = roomIds.map((roomId, index) => { let currentState = this._visibilityMap.roomVisibilities[roomId]; let correctState = roomCorrectVisibilities[index]; if (currentState !== correctState) { return cli.setRoomDirectoryVisibility(roomId, correctState).then( () => { // Update cache this._visibilityMap.roomVisibilities[roomId] = correctState; } ).catch((e) => console.err); } }); return Promise.all(promises); }); module.exports = PublicitySyncer;
Response to code review
lib/bridge/PublicitySyncer.js
Response to code review
<ide><path>ib/bridge/PublicitySyncer.js <ide> if (hasChanged) { <ide> clearTimeout(solveVisibilityTimeoutId); <ide> <del> log.info('Solving in 10s'); <ide> solveVisibilityTimeoutId = setTimeout(() => { <ide> this._solveVisibility().catch((err) => { <del> log.error(err.message); <add> log.error("Failed to sync publicity: " + err.message); <ide> }); <ide> }, 10000); <ide> return Promise.resolve(); <ide> <ide> The bare minimum is done to make sure no private channels are leaked into public <ide> matrix channels. If ANY +s channel is somehow being bridged into a room, that room <del> is updated to private. If ALL channels somehow being bridged into a room, that <del> room is allowed to be public. <add> is updated to private. If ALL channels somehow being bridged into a room are NOT +s, <add> that room is allowed to be public. <ide> */ <ide> PublicitySyncer.prototype._solveVisibility = Promise.coroutine(function*() { <ide> // For each room, do a big OR on all of the channels that are linked in any way <ide> <ide> let roomCorrectVisibilities = roomIds.map( <ide> (roomId) => { <del> return shouldBePrivate(roomId, []); <add> return shouldBePrivate(roomId, []) ? 'private' : 'public'; <ide> } <del> ).map((b) => b ? 'private' : 'public'); <add> ); <ide> <ide> let cli = this.ircBridge._bridge.getBot().client; <ide> <ide> // Update cache <ide> this._visibilityMap.roomVisibilities[roomId] = correctState; <ide> } <del> ).catch((e) => console.err); <add> ).catch((e) => { <add> log.error(`Failed to setRoomDirectoryVisibility (${e.message})`); <add> }); <ide> } <ide> }); <ide>
Java
apache-2.0
54fa630ba5e2d46a4156fceeb11b0997c9451b93
0
edigrid/camel,johnpoth/camel,bgaudaen/camel,mzapletal/camel,drsquidop/camel,anoordover/camel,davidwilliams1978/camel,mohanaraosv/camel,joakibj/camel,veithen/camel,sirlatrom/camel,atoulme/camel,rmarting/camel,mzapletal/camel,nboukhed/camel,yury-vashchyla/camel,brreitme/camel,gilfernandes/camel,stravag/camel,jamesnetherton/camel,bhaveshdt/camel,lasombra/camel,anoordover/camel,rparree/camel,haku/camel,josefkarasek/camel,josefkarasek/camel,YMartsynkevych/camel,lasombra/camel,snurmine/camel,bdecoste/camel,dmvolod/camel,oscerd/camel,stalet/camel,arnaud-deprez/camel,brreitme/camel,tarilabs/camel,sebi-hgdata/camel,dkhanolkar/camel,isavin/camel,sebi-hgdata/camel,mgyongyosi/camel,mnki/camel,anoordover/camel,Thopap/camel,Fabryprog/camel,alvinkwekel/camel,satishgummadelli/camel,rmarting/camel,partis/camel,driseley/camel,scranton/camel,trohovsky/camel,apache/camel,grange74/camel,tkopczynski/camel,sebi-hgdata/camel,satishgummadelli/camel,lowwool/camel,grgrzybek/camel,trohovsky/camel,gilfernandes/camel,cunningt/camel,driseley/camel,borcsokj/camel,tlehoux/camel,pax95/camel,tdiesler/camel,maschmid/camel,mcollovati/camel,cunningt/camel,oalles/camel,ekprayas/camel,gyc567/camel,pmoerenhout/camel,christophd/camel,askannon/camel,onders86/camel,jonmcewen/camel,mcollovati/camel,qst-jdc-labs/camel,yuruki/camel,gilfernandes/camel,yury-vashchyla/camel,arnaud-deprez/camel,JYBESSON/camel,eformat/camel,bdecoste/camel,kevinearls/camel,jarst/camel,jkorab/camel,YMartsynkevych/camel,dkhanolkar/camel,ekprayas/camel,coderczp/camel,yogamaha/camel,jameszkw/camel,ssharma/camel,isavin/camel,tadayosi/camel,neoramon/camel,mzapletal/camel,snadakuduru/camel,jmandawg/camel,duro1/camel,royopa/camel,borcsokj/camel,objectiser/camel,chanakaudaya/camel,snadakuduru/camel,isururanawaka/camel,royopa/camel,jollygeorge/camel,tadayosi/camel,skinzer/camel,bfitzpat/camel,nboukhed/camel,drsquidop/camel,YoshikiHigo/camel,NickCis/camel,anton-k11/camel,jlpedrosa/camel,dpocock/camel,woj-i/camel,w4tson/camel,hqstevenson/camel,jlpedrosa/camel,anoordover/camel,w4tson/camel,gnodet/camel,gyc567/camel,pkletsko/camel,MohammedHammam/camel,w4tson/camel,tdiesler/camel,nikvaessen/camel,dvankleef/camel,josefkarasek/camel,mike-kukla/camel,edigrid/camel,jmandawg/camel,scranton/camel,nikhilvibhav/camel,snadakuduru/camel,isururanawaka/camel,hqstevenson/camel,scranton/camel,haku/camel,mgyongyosi/camel,akhettar/camel,tarilabs/camel,RohanHart/camel,NetNow/camel,dpocock/camel,ssharma/camel,Thopap/camel,mike-kukla/camel,NetNow/camel,YoshikiHigo/camel,pplatek/camel,onders86/camel,curso007/camel,snadakuduru/camel,ssharma/camel,partis/camel,jlpedrosa/camel,tkopczynski/camel,NickCis/camel,sebi-hgdata/camel,tarilabs/camel,pkletsko/camel,lburgazzoli/camel,ge0ffrey/camel,tlehoux/camel,edigrid/camel,nicolaferraro/camel,acartapanis/camel,rmarting/camel,neoramon/camel,ge0ffrey/camel,mnki/camel,RohanHart/camel,woj-i/camel,nboukhed/camel,gautric/camel,MrCoder/camel,yuruki/camel,dsimansk/camel,pax95/camel,johnpoth/camel,oalles/camel,chirino/camel,erwelch/camel,lasombra/camel,bhaveshdt/camel,jamesnetherton/camel,jameszkw/camel,tadayosi/camel,FingolfinTEK/camel,veithen/camel,MohammedHammam/camel,johnpoth/camel,lburgazzoli/apache-camel,jollygeorge/camel,CodeSmell/camel,jpav/camel,bhaveshdt/camel,rparree/camel,stravag/camel,akhettar/camel,atoulme/camel,punkhorn/camel-upstream,coderczp/camel,edigrid/camel,edigrid/camel,arnaud-deprez/camel,mnki/camel,mnki/camel,mgyongyosi/camel,bhaveshdt/camel,lowwool/camel,koscejev/camel,iweiss/camel,lburgazzoli/apache-camel,acartapanis/camel,hqstevenson/camel,Thopap/camel,dmvolod/camel,jmandawg/camel,johnpoth/camel,joakibj/camel,jpav/camel,erwelch/camel,bhaveshdt/camel,akhettar/camel,Thopap/camel,sebi-hgdata/camel,royopa/camel,qst-jdc-labs/camel,mohanaraosv/camel,ullgren/camel,coderczp/camel,CodeSmell/camel,ekprayas/camel,mnki/camel,pax95/camel,koscejev/camel,bgaudaen/camel,jonmcewen/camel,bfitzpat/camel,prashant2402/camel,yogamaha/camel,punkhorn/camel-upstream,duro1/camel,haku/camel,eformat/camel,coderczp/camel,nikvaessen/camel,bfitzpat/camel,Thopap/camel,dvankleef/camel,nicolaferraro/camel,NetNow/camel,jmandawg/camel,YMartsynkevych/camel,noelo/camel,ssharma/camel,adessaigne/camel,prashant2402/camel,oalles/camel,skinzer/camel,tkopczynski/camel,kevinearls/camel,tarilabs/camel,dkhanolkar/camel,tadayosi/camel,lasombra/camel,oscerd/camel,askannon/camel,ssharma/camel,dpocock/camel,zregvart/camel,ekprayas/camel,nikhilvibhav/camel,lburgazzoli/apache-camel,FingolfinTEK/camel,pax95/camel,dvankleef/camel,pplatek/camel,lowwool/camel,mcollovati/camel,gyc567/camel,grange74/camel,CandleCandle/camel,yogamaha/camel,josefkarasek/camel,dvankleef/camel,mike-kukla/camel,erwelch/camel,duro1/camel,sebi-hgdata/camel,prashant2402/camel,objectiser/camel,allancth/camel,partis/camel,haku/camel,tdiesler/camel,iweiss/camel,arnaud-deprez/camel,pkletsko/camel,snurmine/camel,ekprayas/camel,christophd/camel,maschmid/camel,nicolaferraro/camel,gyc567/camel,bdecoste/camel,jarst/camel,dkhanolkar/camel,grgrzybek/camel,satishgummadelli/camel,isururanawaka/camel,erwelch/camel,woj-i/camel,davidkarlsen/camel,yogamaha/camel,tkopczynski/camel,noelo/camel,punkhorn/camel-upstream,nikvaessen/camel,YMartsynkevych/camel,christophd/camel,askannon/camel,yogamaha/camel,DariusX/camel,chanakaudaya/camel,curso007/camel,onders86/camel,davidwilliams1978/camel,dpocock/camel,sirlatrom/camel,cunningt/camel,davidwilliams1978/camel,onders86/camel,NickCis/camel,bgaudaen/camel,tlehoux/camel,mzapletal/camel,acartapanis/camel,christophd/camel,isavin/camel,rparree/camel,sirlatrom/camel,allancth/camel,YoshikiHigo/camel,stalet/camel,acartapanis/camel,driseley/camel,sverkera/camel,JYBESSON/camel,FingolfinTEK/camel,lasombra/camel,bhaveshdt/camel,sabre1041/camel,royopa/camel,jlpedrosa/camel,bdecoste/camel,chanakaudaya/camel,apache/camel,grange74/camel,gautric/camel,joakibj/camel,akhettar/camel,josefkarasek/camel,nicolaferraro/camel,satishgummadelli/camel,mohanaraosv/camel,mike-kukla/camel,lowwool/camel,MohammedHammam/camel,anton-k11/camel,jollygeorge/camel,isururanawaka/camel,RohanHart/camel,prashant2402/camel,woj-i/camel,isavin/camel,veithen/camel,sabre1041/camel,anoordover/camel,yuruki/camel,gautric/camel,eformat/camel,stalet/camel,chanakaudaya/camel,dpocock/camel,skinzer/camel,JYBESSON/camel,tadayosi/camel,yuruki/camel,iweiss/camel,ge0ffrey/camel,woj-i/camel,manuelh9r/camel,kevinearls/camel,dsimansk/camel,jkorab/camel,dmvolod/camel,tkopczynski/camel,salikjan/camel,zregvart/camel,jarst/camel,josefkarasek/camel,NetNow/camel,nikhilvibhav/camel,YoshikiHigo/camel,RohanHart/camel,pkletsko/camel,yury-vashchyla/camel,pmoerenhout/camel,duro1/camel,christophd/camel,hqstevenson/camel,gilfernandes/camel,jonmcewen/camel,noelo/camel,joakibj/camel,borcsokj/camel,chanakaudaya/camel,pplatek/camel,gautric/camel,driseley/camel,apache/camel,jamesnetherton/camel,NickCis/camel,pax95/camel,MrCoder/camel,brreitme/camel,lburgazzoli/apache-camel,snurmine/camel,manuelh9r/camel,davidkarlsen/camel,anton-k11/camel,pplatek/camel,qst-jdc-labs/camel,NickCis/camel,gnodet/camel,borcsokj/camel,isururanawaka/camel,CodeSmell/camel,yury-vashchyla/camel,bgaudaen/camel,qst-jdc-labs/camel,FingolfinTEK/camel,askannon/camel,gnodet/camel,FingolfinTEK/camel,stravag/camel,lburgazzoli/camel,pplatek/camel,royopa/camel,nikhilvibhav/camel,stalet/camel,grgrzybek/camel,mohanaraosv/camel,allancth/camel,grgrzybek/camel,bgaudaen/camel,jamesnetherton/camel,ekprayas/camel,qst-jdc-labs/camel,MrCoder/camel,mgyongyosi/camel,Fabryprog/camel,anton-k11/camel,pmoerenhout/camel,yogamaha/camel,sabre1041/camel,onders86/camel,trohovsky/camel,adessaigne/camel,atoulme/camel,chanakaudaya/camel,neoramon/camel,cunningt/camel,CandleCandle/camel,MrCoder/camel,jmandawg/camel,apache/camel,nikvaessen/camel,chirino/camel,dmvolod/camel,snurmine/camel,MohammedHammam/camel,dvankleef/camel,nboukhed/camel,anoordover/camel,jkorab/camel,NetNow/camel,stravag/camel,rparree/camel,pkletsko/camel,royopa/camel,jlpedrosa/camel,gyc567/camel,kevinearls/camel,gyc567/camel,davidwilliams1978/camel,adessaigne/camel,mgyongyosi/camel,zregvart/camel,stalet/camel,gilfernandes/camel,arnaud-deprez/camel,askannon/camel,w4tson/camel,davidkarlsen/camel,grgrzybek/camel,koscejev/camel,maschmid/camel,haku/camel,tarilabs/camel,tkopczynski/camel,drsquidop/camel,anton-k11/camel,acartapanis/camel,curso007/camel,snurmine/camel,YoshikiHigo/camel,dmvolod/camel,nikvaessen/camel,christophd/camel,brreitme/camel,prashant2402/camel,skinzer/camel,RohanHart/camel,DariusX/camel,onders86/camel,noelo/camel,oscerd/camel,jpav/camel,rmarting/camel,dsimansk/camel,dmvolod/camel,oscerd/camel,driseley/camel,tadayosi/camel,ullgren/camel,oscerd/camel,satishgummadelli/camel,NickCis/camel,jkorab/camel,tlehoux/camel,CandleCandle/camel,joakibj/camel,dsimansk/camel,gilfernandes/camel,curso007/camel,gautric/camel,isavin/camel,partis/camel,jonmcewen/camel,chirino/camel,jonmcewen/camel,dkhanolkar/camel,jmandawg/camel,tdiesler/camel,mcollovati/camel,rparree/camel,jpav/camel,jpav/camel,w4tson/camel,jollygeorge/camel,lowwool/camel,koscejev/camel,sverkera/camel,chirino/camel,tlehoux/camel,hqstevenson/camel,dsimansk/camel,bfitzpat/camel,grange74/camel,grange74/camel,bfitzpat/camel,manuelh9r/camel,borcsokj/camel,kevinearls/camel,jpav/camel,drsquidop/camel,snadakuduru/camel,manuelh9r/camel,trohovsky/camel,apache/camel,bgaudaen/camel,lowwool/camel,edigrid/camel,joakibj/camel,dsimansk/camel,noelo/camel,DariusX/camel,pmoerenhout/camel,JYBESSON/camel,oscerd/camel,punkhorn/camel-upstream,arnaud-deprez/camel,dpocock/camel,akhettar/camel,dvankleef/camel,erwelch/camel,duro1/camel,grgrzybek/camel,mike-kukla/camel,eformat/camel,jonmcewen/camel,scranton/camel,erwelch/camel,johnpoth/camel,akhettar/camel,brreitme/camel,MohammedHammam/camel,sverkera/camel,eformat/camel,oalles/camel,jollygeorge/camel,partis/camel,NetNow/camel,sirlatrom/camel,objectiser/camel,YMartsynkevych/camel,CandleCandle/camel,YoshikiHigo/camel,MrCoder/camel,curso007/camel,oalles/camel,duro1/camel,pkletsko/camel,nikvaessen/camel,jkorab/camel,jkorab/camel,stravag/camel,pplatek/camel,Fabryprog/camel,YMartsynkevych/camel,manuelh9r/camel,manuelh9r/camel,ullgren/camel,yuruki/camel,coderczp/camel,pmoerenhout/camel,kevinearls/camel,jameszkw/camel,lburgazzoli/camel,tdiesler/camel,stalet/camel,CandleCandle/camel,jarst/camel,tdiesler/camel,jameszkw/camel,maschmid/camel,snadakuduru/camel,JYBESSON/camel,partis/camel,adessaigne/camel,chirino/camel,scranton/camel,hqstevenson/camel,ge0ffrey/camel,jarst/camel,atoulme/camel,veithen/camel,drsquidop/camel,lburgazzoli/camel,skinzer/camel,bfitzpat/camel,prashant2402/camel,davidwilliams1978/camel,isavin/camel,lasombra/camel,sirlatrom/camel,oalles/camel,jameszkw/camel,ge0ffrey/camel,gnodet/camel,iweiss/camel,mohanaraosv/camel,noelo/camel,allancth/camel,neoramon/camel,chirino/camel,apache/camel,lburgazzoli/apache-camel,jarst/camel,objectiser/camel,Fabryprog/camel,jamesnetherton/camel,bdecoste/camel,pax95/camel,mnki/camel,yuruki/camel,stravag/camel,koscejev/camel,sabre1041/camel,pmoerenhout/camel,iweiss/camel,lburgazzoli/apache-camel,maschmid/camel,nboukhed/camel,cunningt/camel,woj-i/camel,mzapletal/camel,alvinkwekel/camel,maschmid/camel,trohovsky/camel,neoramon/camel,atoulme/camel,davidwilliams1978/camel,gautric/camel,tarilabs/camel,acartapanis/camel,sverkera/camel,driseley/camel,ge0ffrey/camel,allancth/camel,CodeSmell/camel,drsquidop/camel,alvinkwekel/camel,qst-jdc-labs/camel,sverkera/camel,cunningt/camel,alvinkwekel/camel,lburgazzoli/camel,sabre1041/camel,mohanaraosv/camel,nboukhed/camel,grange74/camel,satishgummadelli/camel,sabre1041/camel,RohanHart/camel,bdecoste/camel,sverkera/camel,mike-kukla/camel,yury-vashchyla/camel,allancth/camel,iweiss/camel,jollygeorge/camel,CandleCandle/camel,davidkarlsen/camel,askannon/camel,FingolfinTEK/camel,johnpoth/camel,eformat/camel,rparree/camel,veithen/camel,trohovsky/camel,coderczp/camel,tlehoux/camel,dkhanolkar/camel,Thopap/camel,anton-k11/camel,brreitme/camel,jlpedrosa/camel,sirlatrom/camel,DariusX/camel,MohammedHammam/camel,adessaigne/camel,w4tson/camel,jameszkw/camel,haku/camel,koscejev/camel,veithen/camel,pplatek/camel,rmarting/camel,MrCoder/camel,yury-vashchyla/camel,JYBESSON/camel,ullgren/camel,atoulme/camel,snurmine/camel,salikjan/camel,mzapletal/camel,lburgazzoli/camel,borcsokj/camel,adessaigne/camel,scranton/camel,gnodet/camel,isururanawaka/camel,curso007/camel,zregvart/camel,jamesnetherton/camel,neoramon/camel,mgyongyosi/camel,skinzer/camel,rmarting/camel,ssharma/camel
/** * 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.camel.component.elasticsearch; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchResponse; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.notNullValue; public class ElasticsearchComponentTest extends CamelTestSupport { @BeforeClass public static void cleanupOnce() { deleteDirectory("target/data"); } @Override public boolean isCreateCamelContextPerClass() { // let's speed up the tests using the same context return true; } /** * As we don't delete the {@code target/data} folder for <b>each</b> test * below (otherwise they would run much slower), we need to make sure * there's no side effect of the same used data through creating unique * indexes. */ private Map<String, String> createIndexedData(String... additionalPrefixes) { String prefix = createPrefix(); // take over any potential prefixes we may have been asked for if (additionalPrefixes.length > 1) { StringBuilder sb = new StringBuilder(prefix); for (String additionalPrefix : additionalPrefixes) { sb.append(additionalPrefix); } prefix = sb.toString(); } String key = prefix + "key"; String value = prefix + "value"; log.info("Creating index data using the key/value pair {} => {}", key, value); Map<String, String> map = new HashMap<String, String>(); map.put(key, value); return map; } private String createPrefix() { // make use of the test method name to avoid collision return getTestMethodName().toLowerCase() + "-"; } @Test public void testIndex() throws Exception { Map<String, String> map = createIndexedData(); String indexId = template.requestBody("direct:index", map, String.class); assertNotNull("indexId should be set", indexId); } @Test public void testBulkIndex() throws Exception { List<Map<String, String>> documents = new ArrayList<Map<String, String>>(); Map<String, String> document1 = createIndexedData("-1"); Map<String, String> document2 = createIndexedData("-2"); documents.add(document1); documents.add(document2); List<?> indexIds = template.requestBody("direct:bulk_index", documents, List.class); assertNotNull("indexIds should be set", indexIds); assertCollectionSize("Indexed documents should match the size of documents", indexIds, documents.size()); } @Test public void testGet() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); sendBody("direct:index", map); String indexId = template.requestBody("direct:index", map, String.class); assertNotNull("indexId should be set", indexId); //now, verify GET succeeded GetResponse response = template.requestBody("direct:get", indexId, GetResponse.class); assertNotNull("response should not be null", response); assertNotNull("response source should not be null", response.getSource()); } @Test public void testDelete() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); sendBody("direct:index", map); String indexId = template.requestBody("direct:index", map, String.class); assertNotNull("indexId should be set", indexId); //now, verify GET succeeded GetResponse response = template.requestBody("direct:get", indexId, GetResponse.class); assertNotNull("response should not be null", response); assertNotNull("response source should not be null", response.getSource()); //now, perform DELETE DeleteResponse deleteResponse = template.requestBody("direct:delete", indexId, DeleteResponse.class); assertNotNull("response should not be null", deleteResponse); //now, verify GET fails to find the indexed value response = template.requestBody("direct:get", indexId, GetResponse.class); assertNotNull("response should not be null", response); assertNull("response source should be null", response.getSource()); } @Test public void testSearch() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); sendBody("direct:index", map); //now, verify GET succeeded Map<String, Object> actualQuery = new HashMap<String, Object>(); actualQuery.put("content", "searchtest"); Map<String, Object> match = new HashMap<String, Object>(); match.put("match", actualQuery); Map<String, Object> query = new HashMap<String, Object>(); query.put("query", match); SearchResponse response = template.requestBody("direct:search", query, SearchResponse.class); assertNotNull("response should not be null", response); assertNotNull("response hits should be == 1", response.getHits().totalHits()); } @Test public void testIndexWithHeaders() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:start", map, headers, String.class); assertNotNull("indexId should be set", indexId); } @Test public void testIndexWithIDInHeader() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_ID, "123"); String indexId = template.requestBodyAndHeaders("direct:start", map, headers, String.class); assertNotNull("indexId should be set", indexId); assertEquals("indexId should be equals to the provided id", "123", indexId); } @Test @Ignore("need to setup the cluster IP for this test") public void indexWithIp() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:indexWithIp", map, headers, String.class); assertNotNull("indexId should be set", indexId); } @Test @Ignore("need to setup the cluster IP/Port for this test") public void indexWithIpAndPort() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:indexWithIpAndPort", map, headers, String.class); assertNotNull("indexId should be set", indexId); } @Test public void testGetWithHeaders() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:start", map, headers, String.class); //now, verify GET headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_GET_BY_ID); GetResponse response = template.requestBodyAndHeaders("direct:start", indexId, headers, GetResponse.class); assertNotNull("response should not be null", response); assertNotNull("response source should not be null", response.getSource()); } @Test public void testDeleteWithHeaders() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:start", map, headers, String.class); //now, verify GET headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_GET_BY_ID); GetResponse response = template.requestBodyAndHeaders("direct:start", indexId, headers, GetResponse.class); assertNotNull("response should not be null", response); assertNotNull("response source should not be null", response.getSource()); //now, perform DELETE headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_DELETE); DeleteResponse deleteResponse = template.requestBodyAndHeaders("direct:start", indexId, headers, DeleteResponse.class); assertNotNull("response should not be null", deleteResponse); //now, verify GET fails to find the indexed value headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_GET_BY_ID); response = template.requestBodyAndHeaders("direct:start", indexId, headers, GetResponse.class); assertNotNull("response should not be null", response); assertNull("response source should be null", response.getSource()); } @Test public void indexRequestBody() throws Exception { String prefix = createPrefix(); // given IndexRequest request = new IndexRequest(prefix + "foo", prefix + "bar", prefix + "testId"); request.source("{\"" + prefix + "content\": \"" + prefix + "hello\"}"); // when String documentId = template.requestBody("direct:index", request, String.class); // then assertThat(documentId, equalTo(prefix + "testId")); } @Test public void getRequestBody() throws Exception { String prefix = createPrefix(); // given GetRequest request = new GetRequest(prefix + "foo").type(prefix + "bar"); // when String documentId = template.requestBody("direct:index", new IndexRequest(prefix + "foo", prefix + "bar", prefix + "testId") .source("{\"" + prefix + "content\": \"" + prefix + "hello\"}"), String.class); GetResponse response = template.requestBody("direct:get", request.id(documentId), GetResponse.class); // then assertThat(response, notNullValue()); assertThat(prefix + "hello", equalTo(response.getSourceAsMap().get(prefix + "content"))); } @Test public void deleteRequestBody() throws Exception { String prefix = createPrefix(); // given DeleteRequest request = new DeleteRequest(prefix + "foo").type(prefix + "bar"); // when String documentId = template.requestBody("direct:index", new IndexRequest("" + prefix + "foo", "" + prefix + "bar", "" + prefix + "testId") .source("{\"" + prefix + "content\": \"" + prefix + "hello\"}"), String.class); DeleteResponse response = template.requestBody("direct:delete", request.id(documentId), DeleteResponse.class); // then assertThat(response, notNullValue()); assertThat(documentId, equalTo(response.getId())); } @Test public void bulkIndexRequestBody() throws Exception { String prefix = createPrefix(); // given BulkRequest request = new BulkRequest(); request.add(new IndexRequest(prefix + "foo", prefix + "bar", prefix + "baz") .source("{\"" + prefix + "content\": \"" + prefix + "hello\"}")); // when @SuppressWarnings("unchecked") List<String> indexedDocumentIds = template.requestBody("direct:bulk_index", request, List.class); // then assertThat(indexedDocumentIds, notNullValue()); assertThat(indexedDocumentIds.size(), equalTo(1)); assertThat(indexedDocumentIds, hasItem(prefix + "baz")); } @Test public void bulkRequestBody() throws Exception { String prefix = createPrefix(); // given BulkRequest request = new BulkRequest(); request.add(new IndexRequest(prefix + "foo", prefix + "bar", prefix + "baz") .source("{\"" + prefix + "content\": \"" + prefix + "hello\"}")); // when BulkResponse response = template.requestBody("direct:bulk", request, BulkResponse.class); // then assertThat(response, notNullValue()); assertEquals(prefix + "baz", response.getItems()[0].getId()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() { from("direct:start").to("elasticsearch://local"); from("direct:index").to("elasticsearch://local?operation=INDEX&indexName=twitter&indexType=tweet"); from("direct:get").to("elasticsearch://local?operation=GET_BY_ID&indexName=twitter&indexType=tweet"); from("direct:delete").to("elasticsearch://local?operation=DELETE&indexName=twitter&indexType=tweet"); from("direct:search").to("elasticsearch://local?operation=SEARCH&indexName=twitter&indexType=tweet"); from("direct:bulk_index").to("elasticsearch://local?operation=BULK_INDEX&indexName=twitter&indexType=tweet"); from("direct:bulk").to("elasticsearch://local?operation=BULK&indexName=twitter&indexType=tweet"); //from("direct:indexWithIp").to("elasticsearch://elasticsearch?operation=INDEX&indexName=twitter&indexType=tweet&ip=localhost"); //from("direct:indexWithIpAndPort").to("elasticsearch://elasticsearch?operation=INDEX&indexName=twitter&indexType=tweet&ip=localhost&port=9300"); } }; } }
components/camel-elasticsearch/src/test/java/org/apache/camel/component/elasticsearch/ElasticsearchComponentTest.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.camel.component.elasticsearch; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchResponse; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.notNullValue; public class ElasticsearchComponentTest extends CamelTestSupport { @BeforeClass public static void cleanupOnce() { deleteDirectory("target/data"); } @Override public boolean isCreateCamelContextPerClass() { // let's speed up the tests using the same context return true; } /** * As we don't delete the {@code target/data} folder for <b>each</b> test * below (otherwise they would run much slower), we need to make sure * there's no side effect of the same used data through creating unique * indexes. */ private Map<String, String> createIndexedData(String... additionalPrefixes) { Map<String, String> map = new HashMap<String, String>(); String prefix = createPrefix(); // take over any potential prefixes we may have been asked for if (additionalPrefixes.length > 1) { StringBuilder sb = new StringBuilder(prefix); for (String additionalPrefix : additionalPrefixes) { sb.append(additionalPrefix); } prefix = sb.toString(); } String key = prefix + "key"; String value = prefix + "value"; log.info("Creating index data using the key/value pair {} => {}", key, value); map.put(key, value); return map; } private String createPrefix() { // make use of the test method name to avoid collision return getTestMethodName().toLowerCase() + "-"; } @Test public void testIndex() throws Exception { Map<String, String> map = createIndexedData(); String indexId = template.requestBody("direct:index", map, String.class); assertNotNull("indexId should be set", indexId); } @Test public void testBulkIndex() throws Exception { List<Map<String, String>> documents = new ArrayList<Map<String, String>>(); Map<String, String> document1 = createIndexedData("-1"); Map<String, String> document2 = createIndexedData("-2"); documents.add(document1); documents.add(document2); List<?> indexIds = template.requestBody("direct:bulk_index", documents, List.class); assertNotNull("indexIds should be set", indexIds); assertCollectionSize("Indexed documents should match the size of documents", indexIds, documents.size()); } @Test public void testGet() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); sendBody("direct:index", map); String indexId = template.requestBody("direct:index", map, String.class); assertNotNull("indexId should be set", indexId); //now, verify GET succeeded GetResponse response = template.requestBody("direct:get", indexId, GetResponse.class); assertNotNull("response should not be null", response); assertNotNull("response source should not be null", response.getSource()); } @Test public void testDelete() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); sendBody("direct:index", map); String indexId = template.requestBody("direct:index", map, String.class); assertNotNull("indexId should be set", indexId); //now, verify GET succeeded GetResponse response = template.requestBody("direct:get", indexId, GetResponse.class); assertNotNull("response should not be null", response); assertNotNull("response source should not be null", response.getSource()); //now, perform DELETE DeleteResponse deleteResponse = template.requestBody("direct:delete", indexId, DeleteResponse.class); assertNotNull("response should not be null", deleteResponse); //now, verify GET fails to find the indexed value response = template.requestBody("direct:get", indexId, GetResponse.class); assertNotNull("response should not be null", response); assertNull("response source should be null", response.getSource()); } @Test public void testSearch() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); sendBody("direct:index", map); //now, verify GET succeeded Map<String, Object> actualQuery = new HashMap<String, Object>(); actualQuery.put("content", "searchtest"); Map<String, Object> match = new HashMap<String, Object>(); match.put("match", actualQuery); Map<String, Object> query = new HashMap<String, Object>(); query.put("query", match); SearchResponse response = template.requestBody("direct:search", query, SearchResponse.class); assertNotNull("response should not be null", response); assertNotNull("response hits should be == 1", response.getHits().totalHits()); } @Test public void testIndexWithHeaders() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:start", map, headers, String.class); assertNotNull("indexId should be set", indexId); } @Test public void testIndexWithIDInHeader() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_ID, "123"); String indexId = template.requestBodyAndHeaders("direct:start", map, headers, String.class); assertNotNull("indexId should be set", indexId); assertEquals("indexId should be equals to the provided id", "123", indexId); } @Test @Ignore("need to setup the cluster IP for this test") public void indexWithIp() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:indexWithIp", map, headers, String.class); assertNotNull("indexId should be set", indexId); } @Test @Ignore("need to setup the cluster IP/Port for this test") public void indexWithIpAndPort() throws Exception { Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:indexWithIpAndPort", map, headers, String.class); assertNotNull("indexId should be set", indexId); } @Test public void testGetWithHeaders() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:start", map, headers, String.class); //now, verify GET headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_GET_BY_ID); GetResponse response = template.requestBodyAndHeaders("direct:start", indexId, headers, GetResponse.class); assertNotNull("response should not be null", response); assertNotNull("response source should not be null", response.getSource()); } @Test public void testDeleteWithHeaders() throws Exception { //first, INDEX a value Map<String, String> map = createIndexedData(); Map<String, Object> headers = new HashMap<String, Object>(); headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_INDEX); headers.put(ElasticsearchConfiguration.PARAM_INDEX_NAME, "twitter"); headers.put(ElasticsearchConfiguration.PARAM_INDEX_TYPE, "tweet"); String indexId = template.requestBodyAndHeaders("direct:start", map, headers, String.class); //now, verify GET headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_GET_BY_ID); GetResponse response = template.requestBodyAndHeaders("direct:start", indexId, headers, GetResponse.class); assertNotNull("response should not be null", response); assertNotNull("response source should not be null", response.getSource()); //now, perform DELETE headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_DELETE); DeleteResponse deleteResponse = template.requestBodyAndHeaders("direct:start", indexId, headers, DeleteResponse.class); assertNotNull("response should not be null", deleteResponse); //now, verify GET fails to find the indexed value headers.put(ElasticsearchConfiguration.PARAM_OPERATION, ElasticsearchConfiguration.OPERATION_GET_BY_ID); response = template.requestBodyAndHeaders("direct:start", indexId, headers, GetResponse.class); assertNotNull("response should not be null", response); assertNull("response source should be null", response.getSource()); } @Test public void indexRequestBody() throws Exception { String prefix = createPrefix(); // given IndexRequest request = new IndexRequest(prefix + "foo", prefix + "bar", prefix + "testId"); request.source("{\"" + prefix + "content\": \"" + prefix + "hello\"}"); // when String documentId = template.requestBody("direct:index", request, String.class); // then assertThat(documentId, equalTo(prefix + "testId")); } @Test public void getRequestBody() throws Exception { String prefix = createPrefix(); // given GetRequest request = new GetRequest(prefix + "foo").type(prefix + "bar"); // when String documentId = template.requestBody("direct:index", new IndexRequest(prefix + "foo", prefix + "bar", prefix + "testId") .source("{\"" + prefix + "content\": \"" + prefix + "hello\"}"), String.class); GetResponse response = template.requestBody("direct:get", request.id(documentId), GetResponse.class); // then assertThat(response, notNullValue()); assertThat(prefix + "hello", equalTo(response.getSourceAsMap().get(prefix + "content"))); } @Test public void deleteRequestBody() throws Exception { String prefix = createPrefix(); // given DeleteRequest request = new DeleteRequest(prefix + "foo").type(prefix + "bar"); // when String documentId = template.requestBody("direct:index", new IndexRequest("" + prefix + "foo", "" + prefix + "bar", "" + prefix + "testId") .source("{\"" + prefix + "content\": \"" + prefix + "hello\"}"), String.class); DeleteResponse response = template.requestBody("direct:delete", request.id(documentId), DeleteResponse.class); // then assertThat(response, notNullValue()); assertThat(documentId, equalTo(response.getId())); } @Test public void bulkIndexRequestBody() throws Exception { String prefix = createPrefix(); // given BulkRequest request = new BulkRequest(); request.add(new IndexRequest(prefix + "foo", prefix + "bar", prefix + "baz") .source("{\"" + prefix + "content\": \"" + prefix + "hello\"}")); // when @SuppressWarnings("unchecked") List<String> indexedDocumentIds = template.requestBody("direct:bulk_index", request, List.class); // then assertThat(indexedDocumentIds, notNullValue()); assertThat(indexedDocumentIds.size(), equalTo(1)); assertThat(indexedDocumentIds, hasItem(prefix + "baz")); } @Test public void bulkRequestBody() throws Exception { String prefix = createPrefix(); // given BulkRequest request = new BulkRequest(); request.add(new IndexRequest(prefix + "foo", prefix + "bar", prefix + "baz") .source("{\"" + prefix + "content\": \"" + prefix + "hello\"}")); // when BulkResponse response = template.requestBody("direct:bulk", request, BulkResponse.class); // then assertThat(response, notNullValue()); assertEquals(prefix + "baz", response.getItems()[0].getId()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() { from("direct:start").to("elasticsearch://local"); from("direct:index").to("elasticsearch://local?operation=INDEX&indexName=twitter&indexType=tweet"); from("direct:get").to("elasticsearch://local?operation=GET_BY_ID&indexName=twitter&indexType=tweet"); from("direct:delete").to("elasticsearch://local?operation=DELETE&indexName=twitter&indexType=tweet"); from("direct:search").to("elasticsearch://local?operation=SEARCH&indexName=twitter&indexType=tweet"); from("direct:bulk_index").to("elasticsearch://local?operation=BULK_INDEX&indexName=twitter&indexType=tweet"); from("direct:bulk").to("elasticsearch://local?operation=BULK&indexName=twitter&indexType=tweet"); //from("direct:indexWithIp").to("elasticsearch://elasticsearch?operation=INDEX&indexName=twitter&indexType=tweet&ip=localhost"); //from("direct:indexWithIpAndPort").to("elasticsearch://elasticsearch?operation=INDEX&indexName=twitter&indexType=tweet&ip=localhost&port=9300"); } }; } }
Polish.
components/camel-elasticsearch/src/test/java/org/apache/camel/component/elasticsearch/ElasticsearchComponentTest.java
Polish.
<ide><path>omponents/camel-elasticsearch/src/test/java/org/apache/camel/component/elasticsearch/ElasticsearchComponentTest.java <ide> * indexes. <ide> */ <ide> private Map<String, String> createIndexedData(String... additionalPrefixes) { <del> Map<String, String> map = new HashMap<String, String>(); <del> <ide> String prefix = createPrefix(); <ide> <ide> // take over any potential prefixes we may have been asked for <ide> String key = prefix + "key"; <ide> String value = prefix + "value"; <ide> log.info("Creating index data using the key/value pair {} => {}", key, value); <add> <add> Map<String, String> map = new HashMap<String, String>(); <ide> map.put(key, value); <ide> <ide> return map;
Java
apache-2.0
3610361095af0ace500819c69de79d3f5971b36b
0
subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai
/** * DISCLAIMER * * The quality of the code is such that you should not copy any of it as best * practice how to build Vaadin applications. * * @author [email protected] * */ package org.safehaus.subutai.server.ui.views; import com.vaadin.event.LayoutEvents; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.server.FileResource; import com.vaadin.ui.*; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.ServiceReference; import org.safehaus.subutai.server.ui.MainUI; import org.safehaus.subutai.server.ui.api.PortalModule; import org.safehaus.subutai.server.ui.api.PortalModuleListener; import org.safehaus.subutai.server.ui.api.PortalModuleService; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public class ModulesView extends VerticalLayout implements View, PortalModuleListener { private static final Logger LOG = Logger.getLogger(MainUI.class.getName()); private TabSheet editors; private CssLayout modulesLayout; private List<Component> modulesList = new ArrayList<>(); @Override public void enter(ViewChangeEvent event) { setSizeFull(); addStyleName("reports"); addComponent(buildDraftsView()); getPortalModuleService().addListener(this); } private Component buildDraftsView() { editors = new TabSheet(); editors.setSizeFull(); editors.addStyleName("borderless"); editors.addStyleName("editors"); VerticalLayout titleAndDrafts = new VerticalLayout(); titleAndDrafts.setSizeUndefined(); titleAndDrafts.setCaption("Modules"); titleAndDrafts.setSpacing(true); titleAndDrafts.addStyleName("drafts"); editors.addComponent(titleAndDrafts); Label draftsTitle = new Label("Modules"); draftsTitle.addStyleName("h1"); draftsTitle.setSizeUndefined(); titleAndDrafts.addComponent(draftsTitle); titleAndDrafts.setComponentAlignment(draftsTitle, Alignment.TOP_CENTER); modulesLayout = new CssLayout(); modulesLayout.setSizeUndefined(); modulesLayout.addStyleName("catalog"); titleAndDrafts.addComponent(modulesLayout); for (PortalModule module : getPortalModuleService().getModules()) { addModule(module); } return editors; } public static PortalModuleService getPortalModuleService() { // get bundle instance via the OSGi Framework Util class BundleContext ctx = FrameworkUtil.getBundle(PortalModuleService.class).getBundleContext(); if (ctx != null) { ServiceReference serviceReference = ctx.getServiceReference(PortalModuleService.class.getName()); if (serviceReference != null) { return PortalModuleService.class.cast(ctx.getService(serviceReference)); } } return null; } private void addModule(final PortalModule module) { if (module.getImage() != null) { if (!contains(module)) { CssLayout moduleLayout = new CssLayout(); moduleLayout.setId(module.getId()); moduleLayout.setWidth(150, Unit.PIXELS); moduleLayout.setHeight(200, Unit.PIXELS); moduleLayout.addStyleName("create"); moduleLayout.addLayoutClickListener(new LayoutEvents.LayoutClickListener() { @Override public void layoutClick(LayoutEvents.LayoutClickEvent layoutClickEvent) { autoCreate(module); } }); Image image = new Image("", new FileResource(module.getImage())); image.setWidth(90, Unit.PERCENTAGE); image.setDescription(module.getName()); moduleLayout.addComponent(image); modulesLayout.addComponent(moduleLayout); modulesList.add(moduleLayout); } } } private boolean contains(PortalModule module) { for (Component component : modulesList) { if (module.getId().equals(component.getId())) { return true; } } return false; } public void autoCreate(PortalModule module) { TabSheet.Tab tab = editors.addTab(module.createComponent()); tab.setCaption(module.getName()); tab.setClosable(true); editors.setSelectedTab(tab); } @Override public void moduleRegistered(PortalModule module) { addModule(module); } @Override public void moduleUnregistered(PortalModule module) { for (Component component : modulesList) { if (component.getId().equals(module.getId())) { modulesLayout.removeComponent(component); modulesList.remove(component); break; } } } }
management/server/vaadin/vaadin-ui/src/main/java/org/safehaus/subutai/server/ui/views/ModulesView.java
/** * DISCLAIMER * * The quality of the code is such that you should not copy any of it as best * practice how to build Vaadin applications. * * @author [email protected] * */ package org.safehaus.subutai.server.ui.views; import com.vaadin.event.LayoutEvents; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.server.FileResource; import com.vaadin.ui.*; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.ServiceReference; import org.safehaus.subutai.server.ui.MainUI; import org.safehaus.subutai.server.ui.api.PortalModule; import org.safehaus.subutai.server.ui.api.PortalModuleListener; import org.safehaus.subutai.server.ui.api.PortalModuleService; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public class ModulesView extends VerticalLayout implements View, PortalModuleListener { private static final Logger LOG = Logger.getLogger(MainUI.class.getName()); private TabSheet editors; private CssLayout modulesLayout; private List<Component> modulesList = new ArrayList<>(); @Override public void enter(ViewChangeEvent event) { setSizeFull(); addStyleName("reports"); addComponent(buildDraftsView()); getPortalModuleService().addListener(this); } private Component buildDraftsView() { editors = new TabSheet(); editors.setSizeFull(); editors.addStyleName("borderless"); editors.addStyleName("editors"); VerticalLayout titleAndDrafts = new VerticalLayout(); titleAndDrafts.setSizeUndefined(); titleAndDrafts.setCaption("Modules"); titleAndDrafts.setSpacing(true); titleAndDrafts.addStyleName("drafts"); editors.addComponent(titleAndDrafts); Label draftsTitle = new Label("Modules"); draftsTitle.addStyleName("h1"); draftsTitle.setSizeUndefined(); titleAndDrafts.addComponent(draftsTitle); titleAndDrafts.setComponentAlignment(draftsTitle, Alignment.TOP_CENTER); modulesLayout = new CssLayout(); modulesLayout.setSizeUndefined(); modulesLayout.addStyleName("catalog"); titleAndDrafts.addComponent(modulesLayout); for (PortalModule module : getPortalModuleService().getModules()) { addModule(module); } return editors; } public static PortalModuleService getPortalModuleService() { // get bundle instance via the OSGi Framework Util class BundleContext ctx = FrameworkUtil.getBundle(PortalModuleService.class).getBundleContext(); if (ctx != null) { ServiceReference serviceReference = ctx.getServiceReference(PortalModuleService.class.getName()); if (serviceReference != null) { return PortalModuleService.class.cast(ctx.getService(serviceReference)); } } return null; } private void addModule(final PortalModule module) { if (module.getImage() != null) { CssLayout moduleLayout = new CssLayout(); moduleLayout.setId(module.getId()); moduleLayout.setWidth(150, Unit.PIXELS); moduleLayout.setHeight(200, Unit.PIXELS); moduleLayout.addStyleName("create"); if (!modulesList.contains(moduleLayout)) { moduleLayout.addLayoutClickListener(new LayoutEvents.LayoutClickListener() { @Override public void layoutClick(LayoutEvents.LayoutClickEvent layoutClickEvent) { autoCreate(module); } }); Image image = new Image("", new FileResource(module.getImage())); image.setWidth(90, Unit.PERCENTAGE); image.setDescription(module.getName()); moduleLayout.addComponent(image); modulesLayout.addComponent(moduleLayout); modulesList.add(moduleLayout); } } } public void autoCreate(PortalModule module) { TabSheet.Tab tab = editors.addTab(module.createComponent()); tab.setCaption(module.getName()); tab.setClosable(true); editors.setSelectedTab(tab); } @Override public void moduleRegistered(PortalModule module) { addModule(module); } @Override public void moduleUnregistered(PortalModule module) { for (Component component : modulesList) { if (component.getId().equals(module.getId())) { modulesLayout.removeComponent(component); modulesList.remove(component); break; } } } }
-m Only one tab for module can be opened. Former-commit-id: fe5ab73a2d78d0cfa94154724251b15353c7da9c
management/server/vaadin/vaadin-ui/src/main/java/org/safehaus/subutai/server/ui/views/ModulesView.java
-m Only one tab for module can be opened.
<ide><path>anagement/server/vaadin/vaadin-ui/src/main/java/org/safehaus/subutai/server/ui/views/ModulesView.java <ide> <ide> private void addModule(final PortalModule module) { <ide> if (module.getImage() != null) { <del> CssLayout moduleLayout = new CssLayout(); <del> moduleLayout.setId(module.getId()); <del> moduleLayout.setWidth(150, Unit.PIXELS); <del> moduleLayout.setHeight(200, Unit.PIXELS); <del> moduleLayout.addStyleName("create"); <add> if (!contains(module)) { <add> CssLayout moduleLayout = new CssLayout(); <add> moduleLayout.setId(module.getId()); <add> moduleLayout.setWidth(150, Unit.PIXELS); <add> moduleLayout.setHeight(200, Unit.PIXELS); <add> moduleLayout.addStyleName("create"); <ide> <del> if (!modulesList.contains(moduleLayout)) { <ide> moduleLayout.addLayoutClickListener(new LayoutEvents.LayoutClickListener() { <ide> @Override <ide> public void layoutClick(LayoutEvents.LayoutClickEvent layoutClickEvent) { <ide> modulesList.add(moduleLayout); <ide> } <ide> } <add> } <add> <add> private boolean contains(PortalModule module) { <add> for (Component component : modulesList) { <add> if (module.getId().equals(component.getId())) { <add> return true; <add> } <add> } <add> <add> return false; <ide> } <ide> <ide> public void autoCreate(PortalModule module) {
Java
apache-2.0
2640f36dabc5b4434b0cac3159f5931a90dc5f32
0
lucastheisen/apache-directory-server,apache/directory-server,lucastheisen/apache-directory-server,apache/directory-server,drankye/directory-server,darranl/directory-server,darranl/directory-server,drankye/directory-server
/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ldap.server.jndi; import java.io.IOException; import java.io.FileFilter; import java.io.File; import java.net.InetSocketAddress; import java.util.Hashtable; import java.util.Iterator; import javax.naming.NamingException; import javax.naming.Context; import javax.naming.directory.DirContext; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttributes; import org.apache.kerberos.kdc.KdcConfiguration; import org.apache.kerberos.kdc.KerberosServer; import org.apache.kerberos.store.JndiPrincipalStoreImpl; import org.apache.kerberos.store.PrincipalStore; import org.apache.ldap.common.exception.LdapConfigurationException; import org.apache.ldap.server.DirectoryService; import org.apache.ldap.server.configuration.ServerStartupConfiguration; import org.apache.ldap.server.protocol.ExtendedOperationHandler; import org.apache.ldap.server.protocol.LdapProtocolProvider; import org.apache.mina.common.TransportType; import org.apache.mina.registry.Service; import org.apache.mina.registry.ServiceRegistry; import org.apache.ntp.NtpServer; import org.apache.ntp.NtpConfiguration; import org.apache.protocol.common.LoadStrategy; import org.apache.protocol.common.store.LdifFileLoader; import org.apache.changepw.ChangePasswordServer; import org.apache.changepw.ChangePasswordConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Adds additional bootstrapping for server socket listeners when firing * up the server. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$ * @see javax.naming.spi.InitialContextFactory */ public class ServerContextFactory extends CoreContextFactory { private static final Logger log = LoggerFactory.getLogger( ServerContextFactory.class.getName() ); private static final String LDIF_FILES_DN = "ou=loadedLdifFiles,ou=configuration,ou=system"; private static Service ldapService; private static KerberosServer kdcServer; private static ChangePasswordServer changePasswordServer; private static NtpServer ntpServer; private static ServiceRegistry minaRegistry; protected ServiceRegistry getMinaRegistry() { return minaRegistry; } public void afterShutdown( DirectoryService service ) { if ( minaRegistry != null ) { if ( ldapService != null ) { minaRegistry.unbind( ldapService ); if ( log.isInfoEnabled() ) { log.info( "Unbind of LDAP Service complete: " + ldapService ); } ldapService = null; } if ( kdcServer != null ) { kdcServer.destroy(); if ( log.isInfoEnabled() ) { log.info( "Unbind of KRB5 Service complete: " + kdcServer ); } kdcServer = null; } if ( changePasswordServer != null ) { changePasswordServer.destroy(); if ( log.isInfoEnabled() ) { log.info( "Unbind of Change Password Service complete: " + changePasswordServer ); } changePasswordServer = null; } if ( ntpServer != null ) { ntpServer.destroy(); if ( log.isInfoEnabled() ) { log.info( "Unbind of NTP Service complete: " + ntpServer ); } ntpServer = null; } } } public void afterStartup( DirectoryService service ) throws NamingException { ServerStartupConfiguration cfg = ( ServerStartupConfiguration ) service.getConfiguration().getStartupConfiguration(); Hashtable env = service.getConfiguration().getEnvironment(); loadLdifs( service ); if ( cfg.isEnableNetworking() ) { setupRegistry( cfg ); startLdapProtocol( cfg, env ); if ( cfg.isEnableKerberos() ) { try { KdcConfiguration kdcConfiguration = new KdcConfiguration( env, LoadStrategy.PROPS ); PrincipalStore kdcStore = new JndiPrincipalStoreImpl( kdcConfiguration, this ); kdcServer = new KerberosServer( kdcConfiguration, minaRegistry, kdcStore ); } catch ( Throwable t ) { log.error( "Failed to start the Kerberos service", t ); } } if ( cfg.isEnableChangePassword() ) { try { ChangePasswordConfiguration changePasswordConfiguration = new ChangePasswordConfiguration( env, LoadStrategy.PROPS ); PrincipalStore store = new JndiPrincipalStoreImpl( changePasswordConfiguration, this ); changePasswordServer = new ChangePasswordServer( changePasswordConfiguration, minaRegistry, store ); } catch ( Throwable t ) { log.error( "Failed to start the Change Password service", t ); } } if ( cfg.isEnableNtp() ) { try { NtpConfiguration ntpConfig = new NtpConfiguration( env, LoadStrategy.PROPS ); ntpServer = new NtpServer( ntpConfig, minaRegistry ); } catch ( Throwable t ) { log.error( "Failed to start the NTP service", t ); } } } } private void ensureLdifFileBase( DirContext root ) throws NamingException { Attributes entry = new BasicAttributes( "ou", "loadedLdifFiles", true ); entry.put( "objectClass", "top" ); entry.get( "objectClass" ).add( "organizationalUnit" ); try { root.createSubcontext( LDIF_FILES_DN, entry ); log.info( "Creating " + LDIF_FILES_DN ); } catch( NamingException e ) { log.info( LDIF_FILES_DN + " exists" );} } private final static String WINDOWSFILE_ATTR = "windowsFilePath"; private final static String UNIXFILE_ATTR = "unixFilePath"; private final static String WINDOWSFILE_OC = "windowsFile"; private final static String UNIXFILE_OC = "unixFile"; private void addFileEntry( DirContext root, File ldif ) throws NamingException { String rdnAttr = File.pathSeparatorChar == '\\' ? WINDOWSFILE_ATTR : UNIXFILE_ATTR; String oc = File.pathSeparatorChar == '\\' ? WINDOWSFILE_OC : UNIXFILE_OC; StringBuffer buf = new StringBuffer(); buf.append( rdnAttr ); buf.append( "=" ); buf.append( getCanonical( ldif ) ); buf.append( "," ); buf.append( LDIF_FILES_DN ); Attributes entry = new BasicAttributes( rdnAttr, getCanonical( ldif ), true ); entry.put( "objectClass", "top" ); entry.get( "objectClass" ).add( oc ); root.createSubcontext( buf.toString(), entry ); } private Attributes getLdifFileEntry( DirContext root, File ldif ) throws NamingException { String rdnAttr = File.pathSeparatorChar == '\\' ? WINDOWSFILE_ATTR : UNIXFILE_ATTR; StringBuffer buf = new StringBuffer(); buf.append( rdnAttr ); buf.append( "=" ); buf.append( getCanonical( ldif ) ); buf.append( "," ); buf.append( LDIF_FILES_DN ); try { return root.getAttributes( buf.toString(), new String[]{ "createTimestamp" }); } catch ( NamingException e ) { return null; } } private String getCanonical( File file ) throws NamingException { String canonical = null; try { canonical = file.getCanonicalPath(); } catch (IOException e) { log.error( "could not get canonical path", e ); return null; } return canonical; } private void loadLdifs( DirectoryService service ) throws NamingException { ServerStartupConfiguration cfg = ( ServerStartupConfiguration ) service.getConfiguration().getStartupConfiguration(); // log and bail if property not set if ( cfg.getLdifDirectory() == null ) { log.info( "LDIF load directory not specified. No LDIF files will be loaded." ); return; } // log and bail if LDIF directory does not exists if ( !cfg.getLdifDirectory().exists() ) { log.warn( "LDIF load directory '" + getCanonical( cfg.getLdifDirectory() ) + "' does not exist. No LDIF files will be loaded."); return; } // get an initial context to the rootDSE for creating the LDIF entries Hashtable env = ( Hashtable ) service.getConfiguration().getEnvironment().clone(); env.put( Context.PROVIDER_URL, "" ); DirContext root = ( DirContext ) this.getInitialContext( env ); // make sure the configuration area for loaded ldif files is present ensureLdifFileBase( root ); // if ldif directory is a file try to load it if ( !cfg.getLdifDirectory().isDirectory() ) { log.info( "LDIF load directory '" + getCanonical( cfg.getLdifDirectory() ) + "' is a file. Will attempt to load as LDIF." ); Attributes fileEntry = getLdifFileEntry( root, cfg.getLdifDirectory() ); if ( fileEntry != null ) { String time = ( String ) fileEntry.get( "createTimestamp" ).get(); log.info( "Load of LDIF file '" + getCanonical( cfg.getLdifDirectory() ) + "' skipped. It has already been loaded on " + time + "." ); return; } LdifFileLoader loader = new LdifFileLoader( root, cfg.getLdifDirectory(), cfg.getLdifFilters() ); loader.execute(); addFileEntry( root, cfg.getLdifDirectory() ); return; } // get all the ldif files within the directory (should be sorted alphabetically) File[] ldifFiles = cfg.getLdifDirectory().listFiles( new FileFilter() { public boolean accept( File pathname ) { boolean isLdif = pathname.getName().toLowerCase().endsWith( ".ldif" ); return pathname.isFile() && pathname.canRead() && isLdif; } }); // log and bail if we could not find any LDIF files if ( ldifFiles == null || ldifFiles.length == 0 ) { log.warn( "LDIF load directory '" + getCanonical( cfg.getLdifDirectory() ) + "' does not contain any LDIF files. No LDIF files will be loaded."); return; } // load all the ldif files and load each one that is loaded for ( int ii = 0; ii < ldifFiles.length; ii++ ) { Attributes fileEntry = getLdifFileEntry( root, ldifFiles[ii] ); if ( fileEntry != null ) { String time = ( String ) fileEntry.get( "createTimestamp" ).get(); log.info( "Load of LDIF file '" + getCanonical( ldifFiles[ii] ) + "' skipped. It has already been loaded on " + time + "." ); continue; } LdifFileLoader loader = new LdifFileLoader( root, ldifFiles[ii], cfg.getLdifFilters() ); int count = loader.execute(); log.info( "Loaded " + count + " entries from LDIF file '" + getCanonical( ldifFiles[ii] ) + "'" ); if ( fileEntry == null ) { addFileEntry( root, ldifFiles[ii] ); } } } /** * Starts up the MINA registry so various protocol providers can be started. */ private void setupRegistry( ServerStartupConfiguration cfg ) { minaRegistry = cfg.getMinaServiceRegistry(); } /** * Starts up the LDAP protocol provider to service LDAP requests * * @throws NamingException if there are problems starting the LDAP provider */ private void startLdapProtocol( ServerStartupConfiguration cfg, Hashtable env ) throws NamingException { int port = cfg.getLdapPort(); Service service = new Service( "ldap", TransportType.SOCKET, new InetSocketAddress( port ) ); // Register all extended operation handlers. LdapProtocolProvider protocolProvider = new LdapProtocolProvider( ( Hashtable ) env.clone() ); for( Iterator i = cfg.getExtendedOperationHandlers().iterator(); i.hasNext(); ) { ExtendedOperationHandler h = ( ExtendedOperationHandler ) i.next(); protocolProvider.addExtendedOperationHandler( h ); } try { minaRegistry.bind( service, protocolProvider ); ldapService = service; if ( log.isInfoEnabled() ) { log.info( "Successful bind of LDAP Service completed: " + ldapService ); } } catch ( IOException e ) { String msg = "Failed to bind the LDAP protocol service to the service registry: " + service; LdapConfigurationException lce = new LdapConfigurationException( msg ); lce.setRootCause( e ); log.error( msg, e ); throw lce; } } }
main/src/main/java/org/apache/ldap/server/jndi/ServerContextFactory.java
/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.ldap.server.jndi; import java.io.IOException; import java.io.FileFilter; import java.io.File; import java.net.InetSocketAddress; import java.util.Hashtable; import java.util.Iterator; import javax.naming.NamingException; import javax.naming.Context; import javax.naming.directory.DirContext; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttributes; import org.apache.kerberos.kdc.KdcConfiguration; import org.apache.kerberos.kdc.KerberosServer; import org.apache.kerberos.store.JndiPrincipalStoreImpl; import org.apache.kerberos.store.PrincipalStore; import org.apache.ldap.common.exception.LdapConfigurationException; import org.apache.ldap.server.DirectoryService; import org.apache.ldap.server.configuration.ServerStartupConfiguration; import org.apache.ldap.server.protocol.ExtendedOperationHandler; import org.apache.ldap.server.protocol.LdapProtocolProvider; import org.apache.mina.common.TransportType; import org.apache.mina.registry.Service; import org.apache.mina.registry.ServiceRegistry; import org.apache.ntp.NtpServer; import org.apache.ntp.NtpConfiguration; import org.apache.protocol.common.LoadStrategy; import org.apache.protocol.common.store.LdifFileLoader; import org.apache.changepw.ChangePasswordServer; import org.apache.changepw.ChangePasswordConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Adds additional bootstrapping for server socket listeners when firing * up the server. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$ * @see javax.naming.spi.InitialContextFactory */ public class ServerContextFactory extends CoreContextFactory { private static final Logger log = LoggerFactory.getLogger( ServerContextFactory.class.getName() ); private static final String LDIF_FILES_DN = "ou=loadedLdifFiles,ou=configuration,ou=system"; private static Service ldapService; private static KerberosServer kdcServer; private static ChangePasswordServer changePasswordServer; private static NtpServer ntpServer; private static ServiceRegistry minaRegistry; protected ServiceRegistry getMinaRegistry() { return minaRegistry; } public void afterShutdown( DirectoryService service ) { if ( minaRegistry != null ) { if ( ldapService != null ) { minaRegistry.unbind( ldapService ); if ( log.isInfoEnabled() ) { log.info( "Unbind of LDAP Service complete: " + ldapService ); } ldapService = null; } if ( kdcServer != null ) { kdcServer.destroy(); if ( log.isInfoEnabled() ) { log.info( "Unbind of KRB5 Service complete: " + kdcServer ); } kdcServer = null; } if ( changePasswordServer != null ) { changePasswordServer.destroy(); if ( log.isInfoEnabled() ) { log.info( "Unbind of Change Password Service complete: " + changePasswordServer ); } changePasswordServer = null; } if ( ntpServer != null ) { ntpServer.destroy(); if ( log.isInfoEnabled() ) { log.info( "Unbind of NTP Service complete: " + ntpServer ); } ntpServer = null; } } } public void afterStartup( DirectoryService service ) throws NamingException { ServerStartupConfiguration cfg = ( ServerStartupConfiguration ) service.getConfiguration().getStartupConfiguration(); Hashtable env = service.getConfiguration().getEnvironment(); loadLdifs( service ); if ( cfg.isEnableNetworking() ) { setupRegistry( cfg ); startLdapProtocol( cfg, env ); if ( cfg.isEnableKerberos() ) { try { KdcConfiguration kdcConfiguration = new KdcConfiguration( env, LoadStrategy.PROPS ); PrincipalStore kdcStore = new JndiPrincipalStoreImpl( kdcConfiguration, this ); kdcServer = new KerberosServer( kdcConfiguration, minaRegistry, kdcStore ); } catch ( Throwable t ) { log.error( "Failed to start the Kerberos service", t ); } } if ( cfg.isEnableChangePassword() ) { try { ChangePasswordConfiguration changePasswordConfiguration = new ChangePasswordConfiguration( env, LoadStrategy.PROPS ); PrincipalStore store = new JndiPrincipalStoreImpl( changePasswordConfiguration, this ); changePasswordServer = new ChangePasswordServer( changePasswordConfiguration, minaRegistry, store ); } catch ( Throwable t ) { log.error( "Failed to start the Change Password service", t ); } } if ( cfg.isEnableNtp() ) { try { NtpConfiguration ntpConfig = new NtpConfiguration( env, LoadStrategy.PROPS ); ntpServer = new NtpServer( ntpConfig, minaRegistry ); } catch ( Throwable t ) { log.error( "Failed to start the NTP service", t ); } } } } private void ensureLdifFileBase( DirContext root ) throws NamingException { Attributes entry = new BasicAttributes( "ou", "loadedLdifFiles", true ); entry.put( "objectClass", "top" ); entry.get( "objectClass" ).add( "organizationalUnit" ); try { root.createSubcontext( LDIF_FILES_DN, entry ); log.info( "Creating " + LDIF_FILES_DN ); } catch( NamingException e ) { log.info( LDIF_FILES_DN + " exists" );} } private final static String WINDOWSFILE_ATTR = "windowsFilePath"; private final static String UNIXFILE_ATTR = "unixFilePath"; private final static String WINDOWSFILE_OC = "windowsFile"; private final static String UNIXFILE_OC = "unixFile"; private void addFileEntry( DirContext root, File ldif ) throws NamingException { String rdnAttr = File.pathSeparatorChar == '\\' ? WINDOWSFILE_ATTR : UNIXFILE_ATTR; String oc = File.pathSeparatorChar == '\\' ? WINDOWSFILE_OC : UNIXFILE_OC; StringBuffer buf = new StringBuffer(); buf.append( rdnAttr ); buf.append( "=" ); buf.append( ldif.getAbsolutePath() ); buf.append( "," ); buf.append( LDIF_FILES_DN ); Attributes entry = new BasicAttributes( rdnAttr, ldif.getAbsolutePath(), true ); entry.put( "objectClass", "top" ); entry.get( "objectClass" ).add( oc ); root.createSubcontext( buf.toString(), entry ); } private Attributes getLdifFileEntry( DirContext root, File ldif ) { String rdnAttr = File.pathSeparatorChar == '\\' ? "windowsFile" : "unixFile"; StringBuffer buf = new StringBuffer(); buf.append( rdnAttr ); buf.append( "=" ); buf.append( ldif.getAbsolutePath() ); buf.append( "," ); buf.append( LDIF_FILES_DN ); try { return root.getAttributes( buf.toString(), new String[]{ "createTimestamp" }); } catch ( NamingException e ) { return null; } } private void loadLdifs( DirectoryService service ) throws NamingException { ServerStartupConfiguration cfg = ( ServerStartupConfiguration ) service.getConfiguration().getStartupConfiguration(); // log and bail if property not set if ( cfg.getLdifDirectory() == null ) { log.info( "LDIF load directory not specified. No LDIF files will be loaded." ); return; } // log and bail if LDIF directory does not exists if ( !cfg.getLdifDirectory().exists() ) { log.warn( "LDIF load directory '" + cfg.getLdifDirectory().getAbsolutePath() + "' does not exist. No LDIF files will be loaded."); return; } // get an initial context to the rootDSE for creating the LDIF entries Hashtable env = ( Hashtable ) service.getConfiguration().getEnvironment().clone(); env.put( Context.PROVIDER_URL, "" ); DirContext root = ( DirContext ) this.getInitialContext( env ); // make sure the configuration area for loaded ldif files is present ensureLdifFileBase( root ); // if ldif directory is a file try to load it if ( !cfg.getLdifDirectory().isDirectory() ) { log.info( "LDIF load directory '" + cfg.getLdifDirectory().getAbsolutePath() + "' is a file. Will attempt to load as LDIF." ); Attributes fileEntry = getLdifFileEntry( root, cfg.getLdifDirectory() ); if ( fileEntry != null ) { String time = ( String ) fileEntry.get( "createTimestamp" ).get(); log.info( "Load of LDIF file '" + cfg.getLdifDirectory().getAbsolutePath() + "' skipped. It has already been loaded on " + time + "." ); return; } LdifFileLoader loader = new LdifFileLoader( root, cfg.getLdifDirectory(), cfg.getLdifFilters() ); loader.execute(); addFileEntry( root, cfg.getLdifDirectory() ); return; } // get all the ldif files within the directory (should be sorted alphabetically) File[] ldifFiles = cfg.getLdifDirectory().listFiles( new FileFilter() { public boolean accept( File pathname ) { boolean isLdif = pathname.getName().toLowerCase().endsWith( ".ldif" ); return pathname.isFile() && pathname.canRead() && isLdif; } }); // log and bail if we could not find any LDIF files if ( ldifFiles == null || ldifFiles.length == 0 ) { log.warn( "LDIF load directory '" + cfg.getLdifDirectory().getAbsolutePath() + "' does not contain any LDIF files. No LDIF files will be loaded."); return; } // load all the ldif files and load each one that is loaded for ( int ii = 0; ii < ldifFiles.length; ii++ ) { Attributes fileEntry = getLdifFileEntry( root, ldifFiles[ii] ); if ( fileEntry != null ) { String time = ( String ) fileEntry.get( "createTimestamp" ).get(); log.info( "Load of LDIF file '" + ldifFiles[ii].getAbsolutePath() + "' skipped. It has already been loaded on " + time + "." ); continue; } LdifFileLoader loader = new LdifFileLoader( root, ldifFiles[ii], cfg.getLdifFilters() ); int count = loader.execute(); addFileEntry( root, cfg.getLdifDirectory() ); log.info( "Loaded " + count + " entries from LDIF file '" + ldifFiles[ii].getAbsolutePath() + "'" ); } } /** * Starts up the MINA registry so various protocol providers can be started. */ private void setupRegistry( ServerStartupConfiguration cfg ) { minaRegistry = cfg.getMinaServiceRegistry(); } /** * Starts up the LDAP protocol provider to service LDAP requests * * @throws NamingException if there are problems starting the LDAP provider */ private void startLdapProtocol( ServerStartupConfiguration cfg, Hashtable env ) throws NamingException { int port = cfg.getLdapPort(); Service service = new Service( "ldap", TransportType.SOCKET, new InetSocketAddress( port ) ); // Register all extended operation handlers. LdapProtocolProvider protocolProvider = new LdapProtocolProvider( ( Hashtable ) env.clone() ); for( Iterator i = cfg.getExtendedOperationHandlers().iterator(); i.hasNext(); ) { ExtendedOperationHandler h = ( ExtendedOperationHandler ) i.next(); protocolProvider.addExtendedOperationHandler( h ); } try { minaRegistry.bind( service, protocolProvider ); ldapService = service; if ( log.isInfoEnabled() ) { log.info( "Successful bind of LDAP Service completed: " + ldapService ); } } catch ( IOException e ) { String msg = "Failed to bind the LDAP protocol service to the service registry: " + service; LdapConfigurationException lce = new LdapConfigurationException( msg ); lce.setRootCause( e ); log.error( msg, e ); throw lce; } } }
Found and fixed bug where the objectClass name was used for the RDN of the loaded LDIF file instead of the RDN attribute. All works nicely now. git-svn-id: 90776817adfbd895fc5cfa90f675377e0a62e745@329711 13f79535-47bb-0310-9956-ffa450edef68
main/src/main/java/org/apache/ldap/server/jndi/ServerContextFactory.java
Found and fixed bug where the objectClass name was used for the RDN of the loaded LDIF file instead of the RDN attribute. All works nicely now.
<ide><path>ain/src/main/java/org/apache/ldap/server/jndi/ServerContextFactory.java <ide> StringBuffer buf = new StringBuffer(); <ide> buf.append( rdnAttr ); <ide> buf.append( "=" ); <del> buf.append( ldif.getAbsolutePath() ); <add> buf.append( getCanonical( ldif ) ); <ide> buf.append( "," ); <ide> buf.append( LDIF_FILES_DN ); <ide> <del> Attributes entry = new BasicAttributes( rdnAttr, ldif.getAbsolutePath(), true ); <add> Attributes entry = new BasicAttributes( rdnAttr, getCanonical( ldif ), true ); <ide> entry.put( "objectClass", "top" ); <ide> entry.get( "objectClass" ).add( oc ); <ide> root.createSubcontext( buf.toString(), entry ); <ide> } <ide> <ide> <del> private Attributes getLdifFileEntry( DirContext root, File ldif ) <del> { <del> String rdnAttr = File.pathSeparatorChar == '\\' ? "windowsFile" : "unixFile"; <add> private Attributes getLdifFileEntry( DirContext root, File ldif ) throws NamingException <add> { <add> String rdnAttr = File.pathSeparatorChar == '\\' ? WINDOWSFILE_ATTR : UNIXFILE_ATTR; <ide> StringBuffer buf = new StringBuffer(); <ide> buf.append( rdnAttr ); <ide> buf.append( "=" ); <del> buf.append( ldif.getAbsolutePath() ); <add> buf.append( getCanonical( ldif ) ); <ide> buf.append( "," ); <ide> buf.append( LDIF_FILES_DN ); <ide> <ide> } <ide> <ide> <add> private String getCanonical( File file ) throws NamingException <add> { <add> String canonical = null; <add> try <add> { <add> canonical = file.getCanonicalPath(); <add> } <add> catch (IOException e) <add> { <add> log.error( "could not get canonical path", e ); <add> return null; <add> } <add> return canonical; <add> } <add> <add> <ide> private void loadLdifs( DirectoryService service ) throws NamingException <ide> { <ide> ServerStartupConfiguration cfg = <ide> // log and bail if LDIF directory does not exists <ide> if ( !cfg.getLdifDirectory().exists() ) <ide> { <del> log.warn( "LDIF load directory '" + cfg.getLdifDirectory().getAbsolutePath() <add> log.warn( "LDIF load directory '" + getCanonical( cfg.getLdifDirectory() ) <ide> + "' does not exist. No LDIF files will be loaded."); <ide> return; <ide> } <ide> // if ldif directory is a file try to load it <ide> if ( !cfg.getLdifDirectory().isDirectory() ) <ide> { <del> log.info( "LDIF load directory '" + cfg.getLdifDirectory().getAbsolutePath() <add> log.info( "LDIF load directory '" + getCanonical( cfg.getLdifDirectory() ) <ide> + "' is a file. Will attempt to load as LDIF." ); <ide> Attributes fileEntry = getLdifFileEntry( root, cfg.getLdifDirectory() ); <ide> if ( fileEntry != null ) <ide> { <ide> String time = ( String ) fileEntry.get( "createTimestamp" ).get(); <del> log.info( "Load of LDIF file '" + cfg.getLdifDirectory().getAbsolutePath() <add> log.info( "Load of LDIF file '" + getCanonical( cfg.getLdifDirectory() ) <ide> + "' skipped. It has already been loaded on " + time + "." ); <ide> return; <ide> } <ide> // log and bail if we could not find any LDIF files <ide> if ( ldifFiles == null || ldifFiles.length == 0 ) <ide> { <del> log.warn( "LDIF load directory '" + cfg.getLdifDirectory().getAbsolutePath() <add> log.warn( "LDIF load directory '" + getCanonical( cfg.getLdifDirectory() ) <ide> + "' does not contain any LDIF files. No LDIF files will be loaded."); <ide> return; <ide> } <ide> if ( fileEntry != null ) <ide> { <ide> String time = ( String ) fileEntry.get( "createTimestamp" ).get(); <del> log.info( "Load of LDIF file '" + ldifFiles[ii].getAbsolutePath() <add> log.info( "Load of LDIF file '" + getCanonical( ldifFiles[ii] ) <ide> + "' skipped. It has already been loaded on " + time + "." ); <ide> continue; <ide> } <ide> LdifFileLoader loader = new LdifFileLoader( root, ldifFiles[ii], cfg.getLdifFilters() ); <ide> int count = loader.execute(); <del> addFileEntry( root, cfg.getLdifDirectory() ); <del> log.info( "Loaded " + count + " entries from LDIF file '" + ldifFiles[ii].getAbsolutePath() + "'" ); <add> log.info( "Loaded " + count + " entries from LDIF file '" + getCanonical( ldifFiles[ii] ) + "'" ); <add> if ( fileEntry == null ) <add> { <add> addFileEntry( root, ldifFiles[ii] ); <add> } <ide> } <ide> } <ide>
Java
bsd-3-clause
e818f1ab24b4c6802026a487fb7b9871ff511cd5
0
vivo-project/Vitro,vivo-project/Vitro,vivo-project/Vitro,vivo-project/Vitro
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.searchengine.solr; import static edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames.ALLTEXT; import static edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames.ALLTEXTUNSTEMMED; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.ORDER; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchFacetField; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchInputDocument; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchInputField; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery.Order; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchResponse; import edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames; import edu.cornell.mannlib.vitro.webapp.searchengine.base.BaseSearchFacetField; import edu.cornell.mannlib.vitro.webapp.searchengine.base.BaseSearchFacetField.BaseCount; import edu.cornell.mannlib.vitro.webapp.searchengine.base.BaseSearchResponse; /** * Utility method for converting from Solr-specific instances to Search-generic * instances, and back. */ public class SolrConversionUtils { // ---------------------------------------------------------------------- // Convert input documents to Solr-specific. // ---------------------------------------------------------------------- static List<SolrInputDocument> convertToSolrInputDocuments( Collection<SearchInputDocument> docs) { List<SolrInputDocument> solrDocs = new ArrayList<>(); for (SearchInputDocument doc : docs) { solrDocs.add(convertToSolrInputDocument(doc)); } return solrDocs; } private static SolrInputDocument convertToSolrInputDocument( SearchInputDocument doc) { SolrInputDocument solrDoc = new SolrInputDocument( convertToSolrInputFieldMap(doc.getFieldMap())); solrDoc.setDocumentBoost(doc.getDocumentBoost()); return solrDoc; } private static Map<String, SolrInputField> convertToSolrInputFieldMap( Map<String, SearchInputField> fieldMap) { Map<String, SolrInputField> solrFieldMap = new HashMap<>(); for (String fieldName : fieldMap.keySet()) { solrFieldMap.put(fieldName, convertToSolrInputField(fieldMap.get(fieldName))); } return solrFieldMap; } private static SolrInputField convertToSolrInputField( SearchInputField searchInputField) { String name = searchInputField.getName(); SolrInputField solrField = new SolrInputField(name); Collection<Object> values; if (name.equals(ALLTEXT) || name.equals(ALLTEXTUNSTEMMED)) { values = joinStringValues(searchInputField.getValues()); } else { values = searchInputField.getValues(); } if (values.isEmpty()) { // No values, nothing to do. } else if (values.size() == 1) { // One value? Insure that it is accepted as such. solrField.addValue(values.iterator().next(), searchInputField.getBoost()); } else { // A collection of values? Add them. solrField.addValue(values, searchInputField.getBoost()); } return solrField; } /** * Join the String values while preserving the non-String values. It * shouldn't affect the score, and it produces better snippets. */ private static Collection<Object> joinStringValues(Collection<Object> values) { StringBuilder buffer = new StringBuilder(); List<Object> betterValues = new ArrayList<>(); for (Object value : values) { if (value instanceof String) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append((String) value); } else { betterValues.add(value); } } if (buffer.length() > 0) { betterValues.add(buffer.toString()); } return betterValues; } // ---------------------------------------------------------------------- // Convert queries to Solr-specific. // ---------------------------------------------------------------------- /** * Convert from a SearchQuery to a SolrQuery, so the Solr server may execute * it. */ @SuppressWarnings("deprecation") static SolrQuery convertToSolrQuery(SearchQuery query) { SolrQuery solrQuery = new SolrQuery(query.getQuery()); solrQuery.setStart(query.getStart()); int rows = query.getRows(); if (rows >= 0) { solrQuery.setRows(rows); } for (String fieldToReturn : query.getFieldsToReturn()) { solrQuery.addField(fieldToReturn); } Map<String, Order> sortFields = query.getSortFields(); for (String sortField : sortFields.keySet()) { solrQuery.addSortField(sortField, convertToSolrOrder(sortFields.get(sortField))); } for (String filter : query.getFilters()) { solrQuery.addFilterQuery(filter); } if (!query.getFacetFields().isEmpty()) { solrQuery.setFacet(true); } for (String facetField : query.getFacetFields()) { solrQuery.addFacetField(facetField); } int facetLimit = query.getFacetLimit(); if (facetLimit >= 0) { solrQuery.setFacetLimit(facetLimit); } int minCount = query.getFacetMinCount(); if (minCount >= 0) { solrQuery.setFacetMinCount(minCount); } return solrQuery; } private static ORDER convertToSolrOrder(Order order) { if (order == Order.DESC) { return ORDER.desc; } else { return ORDER.asc; } } // ---------------------------------------------------------------------- // Convert responses to Search-generic // ---------------------------------------------------------------------- static SearchResponse convertToSearchResponse(QueryResponse response) { return new BaseSearchResponse(response.getHighlighting(), convertToSearchFacetFieldMap(response.getFacetFields()), new SolrSearchResultDocumentList(response.getResults())); } private static Map<String, SearchFacetField> convertToSearchFacetFieldMap( List<FacetField> facetFields) { Map<String, SearchFacetField> map = new HashMap<>(); if (facetFields != null) { for (FacetField facetField : facetFields) { map.put(facetField.getName(), convertToSearchFacetField(facetField)); } } return map; } private static SearchFacetField convertToSearchFacetField( FacetField facetField) { return new BaseSearchFacetField(facetField.getName(), convertToSearchFacetFieldCounts(facetField.getValues())); } private static List<BaseCount> convertToSearchFacetFieldCounts( List<FacetField.Count> solrCounts) { List<BaseCount> searchCounts = new ArrayList<>(); if (solrCounts != null) { for (FacetField.Count solrCount : solrCounts) { searchCounts.add(new BaseCount(solrCount.getName(), solrCount .getCount())); } } return searchCounts; } }
webapp/src/edu/cornell/mannlib/vitro/webapp/searchengine/solr/SolrConversionUtils.java
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.searchengine.solr; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.ORDER; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchFacetField; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchInputDocument; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchInputField; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery.Order; import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchResponse; import edu.cornell.mannlib.vitro.webapp.searchengine.base.BaseSearchFacetField; import edu.cornell.mannlib.vitro.webapp.searchengine.base.BaseSearchFacetField.BaseCount; import edu.cornell.mannlib.vitro.webapp.searchengine.base.BaseSearchResponse; /** * Utility method for converting from Solr-specific instances to Search-generic * instances, and back. */ public class SolrConversionUtils { // ---------------------------------------------------------------------- // Convert input documents to Solr-specific. // ---------------------------------------------------------------------- static List<SolrInputDocument> convertToSolrInputDocuments( Collection<SearchInputDocument> docs) { List<SolrInputDocument> solrDocs = new ArrayList<>(); for (SearchInputDocument doc : docs) { solrDocs.add(convertToSolrInputDocument(doc)); } return solrDocs; } private static SolrInputDocument convertToSolrInputDocument( SearchInputDocument doc) { SolrInputDocument solrDoc = new SolrInputDocument( convertToSolrInputFieldMap(doc.getFieldMap())); solrDoc.setDocumentBoost(doc.getDocumentBoost()); return solrDoc; } private static Map<String, SolrInputField> convertToSolrInputFieldMap( Map<String, SearchInputField> fieldMap) { Map<String, SolrInputField> solrFieldMap = new HashMap<>(); for (String fieldName : fieldMap.keySet()) { solrFieldMap.put(fieldName, convertToSolrInputField(fieldMap.get(fieldName))); } return solrFieldMap; } private static SolrInputField convertToSolrInputField( SearchInputField searchInputField) { SolrInputField solrField = new SolrInputField( searchInputField.getName()); Collection<Object> values = joinStringValues(searchInputField .getValues()); if (values.isEmpty()) { // No values, nothing to do. } else if (values.size() == 1) { // One value? Insure that it is accepted as such. solrField.addValue(values.iterator().next(), searchInputField.getBoost()); } else { // A collection of values? Add them. solrField.addValue(values, searchInputField.getBoost()); } return solrField; } /** * Join the String values while preserving the non-String values. It * shouldn't affect the score, and it produces better snippets. */ private static Collection<Object> joinStringValues(Collection<Object> values) { StringBuilder buffer = new StringBuilder(); List<Object> betterValues = new ArrayList<>(); for (Object value : values) { if (value instanceof String) { if (buffer.length() > 0) { buffer.append(" "); } buffer.append((String) value); } else { betterValues.add(value); } } if (buffer.length() > 0) { betterValues.add(buffer.toString()); } return betterValues; } // ---------------------------------------------------------------------- // Convert queries to Solr-specific. // ---------------------------------------------------------------------- /** * Convert from a SearchQuery to a SolrQuery, so the Solr server may execute * it. */ @SuppressWarnings("deprecation") static SolrQuery convertToSolrQuery(SearchQuery query) { SolrQuery solrQuery = new SolrQuery(query.getQuery()); solrQuery.setStart(query.getStart()); int rows = query.getRows(); if (rows >= 0) { solrQuery.setRows(rows); } for (String fieldToReturn : query.getFieldsToReturn()) { solrQuery.addField(fieldToReturn); } Map<String, Order> sortFields = query.getSortFields(); for (String sortField : sortFields.keySet()) { solrQuery.addSortField(sortField, convertToSolrOrder(sortFields.get(sortField))); } for (String filter : query.getFilters()) { solrQuery.addFilterQuery(filter); } if (!query.getFacetFields().isEmpty()) { solrQuery.setFacet(true); } for (String facetField : query.getFacetFields()) { solrQuery.addFacetField(facetField); } int facetLimit = query.getFacetLimit(); if (facetLimit >= 0) { solrQuery.setFacetLimit(facetLimit); } int minCount = query.getFacetMinCount(); if (minCount >= 0) { solrQuery.setFacetMinCount(minCount); } return solrQuery; } private static ORDER convertToSolrOrder(Order order) { if (order == Order.DESC) { return ORDER.desc; } else { return ORDER.asc; } } // ---------------------------------------------------------------------- // Convert responses to Search-generic // ---------------------------------------------------------------------- static SearchResponse convertToSearchResponse(QueryResponse response) { return new BaseSearchResponse(response.getHighlighting(), convertToSearchFacetFieldMap(response.getFacetFields()), new SolrSearchResultDocumentList(response.getResults())); } private static Map<String, SearchFacetField> convertToSearchFacetFieldMap( List<FacetField> facetFields) { Map<String, SearchFacetField> map = new HashMap<>(); if (facetFields != null) { for (FacetField facetField : facetFields) { map.put(facetField.getName(), convertToSearchFacetField(facetField)); } } return map; } private static SearchFacetField convertToSearchFacetField( FacetField facetField) { return new BaseSearchFacetField(facetField.getName(), convertToSearchFacetFieldCounts(facetField.getValues())); } private static List<BaseCount> convertToSearchFacetFieldCounts( List<FacetField.Count> solrCounts) { List<BaseCount> searchCounts = new ArrayList<>(); if (solrCounts != null) { for (FacetField.Count solrCount : solrCounts) { searchCounts.add(new BaseCount(solrCount.getName(), solrCount .getCount())); } } return searchCounts; } }
VIVO-986 Limit the concatenation of string values to ALLTEXT and ALLTEXTUNSTEMMED
webapp/src/edu/cornell/mannlib/vitro/webapp/searchengine/solr/SolrConversionUtils.java
VIVO-986 Limit the concatenation of string values to ALLTEXT and ALLTEXTUNSTEMMED
<ide><path>ebapp/src/edu/cornell/mannlib/vitro/webapp/searchengine/solr/SolrConversionUtils.java <ide> /* $This file is distributed under the terms of the license in /doc/license.txt$ */ <ide> <ide> package edu.cornell.mannlib.vitro.webapp.searchengine.solr; <add> <add>import static edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames.ALLTEXT; <add>import static edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames.ALLTEXTUNSTEMMED; <ide> <ide> import java.util.ArrayList; <ide> import java.util.Collection; <ide> import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery; <ide> import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchQuery.Order; <ide> import edu.cornell.mannlib.vitro.webapp.modules.searchEngine.SearchResponse; <add>import edu.cornell.mannlib.vitro.webapp.search.VitroSearchTermNames; <ide> import edu.cornell.mannlib.vitro.webapp.searchengine.base.BaseSearchFacetField; <ide> import edu.cornell.mannlib.vitro.webapp.searchengine.base.BaseSearchFacetField.BaseCount; <ide> import edu.cornell.mannlib.vitro.webapp.searchengine.base.BaseSearchResponse; <ide> <ide> private static SolrInputField convertToSolrInputField( <ide> SearchInputField searchInputField) { <del> SolrInputField solrField = new SolrInputField( <del> searchInputField.getName()); <del> <del> Collection<Object> values = joinStringValues(searchInputField <del> .getValues()); <add> String name = searchInputField.getName(); <add> SolrInputField solrField = new SolrInputField(name); <add> <add> Collection<Object> values; <add> if (name.equals(ALLTEXT) || name.equals(ALLTEXTUNSTEMMED)) { <add> values = joinStringValues(searchInputField.getValues()); <add> } else { <add> values = searchInputField.getValues(); <add> } <ide> <ide> if (values.isEmpty()) { <ide> // No values, nothing to do.
Java
apache-2.0
86d4d5304e6911c0c2ce6b485f0b6bfced36392a
0
roshanch/GearVRf,Samsung/GearVRf,xcaostagit/GearVRf,xcaostagit/GearVRf,Samsung/GearVRf,NolaDonato/GearVRf,NolaDonato/GearVRf,NolaDonato/GearVRf,NolaDonato/GearVRf,xcaostagit/GearVRf,Samsung/GearVRf,thomasflynn/GearVRf,Samsung/GearVRf,roshanch/GearVRf,thomasflynn/GearVRf,thomasflynn/GearVRf,Samsung/GearVRf,thomasflynn/GearVRf,xcaostagit/GearVRf,thomasflynn/GearVRf,roshanch/GearVRf,Samsung/GearVRf,roshanch/GearVRf,roshanch/GearVRf,NolaDonato/GearVRf,Samsung/GearVRf,thomasflynn/GearVRf,xcaostagit/GearVRf,thomasflynn/GearVRf,xcaostagit/GearVRf,NolaDonato/GearVRf,NolaDonato/GearVRf
/* Copyright 2015 Samsung Electronics Co., LTD * * 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.gearvrf.scene_objects.view; import org.gearvrf.GVRActivity; import org.gearvrf.scene_objects.GVRViewSceneObject; import android.graphics.Canvas; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; /** * This class represents a {@link WebView} that is rendered * into the attached {@link GVRViewSceneObject} * See {@link GVRView} and {@link GVRViewSceneObject} */ public class GVRWebView extends WebView implements GVRView { private GVRViewSceneObject mSceneObject = null; public GVRWebView(GVRActivity context) { super(context); setWebViewClient(new WebViewClient()); context.registerView(this); } @Override public void draw(Canvas canvas) { if (mSceneObject == null) return; // Canvas attached to GVRViewSceneObject to draw on Canvas attachedCanvas = mSceneObject.lockCanvas(); // translate canvas to reflect view scrolling attachedCanvas.scale(attachedCanvas.getWidth() / (float) canvas.getWidth(), attachedCanvas.getHeight() / (float) canvas.getHeight()); attachedCanvas.translate(-getScrollX(), -getScrollY()); // draw the view to provided canvas super.draw(attachedCanvas); mSceneObject.unlockCanvasAndPost(attachedCanvas); } @Override public void setSceneObject(GVRViewSceneObject sceneObject) { mSceneObject = sceneObject; } @Override public View getView() { return this; } }
GVRf/Framework/framework/src/main/java/org/gearvrf/scene_objects/view/GVRWebView.java
/* Copyright 2015 Samsung Electronics Co., LTD * * 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.gearvrf.scene_objects.view; import org.gearvrf.GVRActivity; import org.gearvrf.scene_objects.GVRViewSceneObject; import android.graphics.Canvas; import android.view.View; import android.webkit.WebView; /** * This class represents a {@link WebView} that is rendered * into the attached {@link GVRViewSceneObject} * See {@link GVRView} and {@link GVRViewSceneObject} */ public class GVRWebView extends WebView implements GVRView { private GVRViewSceneObject mSceneObject = null; public GVRWebView(GVRActivity context) { super(context); context.registerView(this); } @Override public void draw(Canvas canvas) { if (mSceneObject == null) return; // Canvas attached to GVRViewSceneObject to draw on Canvas attachedCanvas = mSceneObject.lockCanvas(); // translate canvas to reflect view scrolling attachedCanvas.scale(attachedCanvas.getWidth() / (float) canvas.getWidth(), attachedCanvas.getHeight() / (float) canvas.getHeight()); attachedCanvas.translate(-getScrollX(), -getScrollY()); // draw the view to provided canvas super.draw(attachedCanvas); mSceneObject.unlockCanvasAndPost(attachedCanvas); } @Override public void setSceneObject(GVRViewSceneObject sceneObject) { mSceneObject = sceneObject; } @Override public View getView() { return this; } }
vulkan: fixes gvr-renderableview (#1366)
GVRf/Framework/framework/src/main/java/org/gearvrf/scene_objects/view/GVRWebView.java
vulkan: fixes gvr-renderableview (#1366)
<ide><path>VRf/Framework/framework/src/main/java/org/gearvrf/scene_objects/view/GVRWebView.java <ide> import android.graphics.Canvas; <ide> import android.view.View; <ide> import android.webkit.WebView; <add>import android.webkit.WebViewClient; <ide> <ide> /** <ide> * This class represents a {@link WebView} that is rendered <ide> public GVRWebView(GVRActivity context) { <ide> super(context); <ide> <add> setWebViewClient(new WebViewClient()); <ide> context.registerView(this); <ide> } <ide>
Java
apache-2.0
c6de095cdef430ceb871f58abff74f9114f5c7d0
0
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
package org.commcare.android.view; import org.commcare.android.adapters.EntityDetailAdapter; import org.commcare.android.adapters.EntityDetailPagerAdapter; import org.commcare.android.util.AndroidUtil; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DisplayUnit; import org.commcare.suite.model.Text; import org.javarosa.core.model.instance.TreeReference; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import org.commcare.android.adapters.EntityDetailPagerAdapter; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DisplayUnit; import org.javarosa.core.model.instance.TreeReference; /** * Widget that combines a ViewPager with a set of page titles styled to look like tabs. * User can navigate either by swiping through pages or by tapping the tabs. * @author jschweers * */ public class TabbedDetailView extends RelativeLayout { private FragmentActivity mContext; private LinearLayout mMenu; private EntityDetailPagerAdapter mEntityDetailPagerAdapter; private ViewPager mViewPager; private View mViewPagerWrapper; private int mAlternateId = -1; public TabbedDetailView(Context context) { this(context, -1); } /** * Create a tabbed detail view with a specific root pager ID * (this is necessary in any context where multiple detail views * will be used at once) * * @param context * @param alternateId */ public TabbedDetailView(Context context, int alternateId) { super(context); mContext = (FragmentActivity) context; this.mAlternateId = alternateId; } public TabbedDetailView(Context context, AttributeSet attrs) { super(context, attrs); if(isInEditMode()) return; mContext = (FragmentActivity) context; } @SuppressLint("NewApi") public TabbedDetailView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = (FragmentActivity) context; } /* * Attach this view to a layout. */ public void setRoot(ViewGroup root) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.tabbed_detail_view, root, true); mMenu = (LinearLayout) root.findViewById(R.id.tabbed_detail_menu); mViewPager = (ViewPager) root.findViewById(R.id.tabbed_detail_pager); if(mAlternateId != -1) { mViewPager.setId(mAlternateId); } mViewPagerWrapper = root.findViewById(R.id.tabbed_detail_pager_wrapper); mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { markSelectedTab(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); } /* * Populate view with content from given Detail. */ public void setDetail(Detail detail) { Detail[] details = detail.getDetails(); LinearLayout.LayoutParams pagerLayout = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); int margin = 0; int menuVisibility = View.GONE; int backgroundColor = Color.TRANSPARENT; if (details.length > 0) { mMenu.setWeightSum(details.length); LinearLayout.LayoutParams fillLayout = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1 ); for (Detail d : details) { OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { int index = ((ViewGroup) v.getParent()).indexOfChild(v); mViewPager.setCurrentItem(index, true); markSelectedTab(index); } }; // Create MenuListEntryView for tab HorizontalMediaView view = new HorizontalMediaView(mContext); DisplayUnit title = d.getTitle(); Text text = title.getText(); Text audio = title.getAudioURI(); Text image = title.getImageURI(); view.setAVT(text == null ? null : text.evaluate(), audio == null ? null : audio.evaluate(), image == null ? null : image.evaluate()); view.setGravity(Gravity.CENTER); view.setClickable(true); view.setOnClickListener(listener); view.setBackgroundDrawable(getResources().getDrawable(R.drawable.title_neutral_tab_vertical)); mMenu.addView(view, fillLayout); } markSelectedTab(0); menuVisibility = View.VISIBLE; backgroundColor = mContext.getResources().getColor(R.color.yellow_green); margin = (int) getResources().getDimension(R.dimen.spacer); pagerLayout.setMargins(0, margin, margin, margin); } mMenu.setVisibility(menuVisibility); mViewPagerWrapper.setBackgroundColor(backgroundColor); pagerLayout.setMargins(0, margin, margin, margin); mViewPager.setLayoutParams(pagerLayout); } /* * Get form list from database and insert into view. */ public void refresh(Detail detail, TreeReference reference, int index, boolean hasDetailCalloutListener) { mEntityDetailPagerAdapter = new EntityDetailPagerAdapter(mContext.getSupportFragmentManager(), detail, index, reference, hasDetailCalloutListener, new DefaultEDVModifier() ); mViewPager.setAdapter(mEntityDetailPagerAdapter); markSelectedTab(0); } /* * Style one tab as "selected". */ private void markSelectedTab(int position) { if (mMenu.getChildCount() <= position) { return; } for (int i = 0; i < mMenu.getChildCount(); i++) { mMenu.getChildAt(i).setBackgroundDrawable(getResources().getDrawable(R.drawable.title_neutral_tab_vertical)); } mMenu.getChildAt(position).setBackgroundDrawable(getResources().getDrawable(R.drawable.title_case_tab_vertical)); } /** * Get the position of the current tab. * @return Zero-indexed integer */ public int getCurrentTab() { return mViewPager.getCurrentItem(); } /** * Get the number of tabs. * @return Integer */ public int getTabCount() { return mViewPager.getAdapter().getCount(); } //region Private classes private class DefaultEDVModifier implements EntityDetailAdapter.EntityDetailViewModifier, Parcelable { final int[] rowColors = AndroidUtil.getThemeColorIDs(getContext(), new int[]{R.attr.drawer_pulldown_even_row_color, R.attr.drawer_pulldown_odd_row_color}); public DefaultEDVModifier() { } @Override public void modifyEntityDetailView(EntityDetailView edv) { edv.setOddEvenRowColors(rowColors[0], rowColors[1]); } @Override public int describeContents() { return rowColors[0] ^ rowColors[1]; } @Override public void writeToParcel(Parcel dest, int flags) { } } //endregion }
app/src/org/commcare/android/view/TabbedDetailView.java
package org.commcare.android.view; import org.commcare.android.adapters.EntityDetailAdapter; import org.commcare.android.adapters.EntityDetailPagerAdapter; import org.commcare.android.util.AndroidUtil; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DisplayUnit; import org.commcare.suite.model.Text; import org.javarosa.core.model.instance.TreeReference; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import org.commcare.android.adapters.EntityDetailPagerAdapter; import org.commcare.dalvik.R; import org.commcare.suite.model.Detail; import org.commcare.suite.model.DisplayUnit; import org.javarosa.core.model.instance.TreeReference; /** * Widget that combines a ViewPager with a set of page titles styled to look like tabs. * User can navigate either by swiping through pages or by tapping the tabs. * @author jschweers * */ public class TabbedDetailView extends RelativeLayout { private FragmentActivity mContext; private LinearLayout mMenu; private EntityDetailPagerAdapter mEntityDetailPagerAdapter; private ViewPager mViewPager; private View mViewPagerWrapper; private int mAlternateId = -1; public TabbedDetailView(Context context) { this(context, -1); } /** * Create a tabbed detail view with a specific root pager ID * (this is necessary in any context where multiple detail views * will be used at once) * * @param context * @param alternateId */ public TabbedDetailView(Context context, int alternateId) { super(context); mContext = (FragmentActivity) context; this.mAlternateId = alternateId; } public TabbedDetailView(Context context, AttributeSet attrs) { super(context, attrs); mContext = (FragmentActivity) context; } @SuppressLint("NewApi") public TabbedDetailView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = (FragmentActivity) context; } /* * Attach this view to a layout. */ public void setRoot(ViewGroup root) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.tabbed_detail_view, root, true); mMenu = (LinearLayout) root.findViewById(R.id.tabbed_detail_menu); mViewPager = (ViewPager) root.findViewById(R.id.tabbed_detail_pager); if(mAlternateId != -1) { mViewPager.setId(mAlternateId); } mViewPagerWrapper = root.findViewById(R.id.tabbed_detail_pager_wrapper); mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { markSelectedTab(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); } /* * Populate view with content from given Detail. */ public void setDetail(Detail detail) { Detail[] details = detail.getDetails(); LinearLayout.LayoutParams pagerLayout = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); int margin = 0; int menuVisibility = View.GONE; int backgroundColor = Color.TRANSPARENT; if (details.length > 0) { mMenu.setWeightSum(details.length); LinearLayout.LayoutParams fillLayout = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1 ); for (Detail d : details) { OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { int index = ((ViewGroup) v.getParent()).indexOfChild(v); mViewPager.setCurrentItem(index, true); markSelectedTab(index); } }; // Create MenuListEntryView for tab HorizontalMediaView view = new HorizontalMediaView(mContext); DisplayUnit title = d.getTitle(); Text text = title.getText(); Text audio = title.getAudioURI(); Text image = title.getImageURI(); view.setAVT(text == null ? null : text.evaluate(), audio == null ? null : audio.evaluate(), image == null ? null : image.evaluate()); view.setGravity(Gravity.CENTER); view.setClickable(true); view.setOnClickListener(listener); view.setBackgroundDrawable(getResources().getDrawable(R.drawable.title_neutral_tab_vertical)); mMenu.addView(view, fillLayout); } markSelectedTab(0); menuVisibility = View.VISIBLE; backgroundColor = mContext.getResources().getColor(R.color.yellow_green); margin = (int) getResources().getDimension(R.dimen.spacer); pagerLayout.setMargins(0, margin, margin, margin); } mMenu.setVisibility(menuVisibility); mViewPagerWrapper.setBackgroundColor(backgroundColor); pagerLayout.setMargins(0, margin, margin, margin); mViewPager.setLayoutParams(pagerLayout); } /* * Get form list from database and insert into view. */ public void refresh(Detail detail, TreeReference reference, int index, boolean hasDetailCalloutListener) { mEntityDetailPagerAdapter = new EntityDetailPagerAdapter(mContext.getSupportFragmentManager(), detail, index, reference, hasDetailCalloutListener, new DefaultEDVModifier() ); mViewPager.setAdapter(mEntityDetailPagerAdapter); markSelectedTab(0); } /* * Style one tab as "selected". */ private void markSelectedTab(int position) { if (mMenu.getChildCount() <= position) { return; } for (int i = 0; i < mMenu.getChildCount(); i++) { mMenu.getChildAt(i).setBackgroundDrawable(getResources().getDrawable(R.drawable.title_neutral_tab_vertical)); } mMenu.getChildAt(position).setBackgroundDrawable(getResources().getDrawable(R.drawable.title_case_tab_vertical)); } /** * Get the position of the current tab. * @return Zero-indexed integer */ public int getCurrentTab() { return mViewPager.getCurrentItem(); } /** * Get the number of tabs. * @return Integer */ public int getTabCount() { return mViewPager.getAdapter().getCount(); } //region Private classes private class DefaultEDVModifier implements EntityDetailAdapter.EntityDetailViewModifier, Parcelable { final int[] rowColors = AndroidUtil.getThemeColorIDs(getContext(), new int[]{R.attr.drawer_pulldown_even_row_color, R.attr.drawer_pulldown_odd_row_color}); public DefaultEDVModifier() { } @Override public void modifyEntityDetailView(EntityDetailView edv) { edv.setOddEvenRowColors(rowColors[0], rowColors[1]); } @Override public int describeContents() { return rowColors[0] ^ rowColors[1]; } @Override public void writeToParcel(Parcel dest, int flags) { } } //endregion }
Making TabbedDetailView work in edit mode
app/src/org/commcare/android/view/TabbedDetailView.java
Making TabbedDetailView work in edit mode
<ide><path>pp/src/org/commcare/android/view/TabbedDetailView.java <ide> <ide> public TabbedDetailView(Context context, AttributeSet attrs) { <ide> super(context, attrs); <add> if(isInEditMode()) return; <ide> mContext = (FragmentActivity) context; <ide> } <ide>
Java
mit
4d5dd6ffd7b5ed87457d06935cf0be829aa47796
0
raoulvdberge/refinedstorage,way2muchnoise/refinedstorage,way2muchnoise/refinedstorage,raoulvdberge/refinedstorage
package storagecraft.tile; import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.BlockPos; import storagecraft.block.BlockMachine; import storagecraft.tile.settings.IRedstoneModeSetting; import storagecraft.tile.settings.RedstoneMode; public abstract class TileMachine extends TileBase implements INetworkTile, IRedstoneModeSetting { protected boolean connected = false; protected boolean redstoneControlled = true; private RedstoneMode redstoneMode = RedstoneMode.IGNORE; private BlockPos controllerPosition; private Block originalBlock; public void onConnected(TileController controller) { if (worldObj.getBlockState(pos).getBlock() == originalBlock) { markDirty(); connected = true; worldObj.setBlockState(pos, worldObj.getBlockState(pos).withProperty(BlockMachine.CONNECTED, true)); controllerPosition = controller.getPos(); } } public void onDisconnected() { if (worldObj.getBlockState(pos).getBlock() == originalBlock) { markDirty(); connected = false; worldObj.setBlockState(pos, worldObj.getBlockState(pos).withProperty(BlockMachine.CONNECTED, false)); } } @Override public void update() { if (ticks == 0) { originalBlock = worldObj.getBlockState(pos).getBlock(); } super.update(); if (!worldObj.isRemote && isConnected()) { updateMachine(); } } public boolean isConnected() { return connected; } @Override public RedstoneMode getRedstoneMode() { return redstoneMode; } @Override public void setRedstoneMode(RedstoneMode mode) { if (redstoneControlled) { markDirty(); this.redstoneMode = mode; } } @Override public BlockPos getMachinePos() { return pos; } @Override public BlockPos getTilePos() { return pos; } public TileController getController() { return (TileController) worldObj.getTileEntity(controllerPosition); } @Override public void fromBytes(ByteBuf buf) { boolean lastConnected = connected; connected = buf.readBoolean(); if (connected) { controllerPosition = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); } redstoneMode = RedstoneMode.getById(buf.readInt()); if (lastConnected != connected) { worldObj.markBlockForUpdate(pos); } } @Override public void toBytes(ByteBuf buf) { buf.writeBoolean(connected); if (connected) { buf.writeInt(controllerPosition.getX()); buf.writeInt(controllerPosition.getY()); buf.writeInt(controllerPosition.getZ()); } buf.writeInt(redstoneMode.id); } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); if (nbt.hasKey(RedstoneMode.NBT)) { redstoneMode = RedstoneMode.getById(nbt.getInteger(RedstoneMode.NBT)); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); nbt.setInteger(RedstoneMode.NBT, redstoneMode.id); } public abstract int getEnergyUsage(); public abstract void updateMachine(); }
src/main/java/storagecraft/tile/TileMachine.java
package storagecraft.tile; import io.netty.buffer.ByteBuf; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.BlockPos; import storagecraft.block.BlockMachine; import storagecraft.tile.settings.IRedstoneModeSetting; import storagecraft.tile.settings.RedstoneMode; public abstract class TileMachine extends TileBase implements INetworkTile, IRedstoneModeSetting { protected boolean connected = false; protected boolean redstoneControlled = true; private RedstoneMode redstoneMode = RedstoneMode.IGNORE; private BlockPos controllerPos; public void onConnected(TileController controller) { markDirty(); connected = true; controllerPos = controller.getPos(); worldObj.setBlockState(pos, worldObj.getBlockState(pos).withProperty(BlockMachine.CONNECTED, true)); } public void onDisconnected() { markDirty(); connected = false; if (!worldObj.isAirBlock(pos)) { worldObj.setBlockState(pos, worldObj.getBlockState(pos).withProperty(BlockMachine.CONNECTED, false)); } } @Override public void update() { super.update(); if (!worldObj.isRemote && isConnected()) { updateMachine(); } } public boolean isConnected() { return connected; } @Override public RedstoneMode getRedstoneMode() { return redstoneMode; } @Override public void setRedstoneMode(RedstoneMode mode) { if (redstoneControlled) { markDirty(); this.redstoneMode = mode; } } @Override public BlockPos getMachinePos() { return pos; } @Override public BlockPos getTilePos() { return pos; } public TileController getController() { return (TileController) worldObj.getTileEntity(controllerPos); } @Override public void fromBytes(ByteBuf buf) { boolean lastConnected = connected; connected = buf.readBoolean(); if (connected) { controllerPos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); } redstoneMode = RedstoneMode.getById(buf.readInt()); if (lastConnected != connected) { worldObj.markBlockForUpdate(pos); } } @Override public void toBytes(ByteBuf buf) { buf.writeBoolean(connected); if (connected) { buf.writeInt(controllerPos.getX()); buf.writeInt(controllerPos.getY()); buf.writeInt(controllerPos.getZ()); } buf.writeInt(redstoneMode.id); } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); if (nbt.hasKey(RedstoneMode.NBT)) { redstoneMode = RedstoneMode.getById(nbt.getInteger(RedstoneMode.NBT)); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); nbt.setInteger(RedstoneMode.NBT, redstoneMode.id); } public abstract int getEnergyUsage(); public abstract void updateMachine(); }
fix crash on explosion in machines
src/main/java/storagecraft/tile/TileMachine.java
fix crash on explosion in machines
<ide><path>rc/main/java/storagecraft/tile/TileMachine.java <ide> package storagecraft.tile; <ide> <ide> import io.netty.buffer.ByteBuf; <add>import net.minecraft.block.Block; <ide> import net.minecraft.nbt.NBTTagCompound; <ide> import net.minecraft.util.BlockPos; <ide> import storagecraft.block.BlockMachine; <ide> <ide> private RedstoneMode redstoneMode = RedstoneMode.IGNORE; <ide> <del> private BlockPos controllerPos; <add> private BlockPos controllerPosition; <add> <add> private Block originalBlock; <ide> <ide> public void onConnected(TileController controller) <ide> { <del> markDirty(); <add> if (worldObj.getBlockState(pos).getBlock() == originalBlock) <add> { <add> markDirty(); <ide> <del> connected = true; <add> connected = true; <ide> <del> controllerPos = controller.getPos(); <add> worldObj.setBlockState(pos, worldObj.getBlockState(pos).withProperty(BlockMachine.CONNECTED, true)); <ide> <del> worldObj.setBlockState(pos, worldObj.getBlockState(pos).withProperty(BlockMachine.CONNECTED, true)); <add> controllerPosition = controller.getPos(); <add> } <ide> } <ide> <ide> public void onDisconnected() <ide> { <del> markDirty(); <add> if (worldObj.getBlockState(pos).getBlock() == originalBlock) <add> { <add> markDirty(); <ide> <del> connected = false; <add> connected = false; <ide> <del> if (!worldObj.isAirBlock(pos)) <del> { <ide> worldObj.setBlockState(pos, worldObj.getBlockState(pos).withProperty(BlockMachine.CONNECTED, false)); <ide> } <ide> } <ide> @Override <ide> public void update() <ide> { <add> if (ticks == 0) <add> { <add> originalBlock = worldObj.getBlockState(pos).getBlock(); <add> } <add> <ide> super.update(); <ide> <ide> if (!worldObj.isRemote && isConnected()) <ide> <ide> public TileController getController() <ide> { <del> return (TileController) worldObj.getTileEntity(controllerPos); <add> return (TileController) worldObj.getTileEntity(controllerPosition); <ide> } <ide> <ide> @Override <ide> <ide> if (connected) <ide> { <del> controllerPos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); <add> controllerPosition = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); <ide> } <ide> <ide> redstoneMode = RedstoneMode.getById(buf.readInt()); <ide> <ide> if (connected) <ide> { <del> buf.writeInt(controllerPos.getX()); <del> buf.writeInt(controllerPos.getY()); <del> buf.writeInt(controllerPos.getZ()); <add> buf.writeInt(controllerPosition.getX()); <add> buf.writeInt(controllerPosition.getY()); <add> buf.writeInt(controllerPosition.getZ()); <ide> } <ide> <ide> buf.writeInt(redstoneMode.id);
Java
apache-2.0
4ecea30babfa89316b14965fd6399c77172ad1be
0
unprofessional/journowatch-spring-api-xml,unprofessional/journowatch-spring-api-xml
package com.devcru.journowatch.api.controllers; import com.devcru.journowatch.api.constants.Constants; import com.devcru.journowatch.api.objects.User; import com.devcru.journowatch.api.services.UserService; import freemarker.core.ParseException; import freemarker.template.Configuration; import freemarker.template.MalformedTemplateNameException; import freemarker.template.TemplateException; import freemarker.template.TemplateNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import static org.springframework.ui.freemarker.FreeMarkerTemplateUtils.processTemplateIntoString; import java.io.IOException; /** * Created by Monitored on 12/25/2015. * User Controller Class */ @Controller //@CrossOrigin(origins = "http://" + Constants.BASEURL_OPENSHIFT, methods={RequestMethod.PUT, RequestMethod.DELETE}) // use https:// when appropriate //@CrossOrigin(origins = {"http://journowatchwebclient-sjw.rhcloud.com/admin/portal#/user", // "http://journowatchwebclient-sjw.rhcloud.com"}, // methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS}, // allowedHeaders = "*") // use https:// when appropriate //@RequestMapping(value = "/user/*") @CrossOrigin public class UserController { @Autowired private UserService userServ; @Autowired private Configuration freemarkerConfiguration; /* * Sample landing page thing * Note that this is not REST by any means * This is a full-fledged MVC application */ @RequestMapping(value="/test", method=RequestMethod.GET) public @ResponseBody String getIndexView() throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException { System.out.println("MainController > test hit! Returning data..."); User user = new User(); user.setUsername("regular"); user.setPassword("password"); return processTemplateIntoString(freemarkerConfiguration.getTemplate("sample.ftl"), new Object()); } @RequestMapping(value="/", method=RequestMethod.POST) @ResponseBody public String createUser(@RequestBody User user) { String username = user.getUsername(); String email = user.getEmail(); String firstName = user.getFirstName(); String lastName = user.getLastName(); String role = user.getRole(); String password = user.getPassword(); System.out.println("UC > username: " + username); System.out.println("UC > email: " + email); System.out.println("UC > firstName: " + firstName); System.out.println("UC > lastName: " + lastName); System.out.println("UC > role: " + role); System.out.println("UC > password: " + password); boolean status = userServ.createUser(user); System.out.println("UC > status: " + status); return status + ""; } @RequestMapping(value="/{username}", method=RequestMethod.GET) @ResponseBody public User createUser(@PathVariable("username") String username) { User user = new User(); user.setUsername(username); user = userServ.getUser(user); //user.setUuid(userDao.getUuid(username)); return user; } @RequestMapping(value = "/{username}", method=RequestMethod.PUT) @ResponseBody public String updateUser(@PathVariable("username") String username, @RequestBody User user) { // Should we first associate the username with the JSON struct? // i.e. is there a data integrity risk here? Analyze further... //user.setUsername(username); boolean status = userServ.updateUser(user); return status + ""; // ???: return JsonResponse; } @RequestMapping(value = "/{username}", method=RequestMethod.DELETE) @ResponseBody public String deleteUser(@PathVariable("username") String username) { User user = new User(); user.setUsername(username); boolean status = userServ.deleteUser(user); return status + ""; // ??? return JsonResponse; } @ResponseStatus(value=HttpStatus.OK) // TODO: Test this to see if this gets sent along with a successful 200 OK public String okay() { System.out.println(">>>>>>>>>>>>>>>: OKAY!"); return "HPOASGBJHSJHDFGGJHSD"; } @ResponseStatus(value=HttpStatus.NOT_FOUND) public String notFound() { System.out.println(">>>>>>>>>>>>>>>: NOT FOUND!"); return "Yotsuba!!"; } @RequestMapping(value="login", method=RequestMethod.POST) public static Object logTheFuckIn(User user) { // TODO: boolean status = userServ.logTheFuckIn(user); return null; } }
src/main/java/com/devcru/journowatch/api/controllers/UserController.java
package com.devcru.journowatch.api.controllers; import com.devcru.journowatch.api.constants.Constants; import com.devcru.journowatch.api.objects.User; import com.devcru.journowatch.api.services.UserService; import freemarker.core.ParseException; import freemarker.template.Configuration; import freemarker.template.MalformedTemplateNameException; import freemarker.template.TemplateException; import freemarker.template.TemplateNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import static org.springframework.ui.freemarker.FreeMarkerTemplateUtils.processTemplateIntoString; import java.io.IOException; /** * Created by Monitored on 12/25/2015. * User Controller Class */ @Controller //@CrossOrigin(origins = "http://" + Constants.BASEURL_OPENSHIFT, methods={RequestMethod.PUT, RequestMethod.DELETE}) // use https:// when appropriate @CrossOrigin(origins = {"http://journowatchwebclient-sjw.rhcloud.com/admin/portal#/user", "http://journowatchwebclient-sjw.rhcloud.com"}, methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS}, allowedHeaders = "*") // use https:// when appropriate @RequestMapping(value = "/user/*") public class UserController { @Autowired private UserService userServ; @Autowired private Configuration freemarkerConfiguration; /* * Sample landing page thing * Note that this is not REST by any means * This is a full-fledged MVC application */ @RequestMapping(value="/test", method=RequestMethod.GET) public @ResponseBody String getIndexView() throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException { System.out.println("MainController > test hit! Returning data..."); User user = new User(); user.setUsername("regular"); user.setPassword("password"); return processTemplateIntoString(freemarkerConfiguration.getTemplate("sample.ftl"), new Object()); } @RequestMapping(value="/", method=RequestMethod.POST) @ResponseBody public String createUser(@RequestBody User user) { String username = user.getUsername(); String email = user.getEmail(); String firstName = user.getFirstName(); String lastName = user.getLastName(); String role = user.getRole(); String password = user.getPassword(); System.out.println("UC > username: " + username); System.out.println("UC > email: " + email); System.out.println("UC > firstName: " + firstName); System.out.println("UC > lastName: " + lastName); System.out.println("UC > role: " + role); System.out.println("UC > password: " + password); boolean status = userServ.createUser(user); System.out.println("UC > status: " + status); return status + ""; } @RequestMapping(value="/{username}", method=RequestMethod.GET) @ResponseBody public User createUser(@PathVariable("username") String username) { User user = new User(); user.setUsername(username); user = userServ.getUser(user); //user.setUuid(userDao.getUuid(username)); return user; } @RequestMapping(value = "/{username}", method=RequestMethod.PUT) @ResponseBody public String updateUser(@PathVariable("username") String username, @RequestBody User user) { // Should we first associate the username with the JSON struct? // i.e. is there a data integrity risk here? Analyze further... //user.setUsername(username); boolean status = userServ.updateUser(user); return status + ""; // ???: return JsonResponse; } @RequestMapping(value = "/{username}", method=RequestMethod.DELETE) @ResponseBody public String deleteUser(@PathVariable("username") String username) { User user = new User(); user.setUsername(username); boolean status = userServ.deleteUser(user); return status + ""; // ??? return JsonResponse; } @ResponseStatus(value=HttpStatus.OK) // TODO: Test this to see if this gets sent along with a successful 200 OK public String okay() { System.out.println(">>>>>>>>>>>>>>>: OKAY!"); return "HPOASGBJHSJHDFGGJHSD"; } @ResponseStatus(value=HttpStatus.NOT_FOUND) public String notFound() { System.out.println(">>>>>>>>>>>>>>>: NOT FOUND!"); return "Yotsuba!!"; } @RequestMapping(value="login", method=RequestMethod.POST) public static Object logTheFuckIn(User user) { // TODO: boolean status = userServ.logTheFuckIn(user); return null; } }
Add basic CORS in UserController 7
src/main/java/com/devcru/journowatch/api/controllers/UserController.java
Add basic CORS in UserController 7
<ide><path>rc/main/java/com/devcru/journowatch/api/controllers/UserController.java <ide> <ide> @Controller <ide> //@CrossOrigin(origins = "http://" + Constants.BASEURL_OPENSHIFT, methods={RequestMethod.PUT, RequestMethod.DELETE}) // use https:// when appropriate <del>@CrossOrigin(origins = {"http://journowatchwebclient-sjw.rhcloud.com/admin/portal#/user", <del> "http://journowatchwebclient-sjw.rhcloud.com"}, <del> methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS}, <del> allowedHeaders = "*") // use https:// when appropriate <del>@RequestMapping(value = "/user/*") <add>//@CrossOrigin(origins = {"http://journowatchwebclient-sjw.rhcloud.com/admin/portal#/user", <add>// "http://journowatchwebclient-sjw.rhcloud.com"}, <add>// methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS}, <add>// allowedHeaders = "*") // use https:// when appropriate <add>//@RequestMapping(value = "/user/*") <add>@CrossOrigin <ide> public class UserController { <ide> <ide> @Autowired
Java
mit
3161aff2ae6624145d4462b52c6adb4fc52d7751
0
JosueDanielBust/EventsManagerSoftware
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Mundo; /** * * @author Julian */ public class Ticket { public Ticket(){} public static String preguntaPersona(){ return " AND ticket.PERSON_ID = = "+Person.getPERSON_ID(); } public static String preguntaCategoria(){ return (" AND EVENT_CATEGORY.ECATEGORY = "+ Event.getCategoria()); } public static String preguntaEname(){ return (" AND event_type.etype_name = "+ Event.getEname()); } //tipos de eventos que tienen boletas con este usuario public static String buscarCategorias(){ return ("SELECT ec.ecategory " + " from EVENT_CATEGORY ec "+ " inner join EVENT_TYPE et on ec.ecategory_id = et.ecategory_id" + " inner join event ev on ev.etype_id = et.etype_id" + " inner join ticket_type tt on ev.event_id = tt.event_id" + " inner join ticket tc on tc.ttype_id = tt.ttype_id" + preguntaPersona()); } //Segun la categoria de arriba me trae las ciudades public static String buscarCiudades(){ return ("select city_name " + "from city " + "inner join place on city.city_id = place.city_id " + "inner join event on event.place_id = place.place_id " + "inner join event_type on event.ETYPE_ID = event_type.ETYPE_ID " + "INNER JOIN EVENT_CATEGORY ON event_type.ECATEGORY_ID = EVENT_CATEGORY.ECATEGORY_ID " + preguntaCategoria()+ " INNER JOIN TICKET_TYPE ON TICKET_TYPE.EVENT_ID = event.EVENT_ID " + "INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID " + preguntaPersona()); } //buscamos los eventos en esa ciudad public static String buscarEventos(String ciudad){ return("select ETYPE_NAME from event_type " + "inner join event on event.etype_id = event_type.etype_id " + "inner join place on event.place_id = place.place_id " + "inner join city on place.city_id = city.city_id " + " INNER JOIN TICKET_TYPE ON TICKET_TYPE.EVENT_ID = event.EVENT_ID " + "INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID " + preguntaPersona() + " AND city.city_name = "+ ciudad + preguntaCategoria()); } //revisar este!! //mostramos la fecha y hora del evento seleccionado public static String buscarFecha(String ciudad){ return ("select DATE_HOUR from event" + "inner join event_type on event.etype_id = event_type.etype_id " + " INNER JOIN TICKET_TYPE ON TICKET_TYPE.EVENT_ID = event.EVENT_ID " + "INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID " + preguntaPersona() + " AND city.city_name = "+ ciudad + preguntaEname() + preguntaCategoria()); } //mostrar el lugar del evento que se realiza en esa fecha public static String buscarLugar(String fecha,String ciudad){ return ("inner join event on event.place_id = place.place_id " + "and event.DATE_HOUR = "+fecha + " INNER JOIN TICKET_TYPE ON TICKET_TYPE.EVENT_ID = event.EVENT_ID " + "INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID " + preguntaPersona() + " AND city.city_name = "+ ciudad + preguntaEname()+ preguntaCategoria()); } //PROBAR ESTE CODIGO //boletas compradas para el evento con dicha descripción anterior public static String buscarBoletas(String lugar,String fecha,String ciudad){ return("SELECT tick_type,ttype_cost" + " FROM ticket_type " + " INNER JOIN event ON TICKET_TYPE.EVENT_ID = event.EVENT_ID" + " INNER JOIN place ON event.place_id = place.place_id" + " AND place.place_name = "+ lugar + " INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID" + preguntaPersona() + " AND city.city_name = "+ ciudad + preguntaEname() + preguntaCategoria()); } public static String buscarEventId(String ciudad,String fecha,String lugar){ return ("SELECT event_id "+ "from event e " + "inner join place p on p.place_id = p.place_id " + "inner join city c on c.city_id = c.city_id " + "inner join event_type et on et.etype_id = e.etype_id " + "AND c.city_name = " + ciudad + preguntaEname()+ " AND e.date_hour = "+ fecha + " And p.place_name = "+ lugar); } }
EVS/src/Mundo/Ticket.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Mundo; /** * * @author Julian */ public class Ticket { public Ticket(){} public static String preguntaPersona(){ return " AND ticket.PERSON_ID = = "+Person.getPERSON_ID(); } public static String preguntaCategoria(){ return (" AND EVENT_CATEGORY.ECATEGORY = "+ Event.getCategoria()); } public static String preguntaEname(){ return (" AND event_type.etype_name = "+ Event.getEname()); } //tipos de eventos que tienen boletas con este usuario public static String buscarCategorias(){ return ("SELECT ec.ecategory " + " from EVENT_CATEGORY ec "+ " inner join EVENT_TYPE et on ec.ecategory_id = et.ecategory_id" + " inner join event ev on ev.etype_id = et.etype_id" + " inner join ticket_type tt on ev.event_id = tt.event_id" + " inner join ticket tc on tc.ttype_id = tt.ttype_id" + preguntaPersona()); } //Segun la categoria de arriba me trae las ciudades public static String buscarCiudades(){ return ("select city_name " + "from city " + "inner join place on city.city_id = place.city_id " + "inner join event on event.place_id = place.place_id " + "inner join event_type on event.ETYPE_ID = event_type.ETYPE_ID " + "INNER JOIN EVENT_CATEGORY ON event_type.ECATEGORY_ID = EVENT_CATEGORY.ECATEGORY_ID " + preguntaCategoria()+ " INNER JOIN TICKET_TYPE ON TICKET_TYPE.EVENT_ID = event.EVENT_ID " + "INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID " + preguntaPersona()); } //buscamos los eventos en esa ciudad public static String buscarEventos(String ciudad){ return("select ETYPE_NAME from event_type " + "inner join event on event.etype_id = event_type.etype_id " + "inner join place on event.place_id = place.place_id " + "inner join city on place.city_id = city.city_id " + " INNER JOIN TICKET_TYPE ON TICKET_TYPE.EVENT_ID = event.EVENT_ID " + "INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID " + preguntaPersona() + " AND city.city_name = "+ ciudad + preguntaCategoria()); } //revisar este!! //mostramos la fecha y hora del evento seleccionado public static String buscarFecha(String ciudad){ return ("select DATE_HOUR from event" + "inner join event_type on event.etype_id = event_type.etype_id " + " INNER JOIN TICKET_TYPE ON TICKET_TYPE.EVENT_ID = event.EVENT_ID " + "INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID " + preguntaPersona() + " AND city.city_name = "+ ciudad + preguntaEname() + preguntaCategoria()); } //mostrar el lugar del evento que se realiza en esa fecha public static String buscarLugar(String fecha,String ciudad){ return ("inner join event on event.place_id = place.place_id " + "and event.DATE_HOUR = "+fecha + " INNER JOIN TICKET_TYPE ON TICKET_TYPE.EVENT_ID = event.EVENT_ID " + "INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID " + preguntaPersona() + " AND city.city_name = "+ ciudad + preguntaEname()+ preguntaCategoria()); } //PROBAR ESTE CODIGO //boletas compradas para el evento con dicha descripción anterior public static String buscarBoletas(String lugar,String fecha,String ciudad){ return("SELECT DISTINCT tick_type,ttype_cost,count(TICKET_ID)" + " FROM ticket_type " + " INNER JOIN event ON TICKET_TYPE.EVENT_ID = event.EVENT_ID" + " INNER JOIN place ON event.place_id = place.place_id" + " AND place.place_name = "+ lugar + " INNER JOIN TICKET ON TICKET.TTYPE_ID = TICKET_TYPE.TTYPE_ID" + preguntaPersona() + " AND city.city_name = "+ ciudad + preguntaEname() + preguntaCategoria() + " GROUP BY tick_type "); } public static String buscarEventId(String ciudad,String fecha,String lugar){ return ("SELECT event_id "+ "from event e " + "inner join place p on p.place_id = p.place_id " + "inner join city c on c.city_id = c.city_id " + "inner join event_type et on et.etype_id = e.etype_id " + "AND c.city_name = " + ciudad + preguntaEname()+ " AND e.date_hour = "+ fecha + " And p.place_name = "+ lugar); } }
Corrigiendo interfaces
EVS/src/Mundo/Ticket.java
Corrigiendo interfaces
<ide><path>VS/src/Mundo/Ticket.java <ide> <ide> //boletas compradas para el evento con dicha descripción anterior <ide> public static String buscarBoletas(String lugar,String fecha,String ciudad){ <del> return("SELECT DISTINCT tick_type,ttype_cost,count(TICKET_ID)" + <add> return("SELECT tick_type,ttype_cost" + <ide> " FROM ticket_type " + <ide> " INNER JOIN event ON TICKET_TYPE.EVENT_ID = event.EVENT_ID" + <ide> " INNER JOIN place ON event.place_id = place.place_id" + <ide> preguntaPersona() + <ide> " AND city.city_name = "+ ciudad + <ide> preguntaEname() + <del> preguntaCategoria() + <del> " GROUP BY tick_type "); <add> preguntaCategoria()); <ide> <ide> } <ide>
JavaScript
bsd-3-clause
344055b761dd3fc02aa402f192ca11b62fd6b9f4
0
0u812/nteract,nteract/composition,rgbkrk/nteract,nteract/composition,jdfreder/nteract,rgbkrk/nteract,jdetle/nteract,jdetle/nteract,temogen/nteract,rgbkrk/nteract,captainsafia/nteract,rgbkrk/nteract,nteract/nteract,nteract/nteract,jdfreder/nteract,0u812/nteract,temogen/nteract,rgbkrk/nteract,captainsafia/nteract,nteract/nteract,0u812/nteract,jdetle/nteract,temogen/nteract,captainsafia/nteract,jdfreder/nteract,0u812/nteract,nteract/nteract,captainsafia/nteract,nteract/composition,nteract/nteract,jdfreder/nteract,jdetle/nteract
import React from 'react'; import Immutable from 'immutable'; import { Provider } from 'react-redux'; import { shallow, mount, render } from 'enzyme'; import { displayOrder, transforms } from '../../../src/notebook/components/transforms'; const TestBackend = require('react-dnd-test-backend'); import { DragDropContext } from 'react-dnd'; import Cell from '../../../src/notebook/components/cell/cell'; const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require("sinon-chai"); chai.use(sinonChai); const expect = chai.expect; import { dummyStore } from '../../utils'; import { dummyCommutable, } from '../dummy-nb'; const dummyCellStatuses = dummyCommutable.get('cellOrder') .reduce((statuses, cellID) => statuses.set(cellID, Immutable.fromJS({ outputHidden: false, inputHidden: false })), new Immutable.Map()); import { Notebook, ConnectedNotebook, getLanguageMode, scrollToElement } from '../../../src/notebook/components/notebook'; // Boilerplate test to make sure the testing setup is configured describe('Notebook', () => { it('accepts an Immutable.List of cells', () => { const component = shallow( <Notebook notebook={dummyCommutable} transient={new Immutable.Map({cellMap: new Immutable.Map()})} cellPagers={new Immutable.Map()} cellStatuses={new Immutable.Map()} stickyCells={(new Immutable.Map()) // Sticky the first cell of the notebook so that the sticky code gets // triggered. .set(dummyCommutable.getIn(['cellOrder', 0]), true) } CellComponent={Cell} /> ); expect(component).to.not.be.null; }); it('implements the correct css spec', () => { const component = mount( <Provider store={dummyStore()}> <Notebook notebook={dummyCommutable} transient={new Immutable.Map({cellMap: new Immutable.Map()})} cellPagers={new Immutable.Map()} cellStatuses={dummyCellStatuses} stickyCells={new Immutable.Map()} displayOrder={displayOrder.delete('text/html')} transforms={transforms.delete('text/html')} CellComponent={Cell} /> </Provider> ); expect(component.find('.notebook').length).to.be.above(0, '.notebook'); expect(component.find('.notebook .cell').length).to.be.above(0, '.notebook .cell'); expect(component.find('.notebook .cell.text').length).to.be.above(0, '.notebook .cell.text'); expect(component.find('.notebook .cell.code').length).to.be.above(0, '.notebook .cell.code'); expect(component.find('.notebook .cell.unknown').length).to.equal(0, '.notebook .cell.unknown does not exist'); expect(component.find('.notebook .cell.text .rendered').length).to.be.above(0, '.notebook .cell.text .rendered'); expect(component.find('.notebook .cell.code .input-container').length).to.be.above(0, '.notebook .cell.code .input-container'); expect(component.find('.notebook .cell.code .input-container .prompt').length).to.be.above(0, '.notebook .cell.code .input-container .prompt'); expect(component.find('.notebook .cell.code .input-container .input').length).to.be.above(0, '.notebook .cell.code .input-container .input'); expect(component.find('.notebook .cell.code .outputs').length).to.be.above(0, '.notebook .cell.code .outputs'); }); describe('getLanguageMode', () => { it('determines the right language from the notebook metadata', () => { const lang = getLanguageMode(dummyCommutable); expect(lang).to.equal('ipython'); const lang2 = getLanguageMode(dummyCommutable.setIn(['metadata', 'language_info', 'codemirror_mode', 'name'], 'r')) expect(lang2).to.equal('r'); }); }); describe('keyDown', () => { it('detects a cell execution keypress', () => { const focusedCell = dummyCommutable.getIn(['cellOrder', 1]); const context = { store: dummyStore(), } context.store.dispatch = sinon.spy(); const component = shallow( <Notebook notebook={dummyCommutable} transient={new Immutable.Map({cellMap: new Immutable.Map()})} cellPagers={new Immutable.Map()} cellStatuses={dummyCellStatuses} stickyCells={(new Immutable.Map())} CellComponent={Cell} cellFocused={focusedCell} />, { context }); const inst = component.instance(); const evt = new window.CustomEvent('keydown'); evt.ctrlKey = true; evt.keyCode = 13; inst.keyDown(evt); expect(context.store.dispatch.firstCall).to.have.been.calledWith({ type: 'EXECUTE_CELL', id: focusedCell, source: dummyCommutable.getIn(['cellMap', focusedCell, 'source']) }); }); it('detects a focus to next cell keypress', () => { const focusedCell = dummyCommutable.getIn(['cellOrder', 1]); const context = { store: dummyStore(), } context.store.dispatch = sinon.spy(); const component = shallow( <Notebook notebook={dummyCommutable} transient={new Immutable.Map({cellMap: new Immutable.Map()})} cellPagers={new Immutable.Map()} cellStatuses={dummyCellStatuses} stickyCells={(new Immutable.Map())} CellComponent={Cell} cellFocused={focusedCell} />, { context }); const inst = component.instance(); const evt = new window.CustomEvent('keydown'); evt.shiftKey = true; evt.keyCode = 13; inst.keyDown(evt); expect(context.store.dispatch.firstCall).to.have.been.calledWith({ type: 'FOCUS_NEXT_CELL', id: focusedCell, createCellIfUndefined: true, }); }); }); });
test/renderer/components/notebook-spec.js
import React from 'react'; import Immutable from 'immutable'; import { Provider } from 'react-redux'; import { shallow, mount, render } from 'enzyme'; import { displayOrder, transforms } from '../../../src/notebook/components/transforms'; const TestBackend = require('react-dnd-test-backend'); import { DragDropContext } from 'react-dnd'; import Cell from '../../../src/notebook/components/cell/cell'; const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require("sinon-chai"); chai.use(sinonChai); const expect = chai.expect; import { dummyStore } from '../../utils'; import { dummyCommutable, } from '../dummy-nb'; const dummyCellStatuses = dummyCommutable.get('cellOrder') .reduce((statuses, cellID) => statuses.set(cellID, Immutable.fromJS({ outputHidden: false, inputHidden: false })), new Immutable.Map()); import { Notebook, ConnectedNotebook, getLanguageMode, scrollToElement } from '../../../src/notebook/components/notebook'; // Boilerplate test to make sure the testing setup is configured describe('Notebook', () => { it('accepts an Immutable.List of cells', () => { const component = shallow( <Notebook notebook={dummyCommutable} transient={new Immutable.Map({cellMap: new Immutable.Map()})} cellPagers={new Immutable.Map()} cellStatuses={new Immutable.Map()} stickyCells={(new Immutable.Map()) // Sticky the first cell of the notebook so that the sticky code gets // triggered. .set(dummyCommutable.getIn(['cellOrder', 0]), true) } CellComponent={Cell} /> ); expect(component).to.not.be.null; }); it('implements the correct css spec', () => { const component = mount( <Provider store={dummyStore()}> <Notebook notebook={dummyCommutable} transient={new Immutable.Map({cellMap: new Immutable.Map()})} cellPagers={new Immutable.Map()} cellStatuses={dummyCellStatuses} stickyCells={new Immutable.Map()} displayOrder={displayOrder.delete('text/html')} transforms={transforms.delete('text/html')} CellComponent={Cell} /> </Provider> ); expect(component.find('.notebook').length).to.be.above(0, '.notebook'); expect(component.find('.notebook .cell').length).to.be.above(0, '.notebook .cell'); expect(component.find('.notebook .cell.text').length).to.be.above(0, '.notebook .cell.text'); expect(component.find('.notebook .cell.code').length).to.be.above(0, '.notebook .cell.code'); expect(component.find('.notebook .cell.unknown').length).to.equal(0, '.notebook .cell.unknown does not exist'); expect(component.find('.notebook .cell.text .rendered').length).to.be.above(0, '.notebook .cell.text .rendered'); expect(component.find('.notebook .cell.code .input-container').length).to.be.above(0, '.notebook .cell.code .input-container'); expect(component.find('.notebook .cell.code .input-container .prompt').length).to.be.above(0, '.notebook .cell.code .input-container .prompt'); expect(component.find('.notebook .cell.code .input-container .input').length).to.be.above(0, '.notebook .cell.code .input-container .input'); expect(component.find('.notebook .cell.code .outputs').length).to.be.above(0, '.notebook .cell.code .outputs'); }); describe('getLanguageMode', () => { it('determines the right language from the notebook metadata', () => { const lang = getLanguageMode(dummyCommutable); expect(lang).to.equal('ipython'); const lang2 = getLanguageMode(dummyCommutable.setIn(['metadata', 'language_info', 'codemirror_mode', 'name'], 'r')) expect(lang2).to.equal('r'); }); }); describe('keyDown', () => { it('detects a cell execution keypress', () => { const focusedCell = dummyCommutable.getIn(['cellOrder', 1]); const context = { store: dummyStore(), } context.store.dispatch = sinon.spy(); const component = shallow( <Notebook notebook={dummyCommutable} transient={new Immutable.Map({cellMap: new Immutable.Map()})} cellPagers={new Immutable.Map()} cellStatuses={dummyCellStatuses} stickyCells={(new Immutable.Map())} CellComponent={Cell} cellFocused={focusedCell} />, { context }); const inst = component.instance(); const evt = new window.CustomEvent('keydown'); evt.ctrlKey = true; evt.keyCode = 13; inst.keyDown(evt); expect(context.store.dispatch.firstCall).to.have.been.calledWith({ type: 'EXECUTE_CELL', id: focusedCell, source: dummyCommutable.getIn(['cellMap', focusedCell, 'source']) }); }); it('detects a focus to next cell keypress', () => { const focusedCell = dummyCommutable.getIn(['cellOrder', 1]); const context = { store: dummyStore(), } context.store.dispatch = sinon.spy(); const component = shallow( <Notebook notebook={dummyCommutable} transient={new Immutable.Map({cellMap: new Immutable.Map()})} cellPagers={new Immutable.Map()} cellStatuses={dummyCellStatuses} stickyCells={(new Immutable.Map())} CellComponent={Cell} cellFocused={focusedCell} />, { context }); const inst = component.instance(); const evt = new window.CustomEvent('keydown'); evt.shiftKey = true; evt.keyCode = 13; inst.keyDown(evt); expect(context.store.dispatch.firstCall).to.have.been.calledWith({ type: 'FOCUS_NEXT_CELL', id: focusedCell, createCellIfUndefined: true, }); }); }); }); describe('Notebook DnD', () => { it('drag and drop can be tested', () => { const TestNotebook = DragDropContext(TestBackend)(Notebook); const component = mount( <Provider store={dummyStore()}> <TestNotebook className='test' notebook={dummyCommutable} transient={new Immutable.Map({cellMap: new Immutable.Map()})} cellPagers={new Immutable.Map()} cellStatuses={dummyCellStatuses} stickyCells={(new Immutable.Map())} /> </Provider> ); console.log(component.find(DragDropContext).debug()) const manager = component.find(DragDropContext).get(0).getManager(); const backend = manager.getBackend(); // TODO: Write tests for cell drag and drop }) })
refactor(test): Remove DnD test until it can be improved
test/renderer/components/notebook-spec.js
refactor(test): Remove DnD test until it can be improved
<ide><path>est/renderer/components/notebook-spec.js <ide> }); <ide> }); <ide> }); <del> <del>describe('Notebook DnD', () => { <del> it('drag and drop can be tested', () => { <del> const TestNotebook = DragDropContext(TestBackend)(Notebook); <del> <del> const component = mount( <del> <Provider store={dummyStore()}> <del> <TestNotebook <del> className='test' <del> notebook={dummyCommutable} <del> transient={new Immutable.Map({cellMap: new Immutable.Map()})} <del> cellPagers={new Immutable.Map()} <del> cellStatuses={dummyCellStatuses} <del> stickyCells={(new Immutable.Map())} <del> /> <del> </Provider> <del> ); <del> <del> console.log(component.find(DragDropContext).debug()) <del> <del> const manager = component.find(DragDropContext).get(0).getManager(); <del> const backend = manager.getBackend(); <del> <del> // TODO: Write tests for cell drag and drop <del> }) <del>})
Java
apache-2.0
d39c90d2e4e431a01ff4561897911bd070b650e4
0
kHRYSTAL/Leonids,Volcanoscar/Leonids,Mybrc91/Leonids,Coder-leilei/Leonids,vaavaa/Leonids,tieusangaka/Leonids,aaaliua/Leonids,hanhailong/Leonids,plattysoft/Leonids,Juneor/Leonids,azizjonm/Leonids
package com.plattysoft.leonids.initializers; import java.util.Random; import com.plattysoft.leonids.Particle; public class SpeeddModuleAndRangeInitializer implements ParticleInitializer { private float mSpeedMin; private float mSpeedMax; private int mMinAngle; private int mMaxAngle; public SpeeddModuleAndRangeInitializer(float speedMin, float speedMax, int minAngle, int maxAngle) { mSpeedMin = speedMin; mSpeedMax = speedMax; mMinAngle = minAngle; mMaxAngle = maxAngle; // Make sure the angles are in the [0-360) range while (mMinAngle < 0) { mMinAngle+=360; } while (mMaxAngle < 0) { mMaxAngle+=360; } // Also make sure that mMinAngle is the smaller if (mMinAngle > mMaxAngle) { int tmp = mMinAngle; mMinAngle = mMaxAngle; mMaxAngle = tmp; } } @Override public void initParticle(Particle p, Random r) { float speed = r.nextFloat()*(mSpeedMax-mSpeedMin) + mSpeedMin; int angle; if (mMaxAngle == mMinAngle) { angle = mMinAngle; } else { angle = r.nextInt(mMaxAngle - mMinAngle) + mMinAngle; } float angleInRads = (float) (angle*Math.PI/180f); p.mSpeedX = (float) (speed * Math.cos(angleInRads)); p.mSpeedY = (float) (speed * Math.sin(angleInRads)); } }
LeonidasLib/src/com/plattysoft/leonids/initializers/SpeeddModuleAndRangeInitializer.java
package com.plattysoft.leonids.initializers; import java.util.Random; import com.plattysoft.leonids.Particle; public class SpeeddModuleAndRangeInitializer implements ParticleInitializer { private float mSpeedMin; private float mSpeedMax; private int mMinAngle; private int mMaxAngle; public SpeeddModuleAndRangeInitializer(float speedMin, float speedMax, int minAngle, int maxAngle) { mSpeedMin = speedMin; mSpeedMax = speedMax; mMinAngle = minAngle; mMaxAngle = maxAngle; // Make sure the angles are in the [0-360) range while (mMinAngle < 0) { mMinAngle+=360; } mMinAngle = mMinAngle%360; while (mMaxAngle < 0) { mMaxAngle+=360; } mMaxAngle = mMaxAngle%360; // Also make sure that mMinAngle is the smaller if (mMinAngle > mMaxAngle) { int tmp = mMinAngle; mMinAngle = mMaxAngle; mMaxAngle = tmp; } } @Override public void initParticle(Particle p, Random r) { float speed = r.nextFloat()*(mSpeedMax-mSpeedMin) + mSpeedMin; int angle; if (mMaxAngle == mMinAngle) { angle = mMinAngle; } else { angle = r.nextInt(mMaxAngle - mMinAngle) + mMinAngle; } float angleInRads = (float) (angle*Math.PI/180f); p.mSpeedX = (float) (speed * Math.cos(angleInRads)); p.mSpeedY = (float) (speed * Math.sin(angleInRads)); } }
removing commented out code
LeonidasLib/src/com/plattysoft/leonids/initializers/SpeeddModuleAndRangeInitializer.java
removing commented out code
<ide><path>eonidasLib/src/com/plattysoft/leonids/initializers/SpeeddModuleAndRangeInitializer.java <ide> while (mMinAngle < 0) { <ide> mMinAngle+=360; <ide> } <del> mMinAngle = mMinAngle%360; <ide> while (mMaxAngle < 0) { <ide> mMaxAngle+=360; <ide> } <del> mMaxAngle = mMaxAngle%360; <ide> // Also make sure that mMinAngle is the smaller <ide> if (mMinAngle > mMaxAngle) { <ide> int tmp = mMinAngle;
JavaScript
apache-2.0
30fe5e22c1b5b2ca167f5606e8a2c8e2ab79921c
0
OpenBEL/belhop,OpenBEL/belhop,OpenBEL/belhop
/** * @file BELHop JavaScript library. * @author OpenBEL Committers * @license Apache-2.0 */ (function() { 'use strict'; var root = this; var _defaultAPIURL = 'http://next.belframework.org/api'; var _defaultSchemaURL = 'http://next.belframework.org/schema'; function _invalid() { var x, i; for (i = 0; i < arguments.length; i++) { x = arguments[i]; if (typeof x === 'undefined' || x === null) { return true; } } return false; } function _valid() { var x, i; for (i = 0; i < arguments.length; i++) { x = arguments[i]; if (typeof x === 'undefined' || x === null) { return false; } } return true; } function _ex(message, args) { return { message: message, args: args }; } // declare globals not recognized by eslint /* global module */ /* global $ */ /** * The BELHop module. * @exports belhop * @namespace belhop * @author Nick Bargnesi <[email protected]> * @version 0.1.0 */ var belhop = {}; if (typeof module !== 'undefined' && module.exports) { module.exports = belhop; } else { root.belhop = belhop; } /** * @name DEFAULT_API_URL * @readonly * @type {string} * @default */ Object.defineProperty(belhop, 'DEFAULT_API_URL', { get: function() { return _defaultAPIURL; } }); /** * @name DEFAULT_SCHEMA_URL * @readonly * @type {string} * @default */ Object.defineProperty(belhop, 'DEFAULT_SCHEMA_URL', { get: function() { return _defaultSchemaURL; } }); /** * @name VERSION * @readonly * @type {string} * @default */ Object.defineProperty(belhop, 'VERSION', { get: function() { return '0.1.0'; } }); /* * The options hash can handle a queryParams key. */ function apiGET(path, cb, options) { var url = belhop.configuration.getAPIURL(); // append the path path = encodeURI(path); url += path; // setup the options to our AJAX get var defaultOptions = { queryParams: null }; var argOptions = $.extend(defaultOptions, options || {}); if (argOptions.queryParams !== null) { // append query parameters url += '?' + argOptions.queryParams; } var ajaxOptions = { url: url, success: cb.success, error: cb.error }; $.ajax(ajaxOptions); } /* * The options hash can handle queryParams and contentType keys. */ function apiPOST(path, data, cb, options) { var url = belhop.configuration.getAPIURL(); // append the path path = encodeURI(path); url += path; // setup the options to our AJAX post var defaultOptions = { queryParams: null, contentType: null }; var argOptions = $.extend(defaultOptions, options || {}); if (argOptions.queryParams !== null) { // append query parameters url += '?' + argOptions.queryParams; } var ajaxOptions = { type: 'POST', url: url, data: data, success: cb.success, error: cb.error }; if (argOptions.contentType !== null) { ajaxOptions.contentType = argOptions.contentType; } $.ajax(ajaxOptions); } /* */ function apiDELETE(path, cb) { var url = belhop.configuration.getAPIURL(); // append the path path = encodeURI(path); url += path; var ajaxOptions = { type: 'DELETE', url: url, success: cb.success, error: cb.error }; $.ajax(ajaxOptions); } /** * @namespace belhop.configuration */ belhop.configuration = {}; /** * Get the current API URL. * * @function * @name belhop.configuration.getAPIURL * * @example * > belhop.configuration.getAPIURL() * 'http://next.belframework.org/api' * * @return {string} Current API URL */ belhop.configuration.getAPIURL = function() { var url = belhop.currentAPIURL; if (typeof url === 'undefined' || url === null) { return belhop.DEFAULT_API_URL; } return belhop.currentAPIURL; }; /** * Set the API URL. * * @function * @name belhop.configuration.setAPIURL * * @param {string} url - The API URL to use * * @example * > // reset to the default URL * > belhop.configuration.setAPIURL(null); */ belhop.configuration.setAPIURL = function(url) { belhop.currentAPIURL = url; }; /** * Get the current schema URL. * * @function * @name belhop.configuration.getSchemaURL * * @example * > belhop.configuration.getSchemaURL() * 'http://next.belframework.org/schema' * * @return {string} Current schema URL */ belhop.configuration.getSchemaURL = function() { var url = belhop.currentSchemaURL; if (typeof url === 'undefined' || url === null) { return belhop.DEFAULT_SCHEMA_URL; } return belhop.currentSchemaURL; }; /** * Set the schema URL. * * @function * @name belhop.configuration.setSchemaURL * * @param {string} url - The schema URL to use * * @example * > // reset to the default URL * > belhop.configuration.setSchemaURL(null); */ belhop.configuration.setSchemaURL = function(url) { belhop.currentSchemaURL = url; }; /** * @namespace belhop.complete */ belhop.complete = {}; /** * Applies a completion to the input and returns the result. * @namespace belhop.complete * * @function * @name belhop.complete.apply * * @param {object} completion - BEL API completion object. * @param {string} input - BEL expression to autocomplete. * * @return {string} Completed input string. */ belhop.complete.apply = function(completion, input) { /* applies a single action */ function actOn(action) { if (action.delete) { var startPos = action.delete.start_position; var endPos = action.delete.end_position; input = belhop.complete.actions.delete(input, startPos, endPos); } else if (action.insert) { var value = action.insert.value; var position = action.insert.position; input = belhop.complete.actions.insert(input, value, position); } } /* apply each action, mutating input */ // looks odd but "completion" is a key in the actual completion object var actions = completion.completion.actions; actions.forEach(actOn); return input; }; /** * BELHop completion type definition. * @name Completion * @typedef {Completion} Completion * @property {array} actions - The completion actions. * @property {string} value - The completion value (the proposal). * @property {string} label - Expanded representation of the value. * @property {string} type - The type of the completion (provided by the API). */ /** * BELHop callback type definition. * These types can be created in {@link belhop.factory the factory}. * * @name Callback * @typedef {Callback} Callback * @property {function} success - Function called on success. This function * is called with the response data, status string, and original request (in * that order). * @property {function} error - Function called on error. This function * is called with the original request, error string, and exception object * if one occurred (in that order). * * @example * // no-op callback, w/ function arguments for clarity * var cb = { * success: function(responseData, statusString, request) {}, * error: function(request, errorString, exception) {} * }; */ /** * BELHop evdience type definition. * @name Evidence * @typedef {Evidence} Evidence * @property {string} id - The evidence identifier (if previously created) * @property {string} bel_statement - Represents the biological knowledge * @property {object} citation - Source of the biological knowledge * @property {object} biological_context - Details on where the interaction * was observed * @property {string} summary_text - Abstract from source text * @property {object} metadata - Additional details about the evidence */ /** * @namespace belhop.factory */ belhop.factory = {}; /** * Evidence factory. * * @function * @name belhop.factory.evidence * * @param {string} stmt - The source/relationship/target string * @param {object} citation - Source of the biological knowledge * @param {object} ctxt - Details on where the interaction was observed * @param {string} summary - Abstract from source text * @param {object} meta - Additional details about the evidence * * @return {Evidence} */ belhop.factory.evidence = function(stmt, citation, ctxt, summary, meta) { return { evidence: { bel_statement: stmt, citation: citation, biological_context: ctxt, summary_text: summary, metadata: meta } }; }; /** * Gets completions for the given input and returns the results. * * @function * @name belhop.complete.getCompletions * * @param {string} input - BEL expression to autocomplete. * @param {number} caretPosition - optional caret position * @param {Callback} cb - callback with success and error functions * * @return {Completion} zero or more completions */ belhop.complete.getCompletions = function(input, caretPosition, cb) { var path = '/expressions/' + input + '/completions'; var options = {}; if (typeof caretPosition !== 'undefined' && caretPosition !== null) { options.queryParams = 'caret_position=' + caretPosition; } apiGET(path, cb, options); }; /** * @namespace belhop.complete.actions */ belhop.complete.actions = {}; /** * Delete the characters from startPos to endPos inclusively and return the * result. * * @protected * @function * @name belhop.complete.actions.delete * * @param {string} str - Input string to operate on. * @param {number} startPos - Starting position of the deletion range. * @param {number} endPos - Ending position of the deletion range. * * @example * > // delete "JUNK" from input * > belhop.complete.actions.delete('fooJUNKbar', 3, 6); * 'foobar' * * @return {string} Input string after deletion operation. */ belhop.complete.actions.delete = function(str, startPos, endPos) { var str1 = str.substr(0, startPos); var str2 = str.substr(endPos + 1); var ret = str1 + str2; return ret; }; /** * Insert the string value at position and return the result. * * @protected * @function * @name belhop.complete.actions.insert * * @param {string} str - Input string to operate on. * @param {string} value - String to insert. * @param {number} position - Insertion position. * * @example * > // insert "bar" into input * > belhop.complete.actions.insert('foo', 'bar', 3); * 'foobar' * * @return {string} Input string after insertion operation. */ belhop.complete.actions.insert = function(str, value, position) { var str1 = str.substr(0, position); var str2 = value; var str3 = str.substr(position); var rslt = str1 + str2 + str3; return rslt; }; /** * @namespace belhop.validate */ belhop.validate = {}; /** * Insert the string value at position and return the result. * * @function * @name belhop.validate.syntax * * @param {string} str - Input string to operate on. * @param {string} value - String to insert. * @param {number} position - Insertion position. * * @return {Object} */ belhop.validate.syntax = function(input) { return {}; }; /** * Insert the string value at position and return the result. * * @function * @name belhop.validate.semantics * * @param {string} str - Input string to operate on. * @param {string} value - String to insert. * @param {number} position - Insertion position. * * @return {Object} */ belhop.validate.semantics = function(input) { return {}; }; /** * @namespace belhop.evidence */ belhop.evidence = {}; /** * Create new evidence by its component parts. * * @function * @name belhop.evidence.create * * @param {string} stmt - The source/relationship/target string * @param {object} citation - Source of the biological knowledge * @param {object} ctxt - Details on where the interaction was observed * @param {string} summary - Abstract from source text * @param {object} meta - Additional details about the evidence * @param {Callback} cb - callback with success and error functions */ belhop.evidence.create = function(stmt, citation, ctxt, summary, meta, cb) { var evidence = belhop.factory.evidence( stmt, citation, ctxt, summary, meta); belhop.evidence.createEvidence(evidence, cb); }; /** * Create or update evidence, depending on whether it has an id. * * @function * @name belhop.evidence.createEvidence * * @param {Evidence} evidence - Evidence to create or update * @param {Callback} cb - callback with success and error functions */ belhop.evidence.createEvidence = function(evidence, cb) { var path = '/evidence'; var data = JSON.stringify(evidence); var schemaURL = belhop.configuration.getSchemaURL(); var profile = schemaURL + '/evidence.schema.json'; var contentType = 'application/json;profile=' + profile; var options = { contentType: contentType }; apiPOST(path, data, cb, options); }; /** * Get evidence by its id. On success, the callback's success function will * * @function * @name belhop.evidence.get * * @property {string} id - The evidence identifier to remove * @param {Callback} cb - callback with success and error functions */ belhop.evidence.get = function(id, cb) { var path = '/evidence/' + id; apiGET(path, cb); }; /** * Remove evidence by its id. * * @function * @name belhop.evidence.remove * * @property {string} id - The evidence identifier to remove * @param {Callback} cb - callback with success and error functions */ belhop.evidence.remove = function(id, cb) { if (typeof id === 'undefined' || id === null) { cb.invalid(); return; } var path = '/evidence/' + id; apiDELETE(path, cb); }; /** * Remove evidence. * * @function * @name belhop.evidence.removeEvidence * * @param {Evidence} evidence - Evidence to create or update * @param {Callback} cb - callback with success and error functions */ belhop.evidence.removeEvidence = function(evidence, cb) { var id = evidence.id; belhop.evidence.remove(id, cb); }; }.call(this));
src/belhop.js
/** * @file BELHop JavaScript library. * @author OpenBEL Committers * @license Apache-2.0 */ (function() { 'use strict'; var root = this; var _defaultAPIURL = 'http://next.belframework.org/api'; var _defaultSchemaURL = 'http://next.belframework.org/schema'; function _invalid() { var x, i; for (i = 0; i < arguments.length; i++) { x = arguments[i]; if (typeof x === 'undefined' || x === null) { return true; } } return false; } function _valid() { var x, i; for (i = 0; i < arguments.length; i++) { x = arguments[i]; if (typeof x === 'undefined' || x === null) { return false; } } return true; } function _ex(message, args) { return { message: message, args: args }; } // declare globals not recognized by eslint /* global module */ /* global $ */ /** * The BELHop module. * @exports belhop * @namespace belhop * @author Nick Bargnesi <[email protected]> * @version 0.1.0 */ var belhop = {}; if (typeof module !== 'undefined' && module.exports) { module.exports = belhop; } else { root.belhop = belhop; } /** * @name DEFAULT_API_URL * @readonly * @type {string} * @default */ Object.defineProperty(belhop, 'DEFAULT_API_URL', { get: function() { return _defaultAPIURL; } }); /** * @name DEFAULT_SCHEMA_URL * @readonly * @type {string} * @default */ Object.defineProperty(belhop, 'DEFAULT_SCHEMA_URL', { get: function() { return _defaultSchemaURL; } }); /** * @name VERSION * @readonly * @type {string} * @default */ Object.defineProperty(belhop, 'VERSION', { get: function() { return '0.1.0'; } }); /* * The options hash can handle a queryParams key. */ function apiGET(path, cb, options) { var url = belhop.configuration.getAPIURL(); // append the path path = encodeURI(path); url += path; // setup the options to our AJAX get var defaultOptions = { queryParams: null }; var argOptions = $.extend(defaultOptions, options || {}); if (argOptions.queryParams !== null) { // append query parameters url += '?' + argOptions.queryParams; } var ajaxOptions = { url: url, success: cb.success, error: cb.error }; $.ajax(ajaxOptions); } /* * The options hash can handle queryParams and contentType keys. */ function apiPOST(path, data, cb, options) { var url = belhop.configuration.getAPIURL(); // append the path path = encodeURI(path); url += path; // setup the options to our AJAX post var defaultOptions = { queryParams: null, contentType: null }; var argOptions = $.extend(defaultOptions, options || {}); if (argOptions.queryParams !== null) { // append query parameters url += '?' + argOptions.queryParams; } var ajaxOptions = { type: 'POST', url: url, data: data, success: cb.success, error: cb.error }; if (argOptions.contentType !== null) { ajaxOptions.contentType = argOptions.contentType; } $.ajax(ajaxOptions); } /* */ function apiDELETE(path, cb) { var url = belhop.configuration.getAPIURL(); // append the path path = encodeURI(path); url += path; var ajaxOptions = { type: 'DELETE', url: url, success: cb.success, error: cb.error }; $.ajax(ajaxOptions); } /** * @namespace belhop.configuration */ belhop.configuration = {}; /** * Get the current API URL. * * @function * @name belhop.configuration.getAPIURL * * @example * > belhop.configuration.getAPIURL() * 'http://next.belframework.org/api' * * @return {string} Current API URL */ belhop.configuration.getAPIURL = function() { var url = belhop.currentAPIURL; if (typeof url === 'undefined' || url === null) { return belhop.DEFAULT_API_URL; } return belhop.currentAPIURL; }; /** * Set the API URL. * * @function * @name belhop.configuration.setAPIURL * * @param {string} url - The API URL to use * * @example * > // reset to the default URL * > belhop.configuration.setAPIURL(null); */ belhop.configuration.setAPIURL = function(url) { belhop.currentAPIURL = url; }; /** * Get the current schema URL. * * @function * @name belhop.configuration.getSchemaURL * * @example * > belhop.configuration.getSchemaURL() * 'http://next.belframework.org/schema' * * @return {string} Current schema URL */ belhop.configuration.getSchemaURL = function() { var url = belhop.currentSchemaURL; if (typeof url === 'undefined' || url === null) { return belhop.DEFAULT_SCHEMA_URL; } return belhop.currentSchemaURL; }; /** * Set the schema URL. * * @function * @name belhop.configuration.setSchemaURL * * @param {string} url - The schema URL to use * * @example * > // reset to the default URL * > belhop.configuration.setSchemaURL(null); */ belhop.configuration.setSchemaURL = function(url) { belhop.currentSchemaURL = url; }; /** * @namespace belhop.complete */ belhop.complete = {}; /** * Applies a completion to the input and returns the result. * @namespace belhop.complete * * @function * @name belhop.complete.apply * * @param {object} completion - BEL API completion object. * @param {string} input - BEL expression to autocomplete. * * @return {string} Completed input string. */ belhop.complete.apply = function(completion, input) { /* applies a single action */ function actOn(action) { if (action.delete) { var startPos = action.delete.start_position; var endPos = action.delete.end_position; input = belhop.complete.actions.delete(input, startPos, endPos); } else if (action.insert) { var value = action.insert.value; var position = action.insert.position; input = belhop.complete.actions.insert(input, value, position); } } /* apply each action, mutating input */ // looks odd but "completion" is a key in the actual completion object var actions = completion.completion.actions; actions.forEach(actOn); return input; }; /** * BELHop completion type definition. * @name Completion * @typedef {Completion} Completion * @property {array} actions - The completion actions. * @property {string} value - The completion value (the proposal). * @property {string} label - Expanded representation of the value. * @property {string} type - The type of the completion (provided by the API). */ /** * BELHop callback type definition. * @name Callback * @typedef {Callback} Callback * @property {function} success - Function called on success * @property {function} error - Function called on error * @property {function} invalid - Invalid call */ /** * BELHop evdience type definition. * @name Evidence * @typedef {Evidence} Evidence * @property {string} id - The evidence identifier (if previously created) * @property {string} bel_statement - Represents the biological knowledge * @property {object} citation - Source of the biological knowledge * @property {object} biological_context - Details on where the interaction * was observed * @property {string} summary_text - Abstract from source text * @property {object} metadata - Additional details about the evidence */ /** * @namespace belhop.factory */ belhop.factory = {}; /** * Evidence factory. * * @function * @name belhop.factory.evidence * * @param {string} stmt - The source/relationship/target string * @param {object} citation - Source of the biological knowledge * @param {object} ctxt - Details on where the interaction was observed * @param {string} summary - Abstract from source text * @param {object} meta - Additional details about the evidence * * @return {Evidence} */ belhop.factory.evidence = function(stmt, citation, ctxt, summary, meta) { return { evidence: { bel_statement: stmt, citation: citation, biological_context: ctxt, summary_text: summary, metadata: meta } }; }; /** * Gets completions for the given input and returns the results. * * @function * @name belhop.complete.getCompletions * * @param {string} input - BEL expression to autocomplete. * @param {number} caretPosition - optional caret position * @param {Callback} cb - callback with success and error functions * * @return {Completion} zero or more completions */ belhop.complete.getCompletions = function(input, caretPosition, cb) { var path = '/expressions/' + input + '/completions'; var options = {}; if (typeof caretPosition !== 'undefined' && caretPosition !== null) { options.queryParams = 'caret_position=' + caretPosition; } apiGET(path, cb, options); }; /** * @namespace belhop.complete.actions */ belhop.complete.actions = {}; /** * Delete the characters from startPos to endPos inclusively and return the * result. * * @protected * @function * @name belhop.complete.actions.delete * * @param {string} str - Input string to operate on. * @param {number} startPos - Starting position of the deletion range. * @param {number} endPos - Ending position of the deletion range. * * @example * > // delete "JUNK" from input * > belhop.complete.actions.delete('fooJUNKbar', 3, 6); * 'foobar' * * @return {string} Input string after deletion operation. */ belhop.complete.actions.delete = function(str, startPos, endPos) { var str1 = str.substr(0, startPos); var str2 = str.substr(endPos + 1); var ret = str1 + str2; return ret; }; /** * Insert the string value at position and return the result. * * @protected * @function * @name belhop.complete.actions.insert * * @param {string} str - Input string to operate on. * @param {string} value - String to insert. * @param {number} position - Insertion position. * * @example * > // insert "bar" into input * > belhop.complete.actions.insert('foo', 'bar', 3); * 'foobar' * * @return {string} Input string after insertion operation. */ belhop.complete.actions.insert = function(str, value, position) { var str1 = str.substr(0, position); var str2 = value; var str3 = str.substr(position); var rslt = str1 + str2 + str3; return rslt; }; /** * @namespace belhop.validate */ belhop.validate = {}; /** * Insert the string value at position and return the result. * * @function * @name belhop.validate.syntax * * @param {string} str - Input string to operate on. * @param {string} value - String to insert. * @param {number} position - Insertion position. * * @return {Object} */ belhop.validate.syntax = function(input) { return {}; }; /** * Insert the string value at position and return the result. * * @function * @name belhop.validate.semantics * * @param {string} str - Input string to operate on. * @param {string} value - String to insert. * @param {number} position - Insertion position. * * @return {Object} */ belhop.validate.semantics = function(input) { return {}; }; /** * @namespace belhop.evidence */ belhop.evidence = {}; /** * Create new evidence by its component parts. * * @function * @name belhop.evidence.create * * @param {string} stmt - The source/relationship/target string * @param {object} citation - Source of the biological knowledge * @param {object} ctxt - Details on where the interaction was observed * @param {string} summary - Abstract from source text * @param {object} meta - Additional details about the evidence * @param {Callback} cb - callback with success and error functions */ belhop.evidence.create = function(stmt, citation, ctxt, summary, meta, cb) { var evidence = belhop.factory.evidence( stmt, citation, ctxt, summary, meta); belhop.evidence.createEvidence(evidence, cb); }; /** * Create or update evidence, depending on whether it has an id. * * @function * @name belhop.evidence.createEvidence * * @param {Evidence} evidence - Evidence to create or update * @param {Callback} cb - callback with success and error functions */ belhop.evidence.createEvidence = function(evidence, cb) { var path = '/evidence'; var data = JSON.stringify(evidence); var schemaURL = belhop.configuration.getSchemaURL(); var profile = schemaURL + '/evidence.schema.json'; var contentType = 'application/json;profile=' + profile; var options = { contentType: contentType }; apiPOST(path, data, cb, options); }; /** * Get evidence by its id. On success, the callback's success function will * * @function * @name belhop.evidence.get * * @property {string} id - The evidence identifier to remove * @param {Callback} cb - callback with success and error functions */ belhop.evidence.get = function(id, cb) { var path = '/evidence/' + id; apiGET(path, cb); }; /** * Remove evidence by its id. * * @function * @name belhop.evidence.remove * * @property {string} id - The evidence identifier to remove * @param {Callback} cb - callback with success and error functions */ belhop.evidence.remove = function(id, cb) { if (typeof id === 'undefined' || id === null) { cb.invalid(); return; } var path = '/evidence/' + id; apiDELETE(path, cb); }; /** * Remove evidence. * * @function * @name belhop.evidence.removeEvidence * * @param {Evidence} evidence - Evidence to create or update * @param {Callback} cb - callback with success and error functions */ belhop.evidence.removeEvidence = function(evidence, cb) { var id = evidence.id; belhop.evidence.remove(id, cb); }; }.call(this));
redefine Callback type and improve jsdoc fu
src/belhop.js
redefine Callback type and improve jsdoc fu
<ide><path>rc/belhop.js <ide> <ide> /** <ide> * BELHop callback type definition. <add> * These types can be created in {@link belhop.factory the factory}. <add> * <ide> * @name Callback <ide> * @typedef {Callback} Callback <del> * @property {function} success - Function called on success <del> * @property {function} error - Function called on error <del> * @property {function} invalid - Invalid call <add> * @property {function} success - Function called on success. This function <add> * is called with the response data, status string, and original request (in <add> * that order). <add> * @property {function} error - Function called on error. This function <add> * is called with the original request, error string, and exception object <add> * if one occurred (in that order). <add> * <add> * @example <add> * // no-op callback, w/ function arguments for clarity <add> * var cb = { <add> * success: function(responseData, statusString, request) {}, <add> * error: function(request, errorString, exception) {} <add> * }; <ide> */ <ide> <ide> /**
Java
mit
b75ade48bdb5132ab587c9c953c727b998663aec
0
effine/shopping
/** * @author effine * @Date 2016年2月1日 下午8:51:44 * @email iballader#gmail.com * @site http://www.effine.cn */ package cn.effine.test; import org.junit.Test; import cn.effine.utils.XmlUtils; public class XmlTest { @Test public void parseXmlTest() { XmlUtils.parserXml("src/main/resources/test.xml"); } }
src/test/java/cn/effine/test/XmlTest.java
/** * @author effine * @Date 2016年2月1日 下午8:51:44 * @email iballader#gmail.com * @site http://www.effine.cn */ package cn.effine.test; import org.junit.Test; import cn.effine.utils.XmlUtils; public class XmlTest { @Test public void parseXmlTest() { XmlUtils.parserXml("src/main/resources/test.xml"); } }
update
src/test/java/cn/effine/test/XmlTest.java
update
<ide><path>rc/test/java/cn/effine/test/XmlTest.java <ide> <ide> public class XmlTest { <ide> <del> @Test <del> public void parseXmlTest() { <del> XmlUtils.parserXml("src/main/resources/test.xml"); <del> } <add> @Test <add> public void parseXmlTest() { <add> XmlUtils.parserXml("src/main/resources/test.xml"); <add> } <ide> <ide> }
Java
agpl-3.0
3a7dbb0646da4e8d72e80636eb7948e76243ab43
0
akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow
package org.waterforpeople.mapping.app.web.rest; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.gallatinsystems.common.util.PropertyUtil; @Controller @RequestMapping("/cartodb") public class CartodbRestService { private static final String API_KEY = PropertyUtil.getProperty("cartodbApiKey"); private static final String SQL_API = PropertyUtil.getProperty("cartodbSqlApi"); private static final ObjectMapper objectMapper = new ObjectMapper(); @RequestMapping(method = RequestMethod.GET, value = "answers") @ResponseBody public Map<String, Object> getAnswers(@RequestParam("dataPointId") Long dataPointId, @RequestParam("surveyId") Long surveyId) { Map<String, Object> response = new HashMap<>(); response.put("answers", null); try { String formIdQuery = String.format("SELECT id FROM form WHERE survey_id=%d", surveyId); List<Map<String, Object>> formIdResponse = queryCartodb(formIdQuery); if (!formIdResponse.isEmpty()) { Integer formId = (Integer) formIdResponse.get(0).get("id"); String rawDataQuery = String.format( "SELECT * FROM raw_data_%s WHERE data_point_id=%d", formId, dataPointId); List<Map<String, Object>> rawDataResponse = queryCartodb(rawDataQuery); if (!rawDataResponse.isEmpty()) { response.put("answers", rawDataResponse.get(0)); } } return response; } catch (IOException e) { return response; } } @RequestMapping(method = RequestMethod.GET, value = "surveys") @ResponseBody public Map<String, Object> listSurveys() { Map<String, Object> response = new HashMap<>(); response.put("surveys", null); try { response.put("surveys", queryCartodb("SELECT * FROM survey")); return response; } catch (IOException e) { return response; } } @RequestMapping(method = RequestMethod.GET, value = "forms") @ResponseBody public Map<String, Object> getForms(@RequestParam("surveyId") Long surveyId) { Map<String, Object> response = new HashMap<>(); response.put("forms", null); try { response.put("forms", queryCartodb(String.format("SELECT * FROM form WHERE survey_id=%d", surveyId))); return response; } catch (IOException e) { return response; } } @SuppressWarnings("unchecked") private static List<Map<String, Object>> queryCartodb(String query) throws IOException { String urlString = String.format(SQL_API + "?q=%s&api_key=%s", URLEncoder.encode(query, "UTF-8"), API_KEY); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/json"); JsonNode jsonNode = objectMapper.readTree(connection.getInputStream()); return objectMapper.convertValue(jsonNode.get("rows"), List.class); } }
GAE/src/org/waterforpeople/mapping/app/web/rest/CartodbRestService.java
package org.waterforpeople.mapping.app.web.rest; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.gallatinsystems.common.util.PropertyUtil; @Controller @RequestMapping("/cartodb") public class CartodbRestService { private static final String API_KEY = PropertyUtil.getProperty("cartodbApiKey"); private static final String SQL_API = PropertyUtil.getProperty("cartodbSqlApi"); @RequestMapping(method = RequestMethod.GET, value = "answers") @ResponseBody public Map<String, Object> getAnswers(@RequestParam("dataPointId") Long dataPointId, @RequestParam("surveyId") Long surveyId) { Map<String, Object> response = new HashMap<>(); response.put("answers", null); try { String formIdQuery = String.format("SELECT id FROM form WHERE survey_id=%d", surveyId); List<Map<String, Object>> formIdResponse = queryCartodb(formIdQuery); if (!formIdResponse.isEmpty()) { Integer formId = (Integer) formIdResponse.get(0).get("id"); String rawDataQuery = String.format( "SELECT * FROM raw_data_%s WHERE data_point_id=%d", formId, dataPointId); List<Map<String, Object>> rawDataResponse = queryCartodb(rawDataQuery); if (!rawDataResponse.isEmpty()) { response.put("answers", rawDataResponse.get(0)); } } return response; } catch (IOException e) { return response; } } @RequestMapping(method = RequestMethod.GET, value = "surveys") @ResponseBody public Map<String, Object> listSurveys() { Map<String, Object> response = new HashMap<>(); response.put("surveys", null); try { response.put("surveys", queryCartodb("SELECT * FROM survey")); return response; } catch (IOException e) { return response; } } @RequestMapping(method = RequestMethod.GET, value = "forms") @ResponseBody public Map<String, Object> getForms(@RequestParam("surveyId") Long surveyId) { Map<String, Object> response = new HashMap<>(); response.put("forms", null); try { response.put("forms", queryCartodb(String.format("SELECT * FROM form WHERE survey_id=%d", surveyId))); return response; } catch (IOException e) { return response; } } private static List<Map<String, Object>> queryCartodb(String query) throws IOException { String urlString = String.format(SQL_API + "?q=%s&api_key=%s", URLEncoder.encode(query, "UTF-8"), API_KEY); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/json"); ObjectMapper m = new ObjectMapper(); JsonNode jsonNode = m.readTree(connection.getInputStream()); JsonNode rows = jsonNode.get("rows"); return m.convertValue(rows, List.class); } }
[#1280] small objectMapper refactor
GAE/src/org/waterforpeople/mapping/app/web/rest/CartodbRestService.java
[#1280] small objectMapper refactor
<ide><path>AE/src/org/waterforpeople/mapping/app/web/rest/CartodbRestService.java <ide> <ide> private static final String API_KEY = PropertyUtil.getProperty("cartodbApiKey"); <ide> private static final String SQL_API = PropertyUtil.getProperty("cartodbSqlApi"); <add> private static final ObjectMapper objectMapper = new ObjectMapper(); <ide> <ide> @RequestMapping(method = RequestMethod.GET, value = "answers") <ide> @ResponseBody <ide> } <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> private static List<Map<String, Object>> queryCartodb(String query) throws IOException { <del> <ide> String urlString = String.format(SQL_API + "?q=%s&api_key=%s", <ide> URLEncoder.encode(query, "UTF-8"), API_KEY); <del> <ide> URL url = new URL(urlString); <ide> HttpURLConnection connection = (HttpURLConnection) url.openConnection(); <ide> connection.setDoOutput(true); <ide> connection.setRequestMethod("GET"); <ide> connection.setRequestProperty("Content-Type", "application/json"); <ide> <del> ObjectMapper m = new ObjectMapper(); <del> JsonNode jsonNode = m.readTree(connection.getInputStream()); <add> JsonNode jsonNode = objectMapper.readTree(connection.getInputStream()); <ide> <del> JsonNode rows = jsonNode.get("rows"); <del> <del> return m.convertValue(rows, List.class); <add> return objectMapper.convertValue(jsonNode.get("rows"), List.class); <ide> } <ide> }
Java
apache-2.0
833d076952d2bb1cb35df9a0d2d083cb408866c5
0
deib-polimi/tower4clouds,deib-polimi/tower4clouds,deib-polimi/tower4clouds,deib-polimi/tower4clouds,deib-polimi/tower4clouds,deib-polimi/tower4clouds
/** * Copyright (C) 2014 Politecnico di Milano ([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 it.polimi.tower4clouds.manager.server; import it.polimi.deib.csparql_rest_api.exception.ServerErrorException; import it.polimi.tower4clouds.manager.ConfigurationException; import it.polimi.tower4clouds.manager.ManagerConfig; import it.polimi.tower4clouds.manager.MonitoringManager; import java.io.IOException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.jena.atlas.web.HttpException; import org.restlet.Application; import org.restlet.Component; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.LocalReference; import org.restlet.data.Protocol; import org.restlet.resource.Directory; import org.restlet.routing.Redirector; import org.restlet.routing.Router; import org.restlet.routing.Template; import org.restlet.routing.TemplateRoute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MMServer extends Application { public static String APP_NAME; public static String APP_FILE_NAME; public static String APP_VERSION; private MonitoringManager manager = null; private static final String apiVersion = "v1"; private static Logger logger = LoggerFactory.getLogger(MMServer.class); public MMServer(MonitoringManager manager) { this.manager = manager; } public static void main(String[] args) { PropertiesConfiguration releaseProperties = null; try { releaseProperties = new PropertiesConfiguration( "release.properties"); } catch (org.apache.commons.configuration.ConfigurationException e) { logger.error("Internal error", e); System.exit(1); } APP_NAME = releaseProperties.getString("application.name"); APP_FILE_NAME = releaseProperties.getString("dist.file.name"); APP_VERSION = releaseProperties.getString("release.version"); try { ManagerConfig.init(args, APP_FILE_NAME); if (ManagerConfig.getInstance().isHelp()) { logger.info(ManagerConfig.usage); } else if (ManagerConfig.getInstance().isVersion()) { logger.info("Version: {}", APP_VERSION); } else { logger.info("{} {}", APP_NAME, APP_VERSION); logger.info("Current configuration:\n{}", ManagerConfig .getInstance().toString()); MonitoringManager manager = new MonitoringManager( ManagerConfig.getInstance()); System.setProperty("org.restlet.engine.loggerFacadeClass", "org.restlet.ext.slf4j.Slf4jLoggerFacade"); Component component = new Component(); Server server = new Server(Protocol.HTTP, ManagerConfig .getInstance().getMmPort()); Context context = new Context(); context.getParameters().add("maxThreads", "500"); context.getParameters().add("maxTotalConnections", "500"); server.setContext(context); component.getServers().add(server); component.getClients().add(Protocol.CLAP); component.getDefaultHost().attach("", new MMServer(manager)); logger.info("Starting Monitoring Manager server on port " + ManagerConfig.getInstance().getMmPort()); component.start(); } } catch (ConfigurationException e) { logger.error("Configuration problem: " + e.getMessage()); logger.error("Run \"" + APP_FILE_NAME + " -help\" for help"); System.exit(1); } catch (HttpException | IOException | ServerErrorException e) { logger.error("Connection problem: {}", e.getMessage()); System.exit(1); } catch (Exception e) { logger.error("Unknown error", e); System.exit(1); } } public Restlet createInboundRoot() { // String server_address = component.getServers().get(0).getAddress(); // if (server_address == null) { // server_address = "http://localhost"; // server_address = server_address // + ":" // + String.valueOf(component.getServers().get(0) // .getActualPort()); // } // // getContext().getAttributes().put("complete_server_address", // server_address); getContext().getAttributes().put("manager", manager); Router router = new Router(getContext()); router.setDefaultMatchingMode(Template.MODE_EQUALS); router.attach("/" + apiVersion + "/monitoring-rules", MultipleRulesDataServer.class); router.attach("/" + apiVersion + "/monitoring-rules/{id}", SingleRuleDataServer.class); router.attach("/" + apiVersion + "/metrics", MultipleMetricsDataServer.class); router.attach("/" + apiVersion + "/metrics/{metricname}/observers", MultipleObserversDataServer.class); router.attach( "/" + apiVersion + "/metrics/{metricname}/observers/{id}", SingleObserverDataServer.class); router.attach("/" + apiVersion + "/required-metrics", MultipleRequiredMetricsDataServer.class); router.attach("/" + apiVersion + "/resources", MultipleResourcesDataServer.class); router.attach("/" + apiVersion + "/resources/{id}", SingleResourceDataServer.class); router.attach("/" + apiVersion + "/monitoring-rules/{id}/actions", MultipleActionsServer.class); router.attach("/" + apiVersion + "/data-collectors", MultipleDataCollectorServer.class); router.attach("/" + apiVersion + "/data-collectors/{id}", SingleDataCollectorServer.class); router.attach("/" + apiVersion + "/data-collectors/{id}/keepalive", DCKeepAliveServer.class); router.attach("/" + apiVersion + "/data-collectors/{id}/configuration", DCConfigurationServer.class); Redirector redirector = new Redirector(getContext(), "/webapp/index.html", Redirector.MODE_CLIENT_PERMANENT); router.attach("/webapp", redirector); router.attach("/webapp/", redirector); final Directory dir = new Directory(getContext(), new LocalReference( "clap://class/webapp")); dir.setListingAllowed(false); dir.setDeeplyAccessible(true); dir.setIndexName("index"); TemplateRoute route = router.attach("/webapp/", dir); route.setMatchingMode(Template.MODE_STARTS_WITH); return router; } }
manager/manager-server/src/main/java/it/polimi/tower4clouds/manager/server/MMServer.java
/** * Copyright (C) 2014 Politecnico di Milano ([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 it.polimi.tower4clouds.manager.server; import it.polimi.deib.csparql_rest_api.exception.ServerErrorException; import it.polimi.tower4clouds.manager.ConfigurationException; import it.polimi.tower4clouds.manager.ManagerConfig; import it.polimi.tower4clouds.manager.MonitoringManager; import java.io.IOException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.jena.atlas.web.HttpException; import org.restlet.Application; import org.restlet.Component; import org.restlet.Context; import org.restlet.Restlet; import org.restlet.Server; import org.restlet.data.LocalReference; import org.restlet.data.Protocol; import org.restlet.resource.Directory; import org.restlet.routing.Redirector; import org.restlet.routing.Router; import org.restlet.routing.Template; import org.restlet.routing.TemplateRoute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MMServer extends Application { public static String APP_NAME; public static String APP_FILE_NAME; public static String APP_VERSION; private MonitoringManager manager = null; private static final String apiVersion = "v1"; private static Logger logger = LoggerFactory.getLogger(MMServer.class); public MMServer(MonitoringManager manager) { this.manager = manager; } public static void main(String[] args) { PropertiesConfiguration releaseProperties = null; try { releaseProperties = new PropertiesConfiguration( "release.properties"); } catch (org.apache.commons.configuration.ConfigurationException e) { logger.error("Internal error", e); System.exit(1); } APP_NAME = releaseProperties.getString("application.name"); APP_FILE_NAME = releaseProperties.getString("dist.file.name"); APP_VERSION = releaseProperties.getString("release.version"); try { ManagerConfig.init(args, APP_FILE_NAME); if (ManagerConfig.getInstance().isHelp()) { logger.info(ManagerConfig.usage); } else if (ManagerConfig.getInstance().isVersion()) { logger.info("Version: {}", APP_VERSION); } else { logger.info("{} {}", APP_NAME, APP_VERSION); logger.info("Current configuration:\n{}", ManagerConfig .getInstance().toString()); MonitoringManager manager = new MonitoringManager( ManagerConfig.getInstance()); System.setProperty("org.restlet.engine.loggerFacadeClass", "org.restlet.ext.slf4j.Slf4jLoggerFacade"); Component component = new Component(); Server server = new Server(Protocol.HTTP, ManagerConfig .getInstance().getMmPort()); Context context = new Context(); context.getParameters().add("maxThreads", "500"); context.getParameters().add("maxTotalConnections", "500"); server.setContext(context); component.getServers().add(server); component.getClients().add(Protocol.CLAP); component.getDefaultHost().attach("", new MMServer(manager)); logger.info("Starting Monitoring Manager server on port " + ManagerConfig.getInstance().getMmPort()); component.start(); } } catch (ConfigurationException e) { logger.error("Configuration problem: " + e.getMessage()); logger.error("Run \"" + APP_FILE_NAME + " -help\" for help"); System.exit(1); } catch (HttpException | IOException | ServerErrorException e) { logger.error("Connection problem: {}", e.getMessage()); System.exit(1); } catch (Exception e) { logger.error("Unknown error", e); System.exit(1); } } public Restlet createInboundRoot() { // String server_address = component.getServers().get(0).getAddress(); // if (server_address == null) { // server_address = "http://localhost"; // server_address = server_address // + ":" // + String.valueOf(component.getServers().get(0) // .getActualPort()); // } // // getContext().getAttributes().put("complete_server_address", // server_address); getContext().getAttributes().put("manager", manager); Router router = new Router(getContext()); router.setDefaultMatchingMode(Template.MODE_EQUALS); router.attach("/" + apiVersion + "/monitoring-rules", MultipleRulesDataServer.class); router.attach("/" + apiVersion + "/monitoring-rules/{id}", SingleRuleDataServer.class); router.attach("/" + apiVersion + "/metrics", MultipleMetricsDataServer.class); router.attach("/" + apiVersion + "/metrics/{metricname}", SingleMetricDataServer.class); router.attach("/" + apiVersion + "/metrics/{metricname}/observers", MultipleObserversDataServer.class); router.attach( "/" + apiVersion + "/metrics/{metricname}/observers/{id}", SingleObserverDataServer.class); router.attach("/" + apiVersion + "/required-metrics", MultipleRequiredMetricsDataServer.class); router.attach("/" + apiVersion + "/resources", MultipleResourcesDataServer.class); router.attach("/" + apiVersion + "/resources/{id}", SingleResourceDataServer.class); router.attach("/" + apiVersion + "/monitoring-rules/{id}/actions", MultipleActionsServer.class); router.attach("/" + apiVersion + "/data-collectors", MultipleDataCollectorServer.class); router.attach("/" + apiVersion + "/data-collectors/{id}", SingleDataCollectorServer.class); router.attach("/" + apiVersion + "/data-collectors/{id}/keepalive", DCKeepAliveServer.class); router.attach("/" + apiVersion + "/data-collectors/{id}/configuration", DCConfigurationServer.class); Redirector redirector = new Redirector(getContext(), "/webapp/index.html", Redirector.MODE_CLIENT_PERMANENT); router.attach("/webapp", redirector); router.attach("/webapp/", redirector); final Directory dir = new Directory(getContext(), new LocalReference( "clap://class/webapp")); dir.setListingAllowed(false); dir.setDeeplyAccessible(true); dir.setIndexName("index"); TemplateRoute route = router.attach("/webapp/", dir); route.setMatchingMode(Template.MODE_STARTS_WITH); return router; } }
removed unused endpoint
manager/manager-server/src/main/java/it/polimi/tower4clouds/manager/server/MMServer.java
removed unused endpoint
<ide><path>anager/manager-server/src/main/java/it/polimi/tower4clouds/manager/server/MMServer.java <ide> SingleRuleDataServer.class); <ide> router.attach("/" + apiVersion + "/metrics", <ide> MultipleMetricsDataServer.class); <del> router.attach("/" + apiVersion + "/metrics/{metricname}", <del> SingleMetricDataServer.class); <ide> router.attach("/" + apiVersion + "/metrics/{metricname}/observers", <ide> MultipleObserversDataServer.class); <ide> router.attach(
Java
apache-2.0
903c77d559e6703ea5aa486d6c120d603680f2c7
0
MichaelNedzelsky/intellij-community,retomerz/intellij-community,clumsy/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,supersven/intellij-community,signed/intellij-community,hurricup/intellij-community,signed/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,holmes/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,caot/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,fitermay/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,kool79/intellij-community,xfournet/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,slisson/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,fitermay/intellij-community,slisson/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,holmes/intellij-community,da1z/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,jagguli/intellij-community,apixandru/intellij-community,xfournet/intellij-community,clumsy/intellij-community,da1z/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,allotria/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,xfournet/intellij-community,caot/intellij-community,suncycheng/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,fitermay/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,izonder/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,izonder/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,da1z/intellij-community,adedayo/intellij-community,hurricup/intellij-community,allotria/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,xfournet/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,kdwink/intellij-community,clumsy/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,holmes/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,da1z/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,petteyg/intellij-community,signed/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,signed/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,supersven/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,izonder/intellij-community,signed/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,blademainer/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,izonder/intellij-community,amith01994/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,asedunov/intellij-community,ryano144/intellij-community,dslomov/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,supersven/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,petteyg/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,apixandru/intellij-community,ryano144/intellij-community,kool79/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,signed/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,samthor/intellij-community,holmes/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,dslomov/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,supersven/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,holmes/intellij-community,da1z/intellij-community,fitermay/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,semonte/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,adedayo/intellij-community,kool79/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,robovm/robovm-studio,dslomov/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ibinti/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,FHannes/intellij-community,caot/intellij-community,caot/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,kdwink/intellij-community,kool79/intellij-community,nicolargo/intellij-community,samthor/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,signed/intellij-community,izonder/intellij-community,amith01994/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,allotria/intellij-community,semonte/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,vladmm/intellij-community,signed/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,signed/intellij-community,da1z/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,adedayo/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,holmes/intellij-community,apixandru/intellij-community,caot/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,kool79/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,caot/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,slisson/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,diorcety/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,izonder/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,supersven/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,amith01994/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,slisson/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,adedayo/intellij-community,da1z/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,fitermay/intellij-community,blademainer/intellij-community,asedunov/intellij-community,slisson/intellij-community,kdwink/intellij-community,asedunov/intellij-community,diorcety/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,kdwink/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,petteyg/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ibinti/intellij-community,holmes/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,holmes/intellij-community,kool79/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,slisson/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,semonte/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,supersven/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,signed/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,signed/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,asedunov/intellij-community,FHannes/intellij-community,retomerz/intellij-community,caot/intellij-community,signed/intellij-community,allotria/intellij-community,holmes/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,vladmm/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,kool79/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,slisson/intellij-community,semonte/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,caot/intellij-community,petteyg/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,ryano144/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,allotria/intellij-community,allotria/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,samthor/intellij-community,fitermay/intellij-community
/* * Copyright 2000-2015 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.diff.tools.simple; import com.intellij.diff.fragments.DiffFragment; import com.intellij.diff.fragments.LineFragment; import com.intellij.diff.util.DiffDrawUtil; import com.intellij.diff.util.DiffUtil; import com.intellij.diff.util.Side; import com.intellij.diff.util.TextDiffType; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.CalledWithWriteLock; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.List; public class SimpleDiffChange { @NotNull private final SimpleDiffViewer myViewer; @NotNull private final LineFragment myFragment; @Nullable private final List<DiffFragment> myInnerFragments; @Nullable private final EditorEx myEditor1; @Nullable private final EditorEx myEditor2; @NotNull private final List<RangeHighlighter> myHighlighters = new ArrayList<RangeHighlighter>(); @NotNull private final List<MyGutterOperation> myOperations = new ArrayList<MyGutterOperation>(); private boolean myIsValid = true; private int[] myLineStartShifts = new int[2]; private int[] myLineEndShifts = new int[2]; // TODO: adjust color from inner fragments - configurable public SimpleDiffChange(@NotNull SimpleDiffViewer viewer, @NotNull LineFragment fragment, @Nullable EditorEx editor1, @Nullable EditorEx editor2, boolean inlineHighlight) { myViewer = viewer; myFragment = fragment; myInnerFragments = inlineHighlight ? fragment.getInnerFragments() : null; myEditor1 = editor1; myEditor2 = editor2; installHighlighter(); } public void installHighlighter() { assert myHighlighters.isEmpty(); if (myInnerFragments != null) { doInstallHighlighterWithInner(); } else { doInstallHighlighterSimple(); } doInstallActionHighlighters(); } public void destroyHighlighter() { for (RangeHighlighter highlighter : myHighlighters) { highlighter.dispose(); } myHighlighters.clear(); for (MyGutterOperation operation : myOperations) { operation.dispose(); } myOperations.clear(); } private void doInstallHighlighterSimple() { createHighlighter(Side.LEFT, false); createHighlighter(Side.RIGHT, false); } private void doInstallHighlighterWithInner() { assert myInnerFragments != null; createHighlighter(Side.LEFT, true); createHighlighter(Side.RIGHT, true); for (DiffFragment fragment : myInnerFragments) { createInlineHighlighter(fragment, Side.LEFT); createInlineHighlighter(fragment, Side.RIGHT); } } private void doInstallActionHighlighters() { if (myEditor1 != null && myEditor2 != null) { myOperations.add(createOperation(Side.LEFT)); myOperations.add(createOperation(Side.RIGHT)); } } private void createHighlighter(@NotNull Side side, boolean ignored) { Editor editor = side.select(myEditor1, myEditor2); if (editor == null) return; int start = side.getStartOffset(myFragment); int end = side.getEndOffset(myFragment); TextDiffType type = DiffUtil.getLineDiffType(myFragment); myHighlighters.add(DiffDrawUtil.createHighlighter(editor, start, end, type, ignored)); int startLine = side.getStartLine(myFragment); int endLine = side.getEndLine(myFragment); if (startLine == endLine) { if (startLine != 0) myHighlighters.add(DiffDrawUtil.createLineMarker(editor, endLine - 1, type, SeparatorPlacement.BOTTOM, true)); } else { myHighlighters.add(DiffDrawUtil.createLineMarker(editor, startLine, type, SeparatorPlacement.TOP)); myHighlighters.add(DiffDrawUtil.createLineMarker(editor, endLine - 1, type, SeparatorPlacement.BOTTOM)); } } private void createInlineHighlighter(@NotNull DiffFragment fragment, @NotNull Side side) { Editor editor = side.select(myEditor1, myEditor2); if (editor == null) return; int start = side.getStartOffset(fragment); int end = side.getEndOffset(fragment); TextDiffType type = DiffUtil.getDiffType(fragment); int startOffset = side.getStartOffset(myFragment); start += startOffset; end += startOffset; RangeHighlighter highlighter = DiffDrawUtil.createInlineHighlighter(editor, start, end, type); myHighlighters.add(highlighter); } public void updateGutterActions(boolean force) { for (MyGutterOperation operation : myOperations) { operation.update(force); } } // // Getters // public int getStartLine(@NotNull Side side) { return side.getStartLine(myFragment) + side.select(myLineStartShifts); } public int getEndLine(@NotNull Side side) { return side.getEndLine(myFragment) + side.select(myLineEndShifts); } @NotNull public TextDiffType getDiffType() { return DiffUtil.getLineDiffType(myFragment); } // // Shift // public boolean processChange(int oldLine1, int oldLine2, int shift, @NotNull Side side) { int line1 = getStartLine(side); int line2 = getEndLine(side); if (line2 <= oldLine1) return false; if (line1 >= oldLine2) { myLineStartShifts[side.getIndex()] += shift; myLineEndShifts[side.getIndex()] += shift; return false; } if (line1 <= oldLine1 && line2 >= oldLine2) { myLineEndShifts[side.getIndex()] += shift; return false; } for (MyGutterOperation operation : myOperations) { operation.dispose(); } myOperations.clear(); myIsValid = false; return true; } // // Change applying // public boolean isSelectedByLine(int line, @NotNull Side side) { if (myEditor1 == null || myEditor2 == null) return false; int line1 = getStartLine(side); int line2 = getEndLine(side); return DiffUtil.isSelectedByLine(line, line1, line2); } @CalledWithWriteLock public void replaceChange(@NotNull final Side sourceSide) { assert myEditor1 != null && myEditor2 != null; if (!myIsValid) return; final Document document1 = myEditor1.getDocument(); final Document document2 = myEditor2.getDocument(); DiffUtil.applyModification(sourceSide.other().select(document1, document2), getStartLine(sourceSide.other()), getEndLine(sourceSide.other()), sourceSide.select(document1, document2), getStartLine(sourceSide), getEndLine(sourceSide)); destroyHighlighter(); } @CalledWithWriteLock public void appendChange(@NotNull final Side sourceSide) { assert myEditor1 != null && myEditor2 != null; if (!myIsValid) return; if (getStartLine(sourceSide) == getEndLine(sourceSide)) return; final Document document1 = myEditor1.getDocument(); final Document document2 = myEditor2.getDocument(); DiffUtil.applyModification(sourceSide.other().select(document1, document2), getEndLine(sourceSide.other()), getEndLine(sourceSide.other()), sourceSide.select(document1, document2), getStartLine(sourceSide), getEndLine(sourceSide)); destroyHighlighter(); } // // Helpers // @NotNull private MyGutterOperation createOperation(@NotNull Side side) { assert myEditor1 != null && myEditor2 != null; int offset = side.getStartOffset(myFragment); EditorEx editor = side.select(myEditor1, myEditor2); RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(offset, offset, HighlighterLayer.ADDITIONAL_SYNTAX, null, HighlighterTargetArea.LINES_IN_RANGE); return new MyGutterOperation(side, highlighter); } private class MyGutterOperation { @NotNull private final Side mySide; @NotNull private final RangeHighlighter myHighlighter; private boolean myCtrlPressed; private boolean myShiftPressed; private MyGutterOperation(@NotNull Side side, @NotNull RangeHighlighter highlighter) { mySide = side; myHighlighter = highlighter; update(true); } public void dispose() { myHighlighter.dispose(); } public void update(boolean force) { if (!force && !areModifiersChanged()) { return; } if (myHighlighter.isValid()) myHighlighter.setGutterIconRenderer(createRenderer()); } private boolean areModifiersChanged() { return myCtrlPressed != myViewer.getModifierProvider().isCtrlPressed() || myShiftPressed != myViewer.getModifierProvider().isShiftPressed(); } @Nullable public GutterIconRenderer createRenderer() { assert myEditor1 != null && myEditor2 != null; myCtrlPressed = myViewer.getModifierProvider().isCtrlPressed(); myShiftPressed = myViewer.getModifierProvider().isShiftPressed(); boolean isEditable = DiffUtil.isEditable(mySide.select(myEditor1, myEditor2)); boolean isOtherEditable = DiffUtil.isEditable(mySide.other().select(myEditor1, myEditor2)); boolean isAppendable = myFragment.getStartLine1() != myFragment.getEndLine1() && myFragment.getStartLine2() != myFragment.getEndLine2(); if ((myShiftPressed || !isOtherEditable) && isEditable) { return createRevertRenderer(mySide); } if (myCtrlPressed && isAppendable) { return createAppendRenderer(mySide); } return createApplyRenderer(mySide); } } @Nullable private GutterIconRenderer createApplyRenderer(@NotNull final Side side) { return createIconRenderer(side, "Replace", AllIcons.Diff.Arrow, new Runnable() { @Override public void run() { replaceChange(side); } }); } @Nullable private GutterIconRenderer createAppendRenderer(@NotNull final Side side) { return createIconRenderer(side, "Insert", AllIcons.Diff.ArrowLeftDown, new Runnable() { @Override public void run() { appendChange(side); } }); } @Nullable private GutterIconRenderer createRevertRenderer(@NotNull final Side side) { return createIconRenderer(side.other(), "Revert", AllIcons.Diff.Remove, new Runnable() { @Override public void run() { replaceChange(side.other()); } }); } @Nullable private GutterIconRenderer createIconRenderer(@NotNull final Side sourceSide, @NotNull final String tooltipText, @NotNull final Icon icon, @NotNull final Runnable perform) { assert myEditor1 != null && myEditor2 != null; if (!DiffUtil.isEditable(sourceSide.other().select(myEditor1, myEditor2))) return null; return new GutterIconRenderer() { @NotNull @Override public Icon getIcon() { return icon; } public boolean isNavigateAction() { return true; } @Nullable @Override public AnAction getClickAction() { return new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { final Project project = e.getProject(); final Document document1 = myEditor1.getDocument(); final Document document2 = myEditor2.getDocument(); if (!myIsValid) return; DiffUtil.executeWriteCommand(sourceSide.other().select(document1, document2), project, "Replace change", new Runnable() { @Override public void run() { perform.run(); } }); } }; } @Override public boolean equals(Object obj) { return obj == this; } @Override public int hashCode() { return System.identityHashCode(this); } @Nullable @Override public String getTooltipText() { return tooltipText; } }; } }
platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffChange.java
/* * Copyright 2000-2015 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.diff.tools.simple; import com.intellij.diff.fragments.DiffFragment; import com.intellij.diff.fragments.LineFragment; import com.intellij.diff.util.DiffDrawUtil; import com.intellij.diff.util.DiffUtil; import com.intellij.diff.util.Side; import com.intellij.diff.util.TextDiffType; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.CalledWithWriteLock; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.List; public class SimpleDiffChange { @NotNull private final SimpleDiffViewer myViewer; @NotNull private final LineFragment myFragment; @Nullable private final List<DiffFragment> myInnerFragments; @Nullable private final EditorEx myEditor1; @Nullable private final EditorEx myEditor2; @NotNull private final List<RangeHighlighter> myHighlighters = new ArrayList<RangeHighlighter>(); @NotNull private final List<MyGutterOperation> myOperations = new ArrayList<MyGutterOperation>(); private boolean myIsValid = true; private int[] myLineStartShifts = new int[2]; private int[] myLineEndShifts = new int[2]; // TODO: adjust color from inner fragments - configurable public SimpleDiffChange(@NotNull SimpleDiffViewer viewer, @NotNull LineFragment fragment, @Nullable EditorEx editor1, @Nullable EditorEx editor2, boolean inlineHighlight) { myViewer = viewer; myFragment = fragment; myInnerFragments = inlineHighlight ? fragment.getInnerFragments() : null; myEditor1 = editor1; myEditor2 = editor2; installHighlighter(); } public void installHighlighter() { assert myHighlighters.isEmpty(); if (myInnerFragments != null) { doInstallHighlighterWithInner(); } else { doInstallHighlighterSimple(); } doInstallActionHighlighters(); } public void destroyHighlighter() { for (RangeHighlighter highlighter : myHighlighters) { highlighter.dispose(); } myHighlighters.clear(); for (MyGutterOperation operation : myOperations) { operation.destroy(); } myOperations.clear(); } private void doInstallHighlighterSimple() { createHighlighter(Side.LEFT, false); createHighlighter(Side.RIGHT, false); } private void doInstallHighlighterWithInner() { assert myInnerFragments != null; createHighlighter(Side.LEFT, true); createHighlighter(Side.RIGHT, true); for (DiffFragment fragment : myInnerFragments) { createInlineHighlighter(fragment, Side.LEFT); createInlineHighlighter(fragment, Side.RIGHT); } } private void doInstallActionHighlighters() { if (myEditor1 != null && myEditor2 != null) { myOperations.add(createOperation(Side.LEFT)); myOperations.add(createOperation(Side.RIGHT)); } } private void createHighlighter(@NotNull Side side, boolean ignored) { Editor editor = side.select(myEditor1, myEditor2); if (editor == null) return; int start = side.getStartOffset(myFragment); int end = side.getEndOffset(myFragment); TextDiffType type = DiffUtil.getLineDiffType(myFragment); myHighlighters.add(DiffDrawUtil.createHighlighter(editor, start, end, type, ignored)); int startLine = side.getStartLine(myFragment); int endLine = side.getEndLine(myFragment); if (startLine == endLine) { if (startLine != 0) myHighlighters.add(DiffDrawUtil.createLineMarker(editor, endLine - 1, type, SeparatorPlacement.BOTTOM, true)); } else { myHighlighters.add(DiffDrawUtil.createLineMarker(editor, startLine, type, SeparatorPlacement.TOP)); myHighlighters.add(DiffDrawUtil.createLineMarker(editor, endLine - 1, type, SeparatorPlacement.BOTTOM)); } } private void createInlineHighlighter(@NotNull DiffFragment fragment, @NotNull Side side) { Editor editor = side.select(myEditor1, myEditor2); if (editor == null) return; int start = side.getStartOffset(fragment); int end = side.getEndOffset(fragment); TextDiffType type = DiffUtil.getDiffType(fragment); int startOffset = side.getStartOffset(myFragment); start += startOffset; end += startOffset; RangeHighlighter highlighter = DiffDrawUtil.createInlineHighlighter(editor, start, end, type); myHighlighters.add(highlighter); } public void updateGutterActions(boolean force) { for (MyGutterOperation operation : myOperations) { operation.update(force); } } // // Getters // public int getStartLine(@NotNull Side side) { return side.getStartLine(myFragment) + side.select(myLineStartShifts); } public int getEndLine(@NotNull Side side) { return side.getEndLine(myFragment) + side.select(myLineEndShifts); } @NotNull public TextDiffType getDiffType() { return DiffUtil.getLineDiffType(myFragment); } // // Shift // public boolean processChange(int oldLine1, int oldLine2, int shift, @NotNull Side side) { int line1 = getStartLine(side); int line2 = getEndLine(side); if (line2 <= oldLine1) return false; if (line1 >= oldLine2) { myLineStartShifts[side.getIndex()] += shift; myLineEndShifts[side.getIndex()] += shift; return false; } if (line1 <= oldLine1 && line2 >= oldLine2) { myLineEndShifts[side.getIndex()] += shift; return false; } for (MyGutterOperation operation : myOperations) { operation.destroy(); } myOperations.clear(); myIsValid = false; return true; } // // Change applying // public boolean isSelectedByLine(int line, @NotNull Side side) { if (myEditor1 == null || myEditor2 == null) return false; int line1 = getStartLine(side); int line2 = getEndLine(side); return DiffUtil.isSelectedByLine(line, line1, line2); } @CalledWithWriteLock public void replaceChange(@NotNull final Side sourceSide) { assert myEditor1 != null && myEditor2 != null; if (!myIsValid) return; final Document document1 = myEditor1.getDocument(); final Document document2 = myEditor2.getDocument(); DiffUtil.applyModification(sourceSide.other().select(document1, document2), getStartLine(sourceSide.other()), getEndLine(sourceSide.other()), sourceSide.select(document1, document2), getStartLine(sourceSide), getEndLine(sourceSide)); destroyHighlighter(); } @CalledWithWriteLock public void appendChange(@NotNull final Side sourceSide) { assert myEditor1 != null && myEditor2 != null; if (!myIsValid) return; if (getStartLine(sourceSide) == getEndLine(sourceSide)) return; final Document document1 = myEditor1.getDocument(); final Document document2 = myEditor2.getDocument(); DiffUtil.applyModification(sourceSide.other().select(document1, document2), getEndLine(sourceSide.other()), getEndLine(sourceSide.other()), sourceSide.select(document1, document2), getStartLine(sourceSide), getEndLine(sourceSide)); destroyHighlighter(); } // // Helpers // @NotNull private MyGutterOperation createOperation(@NotNull Side side) { assert myEditor1 != null && myEditor2 != null; int offset = side.getStartOffset(myFragment); EditorEx editor = side.select(myEditor1, myEditor2); RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(offset, offset, HighlighterLayer.ADDITIONAL_SYNTAX, null, HighlighterTargetArea.LINES_IN_RANGE); return new MyGutterOperation(side, highlighter); } private class MyGutterOperation { @NotNull private final Side mySide; @NotNull private final RangeHighlighter myHighlighter; private boolean myCtrlPressed; private boolean myShiftPressed; private MyGutterOperation(@NotNull Side side, @NotNull RangeHighlighter highlighter) { mySide = side; myHighlighter = highlighter; update(true); } public void destroy() { myHighlighter.dispose(); } public void update(boolean force) { if (!force && !areModifiersChanged()) { return; } if (myHighlighter.isValid()) myHighlighter.setGutterIconRenderer(createRenderer()); } private boolean areModifiersChanged() { return myCtrlPressed != myViewer.getModifierProvider().isCtrlPressed() || myShiftPressed != myViewer.getModifierProvider().isShiftPressed(); } @Nullable public GutterIconRenderer createRenderer() { assert myEditor1 != null && myEditor2 != null; myCtrlPressed = myViewer.getModifierProvider().isCtrlPressed(); myShiftPressed = myViewer.getModifierProvider().isShiftPressed(); boolean isEditable = DiffUtil.isEditable(mySide.select(myEditor1, myEditor2)); boolean isOtherEditable = DiffUtil.isEditable(mySide.other().select(myEditor1, myEditor2)); boolean isAppendable = myFragment.getStartLine1() != myFragment.getEndLine1() && myFragment.getStartLine2() != myFragment.getEndLine2(); if ((myShiftPressed || !isOtherEditable) && isEditable) { return createRevertRenderer(mySide); } if (myCtrlPressed && isAppendable) { return createAppendRenderer(mySide); } return createApplyRenderer(mySide); } } @Nullable private GutterIconRenderer createApplyRenderer(@NotNull final Side side) { return createIconRenderer(side, "Replace", AllIcons.Diff.Arrow, new Runnable() { @Override public void run() { replaceChange(side); } }); } @Nullable private GutterIconRenderer createAppendRenderer(@NotNull final Side side) { return createIconRenderer(side, "Insert", AllIcons.Diff.ArrowLeftDown, new Runnable() { @Override public void run() { appendChange(side); } }); } @Nullable private GutterIconRenderer createRevertRenderer(@NotNull final Side side) { return createIconRenderer(side.other(), "Revert", AllIcons.Diff.Remove, new Runnable() { @Override public void run() { replaceChange(side.other()); } }); } @Nullable private GutterIconRenderer createIconRenderer(@NotNull final Side sourceSide, @NotNull final String tooltipText, @NotNull final Icon icon, @NotNull final Runnable perform) { assert myEditor1 != null && myEditor2 != null; if (!DiffUtil.isEditable(sourceSide.other().select(myEditor1, myEditor2))) return null; return new GutterIconRenderer() { @NotNull @Override public Icon getIcon() { return icon; } public boolean isNavigateAction() { return true; } @Nullable @Override public AnAction getClickAction() { return new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { final Project project = e.getProject(); final Document document1 = myEditor1.getDocument(); final Document document2 = myEditor2.getDocument(); if (!myIsValid) return; DiffUtil.executeWriteCommand(sourceSide.other().select(document1, document2), project, "Replace change", new Runnable() { @Override public void run() { perform.run(); } }); } }; } @Override public boolean equals(Object obj) { return obj == this; } @Override public int hashCode() { return System.identityHashCode(this); } @Nullable @Override public String getTooltipText() { return tooltipText; } }; } }
diff: cleanup
platform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffChange.java
diff: cleanup
<ide><path>latform/diff-impl/src/com/intellij/diff/tools/simple/SimpleDiffChange.java <ide> myHighlighters.clear(); <ide> <ide> for (MyGutterOperation operation : myOperations) { <del> operation.destroy(); <add> operation.dispose(); <ide> } <ide> myOperations.clear(); <ide> } <ide> } <ide> <ide> for (MyGutterOperation operation : myOperations) { <del> operation.destroy(); <add> operation.dispose(); <ide> } <ide> myOperations.clear(); <ide> <ide> update(true); <ide> } <ide> <del> public void destroy() { <add> public void dispose() { <ide> myHighlighter.dispose(); <ide> } <ide>
Java
apache-2.0
a600c17f6d4c99547d8350d8b5c3740e887fccac
0
Bernardo-MG/Tabletop-Punkapocalyptic-Model,Bernardo-MG/Tabletop-Punkapocalyptic-Model
package com.wandrell.tabletop.business.model.punkapocalyptic.unit; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collection; import java.util.EventObject; import java.util.LinkedList; import javax.swing.event.EventListenerList; import com.google.common.base.MoreObjects; import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Armor; import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Equipment; import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Weapon; import com.wandrell.tabletop.business.model.punkapocalyptic.ruleset.SpecialRule; import com.wandrell.tabletop.business.model.punkapocalyptic.unit.event.UnitListener; import com.wandrell.tabletop.business.model.valuebox.EditableValueBox; import com.wandrell.tabletop.business.model.valuebox.ValueBox; import com.wandrell.tabletop.business.model.valuebox.derived.DerivedValueBox; import com.wandrell.tabletop.business.model.valuebox.derived.DerivedValueViewPoint; import com.wandrell.tabletop.business.model.valuebox.derived.punkapocalyptic.GroupedUnitValorationDerivedValueViewPoint; import com.wandrell.tabletop.business.util.event.ValueChangeEvent; import com.wandrell.tabletop.business.util.event.ValueChangeListener; public final class GroupedUnitWrapper implements GroupedUnit, MutantUnit { private final EventListenerList listeners = new EventListenerList(); private final EditableValueBox size; private final Unit unit; private final ValueBox valoration; public GroupedUnitWrapper(final GroupedUnitWrapper unit) { super(); checkNotNull(unit, "Received a null pointer as unit"); this.unit = unit.unit.createNewInstance(); size = unit.size.createNewInstance(); final DerivedValueViewPoint store; store = new GroupedUnitValorationDerivedValueViewPoint( unit.getBaseCost(), size); valoration = new DerivedValueBox(store); size.addValueChangeListener(new ValueChangeListener() { @Override public final void valueChanged(final ValueChangeEvent event) { fireValorationChangedEvent(new EventObject(this)); } }); } public GroupedUnitWrapper(final Unit unit, final EditableValueBox size) { super(); checkNotNull(unit, "Received a null pointer as unit"); checkNotNull(size, "Received a null pointer as size"); this.unit = unit; this.size = size; final DerivedValueViewPoint store; store = new GroupedUnitValorationDerivedValueViewPoint( unit.getBaseCost(), size); valoration = new DerivedValueBox(store); size.addValueChangeListener(new ValueChangeListener() { @Override public final void valueChanged(final ValueChangeEvent event) { fireValorationChangedEvent(new EventObject(this)); } }); } @Override public final void addEquipment(final Equipment equipment) { getWrappedUnit().addEquipment(equipment); } @Override public final void addMutation(final Mutation mutation) { if (getWrappedUnit() instanceof MutantUnit) { ((MutantUnit) getWrappedUnit()).addMutation(mutation); } } @Override public final void addUnitListener(final UnitListener listener) { checkNotNull(listener, "Received a null pointer as listener"); getListeners().add(UnitListener.class, listener); getWrappedUnit().addUnitListener(listener); } @Override public final void addWeapon(final Weapon weapon) { getWrappedUnit().addWeapon(weapon); } @Override public final void clearEquipment() { getWrappedUnit().clearEquipment(); } @Override public final void clearMutations() { if (getWrappedUnit() instanceof MutantUnit) { ((MutantUnit) getWrappedUnit()).clearMutations(); } } @Override public final void clearWeapons() { getWrappedUnit().clearWeapons(); } @Override public final GroupedUnitWrapper createNewInstance() { return new GroupedUnitWrapper(this); } @Override public final Integer getActions() { return getWrappedUnit().getActions(); } @Override public final Integer getAgility() { return getWrappedUnit().getAgility(); } @Override public final Armor getArmor() { return getWrappedUnit().getArmor(); } @Override public final Integer getBaseCost() { return getWrappedUnit().getBaseCost(); } @Override public final Integer getCombat() { return getWrappedUnit().getCombat(); } @Override public final Collection<Equipment> getEquipment() { return getWrappedUnit().getEquipment(); } @Override public final EditableValueBox getGroupSize() { return size; } @Override public final Collection<Mutation> getMutations() { final Collection<Mutation> mutations; if (getWrappedUnit() instanceof MutantUnit) { mutations = ((MutantUnit) getWrappedUnit()).getMutations(); } else { mutations = new LinkedList<>(); } return mutations; } @Override public final Integer getPrecision() { return getWrappedUnit().getPrecision(); } @Override public final Collection<SpecialRule> getSpecialRules() { return getWrappedUnit().getSpecialRules(); } @Override public final Integer getStrength() { return getWrappedUnit().getStrength(); } @Override public final Integer getTech() { return getWrappedUnit().getTech(); } @Override public final Integer getToughness() { return getWrappedUnit().getToughness(); } @Override public final String getUnitName() { return getWrappedUnit().getUnitName(); } @Override public final Integer getValoration() { return getValorationValueBox().getValue(); } @Override public final Collection<Weapon> getWeapons() { return getWrappedUnit().getWeapons(); } @Override public final void removeEquipment(final Equipment equipment) { getWrappedUnit().removeEquipment(equipment); } @Override public final void removeMutation(final Mutation mutation) { if (getWrappedUnit() instanceof MutantUnit) { ((MutantUnit) getWrappedUnit()).removeMutation(mutation); } } @Override public final void removeUnitListener(final UnitListener listener) { getListeners().remove(UnitListener.class, listener); getWrappedUnit().removeUnitListener(listener); } @Override public final void removeWeapon(final Weapon weapon) { getWrappedUnit().removeWeapon(weapon); } @Override public final void setArmor(final Armor armor) { getWrappedUnit().setArmor(armor); } @Override public final String toString() { return MoreObjects.toStringHelper(this).add("name", getUnitName()) .toString(); } private final void fireValorationChangedEvent(final EventObject evt) { final UnitListener[] listnrs; listnrs = getListeners().getListeners(UnitListener.class); for (final UnitListener l : listnrs) { l.valorationChanged(evt); } } private final EventListenerList getListeners() { return listeners; } private final ValueBox getValorationValueBox() { return valoration; } private final Unit getWrappedUnit() { return unit; } }
src/main/java/com/wandrell/tabletop/business/model/punkapocalyptic/unit/GroupedUnitWrapper.java
package com.wandrell.tabletop.business.model.punkapocalyptic.unit; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collection; import java.util.EventObject; import javax.swing.event.EventListenerList; import com.google.common.base.MoreObjects; import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Armor; import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Equipment; import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Weapon; import com.wandrell.tabletop.business.model.punkapocalyptic.ruleset.SpecialRule; import com.wandrell.tabletop.business.model.punkapocalyptic.unit.event.UnitListener; import com.wandrell.tabletop.business.model.valuebox.EditableValueBox; import com.wandrell.tabletop.business.model.valuebox.ValueBox; import com.wandrell.tabletop.business.model.valuebox.derived.DerivedValueBox; import com.wandrell.tabletop.business.model.valuebox.derived.DerivedValueViewPoint; import com.wandrell.tabletop.business.model.valuebox.derived.punkapocalyptic.GroupedUnitValorationDerivedValueViewPoint; import com.wandrell.tabletop.business.util.event.ValueChangeEvent; import com.wandrell.tabletop.business.util.event.ValueChangeListener; public final class GroupedUnitWrapper implements GroupedUnit { private final EventListenerList listeners = new EventListenerList(); private final EditableValueBox size; private final Unit unit; private final ValueBox valoration; public GroupedUnitWrapper(final GroupedUnitWrapper unit) { super(); checkNotNull(unit, "Received a null pointer as unit"); this.unit = unit.unit.createNewInstance(); size = unit.size.createNewInstance(); final DerivedValueViewPoint store; store = new GroupedUnitValorationDerivedValueViewPoint( unit.getBaseCost(), size); valoration = new DerivedValueBox(store); size.addValueChangeListener(new ValueChangeListener() { @Override public final void valueChanged(final ValueChangeEvent event) { fireValorationChangedEvent(new EventObject(this)); } }); } public GroupedUnitWrapper(final Unit unit, final EditableValueBox size) { super(); checkNotNull(unit, "Received a null pointer as unit"); checkNotNull(size, "Received a null pointer as size"); this.unit = unit; this.size = size; final DerivedValueViewPoint store; store = new GroupedUnitValorationDerivedValueViewPoint( unit.getBaseCost(), size); valoration = new DerivedValueBox(store); size.addValueChangeListener(new ValueChangeListener() { @Override public final void valueChanged(final ValueChangeEvent event) { fireValorationChangedEvent(new EventObject(this)); } }); } @Override public final void addEquipment(final Equipment equipment) { getWrappedUnit().addEquipment(equipment); } @Override public final void addUnitListener(final UnitListener listener) { checkNotNull(listener, "Received a null pointer as listener"); getListeners().add(UnitListener.class, listener); getWrappedUnit().addUnitListener(listener); } @Override public final void addWeapon(final Weapon weapon) { getWrappedUnit().addWeapon(weapon); } @Override public final void clearEquipment() { getWrappedUnit().clearEquipment(); } @Override public final void clearWeapons() { getWrappedUnit().clearWeapons(); } @Override public final GroupedUnitWrapper createNewInstance() { return new GroupedUnitWrapper(this); } @Override public final Integer getActions() { return getWrappedUnit().getActions(); } @Override public final Integer getAgility() { return getWrappedUnit().getAgility(); } @Override public final Armor getArmor() { return getWrappedUnit().getArmor(); } @Override public final Integer getBaseCost() { return getWrappedUnit().getBaseCost(); } @Override public final Integer getCombat() { return getWrappedUnit().getCombat(); } @Override public final Collection<Equipment> getEquipment() { return getWrappedUnit().getEquipment(); } @Override public final EditableValueBox getGroupSize() { return size; } @Override public final Integer getPrecision() { return getWrappedUnit().getPrecision(); } @Override public final Collection<SpecialRule> getSpecialRules() { return getWrappedUnit().getSpecialRules(); } @Override public final Integer getStrength() { return getWrappedUnit().getStrength(); } @Override public final Integer getTech() { return getWrappedUnit().getTech(); } @Override public final Integer getToughness() { return getWrappedUnit().getToughness(); } @Override public final String getUnitName() { return getWrappedUnit().getUnitName(); } @Override public final Integer getValoration() { return getValorationValueBox().getValue(); } @Override public final Collection<Weapon> getWeapons() { return getWrappedUnit().getWeapons(); } @Override public final void removeEquipment(final Equipment equipment) { getWrappedUnit().removeEquipment(equipment); } @Override public final void removeUnitListener(final UnitListener listener) { getListeners().remove(UnitListener.class, listener); getWrappedUnit().removeUnitListener(listener); } @Override public final void removeWeapon(final Weapon weapon) { getWrappedUnit().removeWeapon(weapon); } @Override public final void setArmor(final Armor armor) { getWrappedUnit().setArmor(armor); } @Override public final String toString() { return MoreObjects.toStringHelper(this).add("name", getUnitName()) .toString(); } private final void fireValorationChangedEvent(final EventObject evt) { final UnitListener[] listnrs; listnrs = getListeners().getListeners(UnitListener.class); for (final UnitListener l : listnrs) { l.valorationChanged(evt); } } private final EventListenerList getListeners() { return listeners; } private final ValueBox getValorationValueBox() { return valoration; } private final Unit getWrappedUnit() { return unit; } }
Groupe Units now support mutations.
src/main/java/com/wandrell/tabletop/business/model/punkapocalyptic/unit/GroupedUnitWrapper.java
Groupe Units now support mutations.
<ide><path>rc/main/java/com/wandrell/tabletop/business/model/punkapocalyptic/unit/GroupedUnitWrapper.java <ide> <ide> import java.util.Collection; <ide> import java.util.EventObject; <add>import java.util.LinkedList; <ide> <ide> import javax.swing.event.EventListenerList; <ide> <ide> import com.wandrell.tabletop.business.util.event.ValueChangeEvent; <ide> import com.wandrell.tabletop.business.util.event.ValueChangeListener; <ide> <del>public final class GroupedUnitWrapper implements GroupedUnit { <add>public final class GroupedUnitWrapper implements GroupedUnit, MutantUnit { <ide> <ide> private final EventListenerList listeners = new EventListenerList(); <ide> private final EditableValueBox size; <ide> } <ide> <ide> @Override <add> public final void addMutation(final Mutation mutation) { <add> if (getWrappedUnit() instanceof MutantUnit) { <add> ((MutantUnit) getWrappedUnit()).addMutation(mutation); <add> } <add> } <add> <add> @Override <ide> public final void addUnitListener(final UnitListener listener) { <ide> checkNotNull(listener, "Received a null pointer as listener"); <ide> <ide> } <ide> <ide> @Override <add> public final void clearMutations() { <add> if (getWrappedUnit() instanceof MutantUnit) { <add> ((MutantUnit) getWrappedUnit()).clearMutations(); <add> } <add> } <add> <add> @Override <ide> public final void clearWeapons() { <ide> getWrappedUnit().clearWeapons(); <ide> } <ide> } <ide> <ide> @Override <add> public final Collection<Mutation> getMutations() { <add> final Collection<Mutation> mutations; <add> <add> if (getWrappedUnit() instanceof MutantUnit) { <add> mutations = ((MutantUnit) getWrappedUnit()).getMutations(); <add> } else { <add> mutations = new LinkedList<>(); <add> } <add> <add> return mutations; <add> } <add> <add> @Override <ide> public final Integer getPrecision() { <ide> return getWrappedUnit().getPrecision(); <ide> } <ide> @Override <ide> public final void removeEquipment(final Equipment equipment) { <ide> getWrappedUnit().removeEquipment(equipment); <add> } <add> <add> @Override <add> public final void removeMutation(final Mutation mutation) { <add> if (getWrappedUnit() instanceof MutantUnit) { <add> ((MutantUnit) getWrappedUnit()).removeMutation(mutation); <add> } <ide> } <ide> <ide> @Override
Java
mit
b7f9679e25450d377fc9e9049e304c4f44abf114
0
joetde/LucyTheMoocher,joetde/LucyTheMoocher
package com.lucythemoocher.graphics; import com.lucythemoocher.Globals.Globals; import com.lucythemoocher.actors.PlayerCharacter; import com.lucythemoocher.controls.GlobalController; import com.lucythemoocher.physics.Box; import com.lucythemoocher.util.Direction; import com.lucythemoocher.util.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.RectF; import android.graphics.Typeface; import android.util.SparseArray; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * Render Drawables and Background * Handle scrolling * Camera's system is used in MasterLoop * Camera is not the physical screen, but a representation of the screen, so w() et h() are independent from the * hardware screen's size. * @see MasterLoop */ public class Camera extends SurfaceView implements SurfaceHolder.Callback { private static final float CAMERASPEED = 2f; static final float BACKGROUNDSPEED = 0.5f; private static float DT_ = 1; private Box screen_; // hardware screen's size private Canvas canvas_; private float currX_; private float currY_; private float scale_; // coefficient depending on hardware screen's size private boolean canDraw_ = false; private SparseArray<Paint> hudPaints_; private RectF hudOval_; /** * Constructor */ public Camera() { super(Resources.getActivity()); float h = Resources.getActivity().getWindowManager().getDefaultDisplay().getHeight(); float w = Resources.getActivity().getWindowManager().getDefaultDisplay().getWidth(); currX_ = 1; currY_ = 1; screen_ = new Box(currX_,currY_,h,w); hudPaints_ = new SparseArray<Paint>(); initHudColors(new int[] {Color.GRAY, Color.BLACK}); hudOval_ = new RectF(0, 0, w, h); getHolder().addCallback(this); setFocusable(true); scale_ = screen_.getW() / 1000f; setSpeed(1.0f / 30.0f); this.requestFocus(); this.setFocusableInTouchMode(true); } /** * Target a position at the middle of the screen * @param x coor * @param y coor */ public void moveTo(float x, float y) { currX_ = x; currY_ = y; screen_.setX((currX_ - w() / 2)); screen_.setY((currY_ - h() / 2)); } /** * Initialize the HUD colors * @param colorArray colors to initialize */ private void initHudColors(int colorArray[]) { for (int color : colorArray) { Paint currPaint = new Paint(); currPaint.setStrokeWidth(250); currPaint.setStyle(Paint.Style.STROKE); currPaint.setColor(color); currPaint.setAlpha(50); hudPaints_.put(color, currPaint); } } /** * Update position of the camera */ public void update() { PlayerCharacter pc = Globals.getInstance().getGame().getCharacter(); // follow player if exists if (pc != null) { followPoint( pc.getCinematic().getTargetX(), pc.getCinematic().getTargetY()); } } /** * Getter */ public Box getScreen() { Box scaledScreen = new Box(screen_); scaledScreen.setH(scaledScreen.getH() / scale_); scaledScreen.setW(scaledScreen.getW() / scale_); return scaledScreen; } /** * Follow the point (x, y) without exceeding camera's speed * @param x * @param y */ public void followPoint(float x, float y) { float coeff = camSpeed() * Globals.getInstance().getGame().getDt(); float diffX = x - currX_; float diffY = y - currY_; if (diffX == 0 && diffY == 0) { return; } float ratio = (float) Math.sqrt(Math.abs(diffX) + Math.abs(diffY)); if (coeff / ratio < 1) { currX_ += diffX / ratio * coeff; currY_ += diffY / ratio * coeff; } else { currX_ += diffX; currY_ += diffY; } screen_.setX((currX_ - w() / 2)); screen_.setY((currY_ - h() / 2)); } /** * Must be called before renderings * This locking is currently handled in the MasterLoop * @return true if managed to create the canvas * @see unlockScreen * @see MasterLoop */ public boolean lockScreen() { canvas_ = getHolder().lockCanvas(); return canvas_ != null; } /** * Graphical operation to perform before drawing things * Assume the canvas is not null */ public void prepare() { canvas_.scale(scale_, scale_); } /** * Must be called after renderings, to unlock canvas * Assumes the canvas is not null * @see lockScreen */ public void unlockScreen() { getHolder().unlockCanvasAndPost(canvas_); } /** * Getter * @return True when Camera is ready for rendering */ public boolean canDraw() { return canDraw_; } /** * Getter * @return Camera's speed * * This is just a coeff used, the speed also depends on the distance with * the target point */ private float camSpeed() { return CAMERASPEED*DT_; } /** * Getter * @return Camera's height in dp pixels * * Doesn't depend on the hardware screen's size * @see #physicalH() */ public float h() { return screen_.getH() / scale_; } /** * Getter * @return Camera's width in dp pixels * * Doesn't depend on the hardware screen's size * @see #physicalW() */ public float w() { return screen_.getW() / scale_; } /** * Getter * @return height of the physical screen (real resolution) */ public float physicalH() { return screen_.getH(); } /** * Getter * @return width of the physical screen (real resolution) */ public float physicalW() { return screen_.getW(); } /** * Draw the full screen with color * @param color */ public void drawFullColor(int color) { canvas_.drawColor(color); } /** * Draw text in the middle of the screen * @param text * @param color */ public void drawCenterText(String text, int color) { Paint textPaint = new Paint(); textPaint.setColor(color); textPaint.setTextAlign(Align.CENTER); textPaint.setTextSize(60); textPaint.setTypeface(Typeface.create("Arial",Typeface.BOLD)); canvas_.scale(1/scale_, 1/scale_); canvas_.drawText(text, 200, physicalH()/2, textPaint); canvas_.scale(scale_, scale_); } /** * Draw the image at the position x y * Screen must be locked * @param x x position in dp pixels * @param y y position in dp pixels * @param image * @see #lockScreen() */ public void drawImage(float x, float y, Image image) { float xx = x - offsetx() ; float yy = y - offsety() ; canvas_.drawBitmap(image.getBitmap().getBitmap(), xx, yy, image.getBitmap().getPaint()); } /** * Draw the image without using the scrolling * @param x position in dp pixels * @param y y position in dp pixels * @param image * @see #lockScreen() */ public void drawImageOnHud(float x, float y, Image image) { drawImageOnHud(x, y, image, false); } /** * Draw the image without using the scrolling * @param x position in dp pixels * @param y y position in dp pixels * @param image * @param scale does the image need to be scaled or not * @see #lockScreen() */ public void drawImageOnHud(float x, float y, Image image, boolean scale) { if (scale) canvas_.scale(1/scale_, 1/scale_); canvas_.drawBitmap(image.getBitmap().getBitmap(), x, y, image.getBitmap().getPaint()); if (scale) canvas_.scale(scale_, scale_); } /** * Draw the HUD ellipsis, insensitive to scale * @param dir * @param c */ public void drawControlOnHud(int dir, int c) { int start_radix = 0; int radix_range = 90; int big_radix = 90; int small_radix = 180 - big_radix; if (dir == Direction.UP) { start_radix = -90 - big_radix / 2; radix_range = big_radix; } else if (dir == Direction.RIGHT) { start_radix = 0 - small_radix / 2; radix_range = small_radix; } else if (dir == Direction.DOWN) { start_radix = 90 - big_radix / 2; radix_range = big_radix; } else if (dir == Direction.LEFT) { start_radix = 180 - small_radix / 2; radix_range = small_radix; } // Insensitive to scale (quite dirty :s) canvas_.scale(1/scale_, 1/scale_); canvas_.drawArc(hudOval_, start_radix, radix_range, false, hudPaints_.get(c)); canvas_.scale(scale_, scale_); } /** * Draw the background according to the camera position * Screen must be locked * @param background * @see #lockScreen() */ public void drawBackground(Background background) { float x = -(currX_ - screen_.getW() / 2) * BACKGROUNDSPEED; float y = -(currY_ - screen_.getH() / 2) * BACKGROUNDSPEED; float offsetX = screen_.getW() / 2; float offsetY = screen_.getH() / 2; background.draw(Math.abs(offsetX-x), Math.abs(offsetY-y)); } /** * Draw the background according to the camera position * Screen must be locked * @param * @param * @param * @see #lockScreen() */ void drawBackground(Image im, float x, float y) { canvas_.drawBitmap(im.getBitmap().getBitmap(), x, y, null); } /** * Mutator * @param dt New dt speed */ public static void setSpeed(float dt) { DT_ = dt; } public boolean onTouchEvent(MotionEvent event) { GlobalController.getInstance().process(event); return true; } public boolean onKeyDown (int keyCode, KeyEvent event) { GlobalController.getInstance().processKey(keyCode, event); return true; } public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {} public void surfaceCreated(SurfaceHolder arg0) { canDraw_ = true; } public void surfaceDestroyed(SurfaceHolder arg0) { canDraw_ = false; } public float offsetx() { return screen_.getX(); } public float offsety() { return screen_.getY(); } /** * Getter * @return current scale */ public float getScale() { return scale_; } }
LucyTheMoocher/src/com/lucythemoocher/graphics/Camera.java
package com.lucythemoocher.graphics; import com.lucythemoocher.Globals.Globals; import com.lucythemoocher.actors.PlayerCharacter; import com.lucythemoocher.controls.GlobalController; import com.lucythemoocher.physics.Box; import com.lucythemoocher.util.Direction; import com.lucythemoocher.util.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.RectF; import android.graphics.Typeface; import android.util.SparseArray; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * Render Drawables and Background * Handle scrolling * Camera's system is used in MasterLoop * Camera is not the physical screen, but a representation of the screen, so w() et h() are independent from the * hardware screen's size. * @see MasterLoop */ public class Camera extends SurfaceView implements SurfaceHolder.Callback { private static final float CAMERASPEED = 2f; static final float BACKGROUNDSPEED = 0.5f; private static float DT_ = 1; private Box screen_; // hardware screen's size private Canvas canvas_; private float currX_; private float currY_; private float scale_; // coefficient depending on hardware screen's size private boolean canDraw_ = false; private SparseArray<Paint> hudPaints_; private RectF hudOval_; /** * Constructor */ public Camera() { super(Resources.getActivity()); float h = Resources.getActivity().getWindowManager().getDefaultDisplay().getHeight(); float w = Resources.getActivity().getWindowManager().getDefaultDisplay().getWidth(); currX_ = 1; currY_ = 1; screen_ = new Box(currX_,currY_,h,w); hudPaints_ = new SparseArray<Paint>(); initHudColors(new int[] {Color.GRAY, Color.BLACK}); hudOval_ = new RectF(-100, -100, w + 100, h + 100); getHolder().addCallback(this); setFocusable(true); scale_ = screen_.getW() / 1000f; setSpeed(1.0f / 30.0f); this.requestFocus(); this.setFocusableInTouchMode(true); } /** * Target a position at the middle of the screen * @param x coor * @param y coor */ public void moveTo(float x, float y) { currX_ = x; currY_ = y; screen_.setX((currX_ - w() / 2)); screen_.setY((currY_ - h() / 2)); } /** * Initialize the HUD colors * @param colorArray colors to initialize */ private void initHudColors(int colorArray[]) { for (int color : colorArray) { Paint currPaint = new Paint(); currPaint.setStrokeWidth(250); currPaint.setStyle(Paint.Style.STROKE); currPaint.setColor(color); currPaint.setAlpha(50); hudPaints_.put(color, currPaint); } } /** * Update position of the camera */ public void update() { PlayerCharacter pc = Globals.getInstance().getGame().getCharacter(); // follow player if exists if (pc != null) { followPoint( pc.getCinematic().getTargetX(), pc.getCinematic().getTargetY()); } } /** * Getter */ public Box getScreen() { Box scaledScreen = new Box(screen_); scaledScreen.setH(scaledScreen.getH() / scale_); scaledScreen.setW(scaledScreen.getW() / scale_); return scaledScreen; } /** * Follow the point (x, y) without exceeding camera's speed * @param x * @param y */ public void followPoint(float x, float y) { float coeff = camSpeed() * Globals.getInstance().getGame().getDt(); float diffX = x - currX_; float diffY = y - currY_; if (diffX == 0 && diffY == 0) { return; } float ratio = (float) Math.sqrt(Math.abs(diffX) + Math.abs(diffY)); if (coeff / ratio < 1) { currX_ += diffX / ratio * coeff; currY_ += diffY / ratio * coeff; } else { currX_ += diffX; currY_ += diffY; } screen_.setX((currX_ - w() / 2)); screen_.setY((currY_ - h() / 2)); } /** * Must be called before renderings * This locking is currently handled in the MasterLoop * @return true if managed to create the canvas * @see unlockScreen * @see MasterLoop */ public boolean lockScreen() { canvas_ = getHolder().lockCanvas(); return canvas_ != null; } /** * Graphical operation to perform before drawing things * Assume the canvas is not null */ public void prepare() { canvas_.scale(scale_, scale_); } /** * Must be called after renderings, to unlock canvas * Assumes the canvas is not null * @see lockScreen */ public void unlockScreen() { getHolder().unlockCanvasAndPost(canvas_); } /** * Getter * @return True when Camera is ready for rendering */ public boolean canDraw() { return canDraw_; } /** * Getter * @return Camera's speed * * This is just a coeff used, the speed also depends on the distance with * the target point */ private float camSpeed() { return CAMERASPEED*DT_; } /** * Getter * @return Camera's height in dp pixels * * Doesn't depend on the hardware screen's size * @see #physicalH() */ public float h() { return screen_.getH() / scale_; } /** * Getter * @return Camera's width in dp pixels * * Doesn't depend on the hardware screen's size * @see #physicalW() */ public float w() { return screen_.getW() / scale_; } /** * Getter * @return height of the physical screen (real resolution) */ public float physicalH() { return screen_.getH(); } /** * Getter * @return width of the physical screen (real resolution) */ public float physicalW() { return screen_.getW(); } /** * Draw the full screen with color * @param color */ public void drawFullColor(int color) { canvas_.drawColor(color); } /** * Draw text in the middle of the screen * @param text * @param color */ public void drawCenterText(String text, int color) { Paint textPaint = new Paint(); textPaint.setColor(color); textPaint.setTextAlign(Align.CENTER); textPaint.setTextSize(60); textPaint.setTypeface(Typeface.create("Arial",Typeface.BOLD)); canvas_.scale(1/scale_, 1/scale_); canvas_.drawText(text, 200, physicalH()/2, textPaint); canvas_.scale(scale_, scale_); } /** * Draw the image at the position x y * Screen must be locked * @param x x position in dp pixels * @param y y position in dp pixels * @param image * @see #lockScreen() */ public void drawImage(float x, float y, Image image) { float xx = x - offsetx() ; float yy = y - offsety() ; canvas_.drawBitmap(image.getBitmap().getBitmap(), xx, yy, image.getBitmap().getPaint()); } /** * Draw the image without using the scrolling * @param x position in dp pixels * @param y y position in dp pixels * @param image * @see #lockScreen() */ public void drawImageOnHud(float x, float y, Image image) { drawImageOnHud(x, y, image, false); } /** * Draw the image without using the scrolling * @param x position in dp pixels * @param y y position in dp pixels * @param image * @param scale does the image need to be scaled or not * @see #lockScreen() */ public void drawImageOnHud(float x, float y, Image image, boolean scale) { if (scale) canvas_.scale(1/scale_, 1/scale_); canvas_.drawBitmap(image.getBitmap().getBitmap(), x, y, image.getBitmap().getPaint()); if (scale) canvas_.scale(scale_, scale_); } /** * Draw the HUD rect, insensitive to scale * @param dir * @param c */ public void drawControlOnHud(int dir, int c) { int start_radix = 0; int radix_range = 90; int big_radix = 90; int small_radix = 180 - big_radix; if (dir == Direction.UP) { start_radix = -90 - big_radix / 2; radix_range = big_radix; } else if (dir == Direction.RIGHT) { start_radix = 0 - small_radix / 2; radix_range = small_radix; } else if (dir == Direction.DOWN) { start_radix = 90 - big_radix / 2; radix_range = big_radix; } else if (dir == Direction.LEFT) { start_radix = 180 - small_radix / 2; radix_range = small_radix; } // Insensitive to scale (quite dirty :s) canvas_.scale(1/scale_, 1/scale_); canvas_.drawArc(hudOval_, start_radix, radix_range, false, hudPaints_.get(c)); canvas_.scale(scale_, scale_); } /** * Draw the background according to the camera position * Screen must be locked * @param background * @see #lockScreen() */ public void drawBackground(Background background) { float x = -(currX_ - screen_.getW() / 2) * BACKGROUNDSPEED; float y = -(currY_ - screen_.getH() / 2) * BACKGROUNDSPEED; float offsetX = screen_.getW() / 2; float offsetY = screen_.getH() / 2; background.draw(Math.abs(offsetX-x), Math.abs(offsetY-y)); } /** * Draw the background according to the camera position * Screen must be locked * @param * @param * @param * @see #lockScreen() */ void drawBackground(Image im, float x, float y) { canvas_.drawBitmap(im.getBitmap().getBitmap(), x, y, null); } /** * Mutator * @param dt New dt speed */ public static void setSpeed(float dt) { DT_ = dt; } public boolean onTouchEvent(MotionEvent event) { GlobalController.getInstance().process(event); return true; } public boolean onKeyDown (int keyCode, KeyEvent event) { GlobalController.getInstance().processKey(keyCode, event); return true; } public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {} public void surfaceCreated(SurfaceHolder arg0) { canDraw_ = true; } public void surfaceDestroyed(SurfaceHolder arg0) { canDraw_ = false; } public float offsetx() { return screen_.getX(); } public float offsety() { return screen_.getY(); } /** * Getter * @return current scale */ public float getScale() { return scale_; } }
Simplist HUD
LucyTheMoocher/src/com/lucythemoocher/graphics/Camera.java
Simplist HUD
<ide><path>ucyTheMoocher/src/com/lucythemoocher/graphics/Camera.java <ide> <ide> hudPaints_ = new SparseArray<Paint>(); <ide> initHudColors(new int[] {Color.GRAY, Color.BLACK}); <del> hudOval_ = new RectF(-100, -100, w + 100, h + 100); <add> hudOval_ = new RectF(0, 0, w, h); <ide> <ide> getHolder().addCallback(this); <ide> setFocusable(true); <ide> } <ide> <ide> /** <del> * Draw the HUD rect, insensitive to scale <add> * Draw the HUD ellipsis, insensitive to scale <ide> * @param dir <ide> * @param c <ide> */
Java
mit
1f80573be28670305ffb906a9c0416e7c879fedb
0
bptlab/JEngine,BP2014W1/JEngine,bptlab/JEngine,BP2014W1/JEngine,bptlab/JEngine,bptlab/JEngine,BP2014W1/JEngine,BP2014W1/JEngine
package de.uni_potsdam.hpi.bpt.bp2014.util; import com.google.gson.Gson; import java.util.HashMap; import java.util.LinkedList; /** * Created by Sven Ihde on 23.02.2015. */ /** * This class provides the helper methods/classes used for the JSON representation for the REST connections. */ public class JsonUtil { /** * @param content contains a LinkedList. * @return a wrapped json. */ public static String JsonWrapperLinkedList(LinkedList<Integer> content) { Gson gson = new Gson(); JsonIntegerList json = new JsonIntegerList(content); return gson.toJson(json); } /** * @param content contains a LinkedList. * @param labels contains a String. * @return a wrapped json */ public static String JsonWrapperHashMap(LinkedList<Integer> content, HashMap<Integer, String> labels) { Gson gson = new Gson(); JsonHashMapIntegerString json = new JsonHashMapIntegerString(content, labels); return gson.toJson(json); } /** * This class is a JSON HashMap containing a List of ID's and a HashMap consisting of the given ID's and labels as Strings. */ public static class JsonHashMapIntegerString { private LinkedList<Integer> ids; private HashMap<Integer, String> label; /** * constructor. * * @param ids This are the database ID's for the given Objects in the HashMap. * @param labels This is a HashMap of database ID's and the corresponding labels as a String. */ public JsonHashMapIntegerString(LinkedList<Integer> ids, HashMap<Integer, String> labels) { this.ids = ids; this.label = labels; } } /** * This class handles the JSON representation of a list filled with database ID's. */ public static class JsonIntegerList { private LinkedList<Integer> ids; /** * constructor. * * @param ids These are the database ID's of given objects. */ public JsonIntegerList(LinkedList<Integer> ids) { this.ids = ids; } } /** * This class is the representation of an Integer as JSON. */ public static class JsonInteger { private Integer id; /** * constructor. * * @param id Integer Value of a database ID. */ public JsonInteger(Integer id) { this.id = id; } } /** * This class is the representation of a HashMap that maps a String to a String. */ public static class JsonStringHashMap { private HashMap<String, String> ids; /** * constructor. * * @param ids This is a HashMap of names as a String and database ID's as a String. */ public JsonStringHashMap(HashMap<String, String> ids) { this.ids = ids; } } }
src/main/java/de/uni_potsdam/hpi/bpt/bp2014/util/JsonUtil.java
package de.uni_potsdam.hpi.bpt.bp2014.util; import com.google.gson.Gson; import java.util.HashMap; import java.util.LinkedList; /** * Created by Ihdefix on 23.02.2015. */ public class JsonUtil { /** * @param content contains a LinkedList * @return a wrapped json */ public static String JsonWrapperLinkedList(LinkedList<Integer> content) { Gson gson = new Gson(); JsonIntegerList json = new JsonIntegerList(content); return gson.toJson(json); } /** * @param content contains a LinkedList * @param labels contains a String * @return a wrapped json */ public static String JsonWrapperHashMap(LinkedList<Integer> content, HashMap<Integer, String> labels) { Gson gson = new Gson(); JsonHashMapIntegerString json = new JsonHashMapIntegerString(content, labels); return gson.toJson(json); } public static class JsonHashMapIntegerString { private LinkedList<Integer> ids; private HashMap<Integer, String> label; public JsonHashMapIntegerString(LinkedList<Integer> ids, HashMap<Integer, String> labels) { this.ids = ids; this.label = labels; } } public static class JsonIntegerList { private LinkedList<Integer> ids; public JsonIntegerList(LinkedList<Integer> ids) { this.ids = ids; } } public static class JsonInteger { private Integer id; public JsonInteger(Integer id) { this.id = id; } } public static class JsonStringHashMap { private HashMap<String, String> ids; public JsonStringHashMap(HashMap<String, String> ids) { this.ids = ids; } } }
added java-doc for JsonUtil class
src/main/java/de/uni_potsdam/hpi/bpt/bp2014/util/JsonUtil.java
added java-doc for JsonUtil class
<ide><path>rc/main/java/de/uni_potsdam/hpi/bpt/bp2014/util/JsonUtil.java <ide> import java.util.LinkedList; <ide> <ide> /** <del> * Created by Ihdefix on 23.02.2015. <add> * Created by Sven Ihde on 23.02.2015. <add> */ <add> <add>/** <add> * This class provides the helper methods/classes used for the JSON representation for the REST connections. <ide> */ <ide> public class JsonUtil { <ide> /** <del> * @param content contains a LinkedList <del> * @return a wrapped json <add> * @param content contains a LinkedList. <add> * @return a wrapped json. <ide> */ <ide> public static String JsonWrapperLinkedList(LinkedList<Integer> content) { <ide> Gson gson = new Gson(); <ide> } <ide> <ide> /** <del> * @param content contains a LinkedList <del> * @param labels contains a String <add> * @param content contains a LinkedList. <add> * @param labels contains a String. <ide> * @return a wrapped json <ide> */ <ide> public static String JsonWrapperHashMap(LinkedList<Integer> content, HashMap<Integer, String> labels) { <ide> return gson.toJson(json); <ide> } <ide> <add> /** <add> * This class is a JSON HashMap containing a List of ID's and a HashMap consisting of the given ID's and labels as Strings. <add> */ <ide> public static class JsonHashMapIntegerString { <ide> private LinkedList<Integer> ids; <ide> private HashMap<Integer, String> label; <ide> <add> /** <add> * constructor. <add> * <add> * @param ids This are the database ID's for the given Objects in the HashMap. <add> * @param labels This is a HashMap of database ID's and the corresponding labels as a String. <add> */ <ide> public JsonHashMapIntegerString(LinkedList<Integer> ids, HashMap<Integer, String> labels) { <ide> this.ids = ids; <ide> this.label = labels; <ide> } <ide> } <ide> <add> /** <add> * This class handles the JSON representation of a list filled with database ID's. <add> */ <ide> public static class JsonIntegerList { <ide> private LinkedList<Integer> ids; <ide> <add> /** <add> * constructor. <add> * <add> * @param ids These are the database ID's of given objects. <add> */ <ide> public JsonIntegerList(LinkedList<Integer> ids) { <ide> this.ids = ids; <ide> } <ide> } <ide> <add> /** <add> * This class is the representation of an Integer as JSON. <add> */ <ide> public static class JsonInteger { <ide> private Integer id; <ide> <add> /** <add> * constructor. <add> * <add> * @param id Integer Value of a database ID. <add> */ <ide> public JsonInteger(Integer id) { <ide> this.id = id; <ide> } <ide> } <add> <add> /** <add> * This class is the representation of a HashMap that maps a String to a String. <add> */ <ide> public static class JsonStringHashMap { <ide> private HashMap<String, String> ids; <ide> <add> /** <add> * constructor. <add> * <add> * @param ids This is a HashMap of names as a String and database ID's as a String. <add> */ <ide> public JsonStringHashMap(HashMap<String, String> ids) { <ide> this.ids = ids; <ide> }
JavaScript
mit
60243d9bdef3eecdbaa69b61da13fa74d5f3fd11
0
longze/my-cellar,longze/my-cellar,longze/my-cellar
/** * Created by zhaoxiaoqiang on 15/6/19. * * 提供http的接口探测和查找可用端口服务 */ const DefaultPort = 8080; /** * 查看端口是否可用 * * @param {String | Number} port 要检查的端口 * @param {Function} callback 回调函数 * {Boolean} isAvailable 是否可用(给回调的参数) */ function isAvailable(port, callback) { port = port / 1; // 参数校验 if (Number.isNaN(port)) { callback (false); } // 检查端口是否占用 else { let net = require('net'); let tester = net.createServer().once('error', function (err) { tester.close(); // 端口被占用 if (err.code === 'EADDRINUSE') { callback(false); } }).once('listening', function() { tester.close(); callback(true); }).listen(port); } } /** * 获取一个可用端口 * * @param {String | Number} port 默认端口 * @param {Function} callback 回调函数 * {Number} port 一个可用的端口 */ function getAvailablePort(port, callback) { port = port / 1; // 参数校验 if (Number.isNaN(port)) { port = DefaultPort; } isAvailable(port, function (isAvailable) { if (isAvailable === true) { callback(port); } else { port++; getAvailablePort(port, callback); } }); } module.exports = { isAvailable: isAvailable, getAvailablePort: getAvailablePort };
server/lib/port.js
/** * Created by zhaoxiaoqiang on 15/6/19. * * 提供http的接口探测和查找可用端口服务 */ var DefaultPort = 8080; /** * 查看端口是否可用 * * @param {String | Number} port 要检查的端口 * @param {Function} callback 回调函数 * {Boolean} isAvailable 是否可用(给回调的参数) */ function isAvailable(port, callback) { port = port / 1; // 参数校验 if (Number.isNaN(port)) { callback (false); } // 检查端口是否占用 else { var net = require('net'); var tester = net.createServer().once('error', function (err) { tester.close(); // 端口被占用 if (err.code === 'EADDRINUSE') { callback(false); } }).once('listening', function() { tester.close(); callback(true); }).listen(port); } } /** * 获取一个可用端口 * * @param {String | Number} port 默认端口 * @param {Function} callback 回调函数 * {Number} port 一个可用的端口 */ function getAvailablePort(port, callback) { port = port / 1; // 参数校验 if (Number.isNaN(port)) { port = DefaultPort; } isAvailable(port, function (isAvailable) { if (isAvailable === true) { callback(port); } else { port++; getAvailablePort(port, callback); } }); } module.exports = { isAvailable: isAvailable, getAvailablePort: getAvailablePort };
部分改成了 ES6 的语法
server/lib/port.js
部分改成了 ES6 的语法
<ide><path>erver/lib/port.js <ide> * 提供http的接口探测和查找可用端口服务 <ide> */ <ide> <del>var DefaultPort = 8080; <add>const DefaultPort = 8080; <add> <ide> /** <ide> * 查看端口是否可用 <ide> * <ide> } <ide> // 检查端口是否占用 <ide> else { <del> var net = require('net'); <del> var tester = net.createServer().once('error', function (err) { <add> let net = require('net'); <add> let tester = net.createServer().once('error', function (err) { <ide> tester.close(); <ide> // 端口被占用 <ide> if (err.code === 'EADDRINUSE') {
Java
mit
6ece6c4a691e7cea136597cb77e7c803bb002814
0
KJ4IPS/KaBan
package guru.haun.kaban.listener; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.UUID; import guru.haun.kaban.KaBan; import guru.haun.kaban.KaBanBanEntry; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result; public class KabanPreLoginListener implements Listener { private static Date timeZero; private KaBan kaban; public KabanPreLoginListener(KaBan kaban){ this.kaban = kaban; Calendar tempCal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); tempCal.setTimeInMillis(0); timeZero = tempCal.getTime(); } @EventHandler public void onPlayerPreLogin(AsyncPlayerPreLoginEvent e){ UUID uuid = e.getUniqueId(); String banmsg; for(KaBanBanEntry ban : kaban.banlist){ if(ban.getBanned().equals(uuid)&&!ban.hasExpired()){ e.setLoginResult(Result.KICK_BANNED); banmsg = ChatColor.DARK_AQUA + "You were banned by " + ChatColor.GOLD + ban.getBannerName() + ChatColor.DARK_AQUA +"\non " + ChatColor.YELLOW +ban.getBannedTime().toString() + ChatColor.DARK_AQUA +"\nuntil " + ChatColor.GREEN + ( ban.getExpireTime().compareTo(timeZero) == 0 ? ChatColor.RED + "the end of time" : ban.getExpireTime().toString() ) + ChatColor.DARK_AQUA + "\nReason: " + ChatColor.AQUA + ban.getReason(); if(!ban.getBannedName().equalsIgnoreCase(e.getName())) banmsg += "\n" + ChatColor.LIGHT_PURPLE + "Nice try changing your name, " + ban.getBannedName() + ", or shall I say, " + e.getName(); e.setKickMessage(banmsg); } } } }
src/main/java/guru/haun/kaban/listener/KabanPreLoginListener.java
package guru.haun.kaban.listener; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.UUID; import guru.haun.kaban.KaBan; import guru.haun.kaban.KaBanBanEntry; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result; public class KabanPreLoginListener implements Listener { private static Date timeZero; private KaBan kaban; public KabanPreLoginListener(KaBan kaban){ this.kaban = kaban; Calendar tempCal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); tempCal.setTimeInMillis(0); timeZero = tempCal.getTime(); } @EventHandler public void onPlayerPreLogin(AsyncPlayerPreLoginEvent e){ UUID uuid = e.getUniqueId(); String banmsg; for(KaBanBanEntry ban : kaban.banlist){ if(ban.getBanned().equals(uuid)){ e.setLoginResult(Result.KICK_BANNED); banmsg = ChatColor.DARK_AQUA + "You were banned by " + ChatColor.GOLD + ban.getBannerName() + ChatColor.DARK_AQUA +"\non " + ChatColor.YELLOW +ban.getBannedTime().toString() + ChatColor.DARK_AQUA +"\nuntil " + ChatColor.GREEN + ( ban.getExpireTime().compareTo(timeZero) == 0 ? ChatColor.RED + "the end of time" : ban.getExpireTime().toString() ) + ChatColor.DARK_AQUA + "\nReason: " + ChatColor.AQUA + ban.getReason(); if(!ban.getBannedName().equalsIgnoreCase(e.getName())) banmsg += "\n" + ChatColor.LIGHT_PURPLE + "Nice try changing your name, " + ban.getBannedName() + ", or shall I say, " + e.getName(); e.setKickMessage(banmsg); } } } }
Re-enabled ban expiry check
src/main/java/guru/haun/kaban/listener/KabanPreLoginListener.java
Re-enabled ban expiry check
<ide><path>rc/main/java/guru/haun/kaban/listener/KabanPreLoginListener.java <ide> UUID uuid = e.getUniqueId(); <ide> String banmsg; <ide> for(KaBanBanEntry ban : kaban.banlist){ <del> if(ban.getBanned().equals(uuid)){ <add> if(ban.getBanned().equals(uuid)&&!ban.hasExpired()){ <ide> e.setLoginResult(Result.KICK_BANNED); <ide> banmsg = ChatColor.DARK_AQUA + "You were banned by " + ChatColor.GOLD + ban.getBannerName() + <ide> ChatColor.DARK_AQUA +"\non " + ChatColor.YELLOW +ban.getBannedTime().toString() +
Java
epl-1.0
error: pathspec 'src/main/java/kuleuven/group2/TestDaemon.java' did not match any file(s) known to git
777342e4b0746bd8045c174078e2ce4e2a045d09
1
MattiasBuelens/junit,MattiasBuelens/junit,MattiasBuelens/junit,MattiasBuelens/junit
package kuleuven.group2; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.junit.runner.JUnitCore; import org.junit.runner.notification.RunListener; /** * A class of test daemons for running tests periodically. */ public class TestDaemon { /** * Starts a test daemon. * * @param args * Not used arguments. */ public static void main(String[] args) { new TestDaemon(); } /** * The executor service used for periodically running the tests. */ private final ScheduledExecutorService scheduler; /** * The default initial delay for delaying the first execution. [sec] */ public static final long DEFAULT_INITIAL_DELAY = 30l; /** * The default period between successive executions. [sec] */ public static final long DEFAULT_PERIOD = 30l; /** * The run task of this test deamon. */ private RunTask runTask; /** * The JUnitCore facade used for building a test runner * for the test suite and running that same test runner * for the test suite of this test deamon. */ private final JUnitCore jUnitCore; /** * The class that contains the test suite that has to be run. */ private Class<?> testSuite; /** * Creates a new test daemon with default initial delay * and default period. */ public TestDaemon() { this(DEFAULT_INITIAL_DELAY, DEFAULT_PERIOD); } /** * Creates a new test daemon with given initial delay * and given period. * * @param initialDelay * The initial delay for this new test daemon. * @param period * The period for this new test daemon. * @throws RejectedExecutionException * If the run task cannot be scheduled for execution. * @throws IllegalArgumentException * if the given period less than or equal to zero. */ public TestDaemon(long initialDelay, long period) throws RejectedExecutionException, IllegalArgumentException{ this.jUnitCore = new JUnitCore(); this.runTask = new RunTask(); this.scheduler = Executors.newScheduledThreadPool(1); this.scheduler.scheduleAtFixedRate(this.runTask, initialDelay, period, TimeUnit.SECONDS); } /** * Sets the class with the test suite of this test daemon * to the given class. * * @param testSuite * The class with the test suite. */ public void setTestSuite(Class<?> testSuite) { if (!this.runTask.isRunning) { this.testSuite = testSuite; } else { this.notYetAcceptedClass = testSuite; } } /** * The not yet accepted class to set to the class of this test daemon after the current test. */ private Class<?> notYetAcceptedClass; /** * Sets the not yet accepted class to the class with the test suite * of this test daemon. */ private void classSetUp() { if (this.notYetAcceptedClass != null) { // TODO: Needs to be atomic this.testSuite = this.notYetAcceptedClass; } } /** * Returns the class with the test suite of this test daemon. * * @return The class with the test suite of this test daemon. */ public Class<?> getTestSuite() { return this.testSuite; } /** * Add a listener to be notified as the tests run. * * @param listener * the listener to add * @see org.junit.runner.notification.RunListener */ public void addListener(RunListener listener) { if (!this.runTask.isRunning) { // TODO: Needs to be atomic this.jUnitCore.addListener(listener); } else { this.notYetAcceptedListeners.add(listener); } } /** * The not yet accepted listeners who needs to be registered after the current run. */ private Set<RunListener> notYetAcceptedListeners = new HashSet<RunListener>(); /** * Adds the not yet accepted listeners. */ private void listenerSetUp() { for (RunListener listener : notYetAcceptedListeners) { addListener(listener); } notYetAcceptedListeners = new HashSet<RunListener>(); } private void setUp() { classSetUp(); listenerSetUp(); } /** * A class of run tasks for running the current test suite of the test daemon. */ private class RunTask implements Runnable { /** * Is this run task running. */ private boolean isRunning; /** * Creates a new run task. */ public RunTask() { } /** * Runs this run task. */ public void run() { this.isRunning = true; setUp(); if (getTestSuite() != null) { jUnitCore.run(getTestSuite()); } this.isRunning = false; } } }
src/main/java/kuleuven/group2/TestDaemon.java
TestDaemon: initial import TODO: atomic operations needed Adding a listener or changing the class may never result in a block of the requester or a block of the run task. So no synchronization is allowed for this purpose.
src/main/java/kuleuven/group2/TestDaemon.java
TestDaemon: initial import
<ide><path>rc/main/java/kuleuven/group2/TestDaemon.java <add>package kuleuven.group2; <add> <add>import java.util.HashSet; <add>import java.util.Set; <add>import java.util.concurrent.Executors; <add>import java.util.concurrent.RejectedExecutionException; <add>import java.util.concurrent.ScheduledExecutorService; <add>import java.util.concurrent.TimeUnit; <add> <add>import org.junit.runner.JUnitCore; <add>import org.junit.runner.notification.RunListener; <add> <add>/** <add> * A class of test daemons for running tests periodically. <add> */ <add>public class TestDaemon { <add> <add> /** <add> * Starts a test daemon. <add> * <add> * @param args <add> * Not used arguments. <add> */ <add> public static void main(String[] args) { <add> new TestDaemon(); <add> } <add> <add> /** <add> * The executor service used for periodically running the tests. <add> */ <add> private final ScheduledExecutorService scheduler; <add> <add> /** <add> * The default initial delay for delaying the first execution. [sec] <add> */ <add> public static final long DEFAULT_INITIAL_DELAY = 30l; <add> <add> /** <add> * The default period between successive executions. [sec] <add> */ <add> public static final long DEFAULT_PERIOD = 30l; <add> <add> /** <add> * The run task of this test deamon. <add> */ <add> private RunTask runTask; <add> <add> /** <add> * The JUnitCore facade used for building a test runner <add> * for the test suite and running that same test runner <add> * for the test suite of this test deamon. <add> */ <add> private final JUnitCore jUnitCore; <add> <add> /** <add> * The class that contains the test suite that has to be run. <add> */ <add> private Class<?> testSuite; <add> <add> /** <add> * Creates a new test daemon with default initial delay <add> * and default period. <add> */ <add> public TestDaemon() { <add> this(DEFAULT_INITIAL_DELAY, DEFAULT_PERIOD); <add> } <add> <add> /** <add> * Creates a new test daemon with given initial delay <add> * and given period. <add> * <add> * @param initialDelay <add> * The initial delay for this new test daemon. <add> * @param period <add> * The period for this new test daemon. <add> * @throws RejectedExecutionException <add> * If the run task cannot be scheduled for execution. <add> * @throws IllegalArgumentException <add> * if the given period less than or equal to zero. <add> */ <add> public TestDaemon(long initialDelay, long period) <add> throws RejectedExecutionException, IllegalArgumentException{ <add> this.jUnitCore = new JUnitCore(); <add> this.runTask = new RunTask(); <add> this.scheduler = Executors.newScheduledThreadPool(1); <add> this.scheduler.scheduleAtFixedRate(this.runTask, initialDelay, period, TimeUnit.SECONDS); <add> } <add> <add> /** <add> * Sets the class with the test suite of this test daemon <add> * to the given class. <add> * <add> * @param testSuite <add> * The class with the test suite. <add> */ <add> public void setTestSuite(Class<?> testSuite) { <add> if (!this.runTask.isRunning) { <add> this.testSuite = testSuite; <add> } else { <add> this.notYetAcceptedClass = testSuite; <add> } <add> } <add> <add> /** <add> * The not yet accepted class to set to the class of this test daemon after the current test. <add> */ <add> private Class<?> notYetAcceptedClass; <add> <add> /** <add> * Sets the not yet accepted class to the class with the test suite <add> * of this test daemon. <add> */ <add> private void classSetUp() { <add> if (this.notYetAcceptedClass != null) { // TODO: Needs to be atomic <add> this.testSuite = this.notYetAcceptedClass; <add> } <add> } <add> <add> /** <add> * Returns the class with the test suite of this test daemon. <add> * <add> * @return The class with the test suite of this test daemon. <add> */ <add> public Class<?> getTestSuite() { <add> return this.testSuite; <add> } <add> <add> /** <add> * Add a listener to be notified as the tests run. <add> * <add> * @param listener <add> * the listener to add <add> * @see org.junit.runner.notification.RunListener <add> */ <add> public void addListener(RunListener listener) { <add> if (!this.runTask.isRunning) { // TODO: Needs to be atomic <add> this.jUnitCore.addListener(listener); <add> } else { <add> this.notYetAcceptedListeners.add(listener); <add> } <add> } <add> <add> /** <add> * The not yet accepted listeners who needs to be registered after the current run. <add> */ <add> private Set<RunListener> notYetAcceptedListeners = new HashSet<RunListener>(); <add> <add> /** <add> * Adds the not yet accepted listeners. <add> */ <add> private void listenerSetUp() { <add> for (RunListener listener : notYetAcceptedListeners) { <add> addListener(listener); <add> } <add> notYetAcceptedListeners = new HashSet<RunListener>(); <add> } <add> <add> private void setUp() { <add> classSetUp(); <add> listenerSetUp(); <add> } <add> <add> /** <add> * A class of run tasks for running the current test suite of the test daemon. <add> */ <add> private class RunTask implements Runnable { <add> <add> /** <add> * Is this run task running. <add> */ <add> private boolean isRunning; <add> <add> /** <add> * Creates a new run task. <add> */ <add> public RunTask() { <add> <add> } <add> <add> /** <add> * Runs this run task. <add> */ <add> public void run() { <add> <add> this.isRunning = true; <add> <add> setUp(); <add> <add> if (getTestSuite() != null) { <add> jUnitCore.run(getTestSuite()); <add> } <add> <add> this.isRunning = false; <add> } <add> } <add>}
Java
apache-2.0
3ddfb0fbe86811abe8bdf6784abcc9d7a6fac84e
0
wrooot/Spark,speedy01/Spark,wrooot/Spark,igniterealtime/Spark,wrooot/Spark,igniterealtime/Spark,speedy01/Spark,igniterealtime/Spark,wrooot/Spark,guusdk/Spark,guusdk/Spark,speedy01/Spark,speedy01/Spark,guusdk/Spark,guusdk/Spark,igniterealtime/Spark
package org.jivesoftware.spark.roar; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import org.jivesoftware.spark.util.log.Log; public class RoarResources { private static PropertyResourceBundle prb; static ClassLoader cl = RoarResources.class.getClassLoader(); static { prb = (PropertyResourceBundle) ResourceBundle.getBundle("i18n/roar_i18n"); } public static final String getString(String propertyName) { try { /* Revert to this code after Spark is moved to Java 11 or newer return prb.getString(propertyName); */ return new String(prb.getString(propertyName).getBytes("ISO-8859-1"), "UTF-8"); } catch (Exception e) { Log.error(e); return propertyName; } } }
plugins/roar/src/main/java/org/jivesoftware/spark/roar/RoarResources.java
package org.jivesoftware.spark.roar; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import org.jivesoftware.spark.util.log.Log; public class RoarResources { private static PropertyResourceBundle prb; static ClassLoader cl = RoarResources.class.getClassLoader(); static { prb = (PropertyResourceBundle) ResourceBundle.getBundle("i18n/roar_i18n"); } public static final String getString(String propertyName) { try { return prb.getString(propertyName); } catch (Exception e) { Log.error(e); return propertyName; } } }
SPARK-2093 plugins fixes
plugins/roar/src/main/java/org/jivesoftware/spark/roar/RoarResources.java
SPARK-2093 plugins fixes
<ide><path>lugins/roar/src/main/java/org/jivesoftware/spark/roar/RoarResources.java <ide> <ide> public static final String getString(String propertyName) { <ide> try { <del> return prb.getString(propertyName); <add> /* Revert to this code after Spark is moved to Java 11 or newer <add> return prb.getString(propertyName); <add> */ <add> return new String(prb.getString(propertyName).getBytes("ISO-8859-1"), "UTF-8"); <ide> } catch (Exception e) { <ide> Log.error(e); <ide> return propertyName;
Java
apache-2.0
4de329aa5b8c9c5f131c2c0109e3c2a94acb5599
0
andrewshadura/omim,victorbriz/omim,Zverik/omim,augmify/omim,syershov/omim,matsprea/omim,stangls/omim,edl00k/omim,Zverik/omim,vng/omim,TimurTarasenko/omim,bykoianko/omim,rokuz/omim,albertshift/omim,TimurTarasenko/omim,victorbriz/omim,dobriy-eeh/omim,simon247/omim,felipebetancur/omim,Komzpa/omim,VladiMihaylenko/omim,augmify/omim,Endika/omim,milchakov/omim,yunikkk/omim,therearesomewhocallmetim/omim,guard163/omim,trashkalmar/omim,bykoianko/omim,bykoianko/omim,andrewshadura/omim,mgsergio/omim,AlexanderMatveenko/omim,wersoo/omim,igrechuhin/omim,dobriy-eeh/omim,VladiMihaylenko/omim,Saicheg/omim,AlexanderMatveenko/omim,bykoianko/omim,syershov/omim,AlexanderMatveenko/omim,goblinr/omim,ygorshenin/omim,darina/omim,Komzpa/omim,dkorolev/omim,mgsergio/omim,mgsergio/omim,lydonchandra/omim,milchakov/omim,edl00k/omim,milchakov/omim,sidorov-panda/omim,Zverik/omim,vng/omim,matsprea/omim,vasilenkomike/omim,Saicheg/omim,krasin/omim,Transtech/omim,stangls/omim,Komzpa/omim,edl00k/omim,augmify/omim,mgsergio/omim,albertshift/omim,alexzatsepin/omim,jam891/omim,matsprea/omim,victorbriz/omim,Zverik/omim,dobriy-eeh/omim,augmify/omim,therearesomewhocallmetim/omim,krasin/omim,edl00k/omim,milchakov/omim,dkorolev/omim,albertshift/omim,UdjinM6/omim,Endika/omim,dkorolev/omim,darina/omim,65apps/omim,Transtech/omim,trashkalmar/omim,mpimenov/omim,milchakov/omim,darina/omim,goblinr/omim,VladiMihaylenko/omim,igrechuhin/omim,kw217/omim,vasilenkomike/omim,goblinr/omim,andrewshadura/omim,stangls/omim,augmify/omim,lydonchandra/omim,mapsme/omim,sidorov-panda/omim,mapsme/omim,programming086/omim,AlexanderMatveenko/omim,simon247/omim,Volcanoscar/omim,darina/omim,bykoianko/omim,Zverik/omim,vasilenkomike/omim,darina/omim,darina/omim,Zverik/omim,mapsme/omim,jam891/omim,Zverik/omim,ygorshenin/omim,simon247/omim,rokuz/omim,lydonchandra/omim,trashkalmar/omim,syershov/omim,milchakov/omim,65apps/omim,Endika/omim,ygorshenin/omim,Volcanoscar/omim,65apps/omim,vng/omim,65apps/omim,goblinr/omim,augmify/omim,65apps/omim,lydonchandra/omim,gardster/omim,igrechuhin/omim,jam891/omim,mgsergio/omim,Saicheg/omim,goblinr/omim,Saicheg/omim,yunikkk/omim,yunikkk/omim,programming086/omim,lydonchandra/omim,milchakov/omim,Komzpa/omim,programming086/omim,krasin/omim,AlexanderMatveenko/omim,rokuz/omim,vasilenkomike/omim,victorbriz/omim,syershov/omim,VladiMihaylenko/omim,guard163/omim,Transtech/omim,Endika/omim,milchakov/omim,mpimenov/omim,victorbriz/omim,krasin/omim,lydonchandra/omim,TimurTarasenko/omim,ygorshenin/omim,alexzatsepin/omim,mapsme/omim,felipebetancur/omim,goblinr/omim,darina/omim,rokuz/omim,Endika/omim,gardster/omim,alexzatsepin/omim,Zverik/omim,alexzatsepin/omim,TimurTarasenko/omim,Komzpa/omim,Komzpa/omim,Transtech/omim,programming086/omim,andrewshadura/omim,UdjinM6/omim,mpimenov/omim,kw217/omim,rokuz/omim,victorbriz/omim,bykoianko/omim,yunikkk/omim,TimurTarasenko/omim,trashkalmar/omim,TimurTarasenko/omim,albertshift/omim,syershov/omim,Volcanoscar/omim,Saicheg/omim,felipebetancur/omim,igrechuhin/omim,therearesomewhocallmetim/omim,Endika/omim,vladon/omim,alexzatsepin/omim,programming086/omim,edl00k/omim,UdjinM6/omim,vng/omim,bykoianko/omim,darina/omim,dkorolev/omim,victorbriz/omim,therearesomewhocallmetim/omim,jam891/omim,UdjinM6/omim,dobriy-eeh/omim,dkorolev/omim,simon247/omim,lydonchandra/omim,mpimenov/omim,dobriy-eeh/omim,vladon/omim,stangls/omim,yunikkk/omim,65apps/omim,gardster/omim,Volcanoscar/omim,andrewshadura/omim,Saicheg/omim,Volcanoscar/omim,goblinr/omim,jam891/omim,felipebetancur/omim,therearesomewhocallmetim/omim,wersoo/omim,rokuz/omim,gardster/omim,goblinr/omim,mgsergio/omim,guard163/omim,wersoo/omim,Transtech/omim,syershov/omim,darina/omim,mgsergio/omim,programming086/omim,kw217/omim,albertshift/omim,milchakov/omim,mapsme/omim,felipebetancur/omim,goblinr/omim,guard163/omim,yunikkk/omim,andrewshadura/omim,Endika/omim,65apps/omim,sidorov-panda/omim,Saicheg/omim,trashkalmar/omim,Zverik/omim,mapsme/omim,kw217/omim,dobriy-eeh/omim,vladon/omim,UdjinM6/omim,rokuz/omim,igrechuhin/omim,augmify/omim,felipebetancur/omim,vasilenkomike/omim,mgsergio/omim,goblinr/omim,programming086/omim,matsprea/omim,jam891/omim,albertshift/omim,AlexanderMatveenko/omim,ygorshenin/omim,Volcanoscar/omim,guard163/omim,65apps/omim,albertshift/omim,wersoo/omim,gardster/omim,Zverik/omim,AlexanderMatveenko/omim,simon247/omim,vladon/omim,ygorshenin/omim,syershov/omim,yunikkk/omim,trashkalmar/omim,VladiMihaylenko/omim,kw217/omim,igrechuhin/omim,jam891/omim,vladon/omim,krasin/omim,therearesomewhocallmetim/omim,bykoianko/omim,wersoo/omim,alexzatsepin/omim,matsprea/omim,sidorov-panda/omim,milchakov/omim,Volcanoscar/omim,VladiMihaylenko/omim,syershov/omim,kw217/omim,jam891/omim,sidorov-panda/omim,vladon/omim,albertshift/omim,Endika/omim,stangls/omim,mpimenov/omim,simon247/omim,edl00k/omim,AlexanderMatveenko/omim,guard163/omim,bykoianko/omim,alexzatsepin/omim,dkorolev/omim,programming086/omim,guard163/omim,ygorshenin/omim,VladiMihaylenko/omim,kw217/omim,krasin/omim,alexzatsepin/omim,vng/omim,Transtech/omim,albertshift/omim,UdjinM6/omim,mapsme/omim,stangls/omim,dobriy-eeh/omim,augmify/omim,felipebetancur/omim,krasin/omim,kw217/omim,augmify/omim,rokuz/omim,Transtech/omim,TimurTarasenko/omim,syershov/omim,alexzatsepin/omim,mpimenov/omim,stangls/omim,trashkalmar/omim,Transtech/omim,krasin/omim,simon247/omim,Saicheg/omim,mapsme/omim,UdjinM6/omim,vasilenkomike/omim,dobriy-eeh/omim,mpimenov/omim,VladiMihaylenko/omim,krasin/omim,augmify/omim,TimurTarasenko/omim,mgsergio/omim,felipebetancur/omim,vladon/omim,igrechuhin/omim,mpimenov/omim,edl00k/omim,andrewshadura/omim,igrechuhin/omim,vasilenkomike/omim,alexzatsepin/omim,sidorov-panda/omim,bykoianko/omim,simon247/omim,simon247/omim,65apps/omim,matsprea/omim,AlexanderMatveenko/omim,rokuz/omim,trashkalmar/omim,victorbriz/omim,alexzatsepin/omim,TimurTarasenko/omim,andrewshadura/omim,bykoianko/omim,wersoo/omim,mgsergio/omim,igrechuhin/omim,vladon/omim,vng/omim,alexzatsepin/omim,VladiMihaylenko/omim,milchakov/omim,dkorolev/omim,wersoo/omim,syershov/omim,dobriy-eeh/omim,rokuz/omim,goblinr/omim,vladon/omim,trashkalmar/omim,Saicheg/omim,felipebetancur/omim,wersoo/omim,UdjinM6/omim,mpimenov/omim,trashkalmar/omim,goblinr/omim,trashkalmar/omim,Endika/omim,alexzatsepin/omim,dkorolev/omim,therearesomewhocallmetim/omim,guard163/omim,stangls/omim,victorbriz/omim,VladiMihaylenko/omim,sidorov-panda/omim,AlexanderMatveenko/omim,ygorshenin/omim,edl00k/omim,therearesomewhocallmetim/omim,therearesomewhocallmetim/omim,dkorolev/omim,yunikkk/omim,andrewshadura/omim,Komzpa/omim,vng/omim,yunikkk/omim,65apps/omim,TimurTarasenko/omim,sidorov-panda/omim,vng/omim,gardster/omim,victorbriz/omim,mapsme/omim,Transtech/omim,gardster/omim,mapsme/omim,andrewshadura/omim,jam891/omim,mpimenov/omim,sidorov-panda/omim,matsprea/omim,VladiMihaylenko/omim,dobriy-eeh/omim,matsprea/omim,rokuz/omim,Volcanoscar/omim,mapsme/omim,ygorshenin/omim,guard163/omim,vasilenkomike/omim,Zverik/omim,matsprea/omim,goblinr/omim,vng/omim,darina/omim,trashkalmar/omim,kw217/omim,vladon/omim,mpimenov/omim,UdjinM6/omim,matsprea/omim,mapsme/omim,stangls/omim,rokuz/omim,Volcanoscar/omim,dobriy-eeh/omim,bykoianko/omim,mgsergio/omim,ygorshenin/omim,Zverik/omim,lydonchandra/omim,Volcanoscar/omim,VladiMihaylenko/omim,Transtech/omim,syershov/omim,mapsme/omim,simon247/omim,Komzpa/omim,stangls/omim,darina/omim,therearesomewhocallmetim/omim,Transtech/omim,edl00k/omim,wersoo/omim,guard163/omim,albertshift/omim,milchakov/omim,programming086/omim,programming086/omim,vasilenkomike/omim,syershov/omim,vasilenkomike/omim,dobriy-eeh/omim,dkorolev/omim,Transtech/omim,darina/omim,rokuz/omim,darina/omim,UdjinM6/omim,igrechuhin/omim,yunikkk/omim,wersoo/omim,gardster/omim,stangls/omim,mpimenov/omim,gardster/omim,ygorshenin/omim,bykoianko/omim,gardster/omim,kw217/omim,syershov/omim,lydonchandra/omim,Komzpa/omim,mpimenov/omim,Endika/omim,vng/omim,VladiMihaylenko/omim,Komzpa/omim,dobriy-eeh/omim,jam891/omim,krasin/omim,65apps/omim,felipebetancur/omim,yunikkk/omim,edl00k/omim,mgsergio/omim,ygorshenin/omim,Zverik/omim,milchakov/omim,sidorov-panda/omim,lydonchandra/omim,Saicheg/omim
package com.mapswithme.maps.downloader; import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import android.annotation.SuppressLint; import android.os.AsyncTask; import android.util.Log; import com.mapswithme.util.Utils; class DownloadChunkTask extends AsyncTask<Void, byte[], Boolean> { private static final String TAG = "DownloadChunkTask"; private long m_httpCallbackID; private String m_url; private long m_beg; private long m_end; private long m_expectedFileSize; private byte[] m_postBody; private String m_userAgent; private final int NOT_SET = -1; private final int IO_ERROR = -2; private final int INVALID_URL = -3; private final int WRITE_ERROR = -4; private final int FILE_SIZE_CHECK_FAILED = -5; private int m_httpErrorCode = NOT_SET; private long m_downloadedBytes = 0; private static Executor s_exec = Executors.newFixedThreadPool(4); native boolean onWrite(long httpCallbackID, long beg, byte[] data, long size); native void onFinish(long httpCallbackID, long httpCode, long beg, long end); public DownloadChunkTask(long httpCallbackID, String url, long beg, long end, long expectedFileSize, byte[] postBody, String userAgent) { m_httpCallbackID = httpCallbackID; m_url = url; m_beg = beg; m_end = end; m_expectedFileSize = expectedFileSize; m_postBody = postBody; m_userAgent = userAgent; } @Override protected void onPreExecute() { } private long getChunkID() { return m_beg; } @Override protected void onPostExecute(Boolean success) { //Log.i(TAG, "Writing chunk " + getChunkID()); // It seems like onPostExecute can be called (from GUI thread queue) // after the task was cancelled in destructor of HttpThread. // Reproduced by Samsung testers: touch Try Again for many times from // start activity when no connection is present. if (!isCancelled()) onFinish(m_httpCallbackID, success ? 200 : m_httpErrorCode, m_beg, m_end); } @Override protected void onProgressUpdate(byte[]... data) { if (!isCancelled()) { // Use progress event to save downloaded bytes. if (onWrite(m_httpCallbackID, m_beg + m_downloadedBytes, data[0], data[0].length)) m_downloadedBytes += data[0].length; else { // Cancel downloading and notify about error. cancel(false); onFinish(m_httpCallbackID, WRITE_ERROR, m_beg, m_end); } } } @SuppressLint("NewApi") void start() { if (Utils.apiEqualOrGreaterThan(11)) executeOnExecutor(s_exec, (Void[])null); else execute((Void[])null); } static long parseContentRange(String contentRangeValue) { if (contentRangeValue != null) { final int slashIndex = contentRangeValue.lastIndexOf('/'); if (slashIndex >= 0) { try { return Long.parseLong(contentRangeValue.substring(slashIndex + 1)); } catch (NumberFormatException ex) { // Return -1 at the end of function } } } return -1; } @Override protected Boolean doInBackground(Void... p) { //Log.i(TAG, "Start downloading chunk " + getChunkID()); HttpURLConnection urlConnection = null; try { URL url = new URL(m_url); urlConnection = (HttpURLConnection) url.openConnection(); if (isCancelled()) return false; urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(15 * 1000); urlConnection.setReadTimeout(15 * 1000); // Set user agent with unique client id urlConnection.setRequestProperty("User-Agent", m_userAgent); // use Range header only if we don't download whole file from start if (!(m_beg == 0 && m_end < 0)) { if (m_end > 0) urlConnection.setRequestProperty("Range", String.format("bytes=%d-%d", m_beg, m_end)); else urlConnection.setRequestProperty("Range", String.format("bytes=%d-", m_beg)); } if (m_postBody != null) { urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(m_postBody.length); final DataOutputStream os = new DataOutputStream(urlConnection.getOutputStream()); os.write(m_postBody); os.flush(); m_postBody = null; Utils.closeStream(os); } if (isCancelled()) return false; final int err = urlConnection.getResponseCode(); // @TODO We can handle redirect (301, 302 and 307) here and display redirected page to user, // to avoid situation when downloading is always failed by "unknown" reason // When we didn't ask for chunks, code should be 200 // When we asked for a chunk, code should be 206 final boolean isChunk = !(m_beg == 0 && m_end < 0); if ((isChunk && err != HttpURLConnection.HTTP_PARTIAL) || (!isChunk && err != HttpURLConnection.HTTP_OK)) { // we've set error code so client should be notified about the error m_httpErrorCode = FILE_SIZE_CHECK_FAILED; Log.w(TAG, "Error for " + urlConnection.getURL() + ": Server replied with code " + err + ", aborting download."); return false; } // Check for content size - are we downloading requested file or some router's garbage? if (m_expectedFileSize > 0) { long contentLength = parseContentRange(urlConnection.getHeaderField("Content-Range")); if (contentLength < 0) contentLength = urlConnection.getContentLength(); // Check even if contentLength is invalid (-1), in this case it's not our server! if (contentLength != m_expectedFileSize) { // we've set error code so client should be notified about the error m_httpErrorCode = FILE_SIZE_CHECK_FAILED; Log.w(TAG, "Error for " + urlConnection.getURL() + ": Invalid file size received (" + contentLength + ") while expecting " + m_expectedFileSize + ". Aborting download."); return false; } // @TODO Else display received web page to user - router is redirecting us to some page } return downloadFromStream(new BufferedInputStream(urlConnection.getInputStream(), 65536)); } catch (MalformedURLException ex) { Log.d(TAG, "Invalid url: " + m_url); // Notify the client about error m_httpErrorCode = INVALID_URL; return false; } catch (IOException ex) { Log.d(TAG, "IOException in doInBackground for URL: " + m_url, ex); // Notify the client about error m_httpErrorCode = IO_ERROR; return false; } finally { //Log.i(TAG, "End downloading chunk " + getChunkID()); if (urlConnection != null) urlConnection.disconnect(); else { m_httpErrorCode = IO_ERROR; return false; } } } /// Because of timeouts in InpetStream.read (for bad connection), /// try to introduce dynamic buffer size to read in one query. private boolean downloadFromStream(InputStream stream) { final int arrSize[] = { 64, 32, 1 }; int ret = -1; for (int i = 0; i < arrSize.length; ++i) { try { // download chunk from stream ret = downloadFromStreamImpl(stream, arrSize[i] * 1024); break; } catch (IOException ex) { Log.d(TAG, "IOException in downloadFromStream for chunk size: " + arrSize[i], ex); } } if (ret < 0) { // notify the client about error m_httpErrorCode = IO_ERROR; } Utils.closeStream(stream); return (ret == 0); } /// @return /// 0 - download successful; /// 1 - download canceled; /// -1 - some error occurred; private int downloadFromStreamImpl(InputStream stream, int bufferSize) throws IOException { byte[] tempBuf = new byte[bufferSize]; int readBytes; while ((readBytes = stream.read(tempBuf)) > 0) { if (isCancelled()) return 1; byte[] chunk = new byte[readBytes]; System.arraycopy(tempBuf, 0, chunk, 0, readBytes); publishProgress(chunk); } // -1 - means the end of the stream (success), else - some error occurred return (readBytes == -1 ? 0 : -1); } }
android/src/com/mapswithme/maps/downloader/DownloadChunkTask.java
package com.mapswithme.maps.downloader; import java.io.BufferedInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import android.annotation.SuppressLint; import android.os.AsyncTask; import android.util.Log; import com.mapswithme.util.Utils; class DownloadChunkTask extends AsyncTask<Void, byte[], Boolean> { private static final String TAG = "DownloadChunkTask"; private long m_httpCallbackID; private String m_url; private long m_beg; private long m_end; private long m_expectedFileSize; private byte[] m_postBody; private String m_userAgent; private final int NOT_SET = -1; private final int IO_ERROR = -2; private final int INVALID_URL = -3; private final int WRITE_ERROR = -4; private final int FILE_SIZE_CHECK_FAILED = -5; private int m_httpErrorCode = NOT_SET; private long m_downloadedBytes = 0; private static Executor s_exec = Executors.newFixedThreadPool(4); native boolean onWrite(long httpCallbackID, long beg, byte[] data, long size); native void onFinish(long httpCallbackID, long httpCode, long beg, long end); public DownloadChunkTask(long httpCallbackID, String url, long beg, long end, long expectedFileSize, byte[] postBody, String userAgent) { m_httpCallbackID = httpCallbackID; m_url = url; m_beg = beg; m_end = end; m_expectedFileSize = expectedFileSize; m_postBody = postBody; m_userAgent = userAgent; } @Override protected void onPreExecute() { } private long getChunkID() { return m_beg; } @Override protected void onPostExecute(Boolean success) { //Log.i(TAG, "Writing chunk " + getChunkID()); // It seems like onPostExecute can be called (from GUI thread queue) // after the task was cancelled in destructor of HttpThread. // Reproduced by Samsung testers: touch Try Again for many times from // start activity when no connection is present. if (!isCancelled()) onFinish(m_httpCallbackID, success ? 200 : m_httpErrorCode, m_beg, m_end); } @Override protected void onProgressUpdate(byte[]... data) { if (!isCancelled()) { // Use progress event to save downloaded bytes. if (onWrite(m_httpCallbackID, m_beg + m_downloadedBytes, data[0], data[0].length)) m_downloadedBytes += data[0].length; else { // Cancel downloading and notify about error. cancel(false); onFinish(m_httpCallbackID, WRITE_ERROR, m_beg, m_end); } } } @SuppressLint("NewApi") void start() { if (Utils.apiEqualOrGreaterThan(11)) executeOnExecutor(s_exec, (Void[])null); else execute((Void[])null); } static long parseContentRange(String contentRangeValue) { if (contentRangeValue != null) { final int slashIndex = contentRangeValue.lastIndexOf('/'); if (slashIndex >= 0) { try { return Long.parseLong(contentRangeValue.substring(slashIndex + 1)); } catch (NumberFormatException ex) { // Return -1 at the end of function } } } return -1; } @Override protected Boolean doInBackground(Void... p) { //Log.i(TAG, "Start downloading chunk " + getChunkID()); HttpURLConnection urlConnection = null; try { URL url = new URL(m_url); urlConnection = (HttpURLConnection) url.openConnection(); if (isCancelled()) return false; urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(15 * 1000); urlConnection.setReadTimeout(15 * 1000); // Set user agent with unique client id urlConnection.setRequestProperty("User-Agent", m_userAgent); // use Range header only if we don't download whole file from start if (!(m_beg == 0 && m_end < 0)) { if (m_end > 0) urlConnection.setRequestProperty("Range", String.format("bytes=%d-%d", m_beg, m_end)); else urlConnection.setRequestProperty("Range", String.format("bytes=%d-", m_beg)); } if (m_postBody != null) { urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(m_postBody.length); final DataOutputStream os = new DataOutputStream(urlConnection.getOutputStream()); os.write(m_postBody); os.flush(); m_postBody = null; Utils.closeStream(os); } if (isCancelled()) return false; final int err = urlConnection.getResponseCode(); // @TODO We can handle redirect (301, 302 and 307) here and display redirected page to user, // to avoid situation when downloading is always failed by "unknown" reason // When we didn't ask for chunks, code should be 200 // When we asked for a chunk, code should be 206 final boolean isChunk = !(m_beg == 0 && m_end < 0); if ((isChunk && err != HttpURLConnection.HTTP_PARTIAL) || (!isChunk && err != HttpURLConnection.HTTP_OK)) { // we've set error code so client should be notified about the error m_httpErrorCode = FILE_SIZE_CHECK_FAILED; Log.w(TAG, "Error for " + urlConnection.getURL() + ": Server replied with code " + err + ", aborting download."); return false; } // Check for content size - are we downloading requested file or some router's garbage? if (m_expectedFileSize > 0) { long contentLength = parseContentRange(urlConnection.getHeaderField("Content-Range")); if (contentLength < 0) contentLength = urlConnection.getContentLength(); // Check even if contentLength is invalid (-1), in this case it's not our server! if (contentLength != m_expectedFileSize) { // we've set error code so client should be notified about the error m_httpErrorCode = FILE_SIZE_CHECK_FAILED; Log.w(TAG, "Error for " + urlConnection.getURL() + ": Invalid file size received (" + contentLength + ") while expecting " + m_expectedFileSize + ". Aborting download."); return false; } // @TODO Else display received web page to user - router is redirecting us to some page } return downloadFromStream(new BufferedInputStream(urlConnection.getInputStream())); } catch (MalformedURLException ex) { Log.d(TAG, "Invalid url: " + m_url); // Notify the client about error m_httpErrorCode = INVALID_URL; return false; } catch (IOException ex) { Log.d(TAG, "IOException in doInBackground for URL: " + m_url, ex); // Notify the client about error m_httpErrorCode = IO_ERROR; return false; } finally { //Log.i(TAG, "End downloading chunk " + getChunkID()); if (urlConnection != null) urlConnection.disconnect(); else { m_httpErrorCode = IO_ERROR; return false; } } } /// Because of timeouts in InpetStream.read (for bad connection), /// try to introduce dynamic buffer size to read in one query. private boolean downloadFromStream(InputStream stream) { final int arrSize[] = { 64, 32, 1 }; int ret = -1; for (int i = 0; i < arrSize.length; ++i) { try { // download chunk from stream ret = downloadFromStreamImpl(stream, arrSize[i] * 1024); break; } catch (IOException ex) { Log.d(TAG, "IOException in downloadFromStream for chunk size: " + arrSize[i], ex); } } if (ret < 0) { // notify the client about error m_httpErrorCode = IO_ERROR; } Utils.closeStream(stream); return (ret == 0); } /// @return /// 0 - download successful; /// 1 - download canceled; /// -1 - some error occurred; private int downloadFromStreamImpl(InputStream stream, int bufferSize) throws IOException { byte[] tempBuf = new byte[bufferSize]; int readBytes; while ((readBytes = stream.read(tempBuf)) > 0) { if (isCancelled()) return 1; byte[] chunk = new byte[readBytes]; System.arraycopy(tempBuf, 0, chunk, 0, readBytes); publishProgress(chunk); } // -1 - means the end of the stream (success), else - some error occurred return (readBytes == -1 ? 0 : -1); } }
[android] Increased java's buffer size when downloading chunks
android/src/com/mapswithme/maps/downloader/DownloadChunkTask.java
[android] Increased java's buffer size when downloading chunks
<ide><path>ndroid/src/com/mapswithme/maps/downloader/DownloadChunkTask.java <ide> // @TODO Else display received web page to user - router is redirecting us to some page <ide> } <ide> <del> return downloadFromStream(new BufferedInputStream(urlConnection.getInputStream())); <add> return downloadFromStream(new BufferedInputStream(urlConnection.getInputStream(), 65536)); <ide> } <ide> catch (MalformedURLException ex) <ide> {
Java
apache-2.0
error: pathspec 'rxlist/src/main/java/rx/list/ReMapList.java' did not match any file(s) known to git
fb8ad4fe07c5702a7e84fb5732ef993cee20c5eb
1
yongjhih/RxList
package rx.list; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import android.support.v4.util.LruCache; public class ReMapList<E> extends ArrayList<E> { private ReMapList() { super(); } private ReMapList(SimpleMapper<?, E> mapper) { super(); mMapper = mapper; } public static <T, E> ReMapList create(List<? extends T> data, Mappable<T, E> mappable) { return new ReMapList(new SimpleMapper(data, mappable)); } public static class SimpleMapper<T, R> { List<? extends T> data; Mappable<T, R> mappable; LruCache<Integer, R> cache; public SimpleMapper(List<? extends T> data, Mappable<T, R> mappable) { this.data = (data != null) ? Collections.emptyList() : data; this.mappable = mappable; cache = new LruCache<Integer, R>(1000); } public R map(int index) { return mappable.map(data, index); } } private SimpleMapper<?, E> mMapper; @Override public E get(int index) { E ret = mMapper.cache.get(index); if (ret == null) { ret = mMapper.map(index); if (ret != null) { mMapper.cache.put(index, ret); } } return ret; } public E update(int index) { E ret = mMapper.map(index); if (ret != null) { mMapper.cache.put(index, ret); } return ret; } @Override public Object[] toArray() { int s = size(); Object[] result = new Object[s]; for (int i = 0; i < s; i++) { result[i] = get(i); } return result; } @Override public <T> T[] toArray(T[] contents) { int s = size(); if (contents.length < s) { @SuppressWarnings("unchecked") T[] newArray = (T[]) Array.newInstance(contents.getClass().getComponentType(), s); contents = newArray; } for (int i = 0; i < s; i++) { contents[i] = (T) get(i); } if (contents.length > s) { contents[s] = null; } return contents; } @Override public int size() { return mMapper.data.size(); } @Override public boolean isEmpty() { return size() == 0; } @Override public Iterator<E> iterator() { return listIterator(); } @Override public ListIterator<E> listIterator() { return listIterator(0); } @Override public void clear() { mMapper.data = Collections.emptyList(); mMapper.cache.evictAll(); } public List getData() { return mMapper.data; } @Override public boolean addAll(Collection<? extends E> collection) { if (!mMapper.data.isEmpty()) { return false; } if (!(collection instanceof ReMapList)) { return false; } mMapper.data = ((ReMapList) collection).getData(); return true; } @Override public ListIterator<E> listIterator(final int i) { return new ListIterator<E>() { private int index = i; @Override public boolean hasNext() { return index < size(); } @Override public E next() { return get(index++); } @Override public void add(E event) { throw new UnsupportedOperationException(); } @Override public boolean hasPrevious() { return index > 0; } @Override public int nextIndex() { return index + 1; } @Override public E previous() { return get(--index); } @Override public int previousIndex() { return index - 1; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public void set(E event) { throw new UnsupportedOperationException(); } }; } @Override public int indexOf(Object object) { int s = size(); if (object != null) { for (int i = 0; i < s; i++) { if (object.equals(get(i))) { return i; } } } else { for (int i = 0; i < s; i++) { if (get(i) == null) { return i; } } } return -1; } public interface Mappable<T, E> { E map(List<? extends T> data, int index); } }
rxlist/src/main/java/rx/list/ReMapList.java
Add ReMapList for restructuring
rxlist/src/main/java/rx/list/ReMapList.java
Add ReMapList for restructuring
<ide><path>xlist/src/main/java/rx/list/ReMapList.java <add>package rx.list; <add> <add>import java.lang.reflect.Array; <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.Collections; <add>import java.util.Iterator; <add>import java.util.List; <add>import java.util.ListIterator; <add> <add>import android.support.v4.util.LruCache; <add> <add>public class ReMapList<E> extends ArrayList<E> { <add> private ReMapList() { <add> super(); <add> } <add> <add> private ReMapList(SimpleMapper<?, E> mapper) { <add> super(); <add> <add> mMapper = mapper; <add> } <add> <add> public static <T, E> ReMapList create(List<? extends T> data, Mappable<T, E> mappable) { <add> return new ReMapList(new SimpleMapper(data, mappable)); <add> } <add> <add> public static class SimpleMapper<T, R> { <add> List<? extends T> data; <add> Mappable<T, R> mappable; <add> LruCache<Integer, R> cache; <add> <add> public SimpleMapper(List<? extends T> data, Mappable<T, R> mappable) { <add> this.data = (data != null) ? Collections.emptyList() : data; <add> this.mappable = mappable; <add> cache = new LruCache<Integer, R>(1000); <add> } <add> <add> public R map(int index) { <add> return mappable.map(data, index); <add> } <add> } <add> <add> private SimpleMapper<?, E> mMapper; <add> <add> @Override <add> public E get(int index) { <add> E ret = mMapper.cache.get(index); <add> if (ret == null) { <add> ret = mMapper.map(index); <add> if (ret != null) { <add> mMapper.cache.put(index, ret); <add> } <add> } <add> return ret; <add> } <add> <add> public E update(int index) { <add> E ret = mMapper.map(index); <add> if (ret != null) { <add> mMapper.cache.put(index, ret); <add> } <add> return ret; <add> } <add> <add> @Override <add> public Object[] toArray() { <add> int s = size(); <add> Object[] result = new Object[s]; <add> for (int i = 0; i < s; i++) { <add> result[i] = get(i); <add> } <add> return result; <add> } <add> <add> @Override <add> public <T> T[] toArray(T[] contents) { <add> int s = size(); <add> if (contents.length < s) { <add> @SuppressWarnings("unchecked") <add> T[] newArray = (T[]) Array.newInstance(contents.getClass().getComponentType(), s); <add> contents = newArray; <add> } <add> <add> for (int i = 0; i < s; i++) { <add> contents[i] = (T) get(i); <add> } <add> <add> if (contents.length > s) { <add> contents[s] = null; <add> } <add> <add> return contents; <add> } <add> <add> @Override <add> public int size() { <add> return mMapper.data.size(); <add> } <add> <add> @Override <add> public boolean isEmpty() { <add> return size() == 0; <add> } <add> <add> @Override <add> public Iterator<E> iterator() { <add> return listIterator(); <add> } <add> <add> @Override <add> public ListIterator<E> listIterator() { <add> return listIterator(0); <add> } <add> <add> @Override <add> public void clear() { <add> mMapper.data = Collections.emptyList(); <add> mMapper.cache.evictAll(); <add> } <add> <add> public List getData() { <add> return mMapper.data; <add> } <add> <add> @Override <add> public boolean addAll(Collection<? extends E> collection) { <add> if (!mMapper.data.isEmpty()) { <add> return false; <add> } <add> <add> if (!(collection instanceof ReMapList)) { <add> return false; <add> } <add> <add> mMapper.data = ((ReMapList) collection).getData(); <add> return true; <add> } <add> <add> @Override <add> public ListIterator<E> listIterator(final int i) { <add> return new ListIterator<E>() { <add> private int index = i; <add> <add> @Override <add> public boolean hasNext() { <add> return index < size(); <add> } <add> <add> @Override <add> public E next() { <add> return get(index++); <add> } <add> <add> @Override <add> public void add(E event) { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public boolean hasPrevious() { <add> return index > 0; <add> } <add> <add> @Override <add> public int nextIndex() { <add> return index + 1; <add> } <add> <add> @Override <add> public E previous() { <add> return get(--index); <add> } <add> <add> @Override <add> public int previousIndex() { <add> return index - 1; <add> } <add> <add> @Override <add> public void remove() { <add> throw new UnsupportedOperationException(); <add> } <add> <add> @Override <add> public void set(E event) { <add> throw new UnsupportedOperationException(); <add> } <add> }; <add> <add> } <add> <add> @Override <add> public int indexOf(Object object) { <add> int s = size(); <add> if (object != null) { <add> for (int i = 0; i < s; i++) { <add> if (object.equals(get(i))) { <add> return i; <add> } <add> } <add> } else { <add> for (int i = 0; i < s; i++) { <add> if (get(i) == null) { <add> return i; <add> } <add> } <add> } <add> return -1; <add> } <add> <add> public interface Mappable<T, E> { <add> E map(List<? extends T> data, int index); <add> } <add>}
JavaScript
apache-2.0
5469566f8546d124d2bb27656b39522ea6e15c06
0
VishwasShashidhar/SymphonyElectron,KiranNiranjan/SymphonyElectron,VishwasShashidhar/SymphonyElectron,KiranNiranjan/SymphonyElectron,KiranNiranjan/SymphonyElectron,VishwasShashidhar/SymphonyElectron,KiranNiranjan/SymphonyElectron,VishwasShashidhar/SymphonyElectron
'use strict'; const fs = require('fs'); const randomString = require('randomstring'); const electron = require('electron'); const childProcess = require('child_process'); const app = electron.app; const path = require('path'); const isDevEnv = require('../utils/misc.js').isDevEnv; const isMac = require('../utils/misc.js').isMac; // Search library const libSymphonySearch = require('./searchLibrary'); // Path for the exec file and the user data folder const userData = path.join(app.getPath('userData')); const execPath = path.dirname(app.getPath('exe')); // Constants paths for temp indexing folders const TEMP_BATCH_INDEX_FOLDER = isDevEnv ? './data/temp_batch_indexes' : path.join(userData, 'data/temp_batch_indexes'); const TEMP_REALTIME_INDEX = isDevEnv ? './data/temp_realtime_index' : path.join(userData, 'data/temp_realtime_index'); const INDEX_PREFIX = isDevEnv ? './data/search_index' : path.join(userData, 'data/search_index'); const INDEX_DATA_FOLDER = isDevEnv ? './data' : path.join(userData, 'data'); const SEARCH_PERIOD_SUBTRACTOR = 3 * 31 * 24 * 60 * 60 * 1000;//3 months const MINIMUM_DATE = '0000000000000'; const MAXIMUM_DATE = '9999999999999'; const INDEX_VERSION = 'v1'; const INTERNATIONAL_CHARACTER_CODES = '\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC'; const INVALID_CHARACTERS_REGEX = new RegExp('[^#$_a-z0-9' + INTERNATIONAL_CHARACTER_CODES + ']+', 'gmi'); const winArchPath = process.arch === 'ia32' ? 'library/indexvalidator-x86.exe' : 'library/indexvalidator-x64.exe'; const rootPath = isMac ? 'library/indexvalidator.exec' : winArchPath; const productionPath = path.join(execPath, isMac ? '..' : '', rootPath); const devPath = path.join(__dirname, '..', '..', rootPath); const libraryPath = isDevEnv ? devPath : productionPath; let INDEX_VALIDATOR = libraryPath; const SORT_BY_SCORE = 0; const BATCH_RANDOM_INDEX_PATH_LENGTH = 20; class Search { constructor(userId) { this.isInitialized = false; this.userId = userId; this.startIndexingFromDate = (new Date().getTime() - SEARCH_PERIOD_SUBTRACTOR).toString(); this.indexFolderName = INDEX_PREFIX + '_' + userId + '_' + INDEX_VERSION; this.dataFolder = INDEX_DATA_FOLDER; this.realTimeIndex = TEMP_REALTIME_INDEX; this.batchIndex = TEMP_BATCH_INDEX_FOLDER; this.messageData = []; this.init(); } initLib() { return new Promise((resolve) => { if (!this.isInitialized) { this.isInitialized = true; } resolve(libSymphonySearch.symSEInit()); }); } isLibInit() { return this.initLib(); } init() { libSymphonySearch.symSEInit(); libSymphonySearch.symSEEnsureFolderExists(this.dataFolder); libSymphonySearch.symSERemoveFolder(this.realTimeIndex); libSymphonySearch.symSERemoveFolder(this.batchIndex); Search.indexValidator(this.indexFolderName); Search.indexValidator(this.realTimeIndex); let indexDateStartFrom = new Date().getTime() - SEARCH_PERIOD_SUBTRACTOR; libSymphonySearch.symSEDeleteMessages(this.indexFolderName, null, MINIMUM_DATE, indexDateStartFrom.toString()); this.isInitialized = true; } indexBatch(messages) { return new Promise((resolve, reject) => { if (!this.isInitialized) { reject() } let indexId = randomString.generate(BATCH_RANDOM_INDEX_PATH_LENGTH); libSymphonySearch.symSECreatePartialIndexAsync(this.batchIndex, indexId, JSON.stringify(messages), function (err, res) { if (err) reject(err); resolve(res); }); }); } mergeIndexBatches() { let self = this; libSymphonySearch.symSEMergePartialIndexAsync(this.indexFolderName, this.batchIndex, function (err) { if (err) throw err; libSymphonySearch.symSERemoveFolder(self.batchIndex) }); } realTimeIndexing(message) { libSymphonySearch.symSEIndexRealTime(this.realTimeIndex, JSON.stringify(message)); } readJson(batch) { let self = this; return new Promise((resolve, reject) => { let dirPath = path.join(execPath, isMac ? '..' : '', 'msgsjson', batch); let messageFolderPath = isDevEnv ? path.join('./msgsjson', batch) : dirPath; let files = fs.readdirSync(messageFolderPath); self.messageData = []; files.forEach(function (file) { let tempPath = path.join(messageFolderPath, file); let data = fs.readFileSync(tempPath, "utf8"); if (data) { self.messageData.push(JSON.parse(data)); resolve(self.messageData); } else { reject("err on reading files") } }); }); } query(query, senderIds, threadIds, attachments, startDate, endDate, limit, offset, sortOrder) { let _limit = limit; let _offset = offset; let _sortOrder = sortOrder; return new Promise((resolve, reject) => { if (!this.isInitialized) { reject(-1); } let q = Search.constructQuery(query, senderIds, threadIds, attachments); if (q === undefined) { reject(-2); } let sd = new Date().getTime() - SEARCH_PERIOD_SUBTRACTOR; let sd_time = MINIMUM_DATE; if (startDate && startDate !== "" && typeof startDate === 'object') { sd_time = new Date(startDate).getTime(); if (sd_time >= sd) { sd_time = sd; } } let ed_time = MAXIMUM_DATE; if (endDate && endDate !== "" && typeof endDate === 'object') { ed_time = new Date(endDate).getTime(); } if (!_limit && _limit === "" && typeof _limit !== 'number' && Math.round(_limit) !== _limit) { _limit = 25; } if (!_offset && _offset === "" && typeof _offset !== 'number' && Math.round(_offset) !== _offset) { _offset = 0 } if (!_sortOrder && _sortOrder === "" && typeof _sortOrder !== 'number' && Math.round(_sortOrder) !== _sortOrder) { _sortOrder = SORT_BY_SCORE; } const returnedResult = libSymphonySearch.symSESearch(this.indexFolderName, this.realTimeIndex, q, sd_time.toString(), ed_time.toString(), _offset, _limit, _sortOrder); try { let ret = returnedResult.readCString(); resolve(JSON.parse(ret)); } finally { libSymphonySearch.symSEFreeResult(returnedResult); } }); } static constructQuery(query, senderId, threadId) { let q = ""; let tokens = query.toLowerCase() .trim() .replace(INVALID_CHARACTERS_REGEX, ' ') .split(' '); let hasToken = false; let hashCashTagQuery = "("; tokens.forEach((item, i) => { if (i > 0 && (item.startsWith('#') || item.startsWith('$'))) { hashCashTagQuery += " OR "; } if (item.startsWith('#') || item.startsWith('$')) { hashCashTagQuery += ("tags:\"" + item + "\""); hasToken = true; } else { q += item + " "; } }); hashCashTagQuery += ")"; if (q.replace(/ /g, "").length > 0 && hasToken) { q += " OR "; } if (tokens.length > 0 && hasToken) { q += hashCashTagQuery; } if (senderId && senderId !== "" && senderId.replace(/ /g, "").length > 0) { q += ` AND (senderId: ${senderId})`; } if (threadId && threadId !== "" && threadId.replace(/ /g, "").length > 0) { q += ` AND (threadId: ${threadId})`; } return q; } static indexValidator(file) { let data; let result = childProcess.execFileSync(INDEX_VALIDATOR, [file]).toString(); try { data = JSON.parse(result); if (data.status === 'OK') { return data; } return new Error('Unable validate index folder') } catch (err) { throw (err); } } } module.exports = { Search: Search };
js/search/search.js
'use strict'; const fs = require('fs'); const randomString = require('randomstring'); const electron = require('electron'); const childProcess = require('child_process'); const app = electron.app; const path = require('path'); const isDevEnv = require('../utils/misc.js').isDevEnv; const isMac = require('../utils/misc.js').isMac; // Search library const libSymphonySearch = require('./searchLibrary'); // Path for the exec file and the user data folder const userData = path.join(app.getPath('userData')); const execPath = path.dirname(app.getPath('exe')); // Constants paths for temp indexing folders const TEMP_BATCH_INDEX_FOLDER = isDevEnv ? './data/temp_batch_indexes' : path.join(userData, 'data/temp_batch_indexes'); const TEMP_REALTIME_INDEX = isDevEnv ? './data/temp_realtime_index' : path.join(userData, 'data/temp_realtime_index'); const INDEX_PREFIX = isDevEnv ? './data/search_index' : path.join(userData, 'data/search_index'); const INDEX_DATA_FOLDER = isDevEnv ? './data' : path.join(userData, 'data'); const SEARCH_PERIOD_SUBTRACTOR = 3 * 31 * 24 * 60 * 60 * 1000;//3 months const MINIMUM_DATE = '0000000000000'; const MAXIMUM_DATE = '9999999999999'; const INDEX_VERSION = 'v1'; const INTERNATIONAL_CHARACTER_CODES = '\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC'; const INVALID_CHARACTERS_REGEX = new RegExp('[^#$_a-z0-9' + INTERNATIONAL_CHARACTER_CODES + ']+', 'gmi'); const winArchPath = process.arch === 'ia32' ? 'library/indexvalidator-x86.exe' : 'library/indexvalidator-x64.exe'; const rootPath = isMac ? 'library/indexvalidator.exec' : winArchPath; const productionPath = path.join(execPath, isMac ? '..' : '', rootPath); const devPath = path.join(__dirname, '..', '..', rootPath); const libraryPath = isDevEnv ? devPath : productionPath; let INDEX_VALIDATOR = libraryPath; const SORT_BY_SCORE = 0; const BATCH_RANDOM_INDEX_PATH_LENGTH = 20; class Search { //TODO: fix eslint class-methods-use-this /*eslint-disable class-methods-use-this */ constructor(userId) { this.isInitialized = false; this.userId = userId; this.startIndexingFromDate = (new Date().getTime() - SEARCH_PERIOD_SUBTRACTOR).toString(); this.indexFolderName = INDEX_PREFIX + '_' + userId + '_' + INDEX_VERSION; this.init(); } initLib() { return new Promise((resolve) => { if (!this.isInitialized) { this.isInitialized = true; } resolve(libSymphonySearch.symSEInit()); }); } isLibInit() { return this.initLib(); } init() { libSymphonySearch.symSEInit(); libSymphonySearch.symSEEnsureFolderExists(INDEX_DATA_FOLDER); libSymphonySearch.symSERemoveFolder(TEMP_REALTIME_INDEX); libSymphonySearch.symSERemoveFolder(TEMP_BATCH_INDEX_FOLDER); Search.indexValidator(this.indexFolderName); Search.indexValidator(TEMP_REALTIME_INDEX); let indexDateStartFrom = new Date().getTime() - SEARCH_PERIOD_SUBTRACTOR; libSymphonySearch.symSEDeleteMessages(this.indexFolderName, null, MINIMUM_DATE, indexDateStartFrom.toString()); this.isInitialized = true; } indexBatch(messages) { return new Promise((resolve, reject) => { if (!this.isInitialized) { reject() } let indexId = randomString.generate(BATCH_RANDOM_INDEX_PATH_LENGTH); libSymphonySearch.symSECreatePartialIndexAsync(TEMP_BATCH_INDEX_FOLDER, indexId, JSON.stringify(messages), function (err, res) { if (err) reject(err); resolve(res); }); }); } mergeIndexBatches() { libSymphonySearch.symSEMergePartialIndexAsync(this.indexFolderName, TEMP_BATCH_INDEX_FOLDER, function (err) { if (err) throw err; libSymphonySearch.symSERemoveFolder(TEMP_BATCH_INDEX_FOLDER) }); } realTimeIndexing(message) { libSymphonySearch.symSEIndexRealTime(TEMP_REALTIME_INDEX, JSON.stringify(message)); } readJson(batch) { return new Promise((resolve, reject) => { let dirPath = path.join(execPath, isMac ? '..' : '', 'msgsjson', batch); let messageFolderPath = isDevEnv ? path.join('./msgsjson', batch) : dirPath; let files = fs.readdirSync(messageFolderPath); let messageData = []; files.forEach(function (file) { let tempPath = path.join(messageFolderPath, file); let data = fs.readFileSync(tempPath, "utf8"); if (data) { messageData.push(JSON.parse(data)); resolve(messageData); } else { reject("err on reading files") } }); }); } query(query, senderIds, threadIds, attachments, startDate, endDate, limit, offset, sortOrder) { return new Promise((resolve, reject) => { if (!this.isInitialized) { reject(-1); } let q = Search.constructQuery(query, senderIds, threadIds, attachments); if (q === undefined) { reject(-2); } let sd = new Date().getTime() - SEARCH_PERIOD_SUBTRACTOR; let sd_time = MINIMUM_DATE; if (startDate && startDate !== "" && typeof startDate === 'object') { sd_time = new Date(startDate).getTime(); if (sd_time >= sd) { sd_time = sd; } } let ed_time = MAXIMUM_DATE; if (endDate && endDate !== "" && typeof endDate === 'object') { ed_time = new Date(endDate).getTime(); } //TODO: fix eslint no-param-reassign /*eslint-disable no-param-reassign */ if (!limit && limit === "" && typeof limit !== 'number' && Math.round(limit) !== limit) { limit = 25; } if (!offset && offset === "" && typeof offset !== 'number' && Math.round(offset) !== offset) { offset = 0 } if (!sortOrder && sortOrder === "" && typeof sortOrder !== 'number' && Math.round(sortOrder) !== sortOrder) { sortOrder = SORT_BY_SCORE; } const returnedResult = libSymphonySearch.symSESearch(this.indexFolderName, TEMP_REALTIME_INDEX, q, sd_time.toString(), ed_time.toString(), offset, limit, sortOrder); try { let ret = returnedResult.readCString(); resolve(JSON.parse(ret)); } finally { libSymphonySearch.symSEFreeResult(returnedResult); } }); } static constructQuery(query, senderId, threadId) { let q = ""; let tokens = query.toLowerCase() .trim() .replace(INVALID_CHARACTERS_REGEX, ' ') .split(' '); let hasToken = false; let hashCashTagQuery = "("; tokens.forEach((item, i) => { if (i > 0 && (item.startsWith('#') || item.startsWith('$'))) { hashCashTagQuery += " OR "; } if (item.startsWith('#') || item.startsWith('$')) { hashCashTagQuery += ("tags:\"" + item + "\""); hasToken = true; } else { q += item + " "; } }); hashCashTagQuery += ")"; if (q.replace(/ /g, "").length > 0 && hasToken) { q += " OR "; } if (tokens.length > 0 && hasToken) { q += hashCashTagQuery; } if (senderId && senderId !== "" && senderId.replace(/ /g, "").length > 0) { q += ` AND (senderId: ${senderId})`; } if (threadId && threadId !== "" && threadId.replace(/ /g, "").length > 0) { q += ` AND (threadId: ${threadId})`; } console.log(q); return q; } static indexValidator(file) { let data; let result = childProcess.execFileSync(INDEX_VALIDATOR, [file]).toString(); try { data = JSON.parse(result); if (data.status === 'OK') { return data; } return new Error('Unable validate index folder') } catch (err) { throw (err); } } } module.exports = { Search: Search };
Fixed eslint
js/search/search.js
Fixed eslint
<ide><path>s/search/search.js <ide> const BATCH_RANDOM_INDEX_PATH_LENGTH = 20; <ide> <ide> class Search { <del> //TODO: fix eslint class-methods-use-this <del> /*eslint-disable class-methods-use-this */ <ide> <ide> constructor(userId) { <ide> this.isInitialized = false; <ide> this.userId = userId; <ide> this.startIndexingFromDate = (new Date().getTime() - SEARCH_PERIOD_SUBTRACTOR).toString(); <ide> this.indexFolderName = INDEX_PREFIX + '_' + userId + '_' + INDEX_VERSION; <add> this.dataFolder = INDEX_DATA_FOLDER; <add> this.realTimeIndex = TEMP_REALTIME_INDEX; <add> this.batchIndex = TEMP_BATCH_INDEX_FOLDER; <add> this.messageData = []; <ide> this.init(); <ide> } <ide> <ide> <ide> init() { <ide> libSymphonySearch.symSEInit(); <del> libSymphonySearch.symSEEnsureFolderExists(INDEX_DATA_FOLDER); <del> libSymphonySearch.symSERemoveFolder(TEMP_REALTIME_INDEX); <del> libSymphonySearch.symSERemoveFolder(TEMP_BATCH_INDEX_FOLDER); <add> libSymphonySearch.symSEEnsureFolderExists(this.dataFolder); <add> libSymphonySearch.symSERemoveFolder(this.realTimeIndex); <add> libSymphonySearch.symSERemoveFolder(this.batchIndex); <ide> Search.indexValidator(this.indexFolderName); <del> Search.indexValidator(TEMP_REALTIME_INDEX); <add> Search.indexValidator(this.realTimeIndex); <ide> let indexDateStartFrom = new Date().getTime() - SEARCH_PERIOD_SUBTRACTOR; <ide> libSymphonySearch.symSEDeleteMessages(this.indexFolderName, null, <ide> MINIMUM_DATE, indexDateStartFrom.toString()); <ide> reject() <ide> } <ide> let indexId = randomString.generate(BATCH_RANDOM_INDEX_PATH_LENGTH); <del> libSymphonySearch.symSECreatePartialIndexAsync(TEMP_BATCH_INDEX_FOLDER, indexId, JSON.stringify(messages), function (err, res) { <add> libSymphonySearch.symSECreatePartialIndexAsync(this.batchIndex, indexId, JSON.stringify(messages), function (err, res) { <ide> if (err) reject(err); <ide> resolve(res); <ide> }); <ide> } <ide> <ide> mergeIndexBatches() { <del> libSymphonySearch.symSEMergePartialIndexAsync(this.indexFolderName, TEMP_BATCH_INDEX_FOLDER, function (err) { <add> let self = this; <add> libSymphonySearch.symSEMergePartialIndexAsync(this.indexFolderName, this.batchIndex, function (err) { <ide> if (err) throw err; <del> libSymphonySearch.symSERemoveFolder(TEMP_BATCH_INDEX_FOLDER) <add> libSymphonySearch.symSERemoveFolder(self.batchIndex) <ide> }); <ide> } <ide> <ide> realTimeIndexing(message) { <del> libSymphonySearch.symSEIndexRealTime(TEMP_REALTIME_INDEX, JSON.stringify(message)); <add> libSymphonySearch.symSEIndexRealTime(this.realTimeIndex, JSON.stringify(message)); <ide> } <ide> <ide> readJson(batch) { <add> let self = this; <ide> return new Promise((resolve, reject) => { <ide> let dirPath = path.join(execPath, isMac ? '..' : '', 'msgsjson', batch); <ide> let messageFolderPath = isDevEnv ? path.join('./msgsjson', batch) : dirPath; <ide> let files = fs.readdirSync(messageFolderPath); <del> let messageData = []; <add> self.messageData = []; <ide> files.forEach(function (file) { <ide> let tempPath = path.join(messageFolderPath, file); <ide> let data = fs.readFileSync(tempPath, "utf8"); <ide> if (data) { <del> messageData.push(JSON.parse(data)); <del> resolve(messageData); <add> self.messageData.push(JSON.parse(data)); <add> resolve(self.messageData); <ide> } else { <ide> reject("err on reading files") <ide> } <ide> <ide> query(query, senderIds, threadIds, attachments, startDate, <ide> endDate, limit, offset, sortOrder) { <add> <add> let _limit = limit; <add> let _offset = offset; <add> let _sortOrder = sortOrder; <ide> <ide> return new Promise((resolve, reject) => { <ide> if (!this.isInitialized) { <ide> ed_time = new Date(endDate).getTime(); <ide> } <ide> <del> //TODO: fix eslint no-param-reassign <del> /*eslint-disable no-param-reassign */ <del> if (!limit && limit === "" && typeof limit !== 'number' && Math.round(limit) !== limit) { <del> limit = 25; <del> } <del> <del> if (!offset && offset === "" && typeof offset !== 'number' && Math.round(offset) !== offset) { <del> offset = 0 <del> } <del> <del> if (!sortOrder && sortOrder === "" && typeof sortOrder !== 'number' && Math.round(sortOrder) !== sortOrder) { <del> sortOrder = SORT_BY_SCORE; <del> } <del> <del> const returnedResult = libSymphonySearch.symSESearch(this.indexFolderName, TEMP_REALTIME_INDEX, q, sd_time.toString(), ed_time.toString(), offset, limit, sortOrder); <add> if (!_limit && _limit === "" && typeof _limit !== 'number' && Math.round(_limit) !== _limit) { <add> _limit = 25; <add> } <add> <add> if (!_offset && _offset === "" && typeof _offset !== 'number' && Math.round(_offset) !== _offset) { <add> _offset = 0 <add> } <add> <add> if (!_sortOrder && _sortOrder === "" && typeof _sortOrder !== 'number' && Math.round(_sortOrder) !== _sortOrder) { <add> _sortOrder = SORT_BY_SCORE; <add> } <add> <add> const returnedResult = libSymphonySearch.symSESearch(this.indexFolderName, this.realTimeIndex, q, sd_time.toString(), ed_time.toString(), _offset, _limit, _sortOrder); <ide> try { <ide> let ret = returnedResult.readCString(); <ide> resolve(JSON.parse(ret)); <ide> if (threadId && threadId !== "" && threadId.replace(/ /g, "").length > 0) { <ide> q += ` AND (threadId: ${threadId})`; <ide> } <del> console.log(q); <add> <ide> return q; <ide> } <ide>
Java
mit
54c1a92c3770e84d6d19fa3b85b340f1e045c460
0
mchaynes/northpine,mchaynes/northpine,mchaynes/northpine
package com.northpine; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; 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; import java.util.Scanner; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; /** * Scrapes ArcGIS REST Servers */ public class ScrapeJob { private static final int CHUNK_SIZE = 200; private static final String OUTPUT_FOLDER = "output"; private static final List<String> SHP_FILE_EXTENSIONS = Arrays.asList(".shp", ".prj", ".shx", ".dbf"); private static final Logger log = LoggerFactory.getLogger( ScrapeJob.class ); private String layerName; private AtomicInteger current; private AtomicInteger done; private AtomicInteger total; private boolean isDone; private String outputFileBase; private String outputZip; private String layerUrl; private String queryUrlStr; /** * @param layerUrl Does not include "/query" appended to end of url to layer. */ public ScrapeJob(String layerUrl) { current = new AtomicInteger(); total = new AtomicInteger(); this.layerUrl = layerUrl ; this.queryUrlStr = layerUrl + "/query"; this.layerName = getLayerName(); this.outputFileBase = OUTPUT_FOLDER + "/" + layerName; this.outputZip = OUTPUT_FOLDER + "/" + layerName + ".zip"; } public void startScraping() { current = new AtomicInteger(); done = new AtomicInteger(); isDone = false; URL queryUrl = getURL( queryUrlStr + "?where=1=1&returnIdsOnly=true&f=json&outSR=3857" ); JSONObject idsJson = getJsonResponse( queryUrl ); JSONArray arr = idsJson.getJSONArray( "objectIds" ); RequestConfig config = RequestConfig.DEFAULT; CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom() .setDefaultRequestConfig(config) .build(); httpClient.start(); List<String> idStrs = buildIdStrs( arr ); CountDownLatch latch = new CountDownLatch( idStrs.size() ); idStrs.stream() .map( idListStr -> "OBJECTID%20in%20(" + idListStr + ")" ) .map( queryStr -> queryUrlStr + "?f=json&outFields=*&where=" + queryStr ) .map( HttpGet::new ) .forEach( request -> httpClient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { String body = ""; try(Scanner scanner = new Scanner(response.getEntity().getContent())) { StringBuilder sb = new StringBuilder(); while(scanner.hasNext()) { sb.append( scanner.next() ); } body = sb.toString(); } catch ( IOException io ) { log.error("couldn't get body of response", io); } JSONObject jsonObject = new JSONObject( body ); int espg = jsonObject.optInt( "espg", 3857 ); jsonObject.accumulate( "ESPG", espg ); CompletableFuture.supplyAsync( () -> writeJSON( jsonObject ) ) .thenAccept( str -> addToShp( str ) ) .thenRun( latch::countDown ); } @Override public void failed(final Exception ex) { latch.countDown(); log.error(request.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); log.error(request.getRequestLine() + " cancelled"); } }) ); try { latch.await(); log.info("Done waiting for responses"); } catch ( InterruptedException e ) { log.error("Couldn't be awaited", e); } zipUpShp(); isDone = true; log.info("Zipped '" + outputZip + "'"); } public int getNumDone() { if(done != null) { return done.get(); } else { return -1; } } public String getName() { return layerName; } public int getTotal() { return total.get(); } public boolean isJobDone() { return isDone; } private String getLayerName() { String jsonLayerDeetsUrlStr = layerUrl + "?f=json"; URL jsonLayerDeetsUrl = getURL( jsonLayerDeetsUrlStr ); JSONObject response = getJsonResponse( jsonLayerDeetsUrl ); return response.getString( "name" ); } private void zipUpShp() { try (ZipOutputStream zOut = new ZipOutputStream( new FileOutputStream( new File( outputZip ) ) )) { SHP_FILE_EXTENSIONS.forEach( ext -> { try { Path pathToShp = Paths.get(outputFileBase + ext); ZipEntry entry = new ZipEntry( layerName + ext ); zOut.putNextEntry( entry ); if(Files.exists( pathToShp ) && pathToShp.toString().equals( outputFileBase + ".prj" )) { Files.copy(pathToShp, zOut); Files.deleteIfExists( pathToShp ); } zOut.closeEntry(); } catch ( IOException e ) { log.error("Couldn't zip '" + outputFileBase + ext + "'", e); } } ); } catch ( IOException e ) { log.error("Couldn't open zip '" + outputZip + "'", e); } } public String getOutput() { if ( isJobDone() ) { return outputFileBase + ".zip"; } else { return null; } } private URL getURL(String str) { try { return new URL( str ); } catch ( MalformedURLException e ) { throw new IllegalArgumentException( "Query str is invalid '" + str + "'" ); } catch ( Exception e ) { throw new IllegalArgumentException( "Just kill me now" ); } } private JSONObject getJsonResponse(URL queryUrl) { HttpURLConnection connection; try { connection = ( HttpURLConnection ) queryUrl.openConnection(); connection.setRequestMethod( "GET" ); connection.connect(); InputStream inputStream = connection.getInputStream(); Reader reader = new InputStreamReader( inputStream ); Scanner scanner = new Scanner( reader ); StringBuilder sb = new StringBuilder(); while ( scanner.hasNext() ) { sb.append( scanner.next() ); } return new JSONObject( sb.toString() ); } catch ( IOException e ) { throw new IllegalArgumentException( e ); } } private void addToShp(String jsonFile) { try { ProcessBuilder builder = new ProcessBuilder( "ogr2ogr", "-f", "ESRI Shapefile", "-append", outputFileBase + ".shp", jsonFile ); Process p = builder.start(); Scanner scanner = new Scanner( p.getInputStream() ); while(scanner.hasNextLine()) { log.error(scanner.nextLine()); } p.waitFor(); CompletableFuture.runAsync( () -> { try { Files.delete( Paths.get( jsonFile ) ); } catch ( IOException e ) { log.error("Couldn't delete " + jsonFile, e); } } ); done.incrementAndGet(); } catch ( IOException | InterruptedException e ) { log.error("ogr2ogr failed", e); } } private String writeJSON(JSONObject obj) { // e.g. 'output/wetlands1.json' String outFile = outputFileBase + current.incrementAndGet() + ".json"; try ( BufferedWriter br = new BufferedWriter( new FileWriter( new File( outFile ) ) ) ) { br.write( obj.toString() ); } catch ( IOException e ) { log.error("Couldn't write '" + outFile + "'", e); } return outFile; } private List<String> buildIdStrs(JSONArray arr) { List<String> idChunks = new ArrayList<>(); int counter = 0; StringBuilder sb = new StringBuilder(); boolean newRow = true; //Probably a string for ( Object id : arr ) { if ( counter % CHUNK_SIZE == 0 && counter != 0 ) { total.incrementAndGet(); sb.append( "," ).append( id ); idChunks.add( sb.toString() ); sb = new StringBuilder(); newRow = true; } else if ( newRow ) { sb.append( id ); newRow = false; } else { sb.append( "," ).append( id ); } counter++; } return idChunks; } }
src/main/java/com/northpine/ScrapeJob.java
package com.northpine; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; 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; import java.util.Scanner; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; /** * Scrapes ArcGIS REST Servers */ public class ScrapeJob { private static final int CHUNK_SIZE = 200; private static final String OUTPUT_FOLDER = "output"; private static final List<String> SHP_FILE_EXTENSIONS = Arrays.asList(".shp", ".prj", ".shx", ".dbf"); private static final Logger log = LoggerFactory.getLogger( ScrapeJob.class ); private String layerName; private AtomicInteger current; private AtomicInteger done; private AtomicInteger total; private boolean isDone; private String outputFileBase; private String outputZip; private String layerUrl; private String queryUrlStr; /** * @param layerUrl Does not include "/query" appended to end of url to layer. */ public ScrapeJob(String layerUrl) { current = new AtomicInteger(); total = new AtomicInteger(); this.layerUrl = layerUrl ; this.queryUrlStr = layerUrl + "/query"; this.layerName = getLayerName(); this.outputFileBase = OUTPUT_FOLDER + "/" + layerName; this.outputZip = OUTPUT_FOLDER + "/" + layerName + ".zip"; } public void startScraping() { current = new AtomicInteger(); done = new AtomicInteger(); isDone = false; URL queryUrl = getURL( queryUrlStr + "?where=1=1&returnIdsOnly=true&f=json&outSR=3857" ); JSONObject idsJson = getJsonResponse( queryUrl ); JSONArray arr = idsJson.getJSONArray( "objectIds" ); RequestConfig config = RequestConfig.DEFAULT; CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom() .setDefaultRequestConfig(config) .build(); httpClient.start(); List<String> idStrs = buildIdStrs( arr ); CountDownLatch latch = new CountDownLatch( idStrs.size() ); idStrs.stream() .map( idListStr -> "OBJECTID%20in%20(" + idListStr + ")" ) .map( queryStr -> queryUrlStr + "?f=json&outFields=*&where=" + queryStr ) .map( HttpGet::new ) .forEach( request -> httpClient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { String body = ""; try(Scanner scanner = new Scanner(response.getEntity().getContent())) { StringBuilder sb = new StringBuilder(); while(scanner.hasNext()) { sb.append( scanner.next() ); } body = sb.toString(); } catch ( IOException io ) { log.error("couldn't get body of response", io); } String finalBody = body; CompletableFuture.supplyAsync( () -> writeJSON( new JSONObject( finalBody ) ) ) .thenAccept( str -> addToShp( str ) ) .thenRun( latch::countDown ); } @Override public void failed(final Exception ex) { latch.countDown(); log.error(request.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); log.error(request.getRequestLine() + " cancelled"); } }) ); try { latch.await(); log.info("Done waiting for responses"); } catch ( InterruptedException e ) { log.error("Couldn't be awaited", e); } zipUpShp(); isDone = true; log.info("Zipped '" + outputZip + "'"); } public int getNumDone() { if(done != null) { return done.get(); } else { return -1; } } public String getName() { return layerName; } public int getTotal() { return total.get(); } public boolean isJobDone() { return isDone; } private String getLayerName() { String jsonLayerDeetsUrlStr = layerUrl + "?f=json"; URL jsonLayerDeetsUrl = getURL( jsonLayerDeetsUrlStr ); JSONObject response = getJsonResponse( jsonLayerDeetsUrl ); return response.getString( "name" ); } private void zipUpShp() { try (ZipOutputStream zOut = new ZipOutputStream( new FileOutputStream( new File( outputZip ) ) )) { SHP_FILE_EXTENSIONS.forEach( ext -> { try { Path pathToShp = Paths.get(outputFileBase + ext); ZipEntry entry = new ZipEntry( layerName + ext ); zOut.putNextEntry( entry ); if(Files.exists( pathToShp ) && pathToShp.toString().equals( outputFileBase + ".prj" )) { Files.copy(pathToShp, zOut); Files.deleteIfExists( pathToShp ); } else if(pathToShp.toString().equals( outputFileBase + ".prj" )) { log.error("Couldn't find '" + pathToShp + "', using default web_mercator.prj" ); URL filePath = Thread.currentThread().getContextClassLoader().getResource( "web_mercator.prj" ); if(filePath != null) { Path webMercator = Paths.get(filePath.getFile()); Files.copy(webMercator, zOut); } else { log.error("Something really got messed up"); } } zOut.closeEntry(); } catch ( IOException e ) { log.error("Couldn't zip '" + outputFileBase + ext + "'", e); } } ); } catch ( IOException e ) { log.error("Couldn't open zip '" + outputZip + "'", e); } } public String getOutput() { if ( isJobDone() ) { return outputFileBase + ".zip"; } else { return null; } } private URL getURL(String str) { try { return new URL( str ); } catch ( MalformedURLException e ) { throw new IllegalArgumentException( "Query str is invalid '" + str + "'" ); } catch ( Exception e ) { throw new IllegalArgumentException( "Just kill me now" ); } } private JSONObject getJsonResponse(URL queryUrl) { HttpURLConnection connection; try { connection = ( HttpURLConnection ) queryUrl.openConnection(); connection.setRequestMethod( "GET" ); connection.connect(); InputStream inputStream = connection.getInputStream(); Reader reader = new InputStreamReader( inputStream ); Scanner scanner = new Scanner( reader ); StringBuilder sb = new StringBuilder(); while ( scanner.hasNext() ) { sb.append( scanner.next() ); } return new JSONObject( sb.toString() ); } catch ( IOException e ) { throw new IllegalArgumentException( e ); } } private void addToShp(String jsonFile) { try { ProcessBuilder builder = new ProcessBuilder( "ogr2ogr", "-f", "ESRI Shapefile", "-append", outputFileBase + ".shp", jsonFile ); Process p = builder.start(); Scanner scanner = new Scanner( p.getInputStream() ); while(scanner.hasNextLine()) { log.error(scanner.nextLine()); } p.waitFor(); CompletableFuture.runAsync( () -> { try { Files.delete( Paths.get( jsonFile ) ); } catch ( IOException e ) { log.error("Couldn't delete " + jsonFile, e); } } ); done.incrementAndGet(); } catch ( IOException | InterruptedException e ) { log.error("ogr2ogr failed", e); } } private String writeJSON(JSONObject obj) { // e.g. 'output/wetlands1.json' String outFile = outputFileBase + current.incrementAndGet() + ".json"; try ( BufferedWriter br = new BufferedWriter( new FileWriter( new File( outFile ) ) ) ) { br.write( obj.toString() ); } catch ( IOException e ) { log.error("Couldn't write '" + outFile + "'", e); } return outFile; } private List<String> buildIdStrs(JSONArray arr) { List<String> idChunks = new ArrayList<>(); int counter = 0; StringBuilder sb = new StringBuilder(); boolean newRow = true; //Probably a string for ( Object id : arr ) { if ( counter % CHUNK_SIZE == 0 && counter != 0 ) { total.incrementAndGet(); sb.append( "," ).append( id ); idChunks.add( sb.toString() ); sb = new StringBuilder(); newRow = true; } else if ( newRow ) { sb.append( id ); newRow = false; } else { sb.append( "," ).append( id ); } counter++; } return idChunks; } }
trying to capitalize ESPG to see if that works with old ogr2ogr
src/main/java/com/northpine/ScrapeJob.java
trying to capitalize ESPG to see if that works with old ogr2ogr
<ide><path>rc/main/java/com/northpine/ScrapeJob.java <ide> } catch ( IOException io ) { <ide> log.error("couldn't get body of response", io); <ide> } <del> String finalBody = body; <del> CompletableFuture.supplyAsync( () -> writeJSON( new JSONObject( finalBody ) ) ) <add> JSONObject jsonObject = new JSONObject( body ); <add> int espg = jsonObject.optInt( "espg", 3857 ); <add> jsonObject.accumulate( "ESPG", espg ); <add> CompletableFuture.supplyAsync( () -> writeJSON( jsonObject ) ) <ide> .thenAccept( str -> addToShp( str ) ) <ide> .thenRun( latch::countDown ); <ide> } <ide> if(Files.exists( pathToShp ) && pathToShp.toString().equals( outputFileBase + ".prj" )) { <ide> Files.copy(pathToShp, zOut); <ide> Files.deleteIfExists( pathToShp ); <del> } else if(pathToShp.toString().equals( outputFileBase + ".prj" )) { <del> log.error("Couldn't find '" + pathToShp + "', using default web_mercator.prj" ); <del> URL filePath = Thread.currentThread().getContextClassLoader().getResource( "web_mercator.prj" ); <del> if(filePath != null) { <del> Path webMercator = Paths.get(filePath.getFile()); <del> Files.copy(webMercator, zOut); <del> } else { <del> log.error("Something really got messed up"); <del> } <ide> } <ide> zOut.closeEntry(); <ide> } catch ( IOException e ) {
Java
mit
28f6b762a1671bc947805b2df2efb5528fccf9e7
0
aquarellian/jenkins,jenkinsci/jenkins,jzjzjzj/jenkins,recena/jenkins,olivergondza/jenkins,samatdav/jenkins,rsandell/jenkins,wuwen5/jenkins,thomassuckow/jenkins,vvv444/jenkins,morficus/jenkins,wuwen5/jenkins,jglick/jenkins,github-api-test-org/jenkins,wangyikai/jenkins,v1v/jenkins,CodeShane/jenkins,liorhson/jenkins,jglick/jenkins,synopsys-arc-oss/jenkins,damianszczepanik/jenkins,my7seven/jenkins,scoheb/jenkins,rashmikanta-1984/jenkins,h4ck3rm1k3/jenkins,csimons/jenkins,lordofthejars/jenkins,arunsingh/jenkins,kzantow/jenkins,arcivanov/jenkins,Jimilian/jenkins,rlugojr/jenkins,vijayto/jenkins,godfath3r/jenkins,MadsNielsen/jtemp,damianszczepanik/jenkins,mrooney/jenkins,gusreiber/jenkins,rlugojr/jenkins,Vlatombe/jenkins,iqstack/jenkins,olivergondza/jenkins,jzjzjzj/jenkins,jzjzjzj/jenkins,kohsuke/hudson,vjuranek/jenkins,MarkEWaite/jenkins,tastatur/jenkins,godfath3r/jenkins,hemantojhaa/jenkins,jcsirot/jenkins,ajshastri/jenkins,gusreiber/jenkins,MadsNielsen/jtemp,protazy/jenkins,ikedam/jenkins,andresrc/jenkins,lindzh/jenkins,sathiya-mit/jenkins,jglick/jenkins,svanoort/jenkins,olivergondza/jenkins,vijayto/jenkins,ndeloof/jenkins,godfath3r/jenkins,daspilker/jenkins,petermarcoen/jenkins,DanielWeber/jenkins,ydubreuil/jenkins,kohsuke/hudson,arunsingh/jenkins,6WIND/jenkins,olivergondza/jenkins,everyonce/jenkins,tastatur/jenkins,MarkEWaite/jenkins,hplatou/jenkins,KostyaSha/jenkins,hashar/jenkins,dennisjlee/jenkins,mrooney/jenkins,wangyikai/jenkins,h4ck3rm1k3/jenkins,shahharsh/jenkins,jcarrothers-sap/jenkins,Krasnyanskiy/jenkins,292388900/jenkins,shahharsh/jenkins,goldchang/jenkins,batmat/jenkins,alvarolobato/jenkins,SenolOzer/jenkins,hemantojhaa/jenkins,v1v/jenkins,pjanouse/jenkins,damianszczepanik/jenkins,olivergondza/jenkins,pselle/jenkins,mrooney/jenkins,ndeloof/jenkins,292388900/jenkins,mcanthony/jenkins,kohsuke/hudson,dbroady1/jenkins,mdonohue/jenkins,jenkinsci/jenkins,synopsys-arc-oss/jenkins,bpzhang/jenkins,jk47/jenkins,paulmillar/jenkins,jpbriend/jenkins,singh88/jenkins,h4ck3rm1k3/jenkins,mattclark/jenkins,noikiy/jenkins,mrooney/jenkins,svanoort/jenkins,protazy/jenkins,pselle/jenkins,andresrc/jenkins,dennisjlee/jenkins,oleg-nenashev/jenkins,ikedam/jenkins,stephenc/jenkins,paulwellnerbou/jenkins,dennisjlee/jenkins,scoheb/jenkins,1and1/jenkins,chbiel/jenkins,daniel-beck/jenkins,christ66/jenkins,AustinKwang/jenkins,jhoblitt/jenkins,DanielWeber/jenkins,tangkun75/jenkins,tastatur/jenkins,NehemiahMi/jenkins,khmarbaise/jenkins,noikiy/jenkins,hplatou/jenkins,petermarcoen/jenkins,keyurpatankar/hudson,thomassuckow/jenkins,Ykus/jenkins,arunsingh/jenkins,Wilfred/jenkins,ChrisA89/jenkins,NehemiahMi/jenkins,damianszczepanik/jenkins,aquarellian/jenkins,kzantow/jenkins,liupugong/jenkins,pjanouse/jenkins,Ykus/jenkins,elkingtonmcb/jenkins,lordofthejars/jenkins,iqstack/jenkins,lilyJi/jenkins,svanoort/jenkins,scoheb/jenkins,andresrc/jenkins,wangyikai/jenkins,deadmoose/jenkins,bpzhang/jenkins,SebastienGllmt/jenkins,arcivanov/jenkins,tastatur/jenkins,wuwen5/jenkins,ikedam/jenkins,tangkun75/jenkins,vjuranek/jenkins,albers/jenkins,intelchen/jenkins,singh88/jenkins,singh88/jenkins,maikeffi/hudson,synopsys-arc-oss/jenkins,protazy/jenkins,daniel-beck/jenkins,jcarrothers-sap/jenkins,recena/jenkins,guoxu0514/jenkins,paulwellnerbou/jenkins,FarmGeek4Life/jenkins,tfennelly/jenkins,thomassuckow/jenkins,ydubreuil/jenkins,shahharsh/jenkins,khmarbaise/jenkins,tastatur/jenkins,DanielWeber/jenkins,jpbriend/jenkins,ChrisA89/jenkins,bkmeneguello/jenkins,daniel-beck/jenkins,everyonce/jenkins,h4ck3rm1k3/jenkins,MichaelPranovich/jenkins_sc,aquarellian/jenkins,tangkun75/jenkins,v1v/jenkins,ErikVerheul/jenkins,singh88/jenkins,gitaccountforprashant/gittest,my7seven/jenkins,wangyikai/jenkins,aldaris/jenkins,SebastienGllmt/jenkins,alvarolobato/jenkins,kzantow/jenkins,FTG-003/jenkins,evernat/jenkins,protazy/jenkins,hplatou/jenkins,jcarrothers-sap/jenkins,dariver/jenkins,huybrechts/hudson,yonglehou/jenkins,batmat/jenkins,dennisjlee/jenkins,azweb76/jenkins,batmat/jenkins,viqueen/jenkins,mcanthony/jenkins,ChrisA89/jenkins,dbroady1/jenkins,jcsirot/jenkins,iqstack/jenkins,ErikVerheul/jenkins,KostyaSha/jenkins,guoxu0514/jenkins,rashmikanta-1984/jenkins,h4ck3rm1k3/jenkins,kohsuke/hudson,intelchen/jenkins,CodeShane/jenkins,mattclark/jenkins,guoxu0514/jenkins,jenkinsci/jenkins,SebastienGllmt/jenkins,FarmGeek4Life/jenkins,maikeffi/hudson,ns163/jenkins,jk47/jenkins,jk47/jenkins,albers/jenkins,jcarrothers-sap/jenkins,hashar/jenkins,Jochen-A-Fuerbacher/jenkins,chbiel/jenkins,akshayabd/jenkins,jpederzolli/jenkins-1,Jochen-A-Fuerbacher/jenkins,viqueen/jenkins,rlugojr/jenkins,fbelzunc/jenkins,keyurpatankar/hudson,yonglehou/jenkins,goldchang/jenkins,MarkEWaite/jenkins,oleg-nenashev/jenkins,Wilfred/jenkins,FarmGeek4Life/jenkins,Wilfred/jenkins,huybrechts/hudson,gorcz/jenkins,github-api-test-org/jenkins,SebastienGllmt/jenkins,FarmGeek4Life/jenkins,jhoblitt/jenkins,daniel-beck/jenkins,jk47/jenkins,lindzh/jenkins,azweb76/jenkins,gorcz/jenkins,petermarcoen/jenkins,petermarcoen/jenkins,rashmikanta-1984/jenkins,liupugong/jenkins,viqueen/jenkins,KostyaSha/jenkins,Krasnyanskiy/jenkins,morficus/jenkins,alvarolobato/jenkins,aldaris/jenkins,Jochen-A-Fuerbacher/jenkins,escoem/jenkins,ikedam/jenkins,my7seven/jenkins,escoem/jenkins,vlajos/jenkins,gusreiber/jenkins,gusreiber/jenkins,yonglehou/jenkins,alvarolobato/jenkins,ikedam/jenkins,DoctorQ/jenkins,hplatou/jenkins,6WIND/jenkins,jpederzolli/jenkins-1,dbroady1/jenkins,SenolOzer/jenkins,tangkun75/jenkins,6WIND/jenkins,tangkun75/jenkins,daniel-beck/jenkins,thomassuckow/jenkins,patbos/jenkins,ns163/jenkins,varmenise/jenkins,ChrisA89/jenkins,vijayto/jenkins,vlajos/jenkins,jzjzjzj/jenkins,soenter/jenkins,escoem/jenkins,everyonce/jenkins,gitaccountforprashant/gittest,soenter/jenkins,vjuranek/jenkins,jzjzjzj/jenkins,aduprat/jenkins,petermarcoen/jenkins,v1v/jenkins,bpzhang/jenkins,jcsirot/jenkins,292388900/jenkins,hemantojhaa/jenkins,singh88/jenkins,MichaelPranovich/jenkins_sc,morficus/jenkins,Jochen-A-Fuerbacher/jenkins,Ykus/jenkins,aduprat/jenkins,MichaelPranovich/jenkins_sc,6WIND/jenkins,jcsirot/jenkins,wangyikai/jenkins,verbitan/jenkins,stephenc/jenkins,1and1/jenkins,Jochen-A-Fuerbacher/jenkins,svanoort/jenkins,292388900/jenkins,paulwellnerbou/jenkins,mrooney/jenkins,keyurpatankar/hudson,Jochen-A-Fuerbacher/jenkins,jk47/jenkins,arcivanov/jenkins,alvarolobato/jenkins,mcanthony/jenkins,aduprat/jenkins,akshayabd/jenkins,chbiel/jenkins,samatdav/jenkins,liorhson/jenkins,evernat/jenkins,christ66/jenkins,pjanouse/jenkins,hemantojhaa/jenkins,jcsirot/jenkins,FTG-003/jenkins,vjuranek/jenkins,aquarellian/jenkins,verbitan/jenkins,bkmeneguello/jenkins,dbroady1/jenkins,kzantow/jenkins,sathiya-mit/jenkins,nandan4/Jenkins,tangkun75/jenkins,deadmoose/jenkins,shahharsh/jenkins,arcivanov/jenkins,vlajos/jenkins,kzantow/jenkins,singh88/jenkins,amruthsoft9/Jenkis,CodeShane/jenkins,vlajos/jenkins,vvv444/jenkins,dbroady1/jenkins,ns163/jenkins,paulmillar/jenkins,nandan4/Jenkins,kohsuke/hudson,goldchang/jenkins,sathiya-mit/jenkins,morficus/jenkins,jenkinsci/jenkins,noikiy/jenkins,akshayabd/jenkins,jhoblitt/jenkins,jpbriend/jenkins,Krasnyanskiy/jenkins,amuniz/jenkins,evernat/jenkins,vvv444/jenkins,DoctorQ/jenkins,bkmeneguello/jenkins,jcarrothers-sap/jenkins,FarmGeek4Life/jenkins,khmarbaise/jenkins,yonglehou/jenkins,SenolOzer/jenkins,akshayabd/jenkins,brunocvcunha/jenkins,elkingtonmcb/jenkins,luoqii/jenkins,CodeShane/jenkins,nandan4/Jenkins,kohsuke/hudson,damianszczepanik/jenkins,aquarellian/jenkins,everyonce/jenkins,varmenise/jenkins,fbelzunc/jenkins,wuwen5/jenkins,jcarrothers-sap/jenkins,thomassuckow/jenkins,chbiel/jenkins,bkmeneguello/jenkins,liorhson/jenkins,SebastienGllmt/jenkins,goldchang/jenkins,daspilker/jenkins,deadmoose/jenkins,liupugong/jenkins,sathiya-mit/jenkins,pselle/jenkins,shahharsh/jenkins,github-api-test-org/jenkins,my7seven/jenkins,sathiya-mit/jenkins,rsandell/jenkins,noikiy/jenkins,vjuranek/jenkins,dennisjlee/jenkins,escoem/jenkins,recena/jenkins,FTG-003/jenkins,paulwellnerbou/jenkins,varmenise/jenkins,tfennelly/jenkins,lilyJi/jenkins,AustinKwang/jenkins,ndeloof/jenkins,samatdav/jenkins,mdonohue/jenkins,vijayto/jenkins,akshayabd/jenkins,paulmillar/jenkins,AustinKwang/jenkins,ydubreuil/jenkins,arunsingh/jenkins,aduprat/jenkins,kzantow/jenkins,DoctorQ/jenkins,github-api-test-org/jenkins,kzantow/jenkins,huybrechts/hudson,Wilfred/jenkins,stephenc/jenkins,SebastienGllmt/jenkins,ChrisA89/jenkins,oleg-nenashev/jenkins,my7seven/jenkins,christ66/jenkins,tfennelly/jenkins,jcarrothers-sap/jenkins,FarmGeek4Life/jenkins,elkingtonmcb/jenkins,Vlatombe/jenkins,vlajos/jenkins,rsandell/jenkins,guoxu0514/jenkins,amruthsoft9/Jenkis,msrb/jenkins,gorcz/jenkins,gusreiber/jenkins,verbitan/jenkins,mattclark/jenkins,wangyikai/jenkins,amruthsoft9/Jenkis,jcarrothers-sap/jenkins,duzifang/my-jenkins,fbelzunc/jenkins,SenolOzer/jenkins,mdonohue/jenkins,jcsirot/jenkins,liorhson/jenkins,github-api-test-org/jenkins,jhoblitt/jenkins,lindzh/jenkins,guoxu0514/jenkins,amuniz/jenkins,soenter/jenkins,jpederzolli/jenkins-1,lindzh/jenkins,jk47/jenkins,batmat/jenkins,brunocvcunha/jenkins,Vlatombe/jenkins,ydubreuil/jenkins,lordofthejars/jenkins,1and1/jenkins,escoem/jenkins,oleg-nenashev/jenkins,FTG-003/jenkins,duzifang/my-jenkins,mdonohue/jenkins,FTG-003/jenkins,patbos/jenkins,jpederzolli/jenkins-1,soenter/jenkins,goldchang/jenkins,mattclark/jenkins,batmat/jenkins,verbitan/jenkins,ns163/jenkins,morficus/jenkins,MadsNielsen/jtemp,mrooney/jenkins,CodeShane/jenkins,duzifang/my-jenkins,aquarellian/jenkins,duzifang/my-jenkins,bkmeneguello/jenkins,gorcz/jenkins,brunocvcunha/jenkins,akshayabd/jenkins,seanlin816/jenkins,hashar/jenkins,nandan4/Jenkins,recena/jenkins,arcivanov/jenkins,andresrc/jenkins,ns163/jenkins,pselle/jenkins,gitaccountforprashant/gittest,elkingtonmcb/jenkins,AustinKwang/jenkins,Jimilian/jenkins,patbos/jenkins,msrb/jenkins,damianszczepanik/jenkins,gorcz/jenkins,varmenise/jenkins,mattclark/jenkins,guoxu0514/jenkins,godfath3r/jenkins,Krasnyanskiy/jenkins,dariver/jenkins,hemantojhaa/jenkins,ikedam/jenkins,Jimilian/jenkins,csimons/jenkins,1and1/jenkins,everyonce/jenkins,paulwellnerbou/jenkins,Ykus/jenkins,huybrechts/hudson,jzjzjzj/jenkins,daniel-beck/jenkins,noikiy/jenkins,tfennelly/jenkins,1and1/jenkins,svanoort/jenkins,yonglehou/jenkins,v1v/jenkins,rsandell/jenkins,daniel-beck/jenkins,gorcz/jenkins,gusreiber/jenkins,ydubreuil/jenkins,mdonohue/jenkins,stephenc/jenkins,jhoblitt/jenkins,evernat/jenkins,seanlin816/jenkins,paulwellnerbou/jenkins,sathiya-mit/jenkins,luoqii/jenkins,verbitan/jenkins,azweb76/jenkins,luoqii/jenkins,khmarbaise/jenkins,KostyaSha/jenkins,escoem/jenkins,samatdav/jenkins,escoem/jenkins,albers/jenkins,ajshastri/jenkins,albers/jenkins,FTG-003/jenkins,yonglehou/jenkins,mdonohue/jenkins,intelchen/jenkins,ydubreuil/jenkins,arcivanov/jenkins,patbos/jenkins,oleg-nenashev/jenkins,rashmikanta-1984/jenkins,rlugojr/jenkins,protazy/jenkins,Vlatombe/jenkins,pjanouse/jenkins,292388900/jenkins,wuwen5/jenkins,aldaris/jenkins,MarkEWaite/jenkins,msrb/jenkins,iqstack/jenkins,maikeffi/hudson,AustinKwang/jenkins,petermarcoen/jenkins,evernat/jenkins,pjanouse/jenkins,jpederzolli/jenkins-1,evernat/jenkins,alvarolobato/jenkins,evernat/jenkins,vijayto/jenkins,amuniz/jenkins,daspilker/jenkins,mrooney/jenkins,ChrisA89/jenkins,sathiya-mit/jenkins,ndeloof/jenkins,msrb/jenkins,vijayto/jenkins,arunsingh/jenkins,azweb76/jenkins,Ykus/jenkins,NehemiahMi/jenkins,MadsNielsen/jtemp,iqstack/jenkins,everyonce/jenkins,khmarbaise/jenkins,Vlatombe/jenkins,aduprat/jenkins,NehemiahMi/jenkins,seanlin816/jenkins,Krasnyanskiy/jenkins,khmarbaise/jenkins,everyonce/jenkins,duzifang/my-jenkins,csimons/jenkins,ndeloof/jenkins,csimons/jenkins,jhoblitt/jenkins,hemantojhaa/jenkins,soenter/jenkins,jcsirot/jenkins,github-api-test-org/jenkins,paulmillar/jenkins,huybrechts/hudson,batmat/jenkins,hashar/jenkins,DoctorQ/jenkins,olivergondza/jenkins,liupugong/jenkins,DanielWeber/jenkins,aduprat/jenkins,MichaelPranovich/jenkins_sc,jpbriend/jenkins,mdonohue/jenkins,huybrechts/hudson,amuniz/jenkins,chbiel/jenkins,MichaelPranovich/jenkins_sc,ErikVerheul/jenkins,hashar/jenkins,CodeShane/jenkins,elkingtonmcb/jenkins,6WIND/jenkins,rashmikanta-1984/jenkins,khmarbaise/jenkins,azweb76/jenkins,rsandell/jenkins,andresrc/jenkins,lilyJi/jenkins,patbos/jenkins,brunocvcunha/jenkins,scoheb/jenkins,daspilker/jenkins,dennisjlee/jenkins,stephenc/jenkins,KostyaSha/jenkins,Vlatombe/jenkins,oleg-nenashev/jenkins,Jimilian/jenkins,liorhson/jenkins,tangkun75/jenkins,verbitan/jenkins,brunocvcunha/jenkins,varmenise/jenkins,1and1/jenkins,christ66/jenkins,jpbriend/jenkins,nandan4/Jenkins,stephenc/jenkins,MadsNielsen/jtemp,oleg-nenashev/jenkins,scoheb/jenkins,elkingtonmcb/jenkins,msrb/jenkins,jhoblitt/jenkins,SenolOzer/jenkins,dariver/jenkins,ns163/jenkins,liorhson/jenkins,tastatur/jenkins,svanoort/jenkins,ChrisA89/jenkins,lilyJi/jenkins,jenkinsci/jenkins,brunocvcunha/jenkins,intelchen/jenkins,viqueen/jenkins,Wilfred/jenkins,pjanouse/jenkins,liorhson/jenkins,hplatou/jenkins,MarkEWaite/jenkins,KostyaSha/jenkins,bpzhang/jenkins,petermarcoen/jenkins,bpzhang/jenkins,Wilfred/jenkins,Ykus/jenkins,6WIND/jenkins,albers/jenkins,fbelzunc/jenkins,hashar/jenkins,292388900/jenkins,thomassuckow/jenkins,MarkEWaite/jenkins,daspilker/jenkins,damianszczepanik/jenkins,ajshastri/jenkins,scoheb/jenkins,recena/jenkins,nandan4/Jenkins,MichaelPranovich/jenkins_sc,wangyikai/jenkins,scoheb/jenkins,csimons/jenkins,maikeffi/hudson,Wilfred/jenkins,rashmikanta-1984/jenkins,shahharsh/jenkins,luoqii/jenkins,godfath3r/jenkins,guoxu0514/jenkins,DoctorQ/jenkins,csimons/jenkins,bkmeneguello/jenkins,ns163/jenkins,varmenise/jenkins,christ66/jenkins,lindzh/jenkins,paulmillar/jenkins,aquarellian/jenkins,luoqii/jenkins,gitaccountforprashant/gittest,liupugong/jenkins,rsandell/jenkins,rlugojr/jenkins,godfath3r/jenkins,protazy/jenkins,vvv444/jenkins,recena/jenkins,albers/jenkins,singh88/jenkins,intelchen/jenkins,luoqii/jenkins,CodeShane/jenkins,KostyaSha/jenkins,keyurpatankar/hudson,synopsys-arc-oss/jenkins,morficus/jenkins,tfennelly/jenkins,AustinKwang/jenkins,ndeloof/jenkins,azweb76/jenkins,NehemiahMi/jenkins,ajshastri/jenkins,intelchen/jenkins,NehemiahMi/jenkins,intelchen/jenkins,alvarolobato/jenkins,bpzhang/jenkins,msrb/jenkins,samatdav/jenkins,csimons/jenkins,DoctorQ/jenkins,bpzhang/jenkins,SenolOzer/jenkins,olivergondza/jenkins,aldaris/jenkins,luoqii/jenkins,hashar/jenkins,samatdav/jenkins,dariver/jenkins,goldchang/jenkins,jpbriend/jenkins,ikedam/jenkins,christ66/jenkins,deadmoose/jenkins,yonglehou/jenkins,Ykus/jenkins,Jimilian/jenkins,duzifang/my-jenkins,ajshastri/jenkins,varmenise/jenkins,vvv444/jenkins,lordofthejars/jenkins,paulmillar/jenkins,maikeffi/hudson,seanlin816/jenkins,jglick/jenkins,soenter/jenkins,lilyJi/jenkins,1and1/jenkins,jenkinsci/jenkins,viqueen/jenkins,kohsuke/hudson,dariver/jenkins,iqstack/jenkins,verbitan/jenkins,stephenc/jenkins,viqueen/jenkins,gitaccountforprashant/gittest,rashmikanta-1984/jenkins,vjuranek/jenkins,iqstack/jenkins,ndeloof/jenkins,rlugojr/jenkins,pselle/jenkins,jglick/jenkins,recena/jenkins,arunsingh/jenkins,aldaris/jenkins,vlajos/jenkins,arcivanov/jenkins,DanielWeber/jenkins,Vlatombe/jenkins,ErikVerheul/jenkins,MadsNielsen/jtemp,Jimilian/jenkins,ErikVerheul/jenkins,jpederzolli/jenkins-1,vvv444/jenkins,andresrc/jenkins,Jimilian/jenkins,amuniz/jenkins,noikiy/jenkins,thomassuckow/jenkins,DoctorQ/jenkins,shahharsh/jenkins,ajshastri/jenkins,amruthsoft9/Jenkis,svanoort/jenkins,tfennelly/jenkins,aduprat/jenkins,mattclark/jenkins,dariver/jenkins,protazy/jenkins,jpbriend/jenkins,goldchang/jenkins,daniel-beck/jenkins,paulmillar/jenkins,akshayabd/jenkins,Krasnyanskiy/jenkins,albers/jenkins,mcanthony/jenkins,daspilker/jenkins,noikiy/jenkins,duzifang/my-jenkins,github-api-test-org/jenkins,keyurpatankar/hudson,deadmoose/jenkins,ErikVerheul/jenkins,shahharsh/jenkins,patbos/jenkins,github-api-test-org/jenkins,pjanouse/jenkins,amruthsoft9/Jenkis,aldaris/jenkins,gorcz/jenkins,dbroady1/jenkins,SebastienGllmt/jenkins,hplatou/jenkins,viqueen/jenkins,FarmGeek4Life/jenkins,mattclark/jenkins,jglick/jenkins,keyurpatankar/hudson,lindzh/jenkins,keyurpatankar/hudson,fbelzunc/jenkins,vvv444/jenkins,Jochen-A-Fuerbacher/jenkins,MarkEWaite/jenkins,gitaccountforprashant/gittest,lindzh/jenkins,amruthsoft9/Jenkis,jzjzjzj/jenkins,bkmeneguello/jenkins,fbelzunc/jenkins,azweb76/jenkins,keyurpatankar/hudson,seanlin816/jenkins,maikeffi/hudson,chbiel/jenkins,soenter/jenkins,godfath3r/jenkins,h4ck3rm1k3/jenkins,v1v/jenkins,lilyJi/jenkins,liupugong/jenkins,samatdav/jenkins,rsandell/jenkins,wuwen5/jenkins,batmat/jenkins,6WIND/jenkins,MichaelPranovich/jenkins_sc,KostyaSha/jenkins,mcanthony/jenkins,lordofthejars/jenkins,morficus/jenkins,mcanthony/jenkins,pselle/jenkins,my7seven/jenkins,wuwen5/jenkins,synopsys-arc-oss/jenkins,h4ck3rm1k3/jenkins,synopsys-arc-oss/jenkins,292388900/jenkins,daspilker/jenkins,jk47/jenkins,hplatou/jenkins,deadmoose/jenkins,lordofthejars/jenkins,liupugong/jenkins,arunsingh/jenkins,elkingtonmcb/jenkins,huybrechts/hudson,vjuranek/jenkins,DanielWeber/jenkins,fbelzunc/jenkins,AustinKwang/jenkins,jenkinsci/jenkins,deadmoose/jenkins,maikeffi/hudson,tfennelly/jenkins,msrb/jenkins,aldaris/jenkins,maikeffi/hudson,MarkEWaite/jenkins,paulwellnerbou/jenkins,amuniz/jenkins,kohsuke/hudson,jpederzolli/jenkins-1,dbroady1/jenkins,jglick/jenkins,andresrc/jenkins,seanlin816/jenkins,tastatur/jenkins,ydubreuil/jenkins,SenolOzer/jenkins,goldchang/jenkins,mcanthony/jenkins,lilyJi/jenkins,my7seven/jenkins,gusreiber/jenkins,FTG-003/jenkins,rsandell/jenkins,christ66/jenkins,ErikVerheul/jenkins,rlugojr/jenkins,brunocvcunha/jenkins,damianszczepanik/jenkins,amruthsoft9/Jenkis,amuniz/jenkins,nandan4/Jenkins,pselle/jenkins,Krasnyanskiy/jenkins,ajshastri/jenkins,chbiel/jenkins,MadsNielsen/jtemp,gorcz/jenkins,vijayto/jenkins,hemantojhaa/jenkins,DoctorQ/jenkins,jenkinsci/jenkins,ikedam/jenkins,seanlin816/jenkins,dennisjlee/jenkins,jzjzjzj/jenkins,DanielWeber/jenkins,NehemiahMi/jenkins,synopsys-arc-oss/jenkins,patbos/jenkins,vlajos/jenkins,gitaccountforprashant/gittest,dariver/jenkins,lordofthejars/jenkins,v1v/jenkins
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Daniel Dyer, Tom Huybrechts, Yahoo!, Inc. * * 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 hudson.model; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import hudson.AbortException; import hudson.XmlFile; import hudson.Util; import hudson.Functions; import hudson.BulkChange; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.model.listeners.ItemListener; import hudson.model.listeners.SaveableListener; import hudson.security.AccessControlled; import hudson.security.Permission; import hudson.security.ACL; import hudson.util.AlternativeUiTextProvider; import hudson.util.AlternativeUiTextProvider.Message; import hudson.util.AtomicFileWriter; import hudson.util.IOException2; import hudson.util.IOUtils; import jenkins.model.Jenkins; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.types.FileSet; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.io.File; import java.io.IOException; import java.util.Collection; import javax.annotation.Nonnull; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.HttpDeletable; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.servlet.ServletException; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; /** * Partial default implementation of {@link Item}. * * @author Kohsuke Kawaguchi */ // Item doesn't necessarily have to be Actionable, but // Java doesn't let multiple inheritance. @ExportedBean public abstract class AbstractItem extends Actionable implements Item, HttpDeletable, AccessControlled, DescriptorByNameOwner { /** * Project name. */ protected /*final*/ transient String name; /** * Project description. Can be HTML. */ protected volatile String description; private transient ItemGroup parent; protected String displayName; protected AbstractItem(ItemGroup parent, String name) { this.parent = parent; doSetName(name); } public void onCreatedFromScratch() { // noop } @Exported(visibility=999) public String getName() { return name; } /** * Get the term used in the UI to represent this kind of * {@link Item}. Must start with a capital letter. */ public String getPronoun() { return AlternativeUiTextProvider.get(PRONOUN, this, Messages.AbstractItem_Pronoun()); } @Exported /** * @return The display name of this object, or if it is not set, the name * of the object. */ public String getDisplayName() { if(null!=displayName) { return displayName; } // if the displayName is not set, then return the name as we use to do return getName(); } @Exported /** * This is intended to be used by the Job configuration pages where * we want to return null if the display name is not set. * @return The display name of this object or null if the display name is not * set */ public String getDisplayNameOrNull() { return displayName; } /** * This method exists so that the Job configuration pages can use * getDisplayNameOrNull so that nothing is shown in the display name text * box if the display name is not set. * @param displayName * @throws IOException */ public void setDisplayNameOrNull(String displayName) throws IOException { setDisplayName(displayName); } public void setDisplayName(String displayName) throws IOException { this.displayName = Util.fixEmpty(displayName); save(); } public File getRootDir() { return getParent().getRootDirFor(this); } /** * This bridge method is to maintain binary compatibility with {@link TopLevelItem#getParent()}. */ @WithBridgeMethods(value=Jenkins.class,castRequired=true) @Override public @Nonnull ItemGroup getParent() { if (parent == null) { throw new IllegalStateException("no parent set on " + getClass().getName() + "[" + name + "]"); } return parent; } /** * Gets the project description HTML. */ @Exported public String getDescription() { return description; } /** * Sets the project description HTML. */ public void setDescription(String description) throws IOException { this.description = description; save(); ItemListener.fireOnUpdated(this); } /** * Just update {@link #name} without performing the rename operation, * which would involve copying files and etc. */ protected void doSetName(String name) { this.name = name; } /** * Renames this item. * Not all the Items need to support this operation, but if you decide to do so, * you can use this method. */ protected void renameTo(String newName) throws IOException { // always synchronize from bigger objects first final ItemGroup parent = getParent(); synchronized (parent) { synchronized (this) { // sanity check if (newName == null) throw new IllegalArgumentException("New name is not given"); // noop? if (this.name.equals(newName)) return; Item existing = parent.getItem(newName); if (existing != null && existing!=this) // the look up is case insensitive, so we need "existing!=this" // to allow people to rename "Foo" to "foo", for example. // see http://www.nabble.com/error-on-renaming-project-tt18061629.html throw new IllegalArgumentException("Job " + newName + " already exists"); String oldName = this.name; File oldRoot = this.getRootDir(); doSetName(newName); File newRoot = this.getRootDir(); boolean success = false; try {// rename data files boolean interrupted = false; boolean renamed = false; // try to rename the job directory. // this may fail on Windows due to some other processes // accessing a file. // so retry few times before we fall back to copy. for (int retry = 0; retry < 5; retry++) { if (oldRoot.renameTo(newRoot)) { renamed = true; break; // succeeded } try { Thread.sleep(500); } catch (InterruptedException e) { // process the interruption later interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); if (!renamed) { // failed to rename. it must be that some lengthy // process is going on // to prevent a rename operation. So do a copy. Ideally // we'd like to // later delete the old copy, but we can't reliably do // so, as before the VM // shuts down there might be a new job created under the // old name. Copy cp = new Copy(); cp.setProject(new org.apache.tools.ant.Project()); cp.setTodir(newRoot); FileSet src = new FileSet(); src.setDir(oldRoot); cp.addFileset(src); cp.setOverwrite(true); cp.setPreserveLastModified(true); cp.setFailOnError(false); // keep going even if // there's an error cp.execute(); // try to delete as much as possible try { Util.deleteRecursive(oldRoot); } catch (IOException e) { // but ignore the error, since we expect that e.printStackTrace(); } } success = true; } finally { // if failed, back out the rename. if (!success) doSetName(oldName); } callOnRenamed(newName, parent, oldName); for (ItemListener l : ItemListener.all()) l.onRenamed(this, oldName, newName); } } } /** * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067 * on BugParade for more details. */ private void callOnRenamed(String newName, ItemGroup parent, String oldName) throws IOException { try { parent.onRenamed(this, oldName, newName); } catch (AbstractMethodError _) { // ignore } } /** * Gets all the jobs that this {@link Item} contains as descendants. */ public abstract Collection<? extends Job> getAllJobs(); public final String getFullName() { String n = getParent().getFullName(); if(n.length()==0) return getName(); else return n+'/'+getName(); } public final String getFullDisplayName() { String n = getParent().getFullDisplayName(); if(n.length()==0) return getDisplayName(); else return n+" » "+getDisplayName(); } /** * Gets the display name of the current item relative to the given group. * * @since 1.515 * @param p the ItemGroup used as point of reference for the item * @return * String like "foo » bar" */ public String getRelativeDisplayNameFrom(ItemGroup p) { return Functions.getRelativeDisplayNameFrom(this, p); } /** * This method only exists to disambiguate {@link #getRelativeNameFrom(ItemGroup)} and {@link #getRelativeNameFrom(Item)} * @since 1.512 * @see #getRelativeNameFrom(ItemGroup) */ public String getRelativeNameFromGroup(ItemGroup p) { return getRelativeNameFrom(p); } /** * @param p * The ItemGroup instance used as context to evaluate the relative name of this AbstractItem * @return * The name of the current item, relative to p. * Nested ItemGroups are separated by / character. */ public String getRelativeNameFrom(ItemGroup p) { return Functions.getRelativeNameFrom(this, p); } public String getRelativeNameFrom(Item item) { return getRelativeNameFrom(item.getParent()); } /** * Called right after when a {@link Item} is loaded from disk. * This is an opporunity to do a post load processing. */ public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { this.parent = parent; doSetName(name); } /** * When a {@link Item} is copied from existing one, * the files are first copied on the file system, * then it will be loaded, then this method will be invoked * to perform any implementation-specific work. * * <p> * * * @param src * Item from which it's copied from. The same type as {@code this}. Never null. */ public void onCopiedFrom(Item src) { } public final String getUrl() { // try to stick to the current view if possible StaplerRequest req = Stapler.getCurrentRequest(); if (req != null) { String seed = Functions.getNearestAncestorUrl(req,this); if(seed!=null) { // trim off the context path portion and leading '/', but add trailing '/' return seed.substring(req.getContextPath().length()+1)+'/'; } } // otherwise compute the path normally return getParent().getUrl()+getShortUrl(); } public String getShortUrl() { String prefix = getParent().getUrlChildPrefix(); String subdir = Util.rawEncode(getName()); return prefix.equals(".") ? subdir + '/' : prefix + '/' + subdir + '/'; } public String getSearchUrl() { return getShortUrl(); } @Exported(visibility=999,name="url") public final String getAbsoluteUrl() { String r = Jenkins.getInstance().getRootUrl(); if(r==null) throw new IllegalStateException("Root URL isn't configured yet. Cannot compute absolute URL."); return Util.encode(r+getUrl()); } /** * Remote API access. */ public final Api getApi() { return new Api(this); } /** * Returns the {@link ACL} for this object. */ public ACL getACL() { return Jenkins.getInstance().getAuthorizationStrategy().getACL(this); } /** * Short for {@code getACL().checkPermission(p)} */ public void checkPermission(Permission p) { getACL().checkPermission(p); } /** * Short for {@code getACL().hasPermission(p)} */ public boolean hasPermission(Permission p) { return getACL().hasPermission(p); } /** * Save the settings to a file. */ public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } public final XmlFile getConfigFile() { return Items.getConfigFile(this); } public Descriptor getDescriptorByName(String className) { return Jenkins.getInstance().getDescriptorByName(className); } /** * Accepts the new description. */ public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { checkPermission(CONFIGURE); setDescription(req.getParameter("description")); rsp.sendRedirect("."); // go to the top page } /** * Deletes this item. * Note on the funny name: for reasons of historical compatibility, this URL is {@code /doDelete} * since it predates {@code <l:confirmationLink>}. {@code /delete} goes to a Jelly page * which should now be unused by core but is left in case plugins are still using it. */ @CLIMethod(name="delete-job") @RequirePOST public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { delete(); if (rsp != null) // null for CLI rsp.sendRedirect2(req.getContextPath()+"/"+getParent().getUrl()); } public void delete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { try { doDoDelete(req,rsp); } catch (InterruptedException e) { // TODO: allow this in Stapler throw new ServletException(e); } } /** * Deletes this item. * * <p> * Any exception indicates the deletion has failed, but {@link AbortException} would prevent the caller * from showing the stack trace. This */ public synchronized void delete() throws IOException, InterruptedException { checkPermission(DELETE); performDelete(); try { invokeOnDeleted(); } catch (AbstractMethodError e) { // ignore } Jenkins.getInstance().rebuildDependencyGraphAsync(); } /** * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067 * on BugParade for more details. */ private void invokeOnDeleted() throws IOException { getParent().onDeleted(this); } /** * Does the real job of deleting the item. */ protected void performDelete() throws IOException, InterruptedException { getConfigFile().delete(); Util.deleteRecursive(getRootDir()); } /** * Accepts <tt>config.xml</tt> submission, as well as serve it. */ @WebMethod(name = "config.xml") public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException { if (req.getMethod().equals("GET")) { // read checkPermission(EXTENDED_READ); rsp.setContentType("application/xml"); IOUtils.copy(getConfigFile().getFile(),rsp.getOutputStream()); return; } if (req.getMethod().equals("POST")) { // submission updateByXml((Source)new StreamSource(req.getReader())); return; } // huh? rsp.sendError(SC_BAD_REQUEST); } /** * @deprecated as of 1.473 * Use {@link #updateByXml(Source)} */ public void updateByXml(StreamSource source) throws IOException { updateByXml((Source)source); } /** * Updates Job by its XML definition. * @since 1.473 */ public void updateByXml(Source source) throws IOException { checkPermission(CONFIGURE); XmlFile configXmlFile = getConfigFile(); AtomicFileWriter out = new AtomicFileWriter(configXmlFile.getFile()); try { try { // this allows us to use UTF-8 for storing data, // plus it checks any well-formedness issue in the submitted // data Transformer t = TransformerFactory.newInstance() .newTransformer(); t.transform(source, new StreamResult(out)); out.close(); } catch (TransformerException e) { throw new IOException2("Failed to persist configuration.xml", e); } // try to reflect the changes by reloading new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this); Items.updatingByXml.set(true); try { onLoad(getParent(), getRootDir().getName()); } finally { Items.updatingByXml.set(false); } Jenkins.getInstance().rebuildDependencyGraphAsync(); // if everything went well, commit this new version out.commit(); SaveableListener.fireOnChange(this, getConfigFile()); } finally { out.abort(); // don't leave anything behind } } /* (non-Javadoc) * @see hudson.model.AbstractModelObject#getSearchName() */ @Override public String getSearchName() { // the search name of abstract items should be the name and not display name. // this will make suggestions use the names and not the display name // so that the links will 302 directly to the thing the user was finding return getName(); } public String toString() { return super.toString()+'['+getFullName()+']'; } /** * Used for CLI binding. */ @CLIResolver public static AbstractItem resolveForCLI( @Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException { AbstractItem item = Jenkins.getInstance().getItemByFullName(name, AbstractItem.class); if (item==null) throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName())); return item; } /** * Replaceable pronoun of that points to a job. Defaults to "Job"/"Project" depending on the context. */ public static final Message<AbstractItem> PRONOUN = new Message<AbstractItem>(); }
core/src/main/java/hudson/model/AbstractItem.java
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Daniel Dyer, Tom Huybrechts, Yahoo!, Inc. * * 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 hudson.model; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import hudson.AbortException; import hudson.XmlFile; import hudson.Util; import hudson.Functions; import hudson.BulkChange; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.model.listeners.ItemListener; import hudson.model.listeners.SaveableListener; import hudson.security.AccessControlled; import hudson.security.Permission; import hudson.security.ACL; import hudson.util.AlternativeUiTextProvider; import hudson.util.AlternativeUiTextProvider.Message; import hudson.util.AtomicFileWriter; import hudson.util.IOException2; import hudson.util.IOUtils; import jenkins.model.Jenkins; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.types.FileSet; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.io.File; import java.io.IOException; import java.util.Collection; import javax.annotation.Nonnull; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.HttpDeletable; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.servlet.ServletException; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; /** * Partial default implementation of {@link Item}. * * @author Kohsuke Kawaguchi */ // Item doesn't necessarily have to be Actionable, but // Java doesn't let multiple inheritance. @ExportedBean public abstract class AbstractItem extends Actionable implements Item, HttpDeletable, AccessControlled, DescriptorByNameOwner { /** * Project name. */ protected /*final*/ transient String name; /** * Project description. Can be HTML. */ protected volatile String description; private transient ItemGroup parent; protected String displayName; protected AbstractItem(ItemGroup parent, String name) { this.parent = parent; doSetName(name); } public void onCreatedFromScratch() { // noop } @Exported(visibility=999) public String getName() { return name; } /** * Get the term used in the UI to represent this kind of * {@link Item}. Must start with a capital letter. */ public String getPronoun() { return AlternativeUiTextProvider.get(PRONOUN, this, Messages.AbstractItem_Pronoun()); } @Exported /** * @return The display name of this object, or if it is not set, the name * of the object. */ public String getDisplayName() { if(null!=displayName) { return displayName; } // if the displayName is not set, then return the name as we use to do return getName(); } @Exported /** * This is intended to be used by the Job configuration pages where * we want to return null if the display name is not set. * @return The display name of this object or null if the display name is not * set */ public String getDisplayNameOrNull() { return displayName; } /** * This method exists so that the Job configuration pages can use * getDisplayNameOrNull so that nothing is shown in the display name text * box if the display name is not set. * @param displayName * @throws IOException */ public void setDisplayNameOrNull(String displayName) throws IOException { setDisplayName(displayName); } public void setDisplayName(String displayName) throws IOException { this.displayName = Util.fixEmpty(displayName); save(); } public File getRootDir() { return getParent().getRootDirFor(this); } /** * This bridge method is to maintain binary compatibility with {@link TopLevelItem#getParent()}. */ @WithBridgeMethods(value=Jenkins.class,castRequired=true) @Override public @Nonnull ItemGroup getParent() { if (parent == null) { throw new IllegalStateException("no parent set on " + getClass().getName() + "[" + name + "]"); } return parent; } /** * Gets the project description HTML. */ @Exported public String getDescription() { return description; } /** * Sets the project description HTML. */ public void setDescription(String description) throws IOException { this.description = description; save(); ItemListener.fireOnUpdated(this); } /** * Just update {@link #name} without performing the rename operation, * which would involve copying files and etc. */ protected void doSetName(String name) { this.name = name; } /** * Renames this item. * Not all the Items need to support this operation, but if you decide to do so, * you can use this method. */ protected void renameTo(String newName) throws IOException { // always synchronize from bigger objects first final ItemGroup parent = getParent(); synchronized (parent) { synchronized (this) { // sanity check if (newName == null) throw new IllegalArgumentException("New name is not given"); // noop? if (this.name.equals(newName)) return; Item existing = parent.getItem(newName); if (existing != null && existing!=this) // the look up is case insensitive, so we need "existing!=this" // to allow people to rename "Foo" to "foo", for example. // see http://www.nabble.com/error-on-renaming-project-tt18061629.html throw new IllegalArgumentException("Job " + newName + " already exists"); String oldName = this.name; File oldRoot = this.getRootDir(); doSetName(newName); File newRoot = this.getRootDir(); boolean success = false; try {// rename data files boolean interrupted = false; boolean renamed = false; // try to rename the job directory. // this may fail on Windows due to some other processes // accessing a file. // so retry few times before we fall back to copy. for (int retry = 0; retry < 5; retry++) { if (oldRoot.renameTo(newRoot)) { renamed = true; break; // succeeded } try { Thread.sleep(500); } catch (InterruptedException e) { // process the interruption later interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); if (!renamed) { // failed to rename. it must be that some lengthy // process is going on // to prevent a rename operation. So do a copy. Ideally // we'd like to // later delete the old copy, but we can't reliably do // so, as before the VM // shuts down there might be a new job created under the // old name. Copy cp = new Copy(); cp.setProject(new org.apache.tools.ant.Project()); cp.setTodir(newRoot); FileSet src = new FileSet(); src.setDir(oldRoot); cp.addFileset(src); cp.setOverwrite(true); cp.setPreserveLastModified(true); cp.setFailOnError(false); // keep going even if // there's an error cp.execute(); // try to delete as much as possible try { Util.deleteRecursive(oldRoot); } catch (IOException e) { // but ignore the error, since we expect that e.printStackTrace(); } } success = true; } finally { // if failed, back out the rename. if (!success) doSetName(oldName); } callOnRenamed(newName, parent, oldName); for (ItemListener l : ItemListener.all()) l.onRenamed(this, oldName, newName); } } } /** * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067 * on BugParade for more details. */ private void callOnRenamed(String newName, ItemGroup parent, String oldName) throws IOException { try { parent.onRenamed(this, oldName, newName); } catch (AbstractMethodError _) { // ignore } } /** * Gets all the jobs that this {@link Item} contains as descendants. */ public abstract Collection<? extends Job> getAllJobs(); public final String getFullName() { String n = getParent().getFullName(); if(n.length()==0) return getName(); else return n+'/'+getName(); } public final String getFullDisplayName() { String n = getParent().getFullDisplayName(); if(n.length()==0) return getDisplayName(); else return n+" » "+getDisplayName(); } /** * Gets the display name of the current item relative to the given group. * * @since 1.515 * @param p the ItemGroup used as point of reference for the item * @return * String like "foo » bar" */ public String getRelativeDisplayNameFrom(ItemGroup p) { return Functions.getRelativeDisplayNameFrom(this, p); } /** * This method only exists to disambiguate {@link #getRelativeNameFrom(ItemGroup)} and {@link #getRelativeNameFrom(Item)} * @since 1.512 * @see #getRelativeNameFrom(ItemGroup) */ public String getRelativeNameFromGroup(ItemGroup p) { return getRelativeNameFrom(p); } /** * @param p * The ItemGroup instance used as context to evaluate the relative name of this AbstractItem * @return * The name of the current item, relative to p. * Nested ItemGroups are separated by / character. */ public String getRelativeNameFrom(ItemGroup p) { return Functions.getRelativeNameFrom(this, p); } public String getRelativeNameFrom(Item item) { return getRelativeNameFrom(item.getParent()); } /** * Called right after when a {@link Item} is loaded from disk. * This is an opporunity to do a post load processing. */ public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { this.parent = parent; doSetName(name); } /** * When a {@link Item} is copied from existing one, * the files are first copied on the file system, * then it will be loaded, then this method will be invoked * to perform any implementation-specific work. * * <p> * * * @param src * Item from which it's copied from. The same type as {@code this}. Never null. */ public void onCopiedFrom(Item src) { } public final String getUrl() { // try to stick to the current view if possible StaplerRequest req = Stapler.getCurrentRequest(); if (req != null) { String seed = Functions.getNearestAncestorUrl(req,this); if(seed!=null) { // trim off the context path portion and leading '/', but add trailing '/' return seed.substring(req.getContextPath().length()+1)+'/'; } } // otherwise compute the path normally return getParent().getUrl()+getShortUrl(); } public String getShortUrl() { String prefix = getParent().getUrlChildPrefix(); String subdir = Util.rawEncode(getName()); return prefix.equals(".") ? subdir + '/' : prefix + '/' + subdir + '/'; } public String getSearchUrl() { return getShortUrl(); } @Exported(visibility=999,name="url") public final String getAbsoluteUrl() { String r = Jenkins.getInstance().getRootUrl(); if(r==null) throw new IllegalStateException("Root URL isn't configured yet. Cannot compute absolute URL."); return Util.encode(r+getUrl()); } /** * Remote API access. */ public final Api getApi() { return new Api(this); } /** * Returns the {@link ACL} for this object. */ public ACL getACL() { return Jenkins.getInstance().getAuthorizationStrategy().getACL(this); } /** * Short for {@code getACL().checkPermission(p)} */ public void checkPermission(Permission p) { getACL().checkPermission(p); } /** * Short for {@code getACL().hasPermission(p)} */ public boolean hasPermission(Permission p) { return getACL().hasPermission(p); } /** * Save the settings to a file. */ public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } public final XmlFile getConfigFile() { return Items.getConfigFile(this); } public Descriptor getDescriptorByName(String className) { return Jenkins.getInstance().getDescriptorByName(className); } /** * Accepts the new description. */ public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { checkPermission(CONFIGURE); setDescription(req.getParameter("description")); rsp.sendRedirect("."); // go to the top page } /** * Deletes this item. * Note on the funny name: for reasons of historical compatibility, this URL is {@code /doDelete} * since it predates {@code <l:confirmationLink>}. {@code /delete} goes to a Jelly page * which should now be unused by core but is left in case plugins are still using it. */ @CLIMethod(name="delete-job") @RequirePOST public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { delete(); if (rsp != null) // null for CLI rsp.sendRedirect2(req.getContextPath()+"/"+getParent().getUrl()); } public void delete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { try { doDoDelete(req,rsp); } catch (InterruptedException e) { // TODO: allow this in Stapler throw new ServletException(e); } } /** * Deletes this item. * * <p> * Any exception indicates the deletion has failed, but {@link AbortException} would prevent the caller * from showing the stack trace. This */ public synchronized void delete() throws IOException, InterruptedException { checkPermission(DELETE); performDelete(); try { invokeOnDeleted(); } catch (AbstractMethodError e) { // ignore } Jenkins.getInstance().rebuildDependencyGraphAsync(); } /** * A pointless function to work around what appears to be a HotSpot problem. See JENKINS-5756 and bug 6933067 * on BugParade for more details. */ private void invokeOnDeleted() throws IOException { getParent().onDeleted(this); } /** * Does the real job of deleting the item. */ protected void performDelete() throws IOException, InterruptedException { getConfigFile().delete(); Util.deleteRecursive(getRootDir()); } /** * Accepts <tt>config.xml</tt> submission, as well as serve it. */ @WebMethod(name = "config.xml") public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException { if (req.getMethod().equals("GET")) { // read checkPermission(EXTENDED_READ); rsp.setContentType("application/xml"); IOUtils.copy(getConfigFile().getFile(),rsp.getOutputStream()); return; } if (req.getMethod().equals("POST")) { // submission updateByXml((Source)new StreamSource(req.getReader())); return; } // huh? rsp.sendError(SC_BAD_REQUEST); } /** * @deprecated as of 1.473 * Use {@link #updateByXml(Source)} */ public void updateByXml(StreamSource source) throws IOException { updateByXml((Source)source); } /** * Updates Job by its XML definition. */ public void updateByXml(Source source) throws IOException { checkPermission(CONFIGURE); XmlFile configXmlFile = getConfigFile(); AtomicFileWriter out = new AtomicFileWriter(configXmlFile.getFile()); try { try { // this allows us to use UTF-8 for storing data, // plus it checks any well-formedness issue in the submitted // data Transformer t = TransformerFactory.newInstance() .newTransformer(); t.transform(source, new StreamResult(out)); out.close(); } catch (TransformerException e) { throw new IOException2("Failed to persist configuration.xml", e); } // try to reflect the changes by reloading new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this); Items.updatingByXml.set(true); try { onLoad(getParent(), getRootDir().getName()); } finally { Items.updatingByXml.set(false); } Jenkins.getInstance().rebuildDependencyGraphAsync(); // if everything went well, commit this new version out.commit(); SaveableListener.fireOnChange(this, getConfigFile()); } finally { out.abort(); // don't leave anything behind } } /* (non-Javadoc) * @see hudson.model.AbstractModelObject#getSearchName() */ @Override public String getSearchName() { // the search name of abstract items should be the name and not display name. // this will make suggestions use the names and not the display name // so that the links will 302 directly to the thing the user was finding return getName(); } public String toString() { return super.toString()+'['+getFullName()+']'; } /** * Used for CLI binding. */ @CLIResolver public static AbstractItem resolveForCLI( @Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException { AbstractItem item = Jenkins.getInstance().getItemByFullName(name, AbstractItem.class); if (item==null) throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName())); return item; } /** * Replaceable pronoun of that points to a job. Defaults to "Job"/"Project" depending on the context. */ public static final Message<AbstractItem> PRONOUN = new Message<AbstractItem>(); }
Missing @since.
core/src/main/java/hudson/model/AbstractItem.java
Missing @since.
<ide><path>ore/src/main/java/hudson/model/AbstractItem.java <ide> <ide> /** <ide> * Updates Job by its XML definition. <add> * @since 1.473 <ide> */ <ide> public void updateByXml(Source source) throws IOException { <ide> checkPermission(CONFIGURE);
JavaScript
mit
152ecc22d4b41d515a3ade105b245fafb122db51
0
jeffh/YACS,JGrippo/YACS,JGrippo/YACS,JGrippo/YACS,jeffh/YACS,jeffh/YACS,jeffh/YACS,JGrippo/YACS
'use strict'; describe("networkIndicator", function(){ var $rootScope, networkIndicator; beforeEach(inject(function($injector){ $rootScope = $injector.get('$rootScope'); networkIndicator = $injector.get('networkIndicator'); })); it("should start out hidden", function(){ expect(networkIndicator.isVisible()).toBeFalsy(); }); describe("when the route changes", function(){ beforeEach(function(){ $rootScope.$broadcast('$routeChangeStart'); }); it("should show the indicator (by acquiring)", function(){ expect(networkIndicator.isVisible()).toBeTruthy(); }); describe("when the route change finishes successfully", function(){ beforeEach(function(){ $rootScope.$broadcast('$routeChangeSuccess'); }); it("should be hidden", function(){ expect(networkIndicator.isVisible()).toBeFalsy(); }); }); describe("when the route fails to change", function(){ beforeEach(function(){ $rootScope.$broadcast('$routeChangeError'); }); it("should be hidden", function(){ expect(networkIndicator.isVisible()).toBeFalsy(); }); }); }); describe("when acquired", function(){ beforeEach(function(){ networkIndicator.acquire(); }); it("should be visible", function(){ expect(networkIndicator.isVisible()).toBeTruthy(); }); describe("when released", function(){ beforeEach(function(){ networkIndicator.release(); }); it("should be hidden", function(){ expect(networkIndicator.isVisible()).toBeFalsy(); }); }); }); describe("when anyone still has the networkIndicator acquired", function(){ beforeEach(function(){ networkIndicator.acquire(); networkIndicator.acquire(); networkIndicator.acquire(); networkIndicator.release(); networkIndicator.acquire(); networkIndicator.release(); networkIndicator.release(); }); it("should still be visible", function(){ expect(networkIndicator.isVisible()).toBeTruthy(); }); }); }); describe("ApiClient", function(){ var client, $httpBackend, $q, networkIndicator; beforeEach(inject(function($injector){ networkIndicator = $injector.get('networkIndicator'); $httpBackend = $injector.get('$httpBackend'); $q = $injector.get('$q'); client = $injector.get('apiClient'); })); afterEach(function() { $httpBackend.verifyNoOutstandingRequest(); }); describe("#get", function(){ describe("when getting a url with params", function(){ var result; beforeEach(function(){ var response = {success: true, result: [1, 2]}; $httpBackend.whenPOST('/api/4/', 'semester_id=1').respond(response); client.get('/api/4/', {semester_id: 1}).then(function(theResult){ result = theResult; }); }); it("should perform an ajax post request with csrf_token", function(){ $httpBackend.expectPOST('/api/4/', 'semester_id=1' , {'X-CSRFToken': 'csrf-token'}); }); it("should activate the network indicator", function(){ expect(networkIndicator.isVisible()).toBeTruthy(); }); describe("when the request succeeds", function(){ beforeEach(function(){ $httpBackend.flush(); }); it("should resolve its promise with the result", function(){ expect(result).toEqual([1, 2]); }); }); }); describe("when getting a url successfully", function(){ var result; beforeEach(function(){ var response = {success: true, result: [1, 2]}; $httpBackend.whenPOST('/api/4/').respond(response); client.get('/api/4/').then(function(theResult){ result = theResult; }); $httpBackend.flush(); }); it("should perform an ajax request", function(){ $httpBackend.expectPOST('/api/4/'); }); it("should resolve its promise with the result", function(){ expect(result).toEqual([1, 2]); }); it("should release the network indicator", function(){ expect(networkIndicator.isVisible()).not.toBeTruthy(); }); it("should cache the response", function(){ var newResult; client.get('/api/4/').then(function(theResult){ newResult = theResult; }); $httpBackend.verifyNoOutstandingExpectation(); expect(result).toEqual(newResult); }); }); describe("when getting a url with a success: false api response", function(){ var err; beforeEach(function(){ var response = {success: false}; $httpBackend.whenPOST('/api/4/').respond(response); client.get('/api/4/').then(angular.noop, function(error){ err = error; }); $httpBackend.flush(); }); it("should reject its promise", function(){ expect(err).toBeTruthy(); }); it("should not cache the response", function(){ client.get('/api/4/'); $httpBackend.expectPOST('/api/4/'); }); it("should release the network indicator", function(){ expect(networkIndicator.isVisible()).not.toBeTruthy(); }); }); describe("when getting a non-200 http response status code", function(){ var err; beforeEach(function(){ var response = {success: true, result: 2}; $httpBackend.whenPOST('/api/4/').respond(500, response); client.get('/api/4/').then(angular.noop, function(error){ err = error; }); }); it("should reject its promise", function(){ $httpBackend.flush(); expect(err).toBeTruthy(); }); it("should not cache the response", function(){ client.get('/api/4/'); $httpBackend.expectPOST('/api/4/'); }); }); }); });
spec/javascripts/domain/APIClientSpec.js
'use strict'; describe("networkIndicator", function(){ var $rootScope, networkIndicator; beforeEach(inject(function($injector){ $rootScope = $injector.get('$rootScope'); networkIndicator = $injector.get('networkIndicator'); })); it("should start out hidden", function(){ expect(networkIndicator.isVisible()).toBeFalsy(); }); describe("when the route changes", function(){ beforeEach(function(){ $rootScope.$broadcast('$routeChangeStart'); }); it("should show the indicator (by acquiring)", function(){ expect(networkIndicator.isVisible()).toBeTruthy(); }); describe("when the route change finishes successfully", function(){ beforeEach(function(){ $rootScope.$broadcast('$routeChangeSuccess'); }); it("should be hidden", function(){ expect(networkIndicator.isVisible()).toBeFalsy(); }); }); describe("when the route fails to change", function(){ beforeEach(function(){ $rootScope.$broadcast('$routeChangeError'); }); it("should be hidden", function(){ expect(networkIndicator.isVisible()).toBeFalsy(); }); }); }); describe("when acquired", function(){ beforeEach(function(){ networkIndicator.acquire(); }); it("should be visible", function(){ expect(networkIndicator.isVisible()).toBeTruthy(); }); describe("when released", function(){ beforeEach(function(){ networkIndicator.release(); }); it("should be hidden", function(){ expect(networkIndicator.isVisible()).toBeFalsy(); }); }); }); describe("when anyone still has the networkIndicator acquired", function(){ beforeEach(function(){ networkIndicator.acquire(); networkIndicator.acquire(); networkIndicator.acquire(); networkIndicator.release(); networkIndicator.acquire(); networkIndicator.release(); networkIndicator.release(); }); it("should still be visible", function(){ expect(networkIndicator.isVisible()).toBeTruthy(); }); }); }); describe("ApiClient", function(){ var client, $httpBackend, $q, networkIndicator; beforeEach(inject(function($injector){ networkIndicator = $injector.get('networkIndicator'); $httpBackend = $injector.get('$httpBackend'); $q = $injector.get('$q'); client = $injector.get('apiClient'); })); afterEach(function() { $httpBackend.verifyNoOutstandingRequest(); }); describe("#get", function(){ describe("when getting a url with params", function(){ var result; beforeEach(function(){ var response = {success: true, result: [1, 2]}; $httpBackend.whenPOST('/api/4/', {semester_id: 1}).respond(response); client.get('/api/4/', {semester_id: 1}).then(function(theResult){ result = theResult; }); }); it("should perform an ajax post request with csrf_token", function(){ $httpBackend.expectPOST('/api/4/', {semester_id: 1} , {'X-CSRFToken': 'csrf-token'}); }); it("should activate the network indicator", function(){ expect(networkIndicator.isVisible()).toBeTruthy(); }); describe("when the request succeeds", function(){ beforeEach(function(){ $httpBackend.flush(); }); it("should resolve its promise with the result", function(){ expect(result).toEqual([1, 2]); }); }); }); describe("when getting a url successfully", function(){ var result; beforeEach(function(){ var response = {success: true, result: [1, 2]}; $httpBackend.whenPOST('/api/4/').respond(response); client.get('/api/4/').then(function(theResult){ result = theResult; }); $httpBackend.flush(); }); it("should perform an ajax request", function(){ $httpBackend.expectPOST('/api/4/'); }); it("should resolve its promise with the result", function(){ expect(result).toEqual([1, 2]); }); it("should release the network indicator", function(){ expect(networkIndicator.isVisible()).not.toBeTruthy(); }); it("should cache the response", function(){ var newResult; client.get('/api/4/').then(function(theResult){ newResult = theResult; }); $httpBackend.verifyNoOutstandingExpectation(); expect(result).toEqual(newResult); }); }); describe("when getting a url with a success: false api response", function(){ var err; beforeEach(function(){ var response = {success: false}; $httpBackend.whenPOST('/api/4/').respond(response); client.get('/api/4/').then(angular.noop, function(error){ err = error; }); $httpBackend.flush(); }); it("should reject its promise", function(){ expect(err).toBeTruthy(); }); it("should not cache the response", function(){ client.get('/api/4/'); $httpBackend.expectPOST('/api/4/'); }); it("should release the network indicator", function(){ expect(networkIndicator.isVisible()).not.toBeTruthy(); }); }); describe("when getting a non-200 http response status code", function(){ var err; beforeEach(function(){ var response = {success: true, result: 2}; $httpBackend.whenPOST('/api/4/').respond(500, response); client.get('/api/4/').then(angular.noop, function(error){ err = error; }); }); it("should reject its promise", function(){ $httpBackend.flush(); expect(err).toBeTruthy(); }); it("should not cache the response", function(){ client.get('/api/4/'); $httpBackend.expectPOST('/api/4/'); }); }); }); });
fixed broken specs
spec/javascripts/domain/APIClientSpec.js
fixed broken specs
<ide><path>pec/javascripts/domain/APIClientSpec.js <ide> var result; <ide> beforeEach(function(){ <ide> var response = {success: true, result: [1, 2]}; <del> $httpBackend.whenPOST('/api/4/', {semester_id: 1}).respond(response); <add> $httpBackend.whenPOST('/api/4/', 'semester_id=1').respond(response); <ide> client.get('/api/4/', {semester_id: 1}).then(function(theResult){ <ide> result = theResult; <ide> }); <ide> }); <ide> <ide> it("should perform an ajax post request with csrf_token", function(){ <del> $httpBackend.expectPOST('/api/4/', {semester_id: 1} , {'X-CSRFToken': 'csrf-token'}); <add> $httpBackend.expectPOST('/api/4/', 'semester_id=1' , {'X-CSRFToken': 'csrf-token'}); <ide> }); <ide> <ide> it("should activate the network indicator", function(){
Java
apache-2.0
9d62ab2bd18715dd2d3ce9acea946ae931ac4ed5
0
paulcadman/reviki,strr/reviki,CoreFiling/reviki,paulcadman/reviki,ashirley/reviki,paulcadman/reviki,CoreFiling/reviki,ashirley/reviki,strr/reviki,strr/reviki,ashirley/reviki,ashirley/reviki,paulcadman/reviki,strr/reviki,CoreFiling/reviki,ashirley/reviki,CoreFiling/reviki,CoreFiling/reviki,strr/reviki
package net.hillsdon.svnwiki.wiki.renderer; import java.io.IOException; import java.util.regex.Matcher; import net.hillsdon.svnwiki.text.Escape; import net.hillsdon.svnwiki.vc.PageReference; import com.uwyn.jhighlight.renderer.XhtmlRendererFactory; /** * Syntax formatting for java as in vqwiki. * * A general syntax needs some thought. * * @author mth */ public class JavaSyntaxHighlightedNode extends AbstractRegexNode { public JavaSyntaxHighlightedNode() { super("(?s)(^|\\n)\\[<java>\\](.*?)(^|\\n)\\[</java>\\]"); } public String handle(final PageReference page, final Matcher matcher) { String content = matcher.group(2); try { return XhtmlRendererFactory.getRenderer(XhtmlRendererFactory.JAVA).highlight("", content, "UTF-8", true); } catch (IOException e) { return "<pre>" + Escape.html(content) + "</pre>"; } } }
src/net/hillsdon/svnwiki/wiki/renderer/JavaSyntaxHighlightedNode.java
package net.hillsdon.svnwiki.wiki.renderer; import java.io.IOException; import java.util.regex.Matcher; import net.hillsdon.svnwiki.text.Escape; import net.hillsdon.svnwiki.vc.PageReference; import com.uwyn.jhighlight.renderer.XhtmlRendererFactory; /** * Syntax formatting for java as in vqwiki. * * A general syntax needs some thought. * * @author mth */ public class JavaSyntaxHighlightedNode extends AbstractRegexNode { public JavaSyntaxHighlightedNode() { super("(?s)(^|\\n)\\[<java>\\](.*?)(^|\\n)\\[</java>\\]"); } public String handle(final PageReference page, final Matcher matcher) { String content = matcher.group(1); try { return XhtmlRendererFactory.getRenderer(XhtmlRendererFactory.JAVA).highlight("", content, "UTF-8", true); } catch (IOException e) { return "<pre>" + Escape.html(content) + "</pre>"; } } }
Fix group referenced.
src/net/hillsdon/svnwiki/wiki/renderer/JavaSyntaxHighlightedNode.java
Fix group referenced.
<ide><path>rc/net/hillsdon/svnwiki/wiki/renderer/JavaSyntaxHighlightedNode.java <ide> } <ide> <ide> public String handle(final PageReference page, final Matcher matcher) { <del> String content = matcher.group(1); <add> String content = matcher.group(2); <ide> try { <ide> return XhtmlRendererFactory.getRenderer(XhtmlRendererFactory.JAVA).highlight("", content, "UTF-8", true); <ide> }
Java
apache-2.0
37b4854775e7f0084e4352ad5306084538159ba9
0
cloudevents/sdk-java
/** * Copyright 2018 The CloudEvents 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 io.cloudevents.json; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import io.cloudevents.Attributes; import io.cloudevents.fun.DataMarshaller; import io.cloudevents.fun.DataUnmarshaller; public final class Json { public static final ObjectMapper MAPPER = new ObjectMapper(); static { // add Jackson datatype for ZonedDateTime MAPPER.registerModule(new Jdk8Module()); final SimpleModule module = new SimpleModule(); module.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer()); module.addDeserializer(ZonedDateTime.class, new ZonedDateTimeDeserializer()); MAPPER.registerModule(module); } /** * Encode a POJO to JSON using the underlying Jackson mapper. * * @param obj a POJO * @return a String containing the JSON representation of the given POJO. * @throws IllegalStateException if a property cannot be encoded. */ public static String encode(final Object obj) throws IllegalStateException { try { return MAPPER.writeValueAsString(obj); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Failed to encode as JSON: " + e.getMessage()); } } /** * Encode a POJO to JSON using the underlying Jackson mapper. * * @param obj a POJO * @return a byte array containing the JSON representation of the given POJO. * @throws IllegalStateException if a property cannot be encoded. */ public static byte[] binaryEncode(final Object obj) throws IllegalStateException { try { return MAPPER.writeValueAsBytes(obj); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Failed to encode as JSON: " + e.getMessage()); } } public static <T> T fromInputStream(final InputStream inputStream, Class<T> clazz) { try { return MAPPER.readValue(inputStream, clazz); } catch (Exception e) { throw new IllegalStateException("Failed to encode as JSON: " + e.getMessage()); } } public static <T> T fromInputStream(final InputStream inputStream, final TypeReference<T> type) { try { return MAPPER.readValue(inputStream, type); } catch (Exception e) { throw new IllegalStateException("Failed to encode as JSON: " + e.getMessage()); } } /** * Decode a given JSON string to a POJO of the given class type. * * @param str the JSON string. * @param clazz the class to map to. * @param <T> the generic type. * @return an instance of T or {@code null} when {@code str} is an empty string or {@code null} * @throws IllegalStateException when there is a parsing or invalid mapping. */ protected static <T> T decodeValue(final String str, final Class<T> clazz) throws IllegalStateException { if(null!= str && !"".equals(str.trim())) { try { return MAPPER.readValue(str.trim(), clazz); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage()); } } return null; } protected static <T> T binaryDecodeValue(byte[] payload, final Class<T> clazz) { if(null!= payload) { try { return MAPPER.readValue(payload, clazz); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage()); } } return null; } /** * Decode a given JSON string to a POJO of the given type. * * @param str the JSON string. * @param type the type to map to. * @param <T> the generic type. * @return an instance of T or {@code null} when {@code str} is an empty string or {@code null} * @throws IllegalStateException when there is a parsing or invalid mapping. */ public static <T> T decodeValue(final String str, final TypeReference<T> type) throws IllegalStateException { if(null!= str && !"".equals(str.trim())) { try { return MAPPER.readValue(str.trim(), type); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage(), e); } } return null; } /** * Example of use: * <pre> * String someJson = "..."; * Class<?> clazz = Much.class; * * Json.decodeValue(someJson, CloudEventImpl.class, clazz); * </pre> * @param str The JSON String to parse * @param parametrized Actual full type * @param parameterClasses Type parameters to apply * @param <T> the generic type. * @return An instance of T or {@code null} when {@code str} is an empty string or {@code null} * @see ObjectMapper#getTypeFactory * @see TypeFactory#constructParametricType(Class, Class...) */ public static <T> T decodeValue(final String str, Class<?> parametrized, Class<?>...parameterClasses) { if(null!= str && !"".equals(str.trim())) { try { JavaType type = MAPPER.getTypeFactory() .constructParametricType(parametrized, parameterClasses); return MAPPER.readValue(str.trim(), type); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage(), e); } } return null; } /** * Example of use: * <pre> * String someJson = "..."; * Class<?> clazz = Much.class; * * Json.decodeValue(someJson, CloudEventImpl.class, clazz); * </pre> * @param json The JSON byte array to parse * @param parametrized Actual full type * @param parameterClasses Type parameters to apply * @param <T> the generic type. * @return An instance of T or {@code null} when {@code str} is an empty string or {@code null} * @see ObjectMapper#getTypeFactory * @see TypeFactory#constructParametricType(Class, Class...) */ public static <T> T binaryDecodeValue(final byte[] json, Class<?> parametrized, Class<?>...parameterClasses) { if(null!= json) { try { JavaType type = MAPPER.getTypeFactory() .constructParametricType(parametrized, parameterClasses); return MAPPER.readValue(json, type); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage(), e); } } return null; } /** * Creates a JSON Data Unmarshaller * @param <T> The 'data' type * @param <A> The attributes type * @param type The type of 'data' * @return A new instance of {@link DataUnmarshaller} */ public static <T, A extends Attributes> DataUnmarshaller<String, T, A> umarshaller(Class<T> type) { return new DataUnmarshaller<String, T, A>() { @Override public T unmarshal(String payload, A attributes) { return Json.decodeValue(payload, type); } }; } /** * Unmarshals a byte array into T type * @param <T> The 'data' type * @param <A> The attributes type * @param payload The byte array * @param attribues * @return The data objects */ public static <T, A extends Attributes> DataUnmarshaller<byte[], T, A> binaryUmarshaller(Class<T> type) { return new DataUnmarshaller<byte[], T, A>() { @Override public T unmarshal(byte[] payload, A attributes) { return Json.binaryDecodeValue(payload, type); } }; } /** * Creates a JSON Data Marshaller that produces a {@link String} * @param <T> The 'data' type * @param <H> The type of headers value * @return A new instance of {@link DataMarshaller} */ public static <T, H> DataMarshaller<String, T, H> marshaller() { return new DataMarshaller<String, T, H>() { @Override public String marshal(T data, Map<String, H> headers) { return Json.encode(data); } }; } /** * Marshalls the 'data' value as JSON, producing a byte array * @param <T> The 'data' type * @param <H> The type of headers value * @param data The 'data' value * @param headers The headers * @return A byte array with 'data' value encoded JSON */ public static <T, H> byte[] binaryMarshal(T data, Map<String, H> headers) { return Json.binaryEncode(data); } private Json() { // no-op } }
api/src/main/java/io/cloudevents/json/Json.java
/** * Copyright 2018 The CloudEvents 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 io.cloudevents.json; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import io.cloudevents.Attributes; import io.cloudevents.fun.DataMarshaller; import io.cloudevents.fun.DataUnmarshaller; public final class Json { public static final ObjectMapper MAPPER = new ObjectMapper(); static { // add Jackson datatype for ZonedDateTime MAPPER.registerModule(new Jdk8Module()); final SimpleModule module = new SimpleModule(); module.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer()); module.addDeserializer(ZonedDateTime.class, new ZonedDateTimeDeserializer()); MAPPER.registerModule(module); } /** * Encode a POJO to JSON using the underlying Jackson mapper. * * @param obj a POJO * @return a String containing the JSON representation of the given POJO. * @throws IllegalStateException if a property cannot be encoded. */ public static String encode(final Object obj) throws IllegalStateException { try { return MAPPER.writeValueAsString(obj); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Failed to encode as JSON: " + e.getMessage()); } } /** * Encode a POJO to JSON using the underlying Jackson mapper. * * @param obj a POJO * @return a byte array containing the JSON representation of the given POJO. * @throws IllegalStateException if a property cannot be encoded. */ public static byte[] binaryEncode(final Object obj) throws IllegalStateException { try { return MAPPER.writeValueAsBytes(obj); } catch (Exception e) { e.printStackTrace(); throw new IllegalStateException("Failed to encode as JSON: " + e.getMessage()); } } public static <T> T fromInputStream(final InputStream inputStream, Class<T> clazz) { try { return MAPPER.readValue(inputStream, clazz); } catch (Exception e) { throw new IllegalStateException("Failed to encode as JSON: " + e.getMessage()); } } /** * Decode a given JSON string to a POJO of the given class type. * * @param str the JSON string. * @param clazz the class to map to. * @param <T> the generic type. * @return an instance of T or {@code null} when {@code str} is an empty string or {@code null} * @throws IllegalStateException when there is a parsing or invalid mapping. */ protected static <T> T decodeValue(final String str, final Class<T> clazz) throws IllegalStateException { if(null!= str && !"".equals(str.trim())) { try { return MAPPER.readValue(str.trim(), clazz); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage()); } } return null; } protected static <T> T binaryDecodeValue(byte[] payload, final Class<T> clazz) { if(null!= payload) { try { return MAPPER.readValue(payload, clazz); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage()); } } return null; } /** * Decode a given JSON string to a POJO of the given type. * * @param str the JSON string. * @param type the type to map to. * @param <T> the generic type. * @return an instance of T or {@code null} when {@code str} is an empty string or {@code null} * @throws IllegalStateException when there is a parsing or invalid mapping. */ public static <T> T decodeValue(final String str, final TypeReference<T> type) throws IllegalStateException { if(null!= str && !"".equals(str.trim())) { try { return MAPPER.readValue(str.trim(), type); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage(), e); } } return null; } /** * Example of use: * <pre> * String someJson = "..."; * Class<?> clazz = Much.class; * * Json.decodeValue(someJson, CloudEventImpl.class, clazz); * </pre> * @param str The JSON String to parse * @param parametrized Actual full type * @param parameterClasses Type parameters to apply * @param <T> the generic type. * @return An instance of T or {@code null} when {@code str} is an empty string or {@code null} * @see ObjectMapper#getTypeFactory * @see TypeFactory#constructParametricType(Class, Class...) */ public static <T> T decodeValue(final String str, Class<?> parametrized, Class<?>...parameterClasses) { if(null!= str && !"".equals(str.trim())) { try { JavaType type = MAPPER.getTypeFactory() .constructParametricType(parametrized, parameterClasses); return MAPPER.readValue(str.trim(), type); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage(), e); } } return null; } /** * Example of use: * <pre> * String someJson = "..."; * Class<?> clazz = Much.class; * * Json.decodeValue(someJson, CloudEventImpl.class, clazz); * </pre> * @param json The JSON byte array to parse * @param parametrized Actual full type * @param parameterClasses Type parameters to apply * @param <T> the generic type. * @return An instance of T or {@code null} when {@code str} is an empty string or {@code null} * @see ObjectMapper#getTypeFactory * @see TypeFactory#constructParametricType(Class, Class...) */ public static <T> T binaryDecodeValue(final byte[] json, Class<?> parametrized, Class<?>...parameterClasses) { if(null!= json) { try { JavaType type = MAPPER.getTypeFactory() .constructParametricType(parametrized, parameterClasses); return MAPPER.readValue(json, type); } catch (Exception e) { throw new IllegalStateException("Failed to decode: " + e.getMessage(), e); } } return null; } /** * Creates a JSON Data Unmarshaller * @param <T> The 'data' type * @param <A> The attributes type * @param type The type of 'data' * @return A new instance of {@link DataUnmarshaller} */ public static <T, A extends Attributes> DataUnmarshaller<String, T, A> umarshaller(Class<T> type) { return new DataUnmarshaller<String, T, A>() { @Override public T unmarshal(String payload, A attributes) { return Json.decodeValue(payload, type); } }; } /** * Unmarshals a byte array into T type * @param <T> The 'data' type * @param <A> The attributes type * @param payload The byte array * @param attribues * @return The data objects */ public static <T, A extends Attributes> DataUnmarshaller<byte[], T, A> binaryUmarshaller(Class<T> type) { return new DataUnmarshaller<byte[], T, A>() { @Override public T unmarshal(byte[] payload, A attributes) { return Json.binaryDecodeValue(payload, type); } }; } /** * Creates a JSON Data Marshaller that produces a {@link String} * @param <T> The 'data' type * @param <H> The type of headers value * @return A new instance of {@link DataMarshaller} */ public static <T, H> DataMarshaller<String, T, H> marshaller() { return new DataMarshaller<String, T, H>() { @Override public String marshal(T data, Map<String, H> headers) { return Json.encode(data); } }; } /** * Marshalls the 'data' value as JSON, producing a byte array * @param <T> The 'data' type * @param <H> The type of headers value * @param data The 'data' value * @param headers The headers * @return A byte array with 'data' value encoded JSON */ public static <T, H> byte[] binaryMarshal(T data, Map<String, H> headers) { return Json.binaryEncode(data); } private Json() { // no-op } }
read from inputstream using typeinference Signed-off-by: Fabio José <[email protected]>
api/src/main/java/io/cloudevents/json/Json.java
read from inputstream using typeinference
<ide><path>pi/src/main/java/io/cloudevents/json/Json.java <ide> + e.getMessage()); <ide> } <ide> } <add> <add> public static <T> T fromInputStream(final InputStream inputStream, <add> final TypeReference<T> type) { <add> try { <add> return MAPPER.readValue(inputStream, type); <add> } catch (Exception e) { <add> throw new IllegalStateException("Failed to encode as JSON: " <add> + e.getMessage()); <add> } <add> } <ide> <ide> /** <ide> * Decode a given JSON string to a POJO of the given class type.
Java
apache-2.0
e557b879d87ebf1306d5c82ba79fa853d585aa0b
0
almende/dialog,almende/dialog,almende/dialog
package com.almende.dialog.util; import java.io.IOException; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import com.almende.dialog.TestFramework; import com.almende.util.ParallelInit; import com.askfast.commons.entity.ResponseLog; import com.askfast.commons.utils.PhoneNumberUtils; import com.askfast.commons.utils.TimeUtils; public class UtilTest extends TestFramework { @Test public void testIfValidPhoneNumberTest() throws Exception { String formattedNumber = PhoneNumberUtils.formatNumber("0614765852", null); Assert.assertEquals("+31614765852", formattedNumber); } @Test public void testIfValidGermanLandlinePhoneNumberTest() throws Exception { String address = "tel:+491739230752"; String formattedAddress = address.replaceFirst("tel:", "").trim(); Boolean valid = PhoneNumberUtils.isValidPhoneNumber( formattedAddress ); Assert.assertTrue( valid ); } @Test public void testIfValidDutchLandlinePhoneNumberTest() throws Exception { String address = "tel:+31851234567"; String formattedAddress = URLDecoder.decode(address.replaceFirst("tel:", "").trim(), "UTF-8"); Boolean valid = PhoneNumberUtils.isValidPhoneNumber( formattedAddress ); Assert.assertTrue( valid ); } /** * This test checks if the {@link AFHttpClient} logs an error when the url * given is invalid * * @throws IOException */ @Test public void httpClientRequestFailTest() throws Exception { AFHttpClient afHttpClient = ParallelInit.getAFHttpClient(); ResponseLog response = afHttpClient.get("blablatest/blaPathParam", true, UUID.randomUUID().toString(), TEST_PUBLIC_KEY, UUID.randomUUID().toString()); Assert.assertThat(response.getHttpCode(), Matchers.is(-1)); } /** * This test checks if the {@link AFHttpClient} logs an error when the url * given is valid * @throws IOException */ @Test public void httpClientRequestSuccessTest() throws Exception { AFHttpClient afHttpClient = ParallelInit.getAFHttpClient(); ResponseLog response = afHttpClient.get("http://api.ask-fast.com", true, UUID.randomUUID().toString(), TEST_PUBLIC_KEY, UUID.randomUUID().toString()); Assert.assertThat(response.getHttpCode(), Matchers.is(200)); Assert.assertThat(response.getHttpResponseTime(), Matchers.instanceOf(Integer.class)); Assert.assertThat(response.getHttpResponseTime(), Matchers.notNullValue()); Assert.assertThat(response.getHeaders().isEmpty(), Matchers.is(false)); } @Test public void splitTest() { List<String> keys = Arrays.asList("A", "B", "C"); String test = " [[A]] > 2 && ([[B]] + [[C]] > 2) "; Pattern compile = Pattern.compile("\\[\\[(.+?)\\]\\]"); Matcher matcher = compile.matcher(test); List<String> result = new ArrayList<String>(); while (matcher.find()) { result.add(matcher.group().replace("[[", "").replace("]]", "")); } Assert.assertArrayEquals(result.toArray(), keys.toArray()); } /** * Test to check the utils method that was updated to format the given date * in millis directly rather than new Date(millis), this fails in a server * environment which doesnt have proper configured date. */ @Test public void timeFormatTest() { long currentTime = TimeUtils.getServerCurrentTimeInMillis(); String timeFormat1 = TimeUtils.getStringFormatFromDateTime(currentTime, null); String timeformat2 = TimeUtils.getStringFormatFromDateTime(new Date(currentTime).getTime(), null); Assert.assertThat(timeFormat1, Matchers.is(timeformat2)); SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z", Locale.ENGLISH); dateFormat.setTimeZone(TimeUtils.getServerTimeZone()); String timeFormat3 = dateFormat.format(new Date(currentTime)); Assert.assertThat(timeFormat3, Matchers.is(timeformat2)); } /** * Test to check the utils method that the previous month start timestamp is * set properly with timezone */ @Test public void timeForLastMonthTest() { String previousMonthStartTimestamp = TimeUtils.getStringFormatFromDateTime(TimeUtils.getPreviousMonthStartTimestamp(), null); Assert.assertThat(previousMonthStartTimestamp, Matchers.containsString("00:00:00")); String previousMonthEndTimestamp = TimeUtils.getStringFormatFromDateTime(TimeUtils.getPreviousMonthEndTimestamp(), null); Assert.assertThat(previousMonthEndTimestamp, Matchers.containsString("23:59:59")); } }
dialoghandler/src/test/java/com/almende/dialog/util/UtilTest.java
package com.almende.dialog.util; import java.io.IOException; import java.net.URLDecoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import com.almende.dialog.TestFramework; import com.almende.util.ParallelInit; import com.askfast.commons.entity.ResponseLog; import com.askfast.commons.utils.PhoneNumberUtils; import com.askfast.commons.utils.TimeUtils; public class UtilTest extends TestFramework { @Test public void testIfValidPhoneNumberTest() throws Exception { String formattedNumber = PhoneNumberUtils.formatNumber("0614765852", null); Assert.assertEquals("+31614765852", formattedNumber); } @Test public void testIfValidGermanLandlinePhoneNumberTest() throws Exception { String address = "tel:+491739230752"; String formattedAddress = address.replaceFirst("tel:", "").trim(); Boolean valid = PhoneNumberUtils.isValidPhoneNumber( formattedAddress ); Assert.assertTrue( valid ); } @Test public void testIfValidDutchLandlinePhoneNumberTest() throws Exception { String address = "tel:+31851234567"; String formattedAddress = URLDecoder.decode(address.replaceFirst("tel:", "").trim(), "UTF-8"); Boolean valid = PhoneNumberUtils.isValidPhoneNumber( formattedAddress ); Assert.assertTrue( valid ); } /** * This test checks if the {@link AFHttpClient} logs an error when the url * given is invalid * * @throws IOException */ @Test public void httpClientRequestFailTest() throws Exception { AFHttpClient afHttpClient = ParallelInit.getAFHttpClient(); ResponseLog response = afHttpClient.get("blablatest/blaPathParam", true, UUID.randomUUID().toString(), TEST_PUBLIC_KEY, UUID.randomUUID().toString()); Assert.assertThat(response.getHttpCode(), Matchers.is(-1)); } /** * This test checks if the {@link AFHttpClient} logs an error when the url * given is valid * @throws IOException */ @Test public void httpClientRequestSuccessTest() throws Exception { AFHttpClient afHttpClient = ParallelInit.getAFHttpClient(); ResponseLog response = afHttpClient.get("http://api.ask-fast.com", true, UUID.randomUUID().toString(), TEST_PUBLIC_KEY, UUID.randomUUID().toString()); Assert.assertThat(response.getHttpCode(), Matchers.is(200)); Assert.assertThat(response.getHttpResponseTime(), Matchers.instanceOf(Integer.class)); Assert.assertThat(response.getHttpResponseTime(), Matchers.notNullValue()); Assert.assertThat(response.getHeaders().isEmpty(), Matchers.is(false)); } @Test public void splitTest() { List<String> keys = Arrays.asList("A", "B", "C"); String test = " [[A]] > 2 && ([[B]] + [[C]] > 2) "; Pattern compile = Pattern.compile("\\[\\[(.+?)\\]\\]"); Matcher matcher = compile.matcher(test); List<String> result = new ArrayList<String>(); while (matcher.find()) { result.add(matcher.group().replace("[[", "").replace("]]", "")); } Assert.assertArrayEquals(result.toArray(), keys.toArray()); } /** * Test to check the utils method that was updated to format the given date * in millis directly rather than new Date(millis), this fails in a server * environment which doesnt have proper configured date. */ @Test public void timeFormatTest() { long currentTime = TimeUtils.getServerCurrentTimeInMillis(); String timeFormat1 = TimeUtils.getStringFormatFromDateTime(currentTime, null); String timeformat2 = TimeUtils.getStringFormatFromDateTime(new Date(currentTime).getTime(), null); Assert.assertThat(timeFormat1, Matchers.is(timeformat2)); SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z", Locale.ENGLISH); dateFormat.setTimeZone(TimeUtils.getServerTimeZone()); String timeFormat3 = dateFormat.format(new Date(currentTime)); Assert.assertThat(timeFormat3, Matchers.is(timeformat2)); } }
update: added unit test for checking server time for last month start
dialoghandler/src/test/java/com/almende/dialog/util/UtilTest.java
update: added unit test for checking server time for last month start
<ide><path>ialoghandler/src/test/java/com/almende/dialog/util/UtilTest.java <ide> String timeFormat3 = dateFormat.format(new Date(currentTime)); <ide> Assert.assertThat(timeFormat3, Matchers.is(timeformat2)); <ide> } <add> <add> /** <add> * Test to check the utils method that the previous month start timestamp is <add> * set properly with timezone <add> */ <add> @Test <add> public void timeForLastMonthTest() { <add> <add> String previousMonthStartTimestamp = TimeUtils.getStringFormatFromDateTime(TimeUtils.getPreviousMonthStartTimestamp(), <add> null); <add> Assert.assertThat(previousMonthStartTimestamp, Matchers.containsString("00:00:00")); <add> String previousMonthEndTimestamp = TimeUtils.getStringFormatFromDateTime(TimeUtils.getPreviousMonthEndTimestamp(), <add> null); <add> Assert.assertThat(previousMonthEndTimestamp, Matchers.containsString("23:59:59")); <add> } <ide> }
JavaScript
mit
a13dcc121cc40d1368e3f7b95f03fe106b821402
0
takashiharano/debug.js,takashiharano/debug.js
/*! * debug.js * Copyright 2015 Takashi Harano * Released under the MIT license * https://debugjs.net/ */ var DebugJS = DebugJS || function() { this.v = '201901090000'; this.DEFAULT_OPTIONS = { visible: false, keyAssign: { key: 113, shift: undefined, ctrl: undefined, alt: undefined, meta: undefined }, popupOnError: { scriptError: true, loadError: true, errorLog: true }, lines: 18, bufsize: 300, width: 533, zoom: 1, position: 'se', adjustX: 20, adjustY: 20, fontSize: 12, fontFamily: 'Consolas, monospace', fontColor: '#fff', logColorV: '#99bcc8', logColorD: '#ccc', logColorI: '#9ef', logColorW: '#eee000', logColorE: '#f88', logColorS: '#fff', clockColor: '#8f0', timerColor: '#9ef', timerColorExpr: '#fcc', sysInfoColor: '#ddd', btnColor: '#6cf', btnHoverColor: '#8ef', promptColor: '#0cf', promptColorE: '#f45', background: 'rgba(0,0,0,0.65)', border: 'solid 1px #888', borderRadius: '0', opacity: '1', showLineNums: true, showTimeStamp: true, resizable: true, togglableShowHide: true, useClock: true, useClearButton: true, useSuspendLogButton: true, usePinButton: true, useWinCtrlButton: true, useStopwatch: true, useWindowSizeInfo: true, useMouseStatusInfo: true, useKeyStatusInfo: true, useLed: true, useMsgDisplay: true, msgDisplayPos: 'right', msgDisplayBackground: 'rgba(0,0,0,0.2)', useScreenMeasure: true, useSystemInfo: true, useHtmlSrc: true, useElementInfo: true, useTools: true, useJsEditor: true, useLogFilter: true, useCommandLine: true, cmdHistoryMax: 100, timerLineColor: '#0cf', disableAllCommands: false, disableAllFeatures: false, mode: '', lockCode: null, target: null }; this.DFLT_ELM_ID = '_debug_'; this.id = null; this.bodyEl = null; this.bodyCursor = ''; this.styleEl = null; this.win = null; this.winBody = null; this.headPanel = null; this.infoPanel = null; this.clockLabel = null; this.clockUpdIntHCnt = 0; this.clockUpdInt = DebugJS.UPDATE_INTERVAL_L; this.measBtn = null; this.measBox = null; this.sysInfoBtn = null; this.sysInfoPanel = null; this.htmlSrcBtn = null; this.htmlSrcPanel = null; this.htmlSrcHeaderPanel = null; this.htmlSrcUpdInpLbl = null; this.htmlSrcUpdInpLbl2 = null; this.htmlSrcUpdBtn = null; this.htmlSrcUpdateInput = null; this.htmlSrcBodyPanel = null; this.htmlSrcUpdateInterval = 0; this.htmlSrcUpdateTimerId = 0; this.elmInfoBtn = null; this.elmInfoPanel = null; this.elmInfoHeaderPanel = null; this.elmPrevBtn = null; this.elmTitle = null; this.elmNextBtn = null; this.elmSelectBtn = null; this.elmHighlightBtn = null; this.elmUpdateBtn = null; this.elmCapBtn = null; this.elmDelBtn = null; this.elmUpdateInput = null; this.elmNumPanel = null; this.elmInfoBodyPanel = null; this.elmInfoStatus = DebugJS.ELMINFO_ST_SELECT | DebugJS.ELMINFO_ST_HIGHLIGHT; this.elmUpdateInterval = 0; this.elmUpdateTimerId = 0; this.elmInfoShowHideStatus = {text: false, allStyles: false, elBorder: false, htmlSrc: false}; this.targetEl = null; this.toolsBtn = null; this.toolsPanel = null; this.toolsHeaderPanel = null; this.toolsBodyPanel = null; this.timerBtn = null; this.timerBasePanel = null; this.timerClockSubPanel = null; this.timerClockLabel = null; this.timerClockSSS = false; this.clockSSSbtn = null; this.timerStopwatchCuSubPanel = null; this.timerStopwatchCuLabel = null; this.timerStopwatchCdSubPanel = null; this.timerStopwatchCdLabel = null; this.timerStopwatchCdInpSubPanel = null; this.timerStopwatchCdInput = null; this.timerTimeUpTime = 0; this.timerSwTimeCd = 0; this.timerSwTimeCdContinue = false; this.timerStartStopBtnCu = null; this.timerSplitBtnCu = null; this.timerStartStopBtnCd = null; this.timerSplitBtnCd = null; this.timer0CntBtnCd1 = null; this.timer0CntBtnCd2 = null; this.timerStartStopBtnCdInp = null; this.txtChkBtn = null; this.txtChkPanel = null; this.txtChkTxt = null; this.txtChkFontSizeRange = null; this.txtChkFontSizeInput = null; this.txtChkFontSizeUnitInput = null; this.txtChkFontWeightRange = null; this.txtChkFontWeightLabel = null; this.txtChkInputFgRGB = null; this.txtChkRangeFgR = null; this.txtChkRangeFgG = null; this.txtChkRangeFgB = null; this.txtChkLabelFgR = null; this.txtChkLabelFgG = null; this.txtChkLabelFgB = null; this.txtChkInputBgRGB = null; this.txtChkRangeBgR = null; this.txtChkRangeBgG = null; this.txtChkRangeBgB = null; this.txtChkLabelBgR = null; this.txtChkLabelBgG = null; this.txtChkLabelBgB = null; this.txtChkTargetEl = null; this.txtChkItalic = false; this.fileVwrMode = 'b64'; this.fileVwrBtn = null; this.fileVwrPanel = null; this.fileInput = null; this.fileVwrLabelB64 = null; this.fileVwrRadioB64 = null; this.fileVwrLabelBin = null; this.fileVwrRadioBin = null; this.fileReloadBtn = null; this.fileClrBtn = null; this.fileVwrFooter = null; this.fileLoadProgBar = null; this.fileLoadProg = null; this.fileLoadCancelBtn = null; this.filePreviewWrapper = null; this.filePreview = null; this.fileVwrDtUrlWrp = null; this.fileVwrDtUrlScheme = null; this.fileVwrDtTxtArea = null; this.fileVwrDecMode = 'b64'; this.fileVwrDecModeBtn = null; this.fileVwrDataSrcType = null; this.fileVwrFile = null; this.fileVwrDataSrc = null; this.fileVwrByteArray = null; this.fileVwrBinViewOpt = {mode: 'hex', addr: true, space: true, ascii: true}, this.fileVwrSysCb = null; this.fileReader = null; this.jsBtn = null; this.jsPanel = null; this.jsEditor = null; this.jsBuf = ''; this.htmlPrevBtn = null; this.htmlPrevBasePanel = null; this.htmlPrevPrevPanel = null; this.htmlPrevEditorPanel = null; this.htmlPrevEditor = null; this.htmlPrevBuf = ''; this.batBtn = null; this.batBasePanel = null; this.batEditorPanel = null; this.batTextEditor = null; this.batRunBtn = null; this.batStopBtn = null; this.batResumeBtn = null; this.batStartTxt = null; this.batEndTxt = null; this.batArgTxt = null; this.batCurPc = null; this.batTotalLine = null; this.batNestLv = null; this.swBtnPanel = null; this.swLabel = null; this.clearBtn = null; this.wdBtn = null; this.suspendLogBtn = null; this.preserveLogBtn = null; this.pinBtn = null; this.winCtrlBtnPanel = null; this.closeBtn = null; this.mousePosLabel = null; this.mousePos = {x: '-', y: '-'}; this.mouseClickLabel = null; this.mouseClick0 = DebugJS.COLOR_INACT; this.mouseClick1 = DebugJS.COLOR_INACT; this.mouseClick2 = DebugJS.COLOR_INACT; this.winSizeLabel = null; this.clientSizeLabel = null; this.bodySizeLabel = null; this.pixelRatioLabel = null; this.scrollPosLabel = null; this.scrollPosX = 0; this.scrollPosY = 0; this.keyDownLabel = null; this.keyPressLabel = null; this.keyUpLabel = null; this.keyDownCode = DebugJS.KEY_ST_DFLT; this.keyPressCode = DebugJS.KEY_ST_DFLT; this.keyUpCode = DebugJS.KEY_ST_DFLT; this.ledPanel = null; this.led = 0; this.msgLabel = null; this.msgStr = ''; this.mainPanel = null; this.overlayBasePanel = null; this.overlayPanels = []; this.logHeaderPanel = null; this.fltrBtnAll = null; this.fltrBtnStd = null; this.fltrBtnVrb = null; this.fltrBtnDbg = null; this.fltrBtnInf = null; this.fltrBtnWrn = null; this.fltrBtnErr = null; this.fltrInputLabel = null; this.fltrInput = null; this.fltrText = ''; this.fltr = false; this.fltrBtn = null; this.fltrCase = false; this.fltrCaseBtn = null; this.fltrTxtHtml = true; this.fltrTxtHtmlBtn = null; this.logPanel = null; this.logPanelHeightAdjust = ''; this.cmdPanel = null; this.cmdLine = null; this.stopErrCb = false; this.cmdHistoryBuf = null; this.CMD_HISTORY_MAX = this.DEFAULT_OPTIONS.cmdHistoryMax; this.cmdHistoryIdx = this.CMD_HISTORY_MAX; this.cmdTmp = ''; this.cmdEchoFlg = true; this.cmdDelayData = {tmid: 0, cmd: null}; this.timers = {}; this.initWidth = 0; this.initHeight = 0; this.orgSizePos = {w: 0, h: 0, t: 0, l: 0}; this.expandModeOrg = {w: 0, h: 0, t: 0, l: 0}; this.winExpandHeight = DebugJS.DBGWIN_EXPAND_C_H * this.DEFAULT_OPTIONS.zoom; this.winExpandCnt = 0; this.clickedPosX = 0; this.clickedPosY = 0; this.prevOffsetTop = 0; this.prevOffsetLeft = 0; this.savedFunc = null; this.computedFontSize = this.DEFAULT_OPTIONS.fontSize; this.computedWidth = this.DEFAULT_OPTIONS.width; this.computedMinW = DebugJS.DBGWIN_MIN_W; this.computedMinH = DebugJS.DBGWIN_MIN_H; this.featStack = []; this.featStackBak = []; this.status = 0; this.uiStatus = 0; this.toolStatus = 0; this.toolTimerMode = DebugJS.TOOL_TIMER_MODE_CLOCK; this.sizeStatus = 0; this.ptOpTm = 0; this.logFilter = DebugJS.LOG_FLTR_ALL; this.toolsActiveFnc = DebugJS.TOOLS_DFLT_ACTIVE_FNC; this.logBuf = new DebugJS.RingBuffer(this.DEFAULT_OPTIONS.bufsize); this.INT_CMD_TBL = [ {cmd: 'alias', fn: this.cmdAlias, desc: 'Define or display aliases', help: 'alias [name=[\'command\']]'}, {cmd: 'base64', fn: this.cmdBase64, desc: 'Encodes/Decodes Base64', help: 'base64 [-e|-d] str'}, {cmd: 'bat', fn: this.cmdBat, desc: 'Operate BAT Script', help: 'bat run [-s s] [-e e] [-arg arg]|pause|stop|list|status|pc|symbols|clear|exec b64-encoded-bat|set key val'}, {cmd: 'bin', fn: this.cmdBin, desc: 'Convert a number to binary', help: 'bin num digit'}, {cmd: 'bsb64', fn: this.cmdBSB64, desc: 'Encodes/Decodes BSB64(Bit Shifted Base64) reversible encryption string', help: 'bsb64 -e|-d -i "&lt;str&gt;" [-n &lt;n&gt[L|R]]'}, {cmd: 'call', fn: this.cmdCall, attr: DebugJS.CMD_ATTR_SYSTEM | DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'close', fn: this.cmdClose, desc: 'Close a function', help: 'close [measure|sys|html|dom|js|tool|ext]'}, {cmd: 'clock', fn: this.cmdClock, desc: 'Open clock mode'}, {cmd: 'cls', fn: this.cmdCls, desc: 'Clear log message', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'condwait', fn: this.cmdCondWait, desc: 'Suspends processing of batch file until condition key is set', help: 'condwait set -key key | pause [-timeout ms|1d2h3m4s500] | init'}, {cmd: 'dbgwin', fn: this.cmdDbgWin, desc: 'Control the debug window', help: 'dbgwin show|hide|pos|size|opacity|status|lock'}, {cmd: 'date', fn: this.cmdDate, desc: 'Convert ms <--> Date-Time', help: 'date [ms|YYYY/MM/DD HH:MI:SS.sss]'}, {cmd: 'delay', fn: this.cmdDelay, desc: 'Delay command execution', help: 'delay [-c] ms|YYYYMMDDTHHMISS|1d2h3m4s500 command'}, {cmd: 'echo', fn: this.cmdEcho, desc: 'Display the ARGs on the log window'}, {cmd: 'elements', fn: this.cmdElements, desc: 'Count elements by #id / .className / tagName', help: 'elements [#id|.className|tagName]'}, {cmd: 'event', fn: this.cmdEvent, desc: 'Manipulate an event', help: 'event create|set|dispatch|clear type|prop value'}, {cmd: 'exit', fn: this.cmdExit, desc: 'Close the debug window and clear all status', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'goto', fn: this.cmdGoto, attr: DebugJS.CMD_ATTR_SYSTEM | DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'help', fn: this.cmdHelp, desc: 'Displays available command list', help: 'help command', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'hex', fn: this.cmdHex, desc: 'Convert a number to hexadecimal', help: 'hex num digit'}, {cmd: 'history', fn: this.cmdHistory, desc: 'Displays command history', help: 'history [-c] [-d offset]', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'http', fn: this.cmdHttp, desc: 'Send an HTTP request', help: 'http [method] url [--user user:pass] [data]'}, {cmd: 'js', fn: this.cmdJs, desc: 'Operate JavaScript code in JS Editor', help: 'js exec'}, {cmd: 'json', fn: this.cmdJson, desc: 'Parse one-line JSON', help: 'json [-l&lt;n&gt;] [-p] one-line-json'}, {cmd: 'jump', fn: this.cmdJump, attr: DebugJS.CMD_ATTR_SYSTEM | DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'keypress', fn: this.cmdKeyPress, desc: 'Dispatch a key event to active element', help: 'keypress keycode [-shift] [-ctrl] [-alt] [-meta]'}, {cmd: 'keys', fn: this.cmdKeys, desc: 'Displays all enumerable property keys of an object', help: 'keys object'}, {cmd: 'laptime', fn: this.cmdLaptime, desc: 'Lap time test'}, {cmd: 'led', fn: this.cmdLed, desc: 'Set a bit pattern to the indicator', help: 'led bit-pattern'}, {cmd: 'log', fn: this.cmdLog, desc: 'Manipulate log output', help: 'log bufsize|dump|filter|html|load|preserve|suspend|lv'}, {cmd: 'msg', fn: this.cmdMsg, desc: 'Set a string to the message display', help: 'msg message'}, {cmd: 'nexttime', fn: this.cmdNextTime, desc: 'Returns next time from given args', help: 'nexttime T0000|T1200|...|1d2h3m4s|ms'}, {cmd: 'now', fn: this.cmdNow, desc: 'Returns the number of milliseconds elapsed since Jan 1, 1970 00:00:00 UTC'}, {cmd: 'open', fn: this.cmdOpen, desc: 'Launch a function', help: 'open [measure|sys|html|dom|js|tool|ext] [timer|text|file|html|bat]|[idx] [clock|cu|cd]|[b64|bin]'}, {cmd: 'p', fn: this.cmdP, desc: 'Print JavaScript Objects', help: 'p [-l&lt;n&gt;] [-json] object'}, {cmd: 'pause', fn: this.cmdPause, desc: 'Suspends processing of batch file', help: 'pause [-key key [-timeout ms|1d2h3m4s500]|-s]'}, {cmd: 'pin', fn: this.cmdPin, desc: 'Fix the window in its position', help: 'pin on|off'}, {cmd: 'point', fn: this.cmdPoint, desc: 'Show the pointer to the specified coordinate', help: 'point [+|-]x [+|-]y|click|cclick|rclick|dblclick|contextmenu|mousedown|mouseup|keydown|keypress|keyup|focus|blur|change|show|hide|getprop|setprop|verify|init|#id|.class [idx]|tagName [idx]|center|mouse|move|drag|text|selectoption|value|scroll|hint|cursor src [w] [h]'}, {cmd: 'prop', fn: this.cmdProp, desc: 'Displays a property value', help: 'prop property-name'}, {cmd: 'props', fn: this.cmdProps, desc: 'Displays property list', help: 'props [-reset]'}, {cmd: 'random', fn: this.cmdRandom, desc: 'Generate a random number/string', help: 'random [-d|-s] [min] [max]'}, {cmd: 'resume', fn: this.cmdResume, desc: 'Resume a suspended batch process', help: 'resume [-key key]'}, {cmd: 'return', fn: this.cmdReturn, attr: DebugJS.CMD_ATTR_SYSTEM | DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'rgb', fn: this.cmdRGB, desc: 'Convert RGB color values between HEX and DEC', help: 'rgb values (#<span style="color:' + DebugJS.COLOR_R + '">R</span><span style="color:' + DebugJS.COLOR_G + '">G</span><span style="color:' + DebugJS.COLOR_B + '">B</span> | <span style="color:' + DebugJS.COLOR_R + '">R</span> <span style="color:' + DebugJS.COLOR_G + '">G</span> <span style="color:' + DebugJS.COLOR_B + '">B</span>)'}, {cmd: 'rot', fn: this.cmdROT, desc: 'Encodes/Decodes ROTx', help: 'rot 5|13|47 -e|-d -i "&lt;str&gt;" [-n &lt;n&gt]'}, {cmd: 'scrollto', fn: this.cmdScrollTo, desc: 'Set scroll position', help: '\nscrollto log top|px|bottom [+|-]px(x)|left|center|right|current\nscrollto window [+|-]px(y)|top|middle|bottom|current [-speed speed(ms)] [-step step(px)]'}, {cmd: 'select', fn: this.cmdSelect, desc: 'Select an option of select element', help: 'select selectors get|set text|texts|value|values val'}, {cmd: 'set', fn: this.cmdSet, desc: 'Set a property value', help: 'set property-name value'}, {cmd: 'setattr', fn: this.cmdSetAttr, desc: 'Set the value of an attribute on the specified element', help: 'setattr selector [idx] name value'}, {cmd: 'sleep', fn: this.cmdSleep, desc: 'Causes the currently executing thread to sleep', help: 'sleep ms'}, {cmd: 'stopwatch', fn: this.cmdStopwatch, desc: 'Manipulate the stopwatch', help: 'stopwatch [sw0|sw1|sw2] start|stop|reset|split|end|val'}, {cmd: 'test', fn: this.cmdTest, desc: 'Manage unit test', help: 'test init|set|count|result|last|ttlresult|status|verify got-val method expected-val|fin'}, {cmd: 'text', fn: this.cmdText, desc: 'Set text value into an element', help: 'text selector "data" [-speed speed(ms)] [-start seqStartPos] [-end seqEndPos]'}, {cmd: 'time', fn: this.cmdTime, desc: 'Time duration calculator', help: 'time ms|-t1 ms|"datestr" -t2 ms|"datestr"'}, {cmd: 'timer', fn: this.cmdTimer, desc: 'Manipulate the timer', help: 'time start|split|stop|list [timer-name]'}, {cmd: 'unalias', fn: this.cmdUnAlias, desc: 'Remove each NAME from the list of defined aliases', help: 'unalias [-a] name [name ...]'}, {cmd: 'unicode', fn: this.cmdUnicode, desc: 'Displays Unicode code point / Decodes unicode string', help: 'unicode [-e|-d] str|codePoint(s)'}, {cmd: 'uri', fn: this.cmdUri, desc: 'Encodes/Decodes a URI component', help: 'uri [-e|-d] str'}, {cmd: 'utf8', fn: this.cmdUtf8, desc: 'Dump UTF-8 byte sequence', help: 'utf8 "str"'}, {cmd: 'v', fn: this.cmdV, desc: 'Displays version info', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'vals', fn: this.cmdVals, desc: 'Displays variable list'}, {cmd: 'watchdog', fn: this.cmdWatchdog, desc: 'Start/Stop watchdog timer', help: 'watchdog [start|stop] [time(ms)]'}, {cmd: 'win', fn: this.cmdWin, desc: 'Set the debugger window size/pos', help: 'win min|normal|expand|full|center|restore|reset', attr: DebugJS.CMD_ATTR_DYNAMIC | DebugJS.CMD_ATTR_NO_KIOSK}, {cmd: 'zoom', fn: this.cmdZoom, desc: 'Zoom the debugger window', help: 'zoom ratio', attr: DebugJS.CMD_ATTR_DYNAMIC}, {cmd: 'wait', fn: this.cmdNop, attr: DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'nop', fn: this.cmdNop, attr: DebugJS.CMD_ATTR_HIDDEN} ]; this.CMD_TBL = []; this.EXT_CMD_TBL = []; this.CMD_ALIAS = {b64: 'base64'}; this.CMDVALS = {}; this.opt = null; this.errStatus = DebugJS.ERR_ST_NONE; this.PROPS_RESTRICTION = { batcont: /^on$|^off$/, batstop: /^[^|][a-z|]+[^|]$/, esc: /^enable$|^disable$/, dumplimit: /^[0-9]+$/, dumpvallen: /^[0-9]+$/, prevlimit: /^[0-9]+$/, hexdumplimit: /^[0-9]+$/, hexdumplastrows: /^[0-9]+$/, indent: /^[0-9]+$/, radix: /^[^|][a-z|]+[^|]$/, pointspeed: /^[0-9]+$/, pointstep: /^[0-9]+$/, pointmsgsize: /.*/, scrollspeed: /^[0-9]+$/, scrollstep: /^[0-9]+$/, textspeed: /^[0-9\-]+$/, textstep: /^[0-9\-]+$/, testvallimit: /^[0-9\-]+$/, wait: /^[0-9]+$/, timer: /.*/, wdt: /^[0-9]+$/, mousemovesim: /^true$|^false$/, consolelog: /^native$|^me$/ }; this.PROPS_DFLT_VALS = { batcont: 'off', batstop: 'error', esc: 'enable', dumplimit: 1000, dumpvallen: 4096, prevlimit: 5 * 1024 * 1024, hexdumplimit: 1048576, hexdumplastrows: 16, indent: 1, radix: 'bin|dec|hex', pointspeed: DebugJS.point.move.speed, pointstep: DebugJS.point.move.step, pointmsgsize: '"12px"', scrollspeed: DebugJS.scrollWinTo.data.speed, scrollstep: DebugJS.scrollWinTo.data.step, textspeed: 30, textstep: 1, testvallimit: 4096, wait: 500, timer: '00:03:00.000', wdt: 500, mousemovesim: 'false', consolelog: 'native' }; this.PROPS_CB = { batcont: this.setPropBatContCb, indent: this.setPropIndentCb, pointmsgsize: this.setPropPointMsgSizeCb, timer: this.setPropTimerCb, consolelog: this.setPropConsoleLogCb }; this.props = {}; this.extBtn = null; this.extBtnLabel = 'EXT'; this.extPanel = null; this.extHeaderPanel = null; this.extBodyPanel = null; this.extActivePanel = null; this.extPanels = []; this.extActPnlIdx = -1; this.evtListener = { batstart: [], batstop: [], ctrlc: [], drop: [], error: [], fileloaded: [], unlock: [], watchdog: [] }; this.unlockCode = null; this.setupDefaultOptions(); DebugJS.copyProp(this.PROPS_DFLT_VALS, this.props); }; DebugJS.MAX_SAFE_INT = 0x1FFFFFFFFFFFFF; DebugJS.DFLT_UNIT = 32; DebugJS.INIT_CAUSE_ZOOM = 1; DebugJS.ST_INITIALIZED = 1; DebugJS.ST_MEASURE = 1 << 2; DebugJS.ST_MEASURING = 1 << 3; DebugJS.ST_SYS_INFO = 1 << 4; DebugJS.ST_ELM_INSPECTING = 1 << 5; DebugJS.ST_ELM_EDIT = 1 << 6; DebugJS.ST_TOOLS = 1 << 7; DebugJS.ST_JS = 1 << 8; DebugJS.ST_HTML_SRC = 1 << 9; DebugJS.ST_LOG_SUSPENDING = 1 << 10; DebugJS.ST_LOG_PRESERVED = 1 << 11; DebugJS.ST_STOPWATCH_RUNNING = 1 << 12; DebugJS.ST_STOPWATCH_LAPTIME = 1 << 13; DebugJS.ST_STOPWATCH_END = 1 << 14; DebugJS.ST_WD = 1 << 15; DebugJS.ST_EXT_PANEL = 1 << 16; DebugJS.ST_BAT_RUNNING = 1 << 17; DebugJS.ST_BAT_PAUSE = 1 << 18; DebugJS.ST_BAT_PAUSE_CMD = 1 << 19; DebugJS.ST_BAT_PAUSE_CMD_KEY = 1 << 20; DebugJS.ST_BAT_CONT = 1 << 21; DebugJS.ST_BAT_BREAK = 1 << 22; DebugJS.UI_ST_VISIBLE = 1; DebugJS.UI_ST_DYNAMIC = 1 << 1; DebugJS.UI_ST_SHOW_CLOCK = 1 << 2; DebugJS.UI_ST_DRAGGABLE = 1 << 3; DebugJS.UI_ST_DRAGGING = 1 << 4; DebugJS.UI_ST_RESIZABLE = 1 << 5; DebugJS.UI_ST_RESIZING = 1 << 6; DebugJS.UI_ST_RESIZING_N = 1 << 7; DebugJS.UI_ST_RESIZING_E = 1 << 8; DebugJS.UI_ST_RESIZING_S = 1 << 9; DebugJS.UI_ST_RESIZING_W = 1 << 10; DebugJS.UI_ST_RESIZING_ALL = DebugJS.UI_ST_RESIZING | DebugJS.UI_ST_RESIZING_N | DebugJS.UI_ST_RESIZING_E | DebugJS.UI_ST_RESIZING_S | DebugJS.UI_ST_RESIZING_W; DebugJS.UI_ST_POS_AUTO_ADJUST = 1 << 11; DebugJS.UI_ST_LOG_SCROLL = 1 << 12; DebugJS.UI_ST_PROTECTED = 1 << 13; DebugJS.TOOL_ST_SW_CU_RUNNING = 1; DebugJS.TOOL_ST_SW_CU_END = 1 << 1; DebugJS.TOOL_ST_SW_CD_RUNNING = 1 << 2; DebugJS.TOOL_ST_SW_CD_RST = 1 << 3; DebugJS.TOOL_ST_SW_CD_EXPIRED = 1 << 4; DebugJS.TOOL_ST_SW_CD_END = 1 << 5; DebugJS.TOOL_TIMER_MODE_CLOCK = 0; DebugJS.TOOL_TIMER_MODE_SW_CU = 1; DebugJS.TOOL_TIMER_MODE_SW_CD = 2; DebugJS.TOOL_TIMER_BTN_COLOR = '#eee'; DebugJS.LOG_FLTR_LOG = 0x1; DebugJS.LOG_FLTR_VRB = 0x2; DebugJS.LOG_FLTR_DBG = 0x4; DebugJS.LOG_FLTR_INF = 0x8; DebugJS.LOG_FLTR_WRN = 0x10; DebugJS.LOG_FLTR_ERR = 0x20; DebugJS.LOG_FLTR_ALL = DebugJS.LOG_FLTR_LOG | DebugJS.LOG_FLTR_DBG | DebugJS.LOG_FLTR_INF | DebugJS.LOG_FLTR_WRN | DebugJS.LOG_FLTR_ERR; DebugJS.LOG_TYPE_LOG = 0x1; DebugJS.LOG_TYPE_VRB = 0x2; DebugJS.LOG_TYPE_DBG = 0x4; DebugJS.LOG_TYPE_INF = 0x8; DebugJS.LOG_TYPE_WRN = 0x10; DebugJS.LOG_TYPE_ERR = 0x20; DebugJS.LOG_TYPE_SYS = 0x40; DebugJS.LOG_TYPE_MLT = 0x80; DebugJS.LOG_TYPE_RES = 0x100; DebugJS.LOG_TYPE_ERES = 0x200; DebugJS.ELMINFO_ST_SELECT = 0x1; DebugJS.ELMINFO_ST_HIGHLIGHT = 0x2; DebugJS.ERR_ST_NONE = 0; DebugJS.ERR_ST_SCRIPT = 0x1; DebugJS.ERR_ST_LOAD = 0x2; DebugJS.ERR_ST_LOG = 0x4; DebugJS.TOOLS_FNC_TIMER = 0x1; DebugJS.TOOLS_FNC_TEXT = 0x2; DebugJS.TOOLS_FNC_HTML = 0x4; DebugJS.TOOLS_FNC_FILE = 0x8; DebugJS.TOOLS_FNC_BAT = 0x10; DebugJS.TOOLS_DFLT_ACTIVE_FNC = DebugJS.TOOLS_FNC_TIMER; DebugJS.CMD_ATTR_SYSTEM = 0x1; DebugJS.CMD_ATTR_HIDDEN = 0x2; DebugJS.CMD_ATTR_DYNAMIC = 0x4; DebugJS.CMD_ATTR_NO_KIOSK = 0x8; DebugJS.CMD_ATTR_DISABLED = 0x10; DebugJS.CMD_ECHO_MAX_LEN = 256; DebugJS.DBGWIN_MIN_W = 292; DebugJS.DBGWIN_MIN_H = 155; DebugJS.DBGWIN_EXPAND_C_W = 960; DebugJS.DBGWIN_EXPAND_C_H = 640; DebugJS.DBGWIN_EXPAND_W = 850; DebugJS.DBGWIN_EXPAND_H = 580; DebugJS.SIZE_ST_MIN = -1; DebugJS.SIZE_ST_NORMAL = 0; DebugJS.SIZE_ST_EXPANDED = 1; DebugJS.SIZE_ST_EXPANDED_C = 2; DebugJS.SIZE_ST_FULL_W = 4; DebugJS.SIZE_ST_FULL_H = 5; DebugJS.SIZE_ST_FULL_WH = 6; DebugJS.DBGWIN_POS_NONE = -9999; DebugJS.WIN_SHADOW = 10; DebugJS.WIN_BORDER = 1; DebugJS.WIN_PADDING = 1; DebugJS.WIN_ADJUST = ((DebugJS.WIN_BORDER * 2) + (DebugJS.WIN_PADDING * 2)); DebugJS.OVERLAY_PANEL_HEIGHT = 77; DebugJS.CMD_LINE_PADDING = 3; DebugJS.COLOR_ACTIVE = '#fff'; DebugJS.SBPNL_COLOR_ACTIVE = '#6cf'; DebugJS.SBPNL_COLOR_INACT = '#ccc'; DebugJS.COLOR_INACT = '#999'; DebugJS.MEAS_BTN_COLOR = '#6cf'; DebugJS.SYS_BTN_COLOR = '#3cf'; DebugJS.HTML_BTN_COLOR = '#8f8'; DebugJS.DOM_BTN_COLOR = '#f63'; DebugJS.JS_BTN_COLOR = '#6df'; DebugJS.TOOLS_BTN_COLOR = '#ff0'; DebugJS.EXT_BTN_COLOR = '#f8f'; DebugJS.LOG_PRESERVE_BTN_COLOR = '#0f0'; DebugJS.LOG_SUSPEND_BTN_COLOR = '#f66'; DebugJS.PIN_BTN_COLOR = '#fa0'; DebugJS.FLT_BTN_COLOR = '#eee'; DebugJS.COLOR_R = '#f66'; DebugJS.COLOR_G = '#6f6'; DebugJS.COLOR_B = '#6bf'; DebugJS.KEY_ST_DFLT = '- <span style="color:' + DebugJS.COLOR_INACT + '">SCAM</span>'; DebugJS.WDAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']; DebugJS.WDAYS_COLOR = ['f74', 'fff', 'fff', 'fff', 'fff', 'fff', '8fd']; DebugJS.UPDATE_INTERVAL_H = 21; DebugJS.UPDATE_INTERVAL_L = 500; DebugJS.DFLT_TIMER_NAME = 'timer0'; DebugJS.TIMER_NAME_SW_0 = 'sw0'; DebugJS.TIMER_NAME_SW_CU = 'sw1'; DebugJS.TIMER_NAME_SW_CD = 'sw2'; DebugJS.LED_BIT = [0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80]; DebugJS.LED_COLOR = ['#4cf', '#0ff', '#6f6', '#ee0', '#f80', '#f66', '#f0f', '#ddd']; DebugJS.LED_COLOR_INACT = '#777'; DebugJS.ITEM_NAME_COLOR = '#cff'; DebugJS.KEYWORD_COLOR = '#0ff'; DebugJS.RND_TYPE_NUM = '-d'; DebugJS.RND_TYPE_STR = '-s'; DebugJS.ELM_HL_CLASS_SUFFIX = '-elhl'; DebugJS.EXPANDBTN = '&gt;'; DebugJS.CLOSEBTN = 'v'; DebugJS.OMIT_LAST = 0; DebugJS.OMIT_MID = 1; DebugJS.OMIT_FIRST = 2; DebugJS.DISP_BIN_DIGITS_THR = 5; DebugJS.TIME_RST_STR = '00:00:00.000'; DebugJS.EXIT_SUCCESS = 0; DebugJS.EXIT_FAILURE = 1; DebugJS.EXIT_SIG = 128; DebugJS.EXIT_CLEARED = -1; DebugJS.SIGINT = 2; DebugJS.SIGTERM = 15; DebugJS.BAT_HEAD = '#!BAT!'; DebugJS.BAT_HEAD_B64 = 'IyFCQVQh'; DebugJS.BAT_TKN_JS = '!__JS__!'; DebugJS.BAT_TKN_TXT = '!__TEXT__!'; DebugJS.BAT_TKN_IF = 'IF'; DebugJS.BAT_TKN_ELIF = 'ELSE IF'; DebugJS.BAT_TKN_ELSE = 'ELSE'; DebugJS.BAT_TKN_LOOP = 'LOOP'; DebugJS.BAT_TKN_BREAK = 'BREAK'; DebugJS.BAT_TKN_CONTINUE = 'CONTINUE'; DebugJS.BAT_TKN_BLOCK_START = '('; DebugJS.BAT_TKN_BLOCK_END = ')'; DebugJS.BAT_TKN_LABEL = ':'; DebugJS.BAT_TKN_FNC = 'FUNCTION'; DebugJS.BAT_TKN_RET = 'return'; DebugJS.RE_ELIF = new RegExp('^\\' + DebugJS.BAT_TKN_BLOCK_END + '\\s?' + DebugJS.BAT_TKN_ELIF + '\\s?\\' + DebugJS.BAT_TKN_BLOCK_START + '?.+'); DebugJS.RE_ELSE = DebugJS.BAT_TKN_BLOCK_END + DebugJS.BAT_TKN_ELSE + DebugJS.BAT_TKN_BLOCK_START; DebugJS.CHR_LED = '&#x25CF;'; DebugJS.CHR_DELTA = '&#x22BF;'; DebugJS.CHR_CRLF = '&#x21b5;'; DebugJS.CHR_LF = '&#x2193;'; DebugJS.CHR_CR = '&#x2190;'; DebugJS.CHR_CRLF_S = '<span style="color:#0cf" class="dbg-cc">' + DebugJS.CHR_CRLF + '</span>'; DebugJS.CHR_LF_S = '<span style="color:#0f0" class="dbg-cc">' + DebugJS.CHR_LF + '</span>'; DebugJS.CHR_CR_S = '<span style="color:#f00" class="dbg-cc">' + DebugJS.CHR_CR + '</span>'; DebugJS.EOF = '<span style="color:#08f" class="dbg-cc">[EOF]</span>'; DebugJS.CHR_WIN_FULL = '&#x25A1;'; DebugJS.CHR_WIN_RST = '&#x2750;'; DebugJS.LOG_HEAD = '[LOG]'; DebugJS.LOG_BOUNDARY_BUF = '-- ORIGINAL LOG BUFFER --'; DebugJS.SYS_INFO_FULL_OVERLAY = true; DebugJS.HTML_SRC_FULL_OVERLAY = true; DebugJS.HTML_SRC_EXPAND_H = false; DebugJS.ELM_INFO_FULL_OVERLAY = false; DebugJS.LS_AVAILABLE = false; DebugJS.SS_AVAILABLE = false; DebugJS.G_EL_AVAILABLE = false; DebugJS.JS_SNIPPET = [ 'dbg.time.s();\nfor (var i = 0; i < 1000000; i++) {\n\n}\ndbg.time.e();\n\'done\';', '', '', ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~', '// Logging performance check\nvar n = 1000;\nvar i = 0;\ndbg.time.s(\'total\');\ntest();\nfunction test() {\n dbg.time.s();\n dbg.time.e();\n i++;\n if (i == n) {\n dbg.msg.clear();\n dbg.time.e(\'total\');\n } else {\n if (i % 100 == 0) {\n dbg.msg(\'i = \' + i + \' / \' + dbg.time.check(\'total\'));\n }\n setTimeout(test, 0);\n }\n}' ]; DebugJS.HTML_SNIPPET = [ '<div style="width:100%; height:100%; background:#fff; color:#000;">\n\n</div>\n', '<img src="data:image/jpeg;base64,">', '<button onclick=""></button>', '<video src="" controls autoplay>', '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="utf-8">\n<meta http-equiv="X-UA-Compatible" content="IE=Edge">\n<title></title>\n<link rel="stylesheet" href="style.css" />\n<script src="script.js"></script>\n<style>\n</style>\n<script>\n</script>\n</head>\n<body>\nhello\n</body>\n</html>\n' ]; DebugJS.FEATURES = [ 'togglableShowHide', 'useClock', 'useClearButton', 'useSuspendLogButton', 'usePinButton', 'useWinCtrlButton', 'useStopwatch', 'useWindowSizeInfo', 'useMouseStatusInfo', 'useKeyStatusInfo', 'useLed', 'useMsgDisplay', 'useScreenMeasure', 'useSystemInfo', 'useElementInfo', 'useHtmlSrc', 'useTools', 'useJsEditor', 'useLogFilter', 'useCommandLine' ]; DebugJS.f_ = function() {}; DebugJS.prototype = { init: function(opt, rstrOpt) { if (!DebugJS.ENABLE) return false; var ctx = DebugJS.ctx; var keepStatus = ((rstrOpt && (rstrOpt.cause == DebugJS.INIT_CAUSE_ZOOM)) ? true : false); ctx.bodyEl = document.body; ctx.finalizeFeatures(ctx); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (ctx.win) { for (var i = ctx.win.childNodes.length - 1; i >= 0; i--) { ctx.win.removeChild(ctx.win.childNodes[i]); } ctx.bodyEl.removeChild(ctx.win); ctx.timerBasePanel = null; ctx.win = null; } } if (!keepStatus) { var preserveStatus = DebugJS.ST_LOG_PRESERVED | DebugJS.ST_STOPWATCH_RUNNING | DebugJS.ST_WD | DebugJS.ST_BAT_RUNNING | DebugJS.ST_BAT_PAUSE | DebugJS.ST_BAT_PAUSE_CMD | DebugJS.ST_BAT_PAUSE_CMD_KEY; ctx.status &= preserveStatus; ctx.uiStatus = 0; ctx.startLogScrolling(); } if ((ctx.opt == null) || ((opt != null) && (!keepStatus)) || (opt === undefined)) { ctx.setupDefaultOptions(); } if (opt) { for (var key1 in opt) { for (var key2 in ctx.opt) { if (key1 == key2) { ctx.opt[key1] = opt[key1]; if ((key1 == 'disableAllFeatures') && (opt[key1])) { ctx.disableAllFeatures(ctx); } break; } } } } if (ctx.logBuf.size() != ctx.opt.bufsize) { if (!(ctx.status & DebugJS.ST_LOG_PRESERVED) || ((ctx.status & DebugJS.ST_LOG_PRESERVED) && (ctx.logBuf.size() < ctx.opt.bufsize))) { ctx.initBuf(ctx, ctx.opt.bufsize); } } if (ctx.opt.mode == 'noui') { ctx.rmvEventHandlers(ctx); ctx.init = DebugJS.f_; DebugJS.init = DebugJS.f_; ctx.status |= DebugJS.ST_INITIALIZED; return false; } if (!ctx.bodyEl) return false; ctx.initUi(ctx, rstrOpt); ctx.initCommandTable(ctx); ctx.status |= DebugJS.ST_INITIALIZED; ctx.initExtension(ctx); ctx.printLogs(); ctx.showDbgWinOnError(ctx); return true; }, initUi: function(ctx, rstrOpt) { ctx.initUiStatus(ctx, ctx.opt, rstrOpt); ctx.computedMinW = DebugJS.DBGWIN_MIN_W * ctx.opt.zoom; ctx.computedMinH = DebugJS.DBGWIN_MIN_H * ctx.opt.zoom; ctx.computedFontSize = Math.round(ctx.opt.fontSize * ctx.opt.zoom); ctx.computedWidth = Math.round(ctx.opt.width * ctx.opt.zoom); if (ctx.opt.target == null) { ctx.id = ctx.DFLT_ELM_ID; ctx.win = document.createElement('div'); ctx.win.id = ctx.id; ctx.win.style.position = 'fixed'; ctx.win.style.zIndex = 0x7fffffff; ctx.win.style.width = ctx.computedWidth + 'px'; ctx.win.style.boxShadow = DebugJS.WIN_SHADOW + 'px ' + DebugJS.WIN_SHADOW + 'px 10px rgba(0,0,0,.3)'; ctx.bodyEl.appendChild(ctx.win); if (ctx.opt.mode == 'kiosk') { ctx.setupKioskMode(ctx); } } else { ctx.id = ctx.opt.target; ctx.win = document.getElementById(ctx.id); ctx.win.style.position = 'relative'; } ctx.win.style.display = 'block'; ctx.win.style.padding = DebugJS.WIN_BORDER + 'px'; ctx.win.style.lineHeight = '1em'; ctx.win.style.boxSizing = 'content-box'; ctx.win.style.border = ctx.opt.border; ctx.win.style.borderRadius = ctx.opt.borderRadius; ctx.win.style.background = ctx.opt.background; ctx.win.style.color = ctx.opt.fontColor; ctx.win.style.fontSize = ctx.computedFontSize + 'px', ctx.win.style.opacity = ctx.opt.opacity; ctx.createPanels(ctx); if (ctx.uiStatus & DebugJS.UI_ST_RESIZABLE) { ctx.initResize(ctx); } ctx.initStyles(ctx); ctx.initDbgWin(ctx); ctx.setupEventHandler(ctx); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (ctx.opt.mode == 'kiosk') { ctx.focusCmdLine(); } else { ctx.setupMove(ctx); ctx.initWidth = ctx.win.offsetWidth; ctx.initHeight = ctx.win.offsetHeight; ctx.resetDbgWinSizePos(); if ((rstrOpt != null) && (rstrOpt.cause == DebugJS.INIT_CAUSE_ZOOM)) { ctx.focusCmdLine(); } if (!(ctx.uiStatus & DebugJS.UI_ST_VISIBLE) || (ctx.uiStatus & DebugJS.UI_ST_PROTECTED)) { ctx.win.style.display = 'none'; } } } else { ctx.initWidth = ctx.win.offsetWidth - DebugJS.WIN_ADJUST; ctx.initHeight = ctx.win.offsetHeight - DebugJS.WIN_ADJUST; } ctx.winExpandHeight = DebugJS.DBGWIN_EXPAND_C_H * ctx.opt.zoom; if ((rstrOpt != null) && (rstrOpt.cause == DebugJS.INIT_CAUSE_ZOOM)) { ctx.resetStylesOnZoom(ctx); ctx.reopenFeatures(ctx); ctx.restoreDbgWinSize(ctx, rstrOpt.sizeStatus); } }, initStyles: function(ctx) { var opt = ctx.opt; var fontSize = ctx.computedFontSize + 'px'; var ltsp = '0'; if (DebugJS.getBrowserType().name == 'Firefox') { ltsp = '-0.35px'; } var styles = {}; styles['#' + ctx.id] = { 'text-align': 'left !important', 'letter-spacing': ltsp + ' !important' }; styles['#' + ctx.id + ' *'] = { 'box-sizing': 'content-box !important', 'color': opt.fontColor, 'font-size': fontSize + ' !important', 'font-family': opt.fontFamily + ' !important' }; styles['#' + ctx.id + ' td'] = { 'width': 'auto !important', 'padding': '0 3px !important', 'border': 'none !important', 'background': 'none !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important' }; styles['#' + ctx.id + ' pre'] = { 'width': 'auto !important', 'height': 'auto !important', 'margin': '0 !important', 'padding': '0 !important', 'line-height': '1em !important', 'border': 'none !important', 'border-radius': '0 !important', 'background': 'none !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important', 'white-space': 'pre-wrap !important', 'word-break': 'break-all !important', 'overflow': 'visible !important' }; styles['.dbg-btn'] = { 'color': opt.btnColor + ' !important' }; styles['.dbg-btn:hover'] = { 'text-shadow': '0 0 3px', 'cursor': 'pointer' }; styles['.dbg-btn-disabled'] = { 'opacity': 0.5 }; styles['.dbg-btn-disabled:hover'] = { 'text-shadow': 'none', 'cursor': 'auto' }; styles['.dbg-btn-red'] = { 'color': '#a88 !important' }; styles['.dbg-btn-wh'] = { 'color': '#fff !important' }; styles['.dbg-sys-info'] = { 'display': 'inline-block', 'margin-right': '10px', 'color': opt.sysInfoColor + ' !important' }; styles['.dbg-resize-corner'] = { 'position': 'absolute', 'width': '6px', 'height': '6px', 'background': 'rgba(0,0,0,0)' }; styles['.dbg-resize-side'] = { 'position': 'absolute', 'background': 'rgba(0,0,0,0)' }; styles['.dbg-overlay-base-panel'] = { 'position': 'relative', 'top': '0', 'left': '0', 'width': 'calc(100% - 2px)', 'height': DebugJS.OVERLAY_PANEL_HEIGHT + '%' }; var overlayPanelBorder = 1; var overlayPanelPadding = 2; styles['.dbg-overlay-panel'] = { 'position': 'absolute', 'top': '0', 'left': '0', 'width': 'calc(100% - ' + ((overlayPanelPadding) * 2) + 'px)', 'height': 'calc(100% - ' + ((overlayPanelPadding) * 2) + 'px)', 'padding': overlayPanelPadding + 'px', 'border': 'solid ' + overlayPanelBorder + 'px #333', 'background': 'rgba(0,0,0,0.5)', 'overflow': 'auto' }; styles['.dbg-overlay-panel pre'] = { 'padding': '0 1px !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important' }; styles['.dbg-overlay-panel-full'] = { 'position': 'absolute', 'top': (ctx.computedFontSize + DebugJS.WIN_ADJUST) + 'px', 'left': '1px', 'width': 'calc(100% - ' + (DebugJS.WIN_SHADOW + DebugJS.WIN_ADJUST - ((overlayPanelPadding * 2) + (overlayPanelBorder * 2))) + 'px)', 'height': 'calc(100% - ' + ((ctx.computedFontSize + DebugJS.WIN_ADJUST) + DebugJS.WIN_SHADOW + ctx.computedFontSize + 10 - (overlayPanelPadding * 2)) + 'px)', 'padding': overlayPanelPadding + 'px', 'border': 'solid ' + overlayPanelBorder + 'px #333', 'background': 'rgba(0,0,0,0.5)', 'overflow': 'auto' }; styles['.dbg-sbpnl'] = { 'position': 'absolute', 'top': 0, 'left': 0, 'width': '100%', 'height': '100%' }; styles['.dbg-sep'] = { 'height': (ctx.computedFontSize * 0.5) + 'px' }; styles['.dbg-na'] = { 'color': '#ccc !important' }; styles['.dbg-showhide-btn'] = { 'color': '#0a0 !important', 'font-size': fontSize + ' !important', 'font-weight': 'bold' }; styles['.dbg-showhide-btn:hover'] = { 'cursor': 'pointer' }; styles['.dbg-cmdtd'] = { 'vertical-align': 'top !important', 'white-space': 'nowrap !important' }; styles['.dbg-txt-range'] = { 'display': 'inline-block !important', 'width': (256 * opt.zoom) + 'px !important', 'height': (15 * opt.zoom) + 'px !important', 'padding': '0 !important', 'border': 'none !important', 'outline': 'none !important', 'box-shadow': 'none !important' }; styles['.dbg-txt-tbl td'] = { 'font-size': fontSize + ' !important', 'line-height': '1em !important' }; styles['.dbg-loading'] = { 'opacity': '1.0 !important' }; styles['#' + ctx.id + ' label'] = { 'display': 'inline !important', 'margin': '0 !important', 'line-height': '1em !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important', 'font-weight': 'normal !important' }; styles['#' + ctx.id + ' input[type="radio"]'] = { 'margin': '0 3px !important', 'width': 13 * opt.zoom + 'px !important', 'height': 13 * opt.zoom + 'px !important' }; styles['.dbg-editor'] = { 'width': 'calc(100% - 6px) !important', 'height': 'calc(100% - ' + (ctx.computedFontSize + 10) + 'px) !important', 'margin': '2px 0 0 0 !important', 'padding': '2px !important', 'border': 'solid 1px #1883d7 !important', 'border-radius': '0 !important', 'outline': 'none !important', 'background': 'transparent !important', 'color': '#fff !important', 'font-size': fontSize + ' !important', 'overflow': 'auto !important', 'resize': 'none !important' }; styles['.dbg-strg'] = { 'display': 'inline-block !important', 'width': 'calc(100% - 1em) !important', 'height': '8em !important', 'margin': '2px 0 0 .5em !important' }; styles['.dbg-strgkey'] = { 'width': 'calc(100% - 10em) !important', 'margin': '0 !important' }; styles['.dbg-txt-hl'] = { 'background': 'rgba(192,192,192,0.5) !important' }; styles['.' + ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX] = { 'outline': 'solid 1px #f00 !important', 'opacity': '0.7 !important' }; styles['.dbg-timer-inp'] = { 'width': '1.1em !important', 'height': '1em !important', 'border': 'none !important', 'outline': 'none !important', 'margin': '0 !important', 'padding': '0 !important', 'text-align': 'center !important', 'vartical-align': 'middle !important', 'background': 'transparent !important', 'color': '#fff !important' }; styles['.dbg-hint'] = { 'position': 'fixed !important', 'display': 'inline-block !important', 'max-width': 'calc(100vw - 35px) !important', 'max-height': 'calc(100vh - 35px) !important', 'overflow': 'auto !important', 'padding': '4px 8px !important', 'box-sizing': 'content-box !important', 'z-index': 0x7ffffffe + ' !important', 'box-shadow': '8px 8px 10px rgba(0,0,0,.3) !important', 'border-radius': '3px !important', 'background': 'rgba(0,0,0,0.65) !important' }; styles['.dbg-txtbox'] = { 'border': 'none !important', 'border-bottom': 'solid 1px #888 !important', 'border-radius': '0 !important', 'outline': 'none !important', 'box-shadow': 'none !important', 'background': 'transparent !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important' }; styles['.dbg-resbox.box'] = { 'display': 'inline-block !important', 'min-width': 'calc(100% - 18px) !important', 'height': '1.5em !important', 'margin-top': '4px !important' }; styles['.dbg-resbox'] = { 'padding': '5px !important', 'color': '#fff !important', 'font-size': fontSize + ' !important', 'font-family': 'Consolas !important', 'overflow': 'auto !important', 'cursor': 'text !important', 'resize': 'none !important' }; styles['.dbg-resbox.ok'] = { 'border': '1px solid #2c6cb8 !important', 'background': 'linear-gradient(rgba(8,8,16,0.6),rgba(0,0,68,0.6)) !important' }; styles['.dbg-resbox.err'] = { 'border': '1px solid #c00 !important', 'background': 'linear-gradient(rgba(16,8,8,0.6),rgba(68,0,0,0.6)) !important' }; ctx.applyStyles(ctx, styles); }, initBuf: function(ctx, newSize) { var buf = DebugJS.ctx.logBuf.getAll(); var oldSize = buf.length; if (oldSize == newSize) return; var i = ((oldSize > newSize) ? (oldSize - newSize) : 0); ctx.logBuf = new DebugJS.RingBuffer(newSize); for (; i < oldSize; i++) { ctx.logBuf.add(buf[i]); } }, createResizeSideArea: function(cursor, state, width, height) { var ctx = DebugJS.ctx; var el = document.createElement('div'); el.className = 'dbg-resize-side'; el.style.width = width; el.style.height = height; el.style.cursor = cursor; el.onmousedown = function(e) { if (!(ctx.uiStatus & DebugJS.UI_ST_RESIZABLE)) return; ctx.startResize(ctx, e); ctx.uiStatus |= state; ctx.bodyCursor = ctx.bodyEl.style.cursor; ctx.bodyEl.style.cursor = cursor; }; return el; }, createResizeCornerArea: function(cursor, state) { var ctx = DebugJS.ctx; var el = document.createElement('div'); el.className = 'dbg-resize-corner'; el.style.cursor = cursor; el.onmousedown = function(e) { if (!(ctx.uiStatus & DebugJS.UI_ST_RESIZABLE)) return; ctx.startResize(ctx, e); ctx.uiStatus |= state; ctx.bodyCursor = ctx.bodyEl.style.cursor; ctx.bodyEl.style.cursor = cursor; }; return el; }, setupDefaultOptions: function() { this.opt = {}; DebugJS.copyProp(this.DEFAULT_OPTIONS, this.opt); }, setupEventHandler: function(ctx) { if (!ctx.isAllFeaturesDisabled(ctx)) { window.addEventListener('keydown', ctx.keyHandler, true); } if ((ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) || (ctx.uiStatus & DebugJS.UI_ST_RESIZABLE) || (ctx.opt.useMouseStatusInfo) || (ctx.opt.useScreenMeasure)) { window.addEventListener('mousedown', ctx.onMouseDown, true); window.addEventListener('mousemove', ctx.onMouseMove, true); window.addEventListener('mouseup', ctx.onMouseUp, true); window.addEventListener('touchstart', ctx.onTouchStart, true); window.addEventListener('touchmove', ctx.onTouchMove, true); window.addEventListener('touchend', ctx.onTouchEnd, true); } if (ctx.opt.useWindowSizeInfo) { window.addEventListener('resize', ctx.onResize, true); ctx.onResize(); window.addEventListener('scroll', ctx.onScroll, true); ctx.onScroll(); } window.addEventListener('keydown', ctx.onKeyDown, true); window.addEventListener('keypress', ctx.onKeyPress, true); window.addEventListener('keyup', ctx.onKeyUp, true); if (ctx.opt.useKeyStatusInfo) { ctx.updateKeyDownLabel(); ctx.updateKeyPressLabel(); ctx.updateKeyUpLabel(); } }, rmvEventHandlers: function(ctx) { window.removeEventListener('keydown', ctx.keyHandler, true); window.removeEventListener('mousedown', ctx.onMouseDown, true); window.removeEventListener('mousemove', ctx.onMouseMove, true); window.removeEventListener('mouseup', ctx.onMouseUp, true); window.removeEventListener('resize', ctx.onResize, true); window.removeEventListener('scroll', ctx.onScroll, true); window.removeEventListener('keydown', ctx.onKeyDown, true); window.removeEventListener('keypress', ctx.onKeyPress, true); window.removeEventListener('keyup', ctx.onKeyUp, true); window.removeEventListener('touchstart', ctx.onTouchStart, true); window.removeEventListener('touchmove', ctx.onTouchMove, true); window.removeEventListener('touchend', ctx.onTouchEnd, true); }, initUiStatus: function(ctx, opt, rstrOpt) { if (ctx.opt.target == null) { ctx.uiStatus |= DebugJS.UI_ST_DYNAMIC; ctx.uiStatus |= DebugJS.UI_ST_DRAGGABLE; if ((ctx.opt.lockCode != null) && (!rstrOpt)) { ctx.uiStatus |= DebugJS.UI_ST_PROTECTED; } } if ((ctx.opt.visible) || (ctx.opt.target != null)) { ctx.uiStatus |= DebugJS.UI_ST_VISIBLE; } else if (ctx.errStatus) { if (((ctx.opt.popupOnError.scriptError) && (ctx.errStatus & DebugJS.ERR_ST_SCRIPT)) || ((ctx.opt.popupOnError.loadError) && (ctx.errStatus & DebugJS.ERR_ST_LOAD)) || ((ctx.opt.popupOnError.errorLog) && (ctx.errStatus & DebugJS.ERR_ST_LOG))) { ctx.uiStatus |= DebugJS.UI_ST_VISIBLE; ctx.errStatus = DebugJS.ERR_ST_NONE; } } if (ctx.opt.resizable) ctx.uiStatus |= DebugJS.UI_ST_RESIZABLE; if (ctx.opt.useClock) ctx.uiStatus |= DebugJS.UI_ST_SHOW_CLOCK; }, setupKioskMode: function(ctx) { ctx.sizeStatus = DebugJS.SIZE_ST_FULL_WH; ctx.win.style.top = 0; ctx.win.style.left = 0; ctx.win.style.width = document.documentElement.clientWidth + 'px'; ctx.win.style.height = document.documentElement.clientHeight + 'px'; ctx.opt.togglableShowHide = false; ctx.opt.usePinButton = false; ctx.opt.useWinCtrlButton = false; ctx.opt.useScreenMeasure = false; ctx.opt.useHtmlSrc = false; ctx.opt.useElementInfo = false; ctx.uiStatus |= DebugJS.UI_ST_VISIBLE; ctx.uiStatus &= ~DebugJS.UI_ST_RESIZABLE; }, disableAllFeatures: function(ctx) { for (var i = 0; i < DebugJS.FEATURES.length; i++) { ctx.opt[DebugJS.FEATURES[i]] = false; } }, isAllFeaturesDisabled: function(ctx) { for (var i = 0; i < DebugJS.FEATURES.length; i++) { if (ctx.opt[DebugJS.FEATURES[i]]) return false; } return true; }, createPanels: function(ctx) { var opt = ctx.opt; var fontSize = ctx.computedFontSize + 'px'; ctx.winBody = document.createElement('div'); ctx.win.appendChild(ctx.winBody); if (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) { ctx.winBody.style.cursor = 'default'; } if (!ctx.isAllFeaturesDisabled(ctx)) { ctx.headPanel = document.createElement('div'); ctx.headPanel.style.padding = '2px'; ctx.winBody.appendChild(ctx.headPanel); ctx.infoPanel = document.createElement('div'); ctx.infoPanel.style.padding = '0 2px 1px 2px'; ctx.winBody.appendChild(ctx.infoPanel); } ctx.mainPanel = document.createElement('div'); if (opt.useLogFilter) { ctx.mainPanel.style.height = (opt.lines + 1) + '.1em'; } else { ctx.mainPanel.style.height = opt.lines + '.1em'; } ctx.mainPanel.style.clear = 'both'; ctx.winBody.appendChild(ctx.mainPanel); if (opt.useLogFilter) { ctx.logHeaderPanel = document.createElement('div'); ctx.logHeaderPanel.style.position = 'relative'; ctx.logHeaderPanel.style.height = fontSize; ctx.logHeaderPanel.style.marginBottom = '2px'; ctx.mainPanel.appendChild(ctx.logHeaderPanel); } if (opt.useClearButton) { ctx.clearBtn = DebugJS.ui.addBtn(ctx.headPanel, '[CLR]', ctx.onClr); } if (opt.useLogFilter) ctx.createLogFilter(ctx); if (opt.useLogFilter) { ctx.logPanelHeightAdjust = ' - 1em'; } else { ctx.logPanelHeightAdjust = ''; } ctx.logPanel = document.createElement('div'); ctx.logPanel.style.width = '100%'; ctx.logPanel.style.height = 'calc(100%' + ctx.logPanelHeightAdjust + ')'; ctx.logPanel.style.padding = '0'; ctx.logPanel.style.overflow = 'auto'; ctx.logPanel.addEventListener('scroll', ctx.onLogScroll, true); ctx.enableDnDFileLoad(ctx.logPanel, ctx.onDropOnLogPanel); ctx.mainPanel.appendChild(ctx.logPanel); if (ctx.isAllFeaturesDisabled(ctx)) return; if (opt.useClock) { ctx.clockLabel = document.createElement('span'); ctx.clockLabel.style.marginLeft = '2px'; ctx.setStyle(ctx.clockLabel, 'color', opt.clockColor); ctx.setStyle(ctx.clockLabel, 'font-size', fontSize); ctx.headPanel.appendChild(ctx.clockLabel); ctx.setIntervalL(ctx); } if (opt.togglableShowHide) { ctx.closeBtn = DebugJS.ui.addBtn(ctx.headPanel, 'x', DebugJS.hide); ctx.closeBtn.style.float = 'right'; ctx.closeBtn.style.position = 'relative'; ctx.closeBtn.style.top = '-1px'; ctx.closeBtn.style.marginRight = '2px'; ctx.setStyle(ctx.closeBtn, 'color', '#888'); ctx.setStyle(ctx.closeBtn, 'font-size', (18 * opt.zoom) + 'px'); ctx.closeBtn.onmouseover = new Function('DebugJS.ctx.setStyle(this, \'color\', \'#d88\');'); ctx.closeBtn.onmouseout = new Function('DebugJS.ctx.setStyle(this, \'color\', \'#888\');'); } if ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.uiStatus & DebugJS.UI_ST_RESIZABLE) && (opt.useWinCtrlButton)) { ctx.winCtrlBtnPanel = document.createElement('span'); ctx.headPanel.appendChild(ctx.winCtrlBtnPanel); } if ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (opt.usePinButton)) { ctx.pinBtn = ctx.createHeaderBtn('pinBtn', 'P', 3, fontSize, ctx.toggleDraggable, 'uiStatus', 'UI_ST_DRAGGABLE', 'PIN_BTN_COLOR', true, 'Fix the window in its position'); } if (opt.useSuspendLogButton) { ctx.suspendLogBtn = ctx.createHeaderBtn('suspendLogBtn', '/', 3, fontSize, ctx.toggleLogSuspend, 'status', 'ST_LOG_SUSPENDING', 'LOG_SUSPEND_BTN_COLOR', false, 'Suspend log'); } if (DebugJS.LS_AVAILABLE) { ctx.preserveLogBtn = ctx.createHeaderBtn('preserveLogBtn', '*', 5, fontSize, ctx.toggleLogPreserve, 'status', 'ST_LOG_PRESERVED', 'LOG_PRESERVE_BTN_COLOR', false, 'Preserve log'); } if (opt.useStopwatch) { ctx.swLabel = document.createElement('span'); ctx.swLabel.style.float = 'right'; ctx.swLabel.style.marginLeft = '3px'; ctx.setStyle(ctx.swLabel, 'color', opt.fontColor); ctx.headPanel.appendChild(ctx.swLabel); ctx.swBtnPanel = document.createElement('span'); ctx.swBtnPanel.style.float = 'right'; ctx.swBtnPanel.style.marginLeft = '4px'; ctx.headPanel.appendChild(ctx.swBtnPanel); } ctx.extBtn = ctx.createHeaderBtn('extBtn', ctx.extBtnLabel, 2, null, ctx.toggleExtPanel, 'status', 'ST_EXT_PANEL', 'EXT_BTN_COLOR', false); ctx.extBtn.style.display = 'none'; if (opt.useTools) { ctx.toolsBtn = ctx.createHeaderBtn('toolsBtn', 'TOOL', 2, null, ctx.toggleTools, 'status', 'ST_TOOLS', 'TOOLS_BTN_COLOR', false); } if (opt.useJsEditor) { ctx.jsBtn = ctx.createHeaderBtn('jsBtn', 'JS', 2, null, ctx.toggleJs, 'status', 'ST_JS', 'JS_BTN_COLOR', false); } if (opt.useElementInfo) { ctx.elmInfoBtn = ctx.createHeaderBtn('elmInfoBtn', 'DOM', 3, null, ctx.toggleElmInfo, 'status', 'ST_ELM_INSPECTING', 'DOM_BTN_COLOR', false); } if (opt.useHtmlSrc) { ctx.htmlSrcBtn = ctx.createHeaderBtn('htmlSrcBtn', 'HTM', 3, null, ctx.toggleHtmlSrc, 'status', 'ST_HTML_SRC', 'HTML_BTN_COLOR', false); } if (opt.useSystemInfo) { ctx.sysInfoBtn = ctx.createHeaderBtn('sysInfoBtn', 'SYS', 3, null, ctx.toggleSystemInfo, 'status', 'ST_SYS_INFO', 'SYS_BTN_COLOR', false); } if (opt.useScreenMeasure) { var measBtn = document.createElement('span'); measBtn.className = 'dbg-btn dbg-nomove'; measBtn.style.display = 'inline-block'; measBtn.style.float = 'right'; measBtn.style.marginTop = ((opt.zoom <= 1) ? 1 : (2 * opt.zoom)) + 'px'; measBtn.style.marginLeft = '3px'; measBtn.style.width = (10 * opt.zoom) + 'px'; measBtn.style.height = (7 * opt.zoom) + 'px'; measBtn.innerText = ' '; measBtn.onclick = ctx.toggleMeasure; measBtn.onmouseover = new Function('DebugJS.ctx.measBtn.style.borderColor=\'' + DebugJS.MEAS_BTN_COLOR + '\';'); measBtn.onmouseout = new Function('DebugJS.ctx.measBtn.style.borderColor=(DebugJS.ctx.status & DebugJS.ST_MEASURE) ? DebugJS.MEAS_BTN_COLOR : DebugJS.COLOR_INACT;'); ctx.headPanel.appendChild(measBtn); ctx.measBtn = measBtn; } if (opt.useLed) { ctx.ledPanel = document.createElement('span'); ctx.ledPanel.className = 'dbg-sys-info'; ctx.ledPanel.style.float = 'right'; ctx.ledPanel.style.marginRight = '4px'; ctx.infoPanel.appendChild(ctx.ledPanel); } if (opt.useWindowSizeInfo) { ctx.winSizeLabel = ctx.createSysInfoLabel(); ctx.clientSizeLabel = ctx.createSysInfoLabel(); ctx.bodySizeLabel = ctx.createSysInfoLabel(); ctx.pixelRatioLabel = ctx.createSysInfoLabel(); ctx.scrollPosLabel = ctx.createSysInfoLabel(); } if (opt.useMouseStatusInfo) { ctx.mousePosLabel = ctx.createSysInfoLabel(); ctx.mouseClickLabel = ctx.createSysInfoLabel(); } if ((opt.useWindowSizeInfo) || (opt.useMouseStatusInfo)) { ctx.infoPanel.appendChild(document.createElement('br')); } if (opt.useKeyStatusInfo) { ctx.keyDownLabel = ctx.createSysInfoLabel(); ctx.keyPressLabel = ctx.createSysInfoLabel(); ctx.keyUpLabel = ctx.createSysInfoLabel(); } if (opt.useMsgDisplay) { var msgLabel = ctx.createSysInfoLabel(); msgLabel.style.float = opt.msgDisplayPos; msgLabel.style.position = 'absolute'; msgLabel.style.marginRight = '0'; msgLabel.style.right = '5px'; msgLabel.style.border = '0'; msgLabel.style.padding = '0 1px'; msgLabel.style.background = opt.msgDisplayBackground; ctx.setStyle(msgLabel, 'color', opt.fontColor); msgLabel.style.whiteSpace = 'pre-wrap'; msgLabel.style.wordBreak = 'break-all'; msgLabel.style.overflow = 'hidden'; msgLabel.style.textOverflow = 'ellipsis'; ctx.msgLabel = msgLabel; } if (opt.useCommandLine) { ctx.cmdPanel = document.createElement('div'); ctx.cmdPanel.style.padding = DebugJS.CMD_LINE_PADDING + 'px'; ctx.winBody.appendChild(ctx.cmdPanel); ctx.cmdPanel.innerHTML = '<span style="color:' + opt.promptColor + ' !important">$</span>'; var cmdLine = document.createElement('input'); ctx.setStyle(cmdLine, 'min-height', fontSize); ctx.setStyle(cmdLine, 'width', 'calc(100% - ' + fontSize + ')'); ctx.setStyle(cmdLine, 'margin', '0 0 0 2px'); ctx.setStyle(cmdLine, 'border', '0'); ctx.setStyle(cmdLine, 'border-bottom', 'solid 1px #888'); ctx.setStyle(cmdLine, 'border-radius', '0'); ctx.setStyle(cmdLine, 'outline', 'none'); ctx.setStyle(cmdLine, 'box-shadow', 'none'); ctx.setStyle(cmdLine, 'padding', '1px'); ctx.setStyle(cmdLine, 'background', 'transparent'); ctx.setStyle(cmdLine, 'color', opt.fontColor); ctx.setStyle(cmdLine, 'font-size', fontSize); ctx.cmdPanel.appendChild(cmdLine); ctx.cmdLine = cmdLine; ctx.initHistory(ctx); } }, initResize: function(ctx) { if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { var resizeN = ctx.createResizeSideArea('ns-resize', DebugJS.UI_ST_RESIZING_N, '100%', '6px'); resizeN.style.top = '-3px'; resizeN.style.left = '0'; ctx.win.appendChild(resizeN); } var resizeE = ctx.createResizeSideArea('ew-resize', DebugJS.UI_ST_RESIZING_E, '6px', '100%'); resizeE.style.top = '0'; resizeE.style.right = '-3px'; ctx.win.appendChild(resizeE); var resizeS = ctx.createResizeSideArea('ns-resize', DebugJS.UI_ST_RESIZING_S, '100%', '6px'); resizeS.style.bottom = '-3px'; resizeS.style.left = '0'; ctx.win.appendChild(resizeS); var resizeSE = ctx.createResizeCornerArea('nwse-resize', DebugJS.UI_ST_RESIZING_S | DebugJS.UI_ST_RESIZING_E); resizeSE.style.bottom = '-3px'; resizeSE.style.right = '-3px'; ctx.win.appendChild(resizeSE); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { var resizeW = ctx.createResizeSideArea('ew-resize', DebugJS.UI_ST_RESIZING_W, '6px', '100%'); resizeW.style.top = '0'; resizeW.style.left = '-3px'; ctx.win.appendChild(resizeW); var resizeNW = ctx.createResizeCornerArea('nwse-resize', DebugJS.UI_ST_RESIZING_N | DebugJS.UI_ST_RESIZING_W); resizeNW.style.top = '-3px'; resizeNW.style.left = '-3px'; ctx.win.appendChild(resizeNW); var resizeNE = ctx.createResizeCornerArea('nesw-resize', DebugJS.UI_ST_RESIZING_N | DebugJS.UI_ST_RESIZING_E); resizeNE.style.top = '-3px'; resizeNE.style.right = '-3px'; ctx.win.appendChild(resizeNE); var resizeSW = ctx.createResizeCornerArea('nesw-resize', DebugJS.UI_ST_RESIZING_S | DebugJS.UI_ST_RESIZING_W); resizeSW.style.bottom = '-3px'; resizeSW.style.left = '-3px'; ctx.win.appendChild(resizeSW); ctx.winBody.ondblclick = ctx.onDbgWinDblClick; } }, initDbgWin: function(ctx) { var opt = ctx.opt; if (ctx.isAllFeaturesDisabled(ctx)) return; if (opt.useLogFilter) ctx.updateLogFilterBtns(); if (ctx.uiStatus & DebugJS.UI_ST_SHOW_CLOCK) ctx.updateClockLabel(); if (opt.useScreenMeasure) ctx.updateMeasBtn(ctx); if (opt.useSystemInfo) ctx.updateSysInfoBtn(ctx); if (opt.useElementInfo) ctx.updateElmInfoBtn(ctx); if (opt.useHtmlSrc) ctx.updateHtmlSrcBtn(ctx); if (opt.useJsEditor) ctx.updateJsBtn(ctx); if (opt.useTools) ctx.updateToolsBtn(ctx); if (ctx.extPanel) ctx.updateExtBtn(ctx); if (opt.useStopwatch) { ctx.updateSwBtnPanel(ctx); ctx.updateSwLabel(); } if ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (opt.usePinButton)) { ctx.updatePinBtn(ctx); } if (ctx.preserveLogBtn) ctx.updatePreserveLogBtn(ctx); if (opt.useSuspendLogButton) ctx.updateSuspendLogBtn(ctx); if ((ctx.uiStatus & DebugJS.UI_ST_RESIZABLE) && (opt.useWinCtrlButton)) { ctx.updateWinCtrlBtnPanel(); } if (opt.useMouseStatusInfo) { ctx.updateMousePosLabel(); ctx.updateMouseClickLabel(); } if (opt.useWindowSizeInfo) { ctx.updateWindowSizeLabel(); ctx.updateClientSizeLabel(); ctx.updateBodySizeLabel(); ctx.updateScrollPosLabel(); } if (opt.useLed) ctx.updateLedPanel(); if (opt.useMsgDisplay) ctx.updateMsgLabel(); }, createHeaderBtn: function(btnObj, label, marginLeft, fontSize, handler, status, state, activeColor, reverse, title) { var ctx = DebugJS.ctx; var btn = DebugJS.ui.addBtn(ctx.headPanel, label, handler); btn.style.float = 'right'; btn.style.marginLeft = (marginLeft * ctx.opt.zoom) + 'px'; if (fontSize) ctx.setStyle(btn, 'font-size', fontSize); ctx.setStyle(btn, 'color', DebugJS.COLOR_INACT); btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', DebugJS.' + activeColor + ');'); var fnSfx = (reverse ? 'DebugJS.COLOR_INACT : DebugJS.' + activeColor + ');' : 'DebugJS.' + activeColor + ' : DebugJS.COLOR_INACT);'); btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', (DebugJS.ctx.' + status + ' & DebugJS.' + state + ') ? ' + fnSfx); if (title) btn.title = title; return btn; }, createSysInfoLabel: function() { var el = document.createElement('span'); el.className = 'dbg-sys-info'; DebugJS.ctx.infoPanel.appendChild(el); return el; }, createLogFilter: function(ctx) { ctx.fltrBtnAll = ctx.createLogFltBtn('ALL', 'fltrBtnAll', 'btnColor'); ctx.fltrBtnStd = ctx.createLogFltBtn('LOG', 'fltrBtnStd', 'fontColor'); ctx.fltrBtnErr = ctx.createLogFltBtn('ERR', 'fltrBtnErr', 'logColorE'); ctx.fltrBtnWrn = ctx.createLogFltBtn('WRN', 'fltrBtnWrn', 'logColorW'); ctx.fltrBtnInf = ctx.createLogFltBtn('INF', 'fltrBtnInf', 'logColorI'); ctx.fltrBtnDbg = ctx.createLogFltBtn('DBG', 'fltrBtnDbg', 'logColorD'); ctx.fltrBtnVrb = ctx.createLogFltBtn('VRB', 'fltrBtnVrb', 'logColorV'); ctx.fltrInputLabel = document.createElement('span'); ctx.fltrInputLabel.style.marginLeft = '4px'; ctx.setStyle(ctx.fltrInputLabel, 'color', ctx.opt.sysInfoColor); ctx.fltrInputLabel.innerText = 'Search:'; ctx.logHeaderPanel.appendChild(ctx.fltrInputLabel); var fltrW = 'calc(100% - 32.3em)'; ctx.fltrInput = DebugJS.ui.addTextInput(ctx.logHeaderPanel, fltrW, null, ctx.opt.sysInfoColor, ctx.fltrText, DebugJS.ctx.onchangeLogFilter); ctx.setStyle(ctx.fltrInput, 'position', 'relative'); ctx.setStyle(ctx.fltrInput, 'top', '-2px'); ctx.setStyle(ctx.fltrInput, 'margin-left', '2px'); ctx.fltrBtn = ctx.createLogFltBtn2(ctx, 'FL', 'fltrBtn', ctx.fltr, 'fltr', ctx.toggleFilter); ctx.fltrCaseBtn = ctx.createLogFltBtn2(ctx, 'Aa', 'fltrCaseBtn', ctx.fltrCase, 'fltrCase', ctx.toggleFilterCase); ctx.fltrTxtHtmlBtn = ctx.createLogFltBtn2(ctx, '</>', 'fltrTxtHtmlBtn', ctx.fltrTxtHtml, 'fltrTxtHtml', ctx.toggleFilterTxtHtml); }, createLogFltBtn: function(type, btnObj, color) { var ctx = DebugJS.ctx; var lbl = '[' + type + ']'; var fn = new Function('DebugJS.ctx.toggleLogFilter(DebugJS.LOG_FLTR_' + type + ');'); var btn = DebugJS.ui.addBtn(ctx.logHeaderPanel, lbl, fn); btn.style.marginLeft = '2px'; btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', DebugJS.ctx.opt.' + color + ');'); btn.onmouseout = ctx.updateLogFilterBtns; return btn; }, createLogFltBtn2: function(ctx, label, btnNm, flg, flgNm, fn) { var btn = DebugJS.ui.addBtn(ctx.logHeaderPanel, label, fn); btn.style.marginLeft = '2px'; ctx.setStyle(btn, 'color', (flg) ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT); btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnNm + ', \'color\', DebugJS.FLT_BTN_COLOR);'); btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnNm + ', \'color\', (DebugJS.ctx.' + flgNm + ') ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT);'); return btn; }, setLogFilter: function(ctx, s, cs, fl) { ctx.fltrInput.value = s; ctx.setFilterCase(ctx, cs); ctx.setFilter(ctx, fl); ctx.onchangeLogFilter(); }, initCommandTable: function(ctx) { ctx.CMD_TBL = []; for (var i = 0; i < ctx.INT_CMD_TBL.length; i++) { if (ctx.opt.disableAllCommands) { if (ctx.INT_CMD_TBL[i].attr & DebugJS.CMD_ATTR_SYSTEM) { ctx.CMD_TBL.push(ctx.INT_CMD_TBL[i]); } } else { if (!(!(ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.INT_CMD_TBL[i].attr & DebugJS.CMD_ATTR_DYNAMIC)) && (!((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.opt.mode == 'kiosk') && (ctx.INT_CMD_TBL[i].attr & DebugJS.CMD_ATTR_NO_KIOSK)))) { ctx.CMD_TBL.push(ctx.INT_CMD_TBL[i]); } } } }, resetStylesOnZoom: function(ctx) { var fontSize = ctx.computedFontSize + 'px'; if (ctx.toolsPanel) { ctx.toolsHeaderPanel.style.height = fontSize; ctx.toolsBodyPanel.style.height = 'calc(100% - ' + ctx.computedFontSize + 'px)'; } if (ctx.fileVwrPanel) { ctx.setStyle(ctx.fileInput, 'width', 'calc(100% - ' + (ctx.computedFontSize * 12) + 'px)'); ctx.setStyle(ctx.fileInput, 'min-height', (20 * ctx.opt.zoom) + 'px'); ctx.setStyle(ctx.fileInput, 'font-size', fontSize); ctx.setStyle(ctx.filePreviewWrapper, 'height', 'calc(100% - ' + ((ctx.computedFontSize * 4) + 10) + 'px)'); ctx.setStyle(ctx.filePreviewWrapper, 'font-size', fontSize); ctx.setStyle(ctx.filePreview, 'font-size', fontSize); ctx.fileVwrFooter.style.height = (ctx.computedFontSize + 3) + 'px'; ctx.fileLoadProgBar.style.width = 'calc(100% - ' + (ctx.computedFontSize * 5) + 'px)'; ctx.setStyle(ctx.fileLoadProg, 'font-size', (ctx.computedFontSize * 0.8) + 'px'); } if (ctx.extPanel) { ctx.extHeaderPanel.style.height = fontSize; ctx.extBodyPanel.style.height = 'calc(100% - ' + ctx.computedFontSize + 'px)'; } }, reopenFeatures: function(ctx) { while (true) { var f = ctx.featStackBak.shift(); if (f == undefined) break; ctx.openFeature(ctx, f, undefined, true); } }, restoreDbgWinSize: function(ctx, sizeStatus) { if (sizeStatus == DebugJS.SIZE_ST_FULL_WH) { ctx.setWinSize('full'); } else if (sizeStatus == DebugJS.SIZE_ST_EXPANDED_C) { ctx.setWinSize('center'); } else if (sizeStatus == DebugJS.SIZE_ST_EXPANDED) { ctx._expandDbgWin(ctx); } }, setWinPos: function(pos, dbgWinW, dbgWinH) { var ctx = DebugJS.ctx; var opt = ctx.opt; var top = opt.adjustY; var left = opt.adjustX; var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; if (clientW > window.outerWidth) clientW = window.outerWidth; if (clientH > window.outerHeight) clientH = window.outerHeight; switch (pos) { case 'se': top = clientH - dbgWinH - opt.adjustY; left = clientW - dbgWinW - opt.adjustX; break; case 'ne': top = opt.adjustY; left = clientW - dbgWinW - opt.adjustX; break; case 'c': top = (clientH / 2) - (dbgWinH / 2); left = (clientW / 2) - (dbgWinW / 2); break; case 'sw': top = clientH - dbgWinH - opt.adjustY; left = opt.adjustX; break; case 'n': top = opt.adjustY; left = (clientW / 2) - (dbgWinW / 2); break; case 'e': top = (clientH / 2) - (dbgWinH / 2); left = clientW - dbgWinW - opt.adjustX; break; case 's': top = clientH - dbgWinH - opt.adjustY; left = (clientW / 2) - (dbgWinW / 2); break; case 'w': top = (clientH / 2) - (dbgWinH / 2); left = opt.adjustX; } ctx.win.style.top = top + 'px'; ctx.win.style.left = left + 'px'; }, updateClockLabel: function() { var ctx = DebugJS.ctx; var dt = DebugJS.getDateTime(); var t = dt.yyyy + '-' + dt.mm + '-' + dt.dd + ' ' + DebugJS.WDAYS[dt.wday] + ' ' + dt.hh + ':' + dt.mi + ':' + dt.ss; ctx.clockLabel.innerText = t; if (ctx.uiStatus & DebugJS.UI_ST_SHOW_CLOCK) { setTimeout(ctx.updateClockLabel, ctx.clockUpdInt); } }, updateWindowSizeLabel: function() { try { var ctx = DebugJS.ctx; var w = window.outerWidth; var h = window.outerHeight; ctx.winSizeLabel.innerText = 'WIN:w=' + w + ',h=' + h; if (ctx.status & DebugJS.ST_SYS_INFO) { document.getElementById(ctx.id + '-sys-win-w').innerText = w; document.getElementById(ctx.id + '-sys-win-h').innerText = h; } } catch (e) {} }, updateClientSizeLabel: function() { var ctx = DebugJS.ctx; var w = document.documentElement.clientWidth; var h = document.documentElement.clientHeight; ctx.clientSizeLabel.innerText = 'CLI:w=' + w + ',h=' + h; if (ctx.status & DebugJS.ST_SYS_INFO) { document.getElementById(ctx.id + '-sys-cli-w').innerText = w; document.getElementById(ctx.id + '-sys-cli-h').innerText = h; } }, updateBodySizeLabel: function() { var ctx = DebugJS.ctx; var w = this.bodyEl.clientWidth; var h = this.bodyEl.clientHeight; ctx.bodySizeLabel.innerText = 'BODY:w=' + w + ',h=' + h; if (ctx.status & DebugJS.ST_SYS_INFO) { document.getElementById(ctx.id + '-sys-body-w').innerText = w; document.getElementById(ctx.id + '-sys-body-h').innerText = h; } ctx.pixelRatioLabel.innerText = DebugJS.getWinZoomRatio(); }, updateScrollPosLabel: function() { this.scrollPosLabel.innerText = 'SCROLL:x=' + this.scrollPosX + ',y=' + this.scrollPosY; }, updateMousePosLabel: function() { this.mousePosLabel.innerText = 'POS:x=' + this.mousePos.x + ',y=' + this.mousePos.y; }, updateMouseClickLabel: function() { var s = '<span style="color:' + this.mouseClick0 + ' !important;margin-right:2px;">0</span>' + '<span style="color:' + this.mouseClick1 + ' !important;margin-right:2px;">1</span>' + '<span style="color:' + this.mouseClick2 + ' !important">2</span>'; this.mouseClickLabel.innerHTML = 'CLICK:' + s; }, updateKeyDownLabel: function() { this.keyDownLabel.innerHTML = 'Key Down:' + this.keyDownCode; }, updateKeyPressLabel: function() { this.keyPressLabel.innerHTML = 'Press:' + this.keyPressCode; }, updateKeyUpLabel: function() { this.keyUpLabel.innerHTML = 'Up:' + this.keyUpCode; }, updateLedPanel: function() { if (!DebugJS.ctx.ledPanel) return; var SHADOW = 'text-shadow:0 0 5px;'; var led = ''; for (var i = 7; i >= 0; i--) { var color = (DebugJS.ctx.led & DebugJS.LED_BIT[i]) ? 'color:' + DebugJS.LED_COLOR[i] + ' !important;' + SHADOW : 'color:' + DebugJS.LED_COLOR_INACT + ' !important;'; var margin = (i == 0 ? '' : 'margin-right:2px'); led += '<span style="' + color + margin + '">' + DebugJS.CHR_LED + '</span>'; } DebugJS.ctx.ledPanel.innerHTML = led; }, updateMsgLabel: function() { var ctx = DebugJS.ctx; var s = ctx.msgStr; if (ctx.msgLabel) { ctx.msgLabel.innerHTML = '<pre>' + s + '</pre>'; var o = (s == '' ? 0 : 1); ctx.msgLabel.style.opacity = o; } }, updateMeasBtn: function(ctx) { ctx.measBtn.style.border = 'solid ' + ctx.opt.zoom + 'px ' + ((ctx.status & DebugJS.ST_MEASURE) ? DebugJS.MEAS_BTN_COLOR : DebugJS.COLOR_INACT); }, updateSysInfoBtn: function(ctx) { ctx.updateBtnActive(ctx.sysInfoBtn, DebugJS.ST_SYS_INFO, DebugJS.SYS_BTN_COLOR); }, updateElmInfoBtn: function(ctx) { ctx.updateBtnActive(ctx.elmInfoBtn, DebugJS.ST_ELM_INSPECTING, DebugJS.DOM_BTN_COLOR); }, updateHtmlSrcBtn: function(ctx) { ctx.updateBtnActive(ctx.htmlSrcBtn, DebugJS.ST_HTML_SRC, DebugJS.HTML_BTN_COLOR); }, updateJsBtn: function(ctx) { ctx.updateBtnActive(ctx.jsBtn, DebugJS.ST_JS, DebugJS.JS_BTN_COLOR); }, updateToolsBtn: function(ctx) { ctx.updateBtnActive(ctx.toolsBtn, DebugJS.ST_TOOLS, DebugJS.TOOLS_BTN_COLOR); }, updateExtBtn: function(ctx) { ctx.updateBtnActive(ctx.extBtn, DebugJS.ST_EXT_PANEL, DebugJS.EXT_BTN_COLOR); }, updateSwBtnPanel: function(ctx) { if (!ctx.swBtnPanel) return; var lbl = (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) ? '||' : '>>'; var margin = (2 * ctx.opt.zoom) + 'px'; var btns = DebugJS.ui.createBtnHtml('0', 'DebugJS.ctx.resetStopwatch();', 'margin-right:' + margin) + DebugJS.ui.createBtnHtml(lbl, 'DebugJS.ctx.startStopStopwatch();', 'margin-right:' + margin); ctx.swBtnPanel.innerHTML = btns; }, updatePreserveLogBtn: function(ctx) { ctx.updateBtnActive(ctx.preserveLogBtn, DebugJS.ST_LOG_PRESERVED, DebugJS.LOG_PRESERVE_BTN_COLOR); }, updateSuspendLogBtn: function(ctx) { ctx.updateBtnActive(ctx.suspendLogBtn, DebugJS.ST_LOG_SUSPENDING, DebugJS.LOG_SUSPEND_BTN_COLOR); }, updatePinBtn: function(ctx) { if (ctx.pinBtn) { ctx.setStyle(ctx.pinBtn, 'color', (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) ? DebugJS.COLOR_INACT : DebugJS.PIN_BTN_COLOR); } }, updateBtnActive: function(btn, status, activeColor) { if (btn) { DebugJS.ctx.setStyle(btn, 'color', (DebugJS.ctx.status & status) ? activeColor : DebugJS.COLOR_INACT); } }, updateWinCtrlBtnPanel: function() { var ctx = DebugJS.ctx; if (!ctx.winCtrlBtnPanel) return; var fn = 'DebugJS.ctx.expandDbgWin(\'full\');'; var btn = DebugJS.CHR_WIN_FULL; if (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH) { fn = 'DebugJS.ctx.restoreDbgWin();'; btn = DebugJS.CHR_WIN_RST; } fn += 'DebugJS.ctx.updateWinCtrlBtnPanel();DebugJS.ctx.focusCmdLine();'; var b = '<span class="dbg-btn dbg-nomove" style="float:right;position:relative;top:-1px;margin-right:' + (3 * ctx.opt.zoom) + 'px;font-size:' + (16 * ctx.opt.zoom) + 'px !important;color:#888 !important" onclick="' + fn + '" onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'#ddd\');" onmouseout="DebugJS.ctx.setStyle(this, \'color\', \'#888\');">' + btn + '</span>' + '<span class="dbg-btn dbg-nomove" style="float:right;position:relative;top:-2px;margin-left:' + 2 * ctx.opt.zoom + 'px;margin-right:' + ctx.opt.zoom + 'px;font-size:' + (30 * ctx.opt.zoom) + 'px !important;color:#888 !important" onclick="DebugJS.ctx.resetDbgWinSizePos();DebugJS.ctx.focusCmdLine();" onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'#ddd\');" onmouseout="DebugJS.ctx.setStyle(this, \'color\', \'#888\');">-</span>'; ctx.winCtrlBtnPanel.innerHTML = b; }, printLogs: function() { var ctx = DebugJS.ctx; ctx._printLogs(ctx); if (ctx.uiStatus & DebugJS.UI_ST_LOG_SCROLL) ctx.scrollLogBtm(ctx); }, _printLogs: function(ctx) { if (!ctx.win) return; var opt = ctx.opt; var buf = ctx.logBuf.getAll(); var cnt = ctx.logBuf.count(); var len = buf.length; var lineCnt = cnt - len; var filter = ctx.fltrText; var fltCase = ctx.fltrCase; if (!fltCase) { filter = filter.toLowerCase(); } var logs = ''; for (var i = 0; i < len; i++) { lineCnt++; var data = buf[i]; var msg = (ctx.fltrTxtHtml ? data.msg : DebugJS.escTags(data.msg)); var style = ''; switch (data.type) { case DebugJS.LOG_TYPE_DBG: if (!(ctx.logFilter & DebugJS.LOG_FLTR_DBG)) continue; style = 'color:' + opt.logColorD; break; case DebugJS.LOG_TYPE_INF: if (!(ctx.logFilter & DebugJS.LOG_FLTR_INF)) continue; style = 'color:' + opt.logColorI; break; case DebugJS.LOG_TYPE_ERR: if (!(ctx.logFilter & DebugJS.LOG_FLTR_ERR)) continue; style = 'color:' + opt.logColorE; break; case DebugJS.LOG_TYPE_WRN: if (!(ctx.logFilter & DebugJS.LOG_TYPE_WRN)) continue; style = 'color:' + opt.logColorW; break; case DebugJS.LOG_TYPE_VRB: if (!(ctx.logFilter & DebugJS.LOG_TYPE_VRB)) continue; style = 'color:' + opt.logColorV; break; case DebugJS.LOG_TYPE_SYS: if (!(ctx.logFilter & DebugJS.LOG_FLTR_LOG)) continue; style = 'color:' + opt.logColorS + ';text-shadow:0 0 3px'; break; case DebugJS.LOG_TYPE_MLT: if (!(ctx.logFilter & DebugJS.LOG_FLTR_LOG)) continue; style = 'display:inline-block;width:100%;margin:' + Math.round(ctx.computedFontSize * 0.5) + 'px 0'; break; default: if (!(ctx.logFilter & DebugJS.LOG_FLTR_LOG)) continue; } if (filter != '') { try { var pos = (fltCase ? msg.indexOf(filter) : msg.toLowerCase().indexOf(filter)); if (pos != -1) { var key = msg.substr(pos, filter.length); var hl = '<span class="dbg-txt-hl">' + key + '</span>'; msg = msg.replace(key, hl, 'ig'); } else if (ctx.fltr) { continue; } } catch (e) {} } var lineNum = ''; if ((opt.showLineNums) && (data.type != DebugJS.LOG_TYPE_MLT)) { var diff = DebugJS.digits(cnt) - DebugJS.digits(lineCnt); var pdng = ''; for (var j = 0; j < diff; j++) { pdng += '0'; } lineNum = pdng + lineCnt + ': '; } var color = ''; if ((data.type == DebugJS.LOG_TYPE_RES) || (data.type == DebugJS.LOG_TYPE_ERES)) { msg = DebugJS.quoteStrIfNeeded(DebugJS.setStyleIfObjNA(msg)); if (data.type == DebugJS.LOG_TYPE_RES) { color = opt.promptColor; } else { color = opt.promptColorE; } msg = '<span style=color:' + color + '>&gt;</span> ' + msg; } var m = (((opt.showTimeStamp) && (data.type != DebugJS.LOG_TYPE_MLT)) ? (DebugJS.getTimeStr(data.time) + ' ' + msg) : msg); if (style) { logs += lineNum + '<span style="' + style + '">' + m + '</span>\n'; } else { logs += lineNum + m + '\n'; } } ctx.logPanel.innerHTML = '<pre style="padding:0 3px !important">' + logs + '</pre>'; }, onLogScroll: function(e) { var ctx = DebugJS.ctx; var rect = ctx.logPanel.getBoundingClientRect(); var h = rect.height; var d = ctx.logPanel.scrollHeight - ctx.logPanel.scrollTop; if ((d - 1 <= h) && (h <= d + 1)) { ctx.startLogScrolling(); } else { ctx.stopLogScrolling(); } }, scrollLogBtm: function(ctx) { ctx.logPanel.scrollTop = ctx.logPanel.scrollHeight; }, startLogScrolling: function() { DebugJS.ctx.uiStatus |= DebugJS.UI_ST_LOG_SCROLL; }, stopLogScrolling: function() { DebugJS.ctx.uiStatus &= ~DebugJS.UI_ST_LOG_SCROLL; }, onClr: function() { DebugJS.ctx.clearLog(); DebugJS.ctx.focusCmdLine(); }, clearLog: function() { DebugJS.ctx.logBuf.clear(); DebugJS.ctx.printLogs(); }, toggleLogFilter: function(fltr) { var ctx = DebugJS.ctx; if (fltr == DebugJS.LOG_FLTR_ALL) { if ((ctx.logFilter & ~DebugJS.LOG_FLTR_VRB) == DebugJS.LOG_FLTR_ALL) { ctx.logFilter = 0; } else { ctx.logFilter |= fltr; } } else if (fltr == DebugJS.LOG_FLTR_VRB) { if (ctx.logFilter & DebugJS.LOG_FLTR_VRB) { ctx.logFilter &= ~fltr; } else { ctx.logFilter |= fltr; } } else { if ((ctx.logFilter & ~DebugJS.LOG_FLTR_VRB) == DebugJS.LOG_FLTR_ALL) { ctx.logFilter = fltr; } else { if (ctx.logFilter & fltr) { ctx.logFilter &= ~fltr; } else { ctx.logFilter |= fltr; } } } ctx.updateLogFilterBtns(); ctx.printLogs(); if (fltr == DebugJS.LOG_FLTR_ALL) ctx.scrollLogBtm(ctx); }, updateLogFilterBtns: function() { var ctx = DebugJS.ctx; var opt = ctx.opt; var fltr = ctx.logFilter; ctx.setStyle(ctx.fltrBtnAll, 'color', ((fltr & ~DebugJS.LOG_FLTR_VRB) == DebugJS.LOG_FLTR_ALL) ? opt.btnColor : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnStd, 'color', (fltr & DebugJS.LOG_FLTR_LOG) ? opt.fontColor : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnErr, 'color', (fltr & DebugJS.LOG_FLTR_ERR) ? opt.logColorE : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnWrn, 'color', (fltr & DebugJS.LOG_FLTR_WRN) ? opt.logColorW : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnInf, 'color', (fltr & DebugJS.LOG_FLTR_INF) ? opt.logColorI : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnDbg, 'color', (fltr & DebugJS.LOG_FLTR_DBG) ? opt.logColorD : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnVrb, 'color', (fltr & DebugJS.LOG_FLTR_VRB) ? opt.logColorV : DebugJS.COLOR_INACT); }, onchangeLogFilter: function() { DebugJS.ctx.fltrText = DebugJS.ctx.fltrInput.value; DebugJS.ctx.printLogs(); }, toggleFilter: function() { var ctx = DebugJS.ctx; ctx.setFilter(ctx, (ctx.fltr ? false : true)); }, setFilter: function(ctx, f) { ctx.fltr = f; ctx.setStyle(ctx.fltrBtn, 'color', (DebugJS.ctx.fltr) ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT); ctx.onchangeLogFilter(); }, toggleFilterCase: function() { var ctx = DebugJS.ctx; ctx.setFilterCase(ctx, (ctx.fltrCase ? false : true)); }, setFilterCase: function(ctx, f) { ctx.fltrCase = f; ctx.setStyle(ctx.fltrCaseBtn, 'color', (DebugJS.ctx.fltrCase) ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT); ctx.onchangeLogFilter(); }, toggleFilterTxtHtml: function() { var ctx = DebugJS.ctx; ctx.setFilterTxtHtml(ctx, (ctx.fltrTxtHtml ? false : true)); }, setFilterTxtHtml: function(ctx, f) { ctx.fltrTxtHtml = f; ctx.setStyle(ctx.fltrTxtHtmlBtn, 'color', (ctx.fltrTxtHtml ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT)); ctx.onchangeLogFilter(); }, applyStyles: function(ctx, styles) { if (ctx.styleEl) document.head.removeChild(ctx.styleEl); ctx.styleEl = document.createElement('style'); document.head.appendChild(ctx.styleEl); ctx.styleEl.appendChild(document.createTextNode('')); var s = ctx.styleEl.sheet; for (var selector in styles) { var props = styles[selector]; var propStr = ''; for (var propName in props) { var propVal = props[propName]; var propImportant = ''; if (propVal[1] === true) { propVal = propVal[0]; propImportant = ' !important'; } propStr += propName + ':' + propVal + propImportant + ';\n'; } s.insertRule(selector + '{' + propStr + '}', s.cssRules.length); } }, setStyle: function(el, n, v) { el.style.setProperty(n, v, 'important'); }, setIntervalL: function(ctx) { if (ctx.clockUpdIntHCnt > 0) { ctx.clockUpdIntHCnt--; } if (ctx.clockUpdIntHCnt == 0) { ctx.clockUpdInt = DebugJS.UPDATE_INTERVAL_L; } }, setIntervalH: function(ctx) { ctx.clockUpdIntHCnt++; ctx.clockUpdInt = DebugJS.UPDATE_INTERVAL_H; }, setupMove: function(ctx) { ctx.winBody.onmousedown = ctx.startMoveM; ctx.winBody.ontouchstart = ctx.startMoveT; }, startMoveM: function(e) { var ctx = DebugJS.ctx; var x = e.clientX; var y = e.clientY; var target = e.target; if (e.button != 0) return; if ((!(ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE)) || !ctx.isMovable(ctx, target, x, y)) { return; } ctx._startMove(ctx, target, x, y); }, startMoveT: function(e) { var ctx = DebugJS.ctx; var x = e.changedTouches[0].pageX; var y = e.changedTouches[0].pageY; var target = e.target; if ((!(ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE)) || !ctx.isMovable(ctx, target, x, y)) { return; } ctx._startMove(ctx, target, x, y); e.preventDefault(); }, _startMove: function(ctx, target, x, y) { ctx.uiStatus |= DebugJS.UI_ST_DRAGGING; ctx.ptOpTm = (new Date()).getTime(); ctx.winBody.style.cursor = 'move'; ctx.disableTextSelect(ctx); ctx.prevOffsetTop = y - ctx.win.offsetTop; ctx.prevOffsetLeft = x - ctx.win.offsetLeft; if (!document.all) { window.getSelection().removeAllRanges(); } }, disableTextSelect: function(ctx) { ctx.savedFunc = document.onselectstart; document.onselectstart = function() {return false;}; }, enableTextSelect: function(ctx) { document.onselectstart = ctx.savedFunc; }, isMovable: function(ctx, el, x, y) { if (el.nodeName == 'INPUT') return false; if (el.nodeName == 'TEXTAREA') return false; if (DebugJS.hasClass(el, 'dbg-nomove')) return false; var ua = DebugJS.getBrowserType(); if ((ua.family == 'IE') || (ua.name == 'Firefox')) { if ((el == ctx.logPanel) || (el == ctx.sysInfoPanel) || (el == ctx.elmInfoBodyPanel) || (el == ctx.htmlSrcBodyPanel) || (el == ctx.filePreviewWrapper) || (el == ctx.toolsPanel) || (el == ctx.extPanel) || (el == ctx.extBodyPanel)) { var scrollBarWH = 17; var rect = el.getBoundingClientRect(); var scrollL = rect.left + rect.width - scrollBarWH; var scrollR = rect.left + rect.width; var scrollT = rect.top + rect.height - scrollBarWH; var scrollB = rect.top + rect.height; if (((x >= scrollL) && (x <= scrollR)) || ((y >= scrollT) && (y <= scrollB))) { return false; } } } return true; }, moveDbgWin: function(ctx, x, y) { if (!(ctx.uiStatus & DebugJS.UI_ST_DRAGGING)) return; ctx.ptOpTm = (new Date()).getTime(); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.win.style.top = y - ctx.prevOffsetTop + 'px'; ctx.win.style.left = x - ctx.prevOffsetLeft + 'px'; }, endMove: function(ctx) { ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGING; ctx.enableTextSelect(ctx); ctx.winBody.style.cursor = 'default'; }, startResize: function(ctx, e) { if (e.button != 0) return; ctx.uiStatus |= DebugJS.UI_ST_RESIZING; ctx.clickedPosX = e.clientX; ctx.clickedPosY = e.clientY; ctx.saveSizeAndPos(ctx); ctx.sizeStatus = DebugJS.SIZE_ST_NORMAL; ctx.updateWinCtrlBtnPanel(); ctx.disableTextSelect(ctx); }, resizeDbgWin: function(ctx, x, y) { var currentX = x; var currentY = y; var moveX, moveY, t, l, w, h; var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; if (currentX > clientW) { currentX = clientW; } else if (currentX < 0) { currentX = 0; } if (currentY > clientH) { currentY = clientH; } else if (currentY < 0) { currentY = 0; } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING_N) { moveY = ctx.clickedPosY - currentY; h = ctx.orgSizePos.h + moveY; if (h < ctx.computedMinH) { h = ctx.computedMinH; } else { t = ctx.orgSizePos.t - moveY; ctx.win.style.top = t + 'px'; } ctx.win.style.height = h + 'px'; if (ctx.logPanel.scrollTop != 0) { ctx.scrollLogBtm(ctx); } } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING_W) { moveX = ctx.clickedPosX - currentX; w = ctx.orgSizePos.w + moveX; if (w < ctx.computedMinW) { w = ctx.computedMinW; } else { l = ctx.orgSizePos.l - moveX; ctx.win.style.left = l + 'px'; } ctx.win.style.width = w + 'px'; } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING_E) { moveX = currentX - ctx.clickedPosX; w = ctx.orgSizePos.w + moveX; if (w < ctx.computedMinW) w = ctx.computedMinW; ctx.win.style.width = w + 'px'; } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING_S) { moveY = currentY - ctx.clickedPosY; h = ctx.orgSizePos.h + moveY; if (ctx.initHeight < ctx.computedMinH) { if (h < ctx.initHeight) { h = ctx.initHeight; } } else if (h < ctx.computedMinH) { h = ctx.computedMinH; } ctx.win.style.height = h + 'px'; if (ctx.logPanel.scrollTop != 0) { ctx.scrollLogBtm(ctx); } } ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, endResize: function(ctx) { ctx.uiStatus &= ~DebugJS.UI_ST_RESIZING_ALL; ctx.bodyEl.style.cursor = ctx.bodyCursor; ctx.enableTextSelect(ctx); }, resizeMainHeight: function() { var ctx = DebugJS.ctx; var headPanelH = (ctx.headPanel) ? ctx.headPanel.offsetHeight : 0; var infoPanelH = (ctx.infoPanel) ? ctx.infoPanel.offsetHeight : 0; var cmdPanelH = (ctx.cmdPanel) ? ctx.cmdPanel.offsetHeight : 0; var mainPanelHeight = ctx.win.offsetHeight - headPanelH - infoPanelH - cmdPanelH - DebugJS.WIN_ADJUST; ctx.mainPanel.style.height = mainPanelHeight + 'px'; }, toggleLogSuspend: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_LOG_SUSPENDING) { ctx.resumeLog(); } else { ctx.suspendLog(); } }, suspendLog: function() { var ctx = DebugJS.ctx; ctx.status |= DebugJS.ST_LOG_SUSPENDING; ctx.updateSuspendLogBtn(ctx); }, resumeLog: function() { var ctx = DebugJS.ctx; ctx.status &= ~DebugJS.ST_LOG_SUSPENDING; ctx.updateSuspendLogBtn(ctx); }, toggleLogPreserve: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_LOG_PRESERVED) { ctx.setLogPreserve(ctx, false); } else { ctx.setLogPreserve(ctx, true); } }, setLogPreserve: function(ctx, f) { if (f) { ctx.status |= DebugJS.ST_LOG_PRESERVED; } else { ctx.status &= ~DebugJS.ST_LOG_PRESERVED; } ctx.updatePreserveLogBtn(ctx); }, toggleMeasure: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_MEASURE) { ctx.closeScreenMeasure(ctx); } else { ctx.openScreenMeasure(ctx); } }, openScreenMeasure: function(ctx, q) { if (!q) DebugJS._log.s('Screen Measure ON'); ctx.status |= DebugJS.ST_MEASURE; ctx.featStack.push(DebugJS.ST_MEASURE); ctx.bodyCursor = ctx.bodyEl.style.cursor; ctx.bodyEl.style.cursor = 'default'; ctx.updateMeasBtn(ctx); }, closeScreenMeasure: function(ctx, q) { ctx.stopMeasure(ctx); ctx.bodyEl.style.cursor = ctx.bodyCursor; ctx.status &= ~DebugJS.ST_MEASURE; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_MEASURE); if (!q) DebugJS._log.s('Screen Measure OFF'); ctx.updateMeasBtn(ctx); }, toggleDraggable: function() { var ctx = DebugJS.ctx; if (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) { ctx.disableDraggable(ctx); } else { ctx.enableDraggable(ctx); } }, enableDraggable: function(ctx) { ctx.uiStatus |= DebugJS.UI_ST_DRAGGABLE; ctx.winBody.style.cursor = 'default'; ctx.updatePinBtn(ctx); }, disableDraggable: function(ctx) { ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGABLE; ctx.winBody.style.cursor = 'auto'; ctx.updatePinBtn(ctx); }, enableResize: function(ctx) { ctx.uiStatus |= DebugJS.UI_ST_RESIZABLE; }, disableResize: function(ctx) { ctx.uiStatus &= ~DebugJS.UI_ST_RESIZABLE; }, startStopStopwatch: function() { if (DebugJS.ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { DebugJS.ctx.stopStopwatch(); } else { DebugJS.ctx.startStopwatch(); } }, startStopwatch: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_STOPWATCH_END) ctx.resetStopwatch(); ctx.status |= DebugJS.ST_STOPWATCH_RUNNING; DebugJS.time.restart(DebugJS.TIMER_NAME_SW_0); ctx.updateSwLabel(); ctx.updateSwBtnPanel(ctx); }, stopStopwatch: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { ctx.status &= ~DebugJS.ST_STOPWATCH_RUNNING; if (ctx.status & DebugJS.ST_STOPWATCH_LAPTIME) { ctx.status &= ~DebugJS.ST_STOPWATCH_LAPTIME; ctx.resetStopwatch(); } DebugJS.time.pause(DebugJS.TIMER_NAME_SW_0); } ctx.updateSwLabel(); ctx.updateSwBtnPanel(ctx); }, resetStopwatch: function() { var ctx = DebugJS.ctx; ctx.status &= ~DebugJS.ST_STOPWATCH_END; DebugJS.time.reset(DebugJS.TIMER_NAME_SW_0); ctx.updateSwLabel(); }, splitStopwatch: function() { if (DebugJS.ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { DebugJS.time._split(DebugJS.TIMER_NAME_SW_0); } }, endStopwatch: function() { DebugJS.ctx.status |= DebugJS.ST_STOPWATCH_END; DebugJS.ctx.stopStopwatch(); }, updateSwLabel: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { DebugJS.time.updateCount(DebugJS.TIMER_NAME_SW_0); } var str = DebugJS.getTimerStr(DebugJS.time.getCount(DebugJS.TIMER_NAME_SW_0)); if (ctx.swLabel) { if (ctx.status & DebugJS.ST_STOPWATCH_LAPTIME) { str = '<span style="color:' + ctx.opt.timerColor + ' !important">' + str + '</span>'; } else if (ctx.status & DebugJS.ST_STOPWATCH_END) { var now = DebugJS.getDateTime(); if (now.sss > 500) { str = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; } } ctx.swLabel.innerHTML = str; } if ((ctx.status & DebugJS.ST_STOPWATCH_RUNNING) || (ctx.status & DebugJS.ST_STOPWATCH_END)) { setTimeout(ctx.updateSwLabel, DebugJS.UPDATE_INTERVAL_H); } }, collapseLogPanel: function(ctx) { ctx.logPanel.style.height = 'calc(' + (100 - DebugJS.OVERLAY_PANEL_HEIGHT) + '%' + ctx.logPanelHeightAdjust + ')'; ctx.scrollLogBtm(ctx); }, expandLogPanel: function(ctx) { ctx.logPanel.style.height = 'calc(100%' + ctx.logPanelHeightAdjust + ')'; }, openFeature: function(ctx, f, subfnc, opt) { ctx.closeFeature(ctx, f); switch (f) { case DebugJS.ST_MEASURE: ctx.openScreenMeasure(ctx, opt); return true; case DebugJS.ST_SYS_INFO: ctx.openSystemInfo(ctx); return true; case DebugJS.ST_HTML_SRC: ctx.openHtmlSrc(ctx); return true; case DebugJS.ST_ELM_INSPECTING: ctx.openElmInfo(ctx); return true; case DebugJS.ST_JS: ctx.openJsEditor(ctx); return true; case DebugJS.ST_TOOLS: var kind; var param; switch (subfnc) { case 'timer': kind = DebugJS.TOOLS_FNC_TIMER; if (opt == 'clock') { param = DebugJS.TOOL_TIMER_MODE_CLOCK; } else if (opt == 'cu') { param = DebugJS.TOOL_TIMER_MODE_SW_CU; } else if (opt == 'cd') { param = DebugJS.TOOL_TIMER_MODE_SW_CD; } break; case 'text': kind = DebugJS.TOOLS_FNC_TEXT; break; case 'html': kind = DebugJS.TOOLS_FNC_HTML; break; case 'file': kind = DebugJS.TOOLS_FNC_FILE; param = (opt ? opt : ctx.fileVwrMode); break; case 'bat': kind = DebugJS.TOOLS_FNC_BAT; break; case undefined: kind = ctx.toolsActiveFnc; break; default: return false; } ctx.openTools(ctx); ctx.switchToolsFunction(kind, param); return true; case DebugJS.ST_EXT_PANEL: if (ctx.extPanels.length == 0) { DebugJS._log('No extension panel'); return false; } var idx = subfnc; if (idx == undefined) idx = ctx.extActPnlIdx; if (idx < 0) idx = 0; if (idx >= ctx.extPanels.length) { DebugJS._log.e('No such panel: ' + idx + ' (0-' + (ctx.extPanels.length - 1) + ')'); return false; } if (!(ctx.status & DebugJS.ST_EXT_PANEL)) { ctx.openExtPanel(ctx); } ctx.switchExtPanel(idx); return true; } return false; }, closeFeature: function(ctx, f) { switch (f) { case DebugJS.ST_MEASURE: ctx.closeScreenMeasure(ctx); break; case DebugJS.ST_SYS_INFO: ctx.closeSystemInfo(ctx); break; case DebugJS.ST_HTML_SRC: ctx.closeHtmlSrc(ctx); break; case DebugJS.ST_ELM_INSPECTING: ctx.closeElmInfo(ctx); break; case DebugJS.ST_JS: ctx.closeJsEditor(); break; case DebugJS.ST_TOOLS: ctx.closeTools(ctx); break; case DebugJS.ST_EXT_PANEL: ctx.closeExtPanel(ctx); break; default: return false; } return true; }, closeTopFeature: function(ctx) { var f = ctx.featStack.pop(); return ctx.closeFeature(ctx, f); }, finalizeFeatures: function(ctx) { if ((ctx.uiStatus & DebugJS.UI_ST_DRAGGING) || (ctx.uiStatus & DebugJS.UI_ST_RESIZING)) { ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGING; ctx.endResize(ctx); } ctx.closeAllFeatures(ctx, true); }, closeAllFeatures: function(ctx, q) { if (ctx.status & DebugJS.ST_MEASURE) ctx.closeScreenMeasure(ctx, q); if (ctx.status & DebugJS.ST_SYS_INFO) ctx.closeSystemInfo(ctx); if (ctx.status & DebugJS.ST_HTML_SRC) ctx.closeHtmlSrc(ctx); if (ctx.status & DebugJS.ST_ELM_INSPECTING) ctx.closeElmInfo(ctx); if (ctx.status & DebugJS.ST_JS) ctx.closeJsEditor(); if (ctx.status & DebugJS.ST_TOOLS) ctx.closeTools(ctx); if (ctx.status & DebugJS.ST_EXT_PANEL) ctx.closeExtPanel(ctx); }, launchFnc: function(ctx, fn, subfn, opt) { var a = { measure: DebugJS.ST_MEASURE, sys: DebugJS.ST_SYS_INFO, html: DebugJS.ST_HTML_SRC, dom: DebugJS.ST_ELM_INSPECTING, js: DebugJS.ST_JS, tool: DebugJS.ST_TOOLS, ext: DebugJS.ST_EXT_PANEL }; var f = (a[fn] === undefined ? 0 : a[fn]); return ctx.openFeature(ctx, f, subfn, opt); }, keyHandler: function(e) { var ctx = DebugJS.ctx; var opt = ctx.opt; var cmds; if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD) { DebugJS.bat._resume('cmd'); } switch (e.keyCode) { case 9: // Tab if ((ctx.status & DebugJS.ST_TOOLS) && (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_FILE)) { if (e.shiftKey) { if (ctx.fileVwrMode == 'b64') ctx.toggleShowHideCC(); } else { ctx.switchFileScreen(); } e.preventDefault(); } break; case 13: // Enter if (document.activeElement == ctx.cmdLine) { ctx.startLogScrolling(); ctx.stopErrCb = true; ctx.execCmd(ctx); ctx.stopErrCb = false; e.preventDefault(); } break; case 18: // Alt ctx.disableDraggable(ctx); break; case 27: // ESC if (ctx.props.esc == 'disable') break; if (ctx.uiStatus & DebugJS.UI_ST_DRAGGING) { ctx.endMove(ctx); break; } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING) { ctx.endResize(ctx); break; } if (ctx.closeTopFeature(ctx)) break; ctx.hideDbgWin(ctx); break; case 38: // Up if (document.activeElement == ctx.cmdLine) { cmds = ctx.cmdHistoryBuf.getAll(); if (cmds.length == 0) return; if (cmds.length < ctx.cmdHistoryIdx) { ctx.cmdHistoryIdx = cmds.length; } if (ctx.cmdHistoryIdx == cmds.length) { ctx.cmdTmp = ctx.cmdLine.value; } if (ctx.cmdHistoryIdx > 0) { ctx.cmdHistoryIdx--; } ctx.cmdLine.value = cmds[ctx.cmdHistoryIdx]; e.preventDefault(); } break; case 40: // Dn if (document.activeElement == ctx.cmdLine) { cmds = ctx.cmdHistoryBuf.getAll(); if (cmds.length == 0) return; if (ctx.cmdHistoryIdx < cmds.length) { ctx.cmdHistoryIdx++; } if (ctx.cmdHistoryIdx == cmds.length) { ctx.cmdLine.value = ctx.cmdTmp; } else { ctx.cmdLine.value = cmds[ctx.cmdHistoryIdx]; } } break; case 67: // C if ((e.ctrlKey) && (document.activeElement == ctx.cmdLine)) { if (((ctx.cmdLine.selectionEnd - ctx.cmdLine.selectionStart) == 0)) { if (ctx.status & DebugJS.ST_BAT_RUNNING) { DebugJS.bat.stop(DebugJS.EXIT_SIG + DebugJS.SIGINT); } ctx.startLogScrolling(); ctx._cmdDelayCancel(ctx); DebugJS.point.move.stop(); DebugJS.point.drag.stop(); DebugJS.scrollWinTo.stop(); DebugJS.setText.stop(); DebugJS._log.s(ctx.cmdLine.value + '^C'); ctx.cmdLine.value = ''; DebugJS.callEvtListeners('ctrlc'); } } break; case 112: // F1 if ((e.ctrlKey) && (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC)) { ctx.win.style.top = 0; ctx.win.style.left = 0; ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGING; } break; case opt.keyAssign.key: if (((opt.keyAssign.shift == undefined) || (e.shiftKey == opt.keyAssign.shift)) && ((opt.keyAssign.ctrl == undefined) || (e.ctrlKey == opt.keyAssign.ctrl)) && ((opt.keyAssign.alt == undefined) || (e.altKey == opt.keyAssign.alt)) && ((opt.keyAssign.meta == undefined) || (e.metaKey == opt.keyAssign.meta))) { if ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.isOutOfWin(ctx))) { ctx.resetToOriginalPosition(ctx); } else if (ctx.uiStatus & DebugJS.UI_ST_VISIBLE) { ctx.closeDbgWin(); } else { ctx.showDbgWin(); } } } }, onKeyDown: function(e) { var ctx = DebugJS.ctx; if (ctx.opt.useKeyStatusInfo) { ctx.updateStatusInfoOnKeyDown(ctx, e); } if (ctx.uiStatus & DebugJS.UI_ST_PROTECTED) { ctx.procOnProtectedD(ctx, e); } }, onKeyPress: function(e) { var ctx = DebugJS.ctx; if (ctx.opt.useKeyStatusInfo) { ctx.updateStatusInfoOnKeyPress(ctx, e); } if (ctx.uiStatus & DebugJS.UI_ST_PROTECTED) { ctx.procOnProtectedP(ctx, e); } }, onKeyUp: function(e) { var ctx = DebugJS.ctx; if (ctx.opt.useKeyStatusInfo) { ctx.updateStatusInfoOnKeyUp(ctx, e); } if (e.keyCode == 18) { ctx.enableDraggable(ctx); } }, procOnProtectedD: function(ctx, e) { switch (e.keyCode) { case 17: if (ctx.unlockCode == null) { ctx.unlockCode = ''; } else if (ctx.unlockCode == ctx.opt.lockCode) { ctx.uiStatus &= ~DebugJS.UI_ST_PROTECTED; ctx.unlockCode = null; DebugJS.callEvtListeners('unlock'); } break; case 27: ctx.unlockCode = null; } }, procOnProtectedP: function(ctx, e) { if (ctx.unlockCode == null) return; var ch = DebugJS.key2ch(e.key); if ((DebugJS.isTypographic(ch))) { ctx.unlockCode += ch; } }, updateStatusInfoOnKeyDown: function(ctx, e) { var modKey = DebugJS.checkModKey(e); ctx.keyDownCode = e.keyCode + '(' + e.key + ') ' + modKey; ctx.updateKeyDownLabel(); ctx.keyPressCode = DebugJS.KEY_ST_DFLT; ctx.updateKeyPressLabel(); ctx.keyUpCode = DebugJS.KEY_ST_DFLT; ctx.updateKeyUpLabel(); ctx.resizeMainHeight(); }, updateStatusInfoOnKeyPress: function(ctx, e) { var modKey = DebugJS.checkModKey(e); ctx.keyPressCode = e.keyCode + '(' + e.key + ') ' + modKey; ctx.updateKeyPressLabel(); ctx.resizeMainHeight(); }, updateStatusInfoOnKeyUp: function(ctx, e) { var modKey = DebugJS.checkModKey(e); ctx.keyUpCode = e.keyCode + '(' + e.key + ') ' + modKey; ctx.updateKeyUpLabel(); ctx.resizeMainHeight(); }, onResize: function() { var ctx = DebugJS.ctx; ctx.updateWindowSizeLabel(); ctx.updateClientSizeLabel(); ctx.updateBodySizeLabel(); if (ctx.uiStatus & DebugJS.UI_ST_VISIBLE) { if (ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) { ctx.adjustDbgWinPos(ctx); } else { ctx.adjustWinMax(ctx); } ctx.resizeMainHeight(); } }, onScroll: function() { var ctx = DebugJS.ctx; if (window.scrollX === undefined) { ctx.scrollPosX = document.documentElement.scrollLeft; ctx.scrollPosY = document.documentElement.scrollTop; } else { ctx.scrollPosX = window.scrollX; ctx.scrollPosY = window.scrollY; } ctx.updateScrollPosLabel(); if (ctx.status & DebugJS.ST_SYS_INFO) { ctx.updateSysInfoScrollPosLabel(ctx); } ctx.resizeMainHeight(); }, updateSysInfoScrollPosLabel: function(ctx) { document.getElementById(ctx.id + '-sys-scroll-x').innerHTML = DebugJS.setStyleIfObjNA(window.scrollX); document.getElementById(ctx.id + '-sys-scroll-y').innerHTML = DebugJS.setStyleIfObjNA(window.scrollY); document.getElementById(ctx.id + '-sys-pgoffset-x').innerText = window.pageXOffset; document.getElementById(ctx.id + '-sys-pgoffset-y').innerText = window.pageYOffset; document.getElementById(ctx.id + '-sys-cli-scroll-x').innerText = document.documentElement.scrollLeft; document.getElementById(ctx.id + '-sys-cli-scroll-y').innerText = document.documentElement.scrollTop; }, onMouseDown: function(e) { var ctx = DebugJS.ctx; var posX = e.clientX; var posY = e.clientY; switch (e.button) { case 0: ctx.mouseClick0 = DebugJS.COLOR_ACTIVE; if (ctx.status & DebugJS.ST_MEASURE) { ctx.startMeasure(ctx, posX, posY); } if (ctx.status & DebugJS.ST_STOPWATCH_LAPTIME) { DebugJS._log('<span style="color:' + ctx.opt.timerColor + '">' + DebugJS.getTimerStr(DebugJS.time.getCount(DebugJS.TIMER_NAME_SW_0)) + '</span>'); ctx.resetStopwatch(); } if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD) { DebugJS.bat._resume('cmd'); } break; case 1: ctx.mouseClick1 = DebugJS.COLOR_ACTIVE; break; case 2: ctx.mouseClick2 = DebugJS.COLOR_ACTIVE; if (ctx.status & DebugJS.ST_ELM_INSPECTING) { if (ctx.isOnDbgWin(posX, posY)) { if ((DebugJS.el) && (DebugJS.el != ctx.targetEl)) { ctx.showElementInfo(DebugJS.el); ctx.updateTargetElm(DebugJS.el); } } else { var pointedElm = document.elementFromPoint(posX, posY); ctx.captureElm(pointedElm); } } } if (ctx.opt.useMouseStatusInfo) { ctx.updateMouseClickLabel(); } }, onTouchStart: function(e) { var x = e.changedTouches[0].pageX; var y = e.changedTouches[0].pageY; if (DebugJS.ctx.status & DebugJS.ST_MEASURE) { DebugJS.ctx.startMeasure(DebugJS.ctx, x, y); e.preventDefault(); } }, onMouseMove: function(e) { var x = e.clientX; var y = e.clientY; DebugJS.ctx._onPointerMove(DebugJS.ctx, x, y); }, onTouchMove: function(e) { var x = e.changedTouches[0].pageX; var y = e.changedTouches[0].pageY; DebugJS.ctx._onPointerMove(DebugJS.ctx, x, y); }, _onPointerMove: function(ctx, x, y) { if (ctx.opt.useMouseStatusInfo) { ctx.mousePos.x = x; ctx.mousePos.y = y; ctx.updateMousePosLabel(); } if (ctx.uiStatus & DebugJS.UI_ST_DRAGGING) ctx.moveDbgWin(ctx, x, y); if (ctx.uiStatus & DebugJS.UI_ST_RESIZING) ctx.resizeDbgWin(ctx, x, y); if (ctx.status & DebugJS.ST_MEASURING) ctx.doMeasure(ctx, x, y); if (ctx.status & DebugJS.ST_ELM_INSPECTING) ctx.inspectElement(x, y); if (DebugJS.point.d) DebugJS.point.move(x, y, 0, 0); ctx.resizeMainHeight(); }, onMouseUp: function(e) { var ctx = DebugJS.ctx; switch (e.button) { case 0: ctx.mouseClick0 = DebugJS.COLOR_INACT; ctx._onPointerUp(ctx, e); break; case 1: ctx.mouseClick1 = DebugJS.COLOR_INACT; break; case 2: ctx.mouseClick2 = DebugJS.COLOR_INACT; } if (ctx.opt.useMouseStatusInfo) { ctx.updateMouseClickLabel(); } }, onTouchEnd: function(e) { DebugJS.ctx._onPointerUp(DebugJS.ctx, e); }, _onPointerUp: function(ctx, e) { var el = e.target; if (ctx.status & DebugJS.ST_MEASURING) { ctx.stopMeasure(ctx); } if (ctx.uiStatus & DebugJS.UI_ST_DRAGGING) { ctx.endMove(ctx); if ((el != ctx.extActivePanel) && (!DebugJS.isDescendant(el, ctx.extActivePanel))) { if (((new Date()).getTime() - ctx.ptOpTm) < 300) { ctx.focusCmdLine(); } } } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING) { ctx.endResize(ctx); ctx.focusCmdLine(); } if (DebugJS.point.d) DebugJS.point.endDragging(); }, onDbgWinDblClick: function(e) { var ctx = DebugJS.ctx; var x = e.clientX; var y = e.clientY; if ((!ctx.isMovable(ctx, e.target, x, y)) || (!(ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE))) { return; } if (ctx.sizeStatus != DebugJS.SIZE_ST_NORMAL) { ctx.setWinSize('restore'); } else { ctx.expandDbgWin('expand'); } ctx.focusCmdLine(); }, expandDbgWin: function(mode) { var ctx = DebugJS.ctx; var sp = ctx.getSelfSizePos(); var border = DebugJS.WIN_BORDER * 2; if ((mode == 'expand') && (sp.w == DebugJS.DBGWIN_EXPAND_W + border) && (sp.h == DebugJS.DBGWIN_EXPAND_H + border)) { return; } ctx.saveSizeAndPos(ctx); switch (mode) { case 'full': ctx.setDbgWinFull(ctx); break; case 'expand': if ((sp.w < DebugJS.DBGWIN_EXPAND_W) && (sp.h < DebugJS.DBGWIN_EXPAND_H)) { ctx._expandDbgWin(ctx); } else { ctx._expandDbgWinAuto(ctx, sp); } break; case 'center': ctx._expandDbgWinCenter(ctx); break; default: ctx._expandDbgWinAuto(ctx, sp); } ctx.updateWinCtrlBtnPanel(); }, _expandDbgWin: function(ctx) { var sp = ctx.getSelfSizePos(); var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var expThrW = clientW * 0.6; var expThrH = clientH * 0.6; if ((sp.w > expThrW) || (sp.h > expThrH)) { ctx.setDbgWinFull(ctx); return; } var l = sp.x1 + 3; var t = sp.y1 + 3; var w = DebugJS.DBGWIN_EXPAND_W; var h = DebugJS.DBGWIN_EXPAND_H; if (sp.x1 > (clientW - sp.x2)) { l = (sp.x1 - (DebugJS.DBGWIN_EXPAND_W - sp.w)) + 1; } if (sp.y1 > (clientH - sp.y2)) { t = (sp.y1 - (DebugJS.DBGWIN_EXPAND_H - sp.h)) + 1; } if (l < 0) l = 0; if (clientH < DebugJS.DBGWIN_EXPAND_H) { t = clientH - DebugJS.DBGWIN_EXPAND_H; } ctx.saveSizeAndPos(ctx); ctx.setDbgWinPos(t, l); ctx.setDbgWinSize(w, h); ctx.sizeStatus = DebugJS.SIZE_ST_EXPANDED; ctx.updateWinCtrlBtnPanel(); }, _expandDbgWinAuto: function(ctx, sp) { if ((sp.w >= DebugJS.DBGWIN_EXPAND_W) && (sp.h >= DebugJS.DBGWIN_EXPAND_H)) { ctx.setDbgWinFull(ctx); return; } var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var expThrW = clientW * 0.6; var expThrH = clientH * 0.6; var w = 0, h = 0, t = 0, l = 0; if ((DebugJS.DBGWIN_EXPAND_W > clientW) || (sp.w > expThrW)) { w = clientW; ctx.sizeStatus |= DebugJS.SIZE_ST_FULL_W; if ((DebugJS.DBGWIN_EXPAND_H > clientH) || (sp.h > expThrH)) { h = clientH; } else { t = DebugJS.DBGWIN_POS_NONE; } } else { if ((DebugJS.DBGWIN_EXPAND_H > clientH) || (sp.h > expThrH)) { h = clientH; if ((DebugJS.DBGWIN_EXPAND_W < clientW) && (sp.w < expThrW)) { l = DebugJS.DBGWIN_POS_NONE; } } else { ctx.setDbgWinFull(ctx); return; } } ctx.setDbgWinPos(t, l); ctx.setDbgWinSize(w, h); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; if ((w == clientW) && (h == clientH)) { ctx.sizeStatus = DebugJS.SIZE_ST_FULL_WH; } else if (w == clientW) { ctx.sizeStatus = DebugJS.SIZE_ST_FULL_W; } else if (h == clientH) { ctx.sizeStatus = DebugJS.SIZE_ST_FULL_H; } }, _expandDbgWinCenter: function(ctx) { var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var w = DebugJS.DBGWIN_EXPAND_C_W; var h = DebugJS.DBGWIN_EXPAND_C_H; var l = clientW / 2 - w / 2; var t = clientH / 2 - h / 2; ctx.setDbgWinPos(t, l); ctx.setDbgWinSize(w, h); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.sizeStatus = DebugJS.SIZE_ST_EXPANDED_C; }, setDbgWinFull: function(ctx) { var w = document.documentElement.clientWidth; var h = document.documentElement.clientHeight; var t = 0, l = 0; ctx.setDbgWinPos(t, l); ctx.setDbgWinSize(w, h); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.sizeStatus = DebugJS.SIZE_ST_FULL_WH; ctx.disableDraggable(ctx); ctx.disableResize(ctx); }, setDbgWinPos: function(t, l) { if (t > DebugJS.DBGWIN_POS_NONE) DebugJS.ctx.win.style.top = t + 'px'; if (l > DebugJS.DBGWIN_POS_NONE) DebugJS.ctx.win.style.left = l + 'px'; }, setDbgWinSize: function(w, h) { var ctx = DebugJS.ctx; if (w > 0) ctx.win.style.width = w + 'px'; if (h > 0) ctx.win.style.height = h + 'px'; ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, adjustDbgWinPos: function(ctx) { var sp = ctx.getSelfSizePos(); ctx.setWinPos(ctx.opt.position, sp.w, sp.h); }, adjustWinMax: function(ctx) { if ((ctx.sizeStatus == DebugJS.SIZE_ST_FULL_W) || (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH)) { ctx.win.style.width = document.documentElement.clientWidth + 'px'; } if ((ctx.sizeStatus == DebugJS.SIZE_ST_FULL_H) || (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH)) { ctx.win.style.height = document.documentElement.clientHeight + 'px'; } ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, saveSizeAndPos: function(ctx) { ctx.saveSize(ctx); ctx.savePos(ctx); }, saveSize: function(ctx) { var shadow = (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) ? (DebugJS.WIN_SHADOW / 2) : 0; ctx.orgSizePos.w = (ctx.win.offsetWidth + DebugJS.WIN_BORDER - shadow); ctx.orgSizePos.h = (ctx.win.offsetHeight + DebugJS.WIN_BORDER - shadow); }, savePos: function(ctx) { ctx.orgSizePos.t = ctx.win.offsetTop; ctx.orgSizePos.l = ctx.win.offsetLeft; }, savePosNone: function(ctx) { ctx.orgSizePos.t = DebugJS.DBGWIN_POS_NONE; ctx.orgSizePos.l = DebugJS.DBGWIN_POS_NONE; }, restoreDbgWin: function() { var ctx = DebugJS.ctx; var w = ctx.orgSizePos.w; var h = ctx.orgSizePos.h; var t = ctx.orgSizePos.t; var l = ctx.orgSizePos.l; if (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH) { ctx.enableDraggable(ctx); ctx.enableResize(ctx); } else { var thold = 10; var sp = ctx.getSelfSizePos(); var orgY2 = t + h; var orgX2 = l + w; if (((Math.abs(sp.x1 - l) > thold) && (Math.abs(sp.x2 - orgX2) > thold)) || ((Math.abs(sp.y1 - t) > thold) && (Math.abs(sp.y2 - orgY2) > thold))) { var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var mL = (sp.x1 < 0 ? 0 : sp.x1); var mT = (sp.y1 < 0 ? 0 : sp.y1); var mR = clientW - sp.x2; var mB = clientH - sp.y2; if (mR < 0) mR = 0; if (mB < 0) mB = 0; t = sp.y1 + 3; l = sp.x1 + 3; if (mT > mB) { t = sp.y2 - h; if ((t > clientH) || (t + h > clientH)) { t = clientH - h; } t -= 6; } if (mL > mR) { l = sp.x2 - w; if ((l > clientW) || (l + w > clientW)) { l = clientW - w; } l -= 6; } if (l < 0) l = 0; if (t < 0) t = 0; } } ctx.setDbgWinSize(w, h); ctx.setDbgWinPos(t, l); ctx.scrollLogBtm(ctx); ctx.sizeStatus = DebugJS.SIZE_ST_NORMAL; if (ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) { ctx.adjustDbgWinPos(ctx); } }, resetDbgWinSizePos: function() { DebugJS.ctx._resetDbgWinSizePos(DebugJS.ctx); DebugJS.ctx.updateWinCtrlBtnPanel(); }, _resetDbgWinSizePos: function(ctx) { var w = (ctx.initWidth - (DebugJS.WIN_SHADOW / 2) + DebugJS.WIN_BORDER); var h = (ctx.initHeight - (DebugJS.WIN_SHADOW / 2) + DebugJS.WIN_BORDER); if (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH) { ctx.enableDraggable(ctx); ctx.enableResize(ctx); } ctx.setWinPos(ctx.opt.position, ctx.initWidth, ctx.initHeight); ctx.setDbgWinSize(w, h); ctx.scrollLogBtm(ctx); ctx.saveExpandModeOrgSizeAndPos(ctx); ctx.sizeStatus = DebugJS.SIZE_ST_NORMAL; if (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) { ctx.uiStatus |= DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.adjustDbgWinPos(ctx); } }, isOutOfWin: function(ctx) { var sp = ctx.getSelfSizePos(); if ((sp.x1 > document.documentElement.clientWidth) || (sp.y1 > document.documentElement.clientHeight) || (sp.x2 < 0) || (sp.y2 < 0)) { return true; } return false; }, resetToOriginalPosition: function(ctx) { var sp = ctx.getSelfSizePos(); ctx.setWinPos(ctx.opt.position, sp.w, sp.h); if (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) { ctx.uiStatus |= DebugJS.UI_ST_POS_AUTO_ADJUST; } }, showDbgWin: function() { var ctx = DebugJS.ctx; if ((ctx.win == null) || (ctx.uiStatus & DebugJS.UI_ST_PROTECTED)) return; ctx.win.style.display = 'block'; ctx.uiStatus |= DebugJS.UI_ST_VISIBLE; if ((ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) || ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.isOutOfWin(ctx)))) { ctx.uiStatus |= DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.adjustDbgWinPos(ctx); } else { ctx.adjustWinMax(ctx); } if (ctx.uiStatus & DebugJS.UI_ST_LOG_SCROLL) { ctx.scrollLogBtm(ctx); } ctx.resizeMainHeight(); }, showDbgWinOnError: function(ctx) { if ((ctx.status & DebugJS.ST_INITIALIZED) && !(ctx.uiStatus & DebugJS.UI_ST_VISIBLE)) { if (((ctx.errStatus) && (((ctx.opt.popupOnError.scriptError) && (ctx.errStatus & DebugJS.ERR_ST_SCRIPT)) || ((ctx.opt.popupOnError.loadError) && (ctx.errStatus & DebugJS.ERR_ST_LOAD)) || ((ctx.opt.popupOnError.errorLog) && (ctx.errStatus & DebugJS.ERR_ST_LOG)))) || ((ctx.status & DebugJS.ST_BAT_RUNNING) && (DebugJS.bat.hasBatStopCond('error')) && (DebugJS.bat.ctrl.stopReq))) { ctx.showDbgWin(); ctx.errStatus = DebugJS.ERR_ST_NONE; } } }, hideDbgWin: function(ctx) { if ((!ctx.opt.togglableShowHide) || (!ctx.win)) return; ctx.errStatus = DebugJS.ERR_ST_NONE; ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGING; ctx.uiStatus &= ~DebugJS.UI_ST_VISIBLE; ctx.win.style.display = 'none'; }, closeDbgWin: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_MEASURE) { ctx.closeScreenMeasure(ctx); } if (ctx.status & DebugJS.ST_ELM_INSPECTING) { ctx.closeElmInfo(ctx); } ctx.hideDbgWin(ctx); }, lockDbgWin: function(ctx) { ctx.uiStatus |= DebugJS.UI_ST_PROTECTED; ctx.closeDbgWin(); }, focusCmdLine: function() { if (DebugJS.ctx.cmdLine) DebugJS.ctx.cmdLine.focus(); }, startMeasure: function(ctx, x, y) { if (ctx.isOnDbgWin(x, y)) return; ctx.status |= DebugJS.ST_MEASURING; ctx.clickedPosX = x; ctx.clickedPosY = y; if (ctx.measBox == null) { var el = document.createElement('div'); el.style.position = 'fixed'; el.style.zIndex = 0x7fffffff; el.style.top = y + 'px'; el.style.left = x + 'px'; el.style.width = '0px'; el.style.height = '0px'; el.style.border = 'dotted 1px #333'; el.style.background = 'rgba(0,0,0,0.1)'; ctx.measBox = el; ctx.bodyEl.appendChild(el); } ctx.disableTextSelect(ctx); }, doMeasure: function(ctx, posX, posY) { var deltaX = posX - ctx.clickedPosX; var deltaY = posY - ctx.clickedPosY; var clientW = document.documentElement.clientWidth; if (deltaX < 0) { ctx.measBox.style.left = posX + 'px'; deltaX *= -1; } if (deltaY < 0) { ctx.measBox.style.top = posY + 'px'; deltaY *= -1; } ctx.measBox.style.width = deltaX + 'px'; ctx.measBox.style.height = deltaY + 'px'; var sizeLabelW = 210; var sizeLabelH = 40; var sizeLabelY = (deltaY / 2) - (sizeLabelH / 2); var sizeLabelX = (deltaX / 2) - (sizeLabelW / 2); var originY = 'top'; var originX = 'left'; if (deltaX < sizeLabelW) { sizeLabelX = 0; if ((deltaY < sizeLabelH) || (deltaY > ctx.clickedPosY)) { if (ctx.clickedPosY < sizeLabelH) { sizeLabelY = deltaY; } else { sizeLabelY = sizeLabelH * (-1); } } else { sizeLabelY = sizeLabelH * (-1); } } if (posY < sizeLabelH) { if (ctx.clickedPosY > sizeLabelH) { sizeLabelY = (deltaY / 2) - (sizeLabelH / 2); } } if (((ctx.clickedPosX + sizeLabelW) > clientW) && ((posX + sizeLabelW) > clientW)) { sizeLabelX = (sizeLabelW - (clientW - ctx.clickedPosX)) * (-1); } if (posX < ctx.clickedPosX) originX = 'right'; if (posY < ctx.clickedPosY) originY = 'bottom'; var size = '<span style="font-family:' + ctx.opt.fontFamily + ';font-size:32px;color:#fff;background:rgba(0,0,0,0.7);padding:1px 3px;white-space:pre;position:relative;top:' + sizeLabelY + 'px;left:' + sizeLabelX + 'px">W=' + (deltaX | 0) + ' H=' + (deltaY | 0) + '</span>'; var origin = '<span style="font-family:' + ctx.opt.fontFamily + ';font-size:12px;color:#fff;background:rgba(0,0,0,0.3);white-space:pre;position:absolute;' + originY + ':1px;' + originX + ':1px;padding:1px">x=' + ctx.clickedPosX + ',y=' + ctx.clickedPosY + '</span>'; ctx.measBox.innerHTML = origin + size; }, stopMeasure: function(ctx) { if (ctx.measBox) { ctx.bodyEl.removeChild(ctx.measBox); ctx.measBox = null; } ctx.enableTextSelect(ctx); ctx.status &= ~DebugJS.ST_MEASURING; }, addOverlayPanel: function(ctx, panel) { if (ctx.overlayBasePanel == null) { ctx.collapseLogPanel(ctx); ctx.overlayBasePanel = document.createElement('div'); ctx.overlayBasePanel.className = 'dbg-overlay-base-panel'; ctx.mainPanel.appendChild(ctx.overlayBasePanel); //ctx.mainPanel.insertBefore(ctx.overlayBasePanel, ctx.logPanel); // to bottom } ctx.overlayBasePanel.appendChild(panel); ctx.overlayPanels.push(panel); }, removeOverlayPanel: function(ctx, panel) { if (ctx.overlayBasePanel) { for (var i = 0; i < ctx.overlayPanels.length; i++) { if (ctx.overlayPanels[i] == panel) { ctx.overlayPanels.splice(i, 1); ctx.overlayBasePanel.removeChild(panel); break; } } if (ctx.overlayPanels.length == 0) { ctx.mainPanel.removeChild(ctx.overlayBasePanel); ctx.overlayBasePanel = null; ctx.expandLogPanel(ctx); } } }, addOverlayPanelFull: function(panel) { DebugJS.ctx.mainPanel.appendChild(panel); }, removeOverlayPanelFull: function(panel) { if (panel.parentNode) { DebugJS.ctx.mainPanel.removeChild(panel); } }, toggleSystemInfo: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_SYS_INFO) { ctx.closeSystemInfo(ctx); } else { ctx.openSystemInfo(ctx); } }, openSystemInfo: function(ctx) { ctx.status |= DebugJS.ST_SYS_INFO; ctx.featStack.push(DebugJS.ST_SYS_INFO); if (!ctx.sysInfoPanel) ctx.createSysInfoPanel(ctx); ctx.updateSysInfoBtn(ctx); ctx.showSystemInfo(); ctx.setIntervalH(ctx); }, createSysInfoPanel: function(ctx) { ctx.sysInfoPanel = document.createElement('div'); ctx.sysInfoPanel.innerHTML = '<span style="color:' + DebugJS.SYS_BTN_COLOR + '">&lt;SYSTEM INFO&gt;</span><span style="float:right">v' + ctx.v + '</span>'; if (DebugJS.SYS_INFO_FULL_OVERLAY) { ctx.sysInfoPanel.className = 'dbg-overlay-panel-full'; ctx.addOverlayPanelFull(ctx.sysInfoPanel); } else { ctx.sysInfoPanel.className = 'dbg-overlay-panel'; ctx.addOverlayPanel(ctx, ctx.sysInfoPanel); ctx.expandHightIfNeeded(ctx); } ctx.sysTimePanel = document.createElement('div'); ctx.sysTimePanel.style.marginRight = '4px'; ctx.sysTimePanel.color = '#fff'; ctx.sysInfoPanel.appendChild(ctx.sysTimePanel); ctx.sysInfoPanelBody = document.createElement('div'); ctx.sysInfoPanelBody.style.top = ctx.computedFontSize; ctx.sysInfoPanel.appendChild(ctx.sysInfoPanelBody); ctx.updateSystemTime(); }, updateSystemTime: function() { if (!(DebugJS.ctx.status & DebugJS.ST_SYS_INFO)) return; var time = (new Date()).getTime(); var timeBin = DebugJS.formatBin(time.toString(2), false, 1); var html = '<pre><span style="color:' + DebugJS.ITEM_NAME_COLOR + '">SYSTEM TIME</span> : ' + DebugJS.convDateTimeStr(DebugJS.getDateTime(time)) + '\n' + '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '"> RAW</span> (new Date()).getTime() = ' + time + '\n' + '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '"> BIN</span> ' + timeBin + '\n</pre>'; DebugJS.ctx.sysTimePanel.innerHTML = html; setTimeout(DebugJS.ctx.updateSystemTime, DebugJS.UPDATE_INTERVAL_H); }, closeSystemInfo: function(ctx) { if (ctx.sysInfoPanel) { if (DebugJS.SYS_INFO_FULL_OVERLAY) { ctx.removeOverlayPanelFull(ctx.sysInfoPanel); } else { ctx.removeOverlayPanel(ctx, ctx.sysInfoPanel); ctx.resetExpandedHeightIfNeeded(ctx); } ctx.sysInfoPanel = null; } ctx.status &= ~DebugJS.ST_SYS_INFO; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_SYS_INFO); ctx.updateSysInfoBtn(ctx); ctx.setIntervalL(ctx); }, showSystemInfo: function(e) { var ctx = DebugJS.ctx; var INDENT = ' '; var offset = (new Date()).getTimezoneOffset(); var screenSize = 'width = ' + screen.width + ' x height = ' + screen.height; var languages = DebugJS.getLanguages(INDENT); var browser = DebugJS.getBrowserType(); var jq = '<span class="dbg-na">not loaded</span>'; if (typeof jQuery != 'undefined') jq = 'v' + jQuery.fn.jquery; var metaTags = document.getElementsByTagName('meta'); var charset; for (var i = 0; i < metaTags.length; i++) { charset = metaTags[i].getAttribute('charset'); if (charset) { break; } else { charset = metaTags[i].getAttribute('content'); if (charset) { var content = charset.match(/charset=(.*)/); if (content != null) { charset = content[1]; break; } } } } if (charset == null) charset = ''; var INDENT = ' '; var links = document.getElementsByTagName('link'); var loadedStyles = '<span class="dbg-na">not loaded</span>'; for (i = 0; i < links.length; i++) { if (links[i].rel == 'stylesheet') { if (i == 0) { loadedStyles = ctx.createFoldingText(links[i].href, 'linkHref' + i, DebugJS.OMIT_MID); } else { loadedStyles += '\n' + INDENT + ctx.createFoldingText(links[i].href, 'linkHref' + i, DebugJS.OMIT_MID); } } } var scripts = document.getElementsByTagName('script'); var loadedScripts = '<span class="dbg-na">not loaded</span>'; for (i = 0; i < scripts.length; i++) { if (scripts[i].src) { if (i == 0) { loadedScripts = ctx.createFoldingText(scripts[i].src, 'scriptSrc' + i, DebugJS.OMIT_MID); } else { loadedScripts += '\n' + INDENT + ctx.createFoldingText(scripts[i].src, 'scriptSrc' + i, DebugJS.OMIT_MID); } } } var navUserAgent = ctx.createFoldingText(navigator.userAgent, 'navUserAgent', DebugJS.OMIT_LAST); var navAppVersion = ctx.createFoldingText(navigator.appVersion, 'navAppVersion', DebugJS.OMIT_LAST); var winOnload = ctx.createFoldingText(window.onload, 'winOnload', DebugJS.OMIT_LAST); var winOnunload = ctx.createFoldingText(window.onunload, 'winOnunload', DebugJS.OMIT_LAST); var winOnclick = ctx.createFoldingText(window.onclick, 'winOnclick', DebugJS.OMIT_LAST); var winOnmousedown = ctx.createFoldingText(window.onmousedown, 'winOnmousedown', DebugJS.OMIT_LAST); var winOnmousemove = ctx.createFoldingText(window.onmousemove, 'winOnmousemove', DebugJS.OMIT_LAST); var winOnmouseup = ctx.createFoldingText(window.onmousedown, 'winOnmouseup', DebugJS.OMIT_LAST); var winOnkeydown = ctx.createFoldingText(window.onkeydown, 'winOnkeydown', DebugJS.OMIT_LAST); var winOnkeypress = ctx.createFoldingText(window.onkeypress, 'winOnkeypress', DebugJS.OMIT_LAST); var winOnkeyup = ctx.createFoldingText(window.onkeyup, 'winOnkeyup', DebugJS.OMIT_LAST); var winOncontextmenu = ctx.createFoldingText(window.oncontextmenu, 'winOncontextmenu', DebugJS.OMIT_LAST); var winOnresize = ctx.createFoldingText(window.oncontextmenu, 'winOnresize', DebugJS.OMIT_LAST); var winOnscroll = ctx.createFoldingText(window.oncontextmenu, 'winOnscroll', DebugJS.OMIT_LAST); var winOnselect = ctx.createFoldingText(window.oncontextmenu, 'winOnselect', DebugJS.OMIT_LAST); var winOnselectstart = ctx.createFoldingText(window.oncontextmenu, 'winOnselectstart', DebugJS.OMIT_LAST); var winOnerror = ctx.createFoldingText(window.onerror, 'winOnerror', DebugJS.OMIT_LAST); var docOnclick = ctx.createFoldingText(document.onclick, 'documentOnclick', DebugJS.OMIT_LAST); var docOnmousedown = ctx.createFoldingText(document.onmousedown, 'documentOnmousedown', DebugJS.OMIT_LAST); var docOnmousemove = ctx.createFoldingText(document.onmousemove, 'documentOnmousemove', DebugJS.OMIT_LAST); var docOnmouseup = ctx.createFoldingText(document.onmousedown, 'documentOnmouseup', DebugJS.OMIT_LAST); var docOnkeydown = ctx.createFoldingText(document.onkeydown, 'documentOnkeydown', DebugJS.OMIT_LAST); var docOnkeypress = ctx.createFoldingText(document.onkeypress, 'documentOnkeypress', DebugJS.OMIT_LAST); var docOnkeyup = ctx.createFoldingText(document.onkeyup, 'documentOnkeyup', DebugJS.OMIT_LAST); var docOnselectstart = ctx.createFoldingText(document.onselectstart, 'documentOnselectstart', DebugJS.OMIT_LAST); var docOncontextmenu = ctx.createFoldingText(document.oncontextmenu, 'documentOncontextmenu', DebugJS.OMIT_LAST); var html = '<pre>'; html += ' getTimezoneOffset() = ' + offset + ' (UTC' + DebugJS.getTimeOffsetStr(offset, true) + ')\n'; html += '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '">screen.</span> : ' + screenSize + '\n'; html += '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '">Browser</span> : ' + DebugJS.browserColoring(browser.name) + ' ' + browser.version + '\n'; html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('navigator'); html += DebugJS.addSysInfoProp('userAgent ', navUserAgent); html += DebugJS.addSysInfoProp('language ', DebugJS.setStyleIfObjNA(navigator.language)); html += DebugJS.addSysInfoProp('browserLanguage', DebugJS.setStyleIfObjNA(navigator.browserLanguage)); html += DebugJS.addSysInfoProp('userLanguage ', DebugJS.setStyleIfObjNA(navigator.userLanguage)); html += DebugJS.addSysInfoProp('languages ', languages); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('charset', charset); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('css ', loadedStyles); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('script ', loadedScripts); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('jQuery ', jq); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('window'); html += DebugJS.addSysInfoPropH(' location'); html += DebugJS.addSysInfoProp(' href ', ctx.createFoldingText(window.location, 'docLocation', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp(' origin ', ctx.createFoldingText(window.location.origin, 'origin', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp(' protocol', window.location.protocol); html += DebugJS.addSysInfoProp(' host ', ctx.createFoldingText(window.location.host, 'host', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp(' port ', window.location.port); html += DebugJS.addSysInfoProp(' pathname', ctx.createFoldingText(window.location.pathname, 'pathname', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp('devicePixelRatio', window.devicePixelRatio, 'sys-win-h'); html += DebugJS.addSysInfoProp('outerWidth ', window.outerWidth, 'sys-win-w'); html += DebugJS.addSysInfoProp('outerHeight ', window.outerHeight, 'sys-win-h'); html += DebugJS.addSysInfoProp('scrollX ', DebugJS.setStyleIfObjNA(window.scrollX), 'sys-scroll-x'); html += DebugJS.addSysInfoProp('pageXOffset ', window.pageXOffset, 'sys-pgoffset-x'); html += DebugJS.addSysInfoProp('scrollY ', DebugJS.setStyleIfObjNA(window.scrollY), 'sys-scroll-y'); html += DebugJS.addSysInfoProp('pageYOffset ', window.pageYOffset, 'sys-pgoffset-y'); html += DebugJS.addSysInfoProp('onload ', winOnload); html += DebugJS.addSysInfoProp('onunload ', winOnunload); html += DebugJS.addSysInfoProp('onclick ', winOnclick); html += DebugJS.addSysInfoProp('onmousedown ', winOnmousedown); html += DebugJS.addSysInfoProp('onmousemove ', winOnmousemove); html += DebugJS.addSysInfoProp('onmouseup ', winOnmouseup); html += DebugJS.addSysInfoProp('onkeydown ', winOnkeydown); html += DebugJS.addSysInfoProp('onkeypress ', winOnkeypress); html += DebugJS.addSysInfoProp('onkeyup ', winOnkeyup); html += DebugJS.addSysInfoProp('onresize ', winOnresize); html += DebugJS.addSysInfoProp('onscroll ', winOnscroll); html += DebugJS.addSysInfoProp('onselect ', winOnselect); html += DebugJS.addSysInfoProp('onselectstart', winOnselectstart); html += DebugJS.addSysInfoProp('oncontextmenu', winOncontextmenu); html += DebugJS.addSysInfoProp('onerror ', winOnerror); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('navigator'); html += DebugJS.addSysInfoProp('appCodeName ', DebugJS.setStyleIfObjNA(navigator.appCodeName)); html += DebugJS.addSysInfoProp('appName ', DebugJS.setStyleIfObjNA(navigator.appName)); html += DebugJS.addSysInfoProp('appVersion ', navAppVersion); html += DebugJS.addSysInfoProp('buildID ', DebugJS.setStyleIfObjNA(navigator.buildID)); html += DebugJS.addSysInfoProp('product ', DebugJS.setStyleIfObjNA(navigator.product)); html += DebugJS.addSysInfoProp('productSub ', DebugJS.setStyleIfObjNA(navigator.productSub)); html += DebugJS.addSysInfoProp('vendor ', DebugJS.setStyleIfObjNA(navigator.vendor)); html += DebugJS.addSysInfoProp('platform ', DebugJS.setStyleIfObjNA(navigator.platform)); html += DebugJS.addSysInfoProp('oscpu ', DebugJS.setStyleIfObjNA(navigator.oscpu)); html += DebugJS.addSysInfoProp('cookieEnabled', navigator.cookieEnabled); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('document'); html += DebugJS.addSysInfoPropH(' body'); html += DebugJS.addSysInfoProp(' clientWidth ', document.body.clientWidth, 'sys-body-w'); html += DebugJS.addSysInfoProp(' clientHeight', document.body.clientHeight, 'sys-body-h'); html += DebugJS.addSysInfoPropH(' documentElement'); html += DebugJS.addSysInfoProp(' clientWidth ', document.documentElement.clientWidth, 'sys-cli-w'); html += DebugJS.addSysInfoProp(' clientHeight', document.documentElement.clientHeight, 'sys-cli-h'); html += DebugJS.addSysInfoProp(' scrollLeft ', document.documentElement.scrollLeft, 'sys-cli-scroll-x'); html += DebugJS.addSysInfoProp(' scrollTop ', document.documentElement.scrollTop, 'sys-cli-scroll-y'); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('onclick ', docOnclick); html += DebugJS.addSysInfoProp('onmousedown ', docOnmousedown); html += DebugJS.addSysInfoProp('onmousemove ', docOnmousemove); html += DebugJS.addSysInfoProp('onmouseup ', docOnmouseup); html += DebugJS.addSysInfoProp('onkeydown ', docOnkeydown); html += DebugJS.addSysInfoProp('onkeypress ', docOnkeypress); html += DebugJS.addSysInfoProp('onkeyup ', docOnkeyup); html += DebugJS.addSysInfoProp('onselectstart', docOnselectstart); html += DebugJS.addSysInfoProp('oncontextmenu', docOncontextmenu); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('baseURI ', ctx.createFoldingText(document.baseURI, 'docBaseURL', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp('cookie', ctx.createFoldingText(document.cookie, 'cookie', DebugJS.OMIT_MID)); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('localStorage'); if (DebugJS.LS_AVAILABLE) { html += ' <span class="dbg-btn" onclick="DebugJS.ctx.clearLocalStrage();">clear()</span>\n<span id="' + ctx.id + '-sys-ls"></span>\n'; html += DebugJS.ctx.createStorageEditor(ctx, 0); } else { html += ' <span class="dbg-na">undefined</span>'; } html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('sessionStorage'); if (DebugJS.SS_AVAILABLE) { html += ' <span class="dbg-btn" onclick="DebugJS.ctx.clearSessionStrage();">clear()</span>\n<span id="' + ctx.id + '-sys-ss"></span>\n'; html += DebugJS.ctx.createStorageEditor(ctx, 1); } else { html += ' <span class="dbg-na">undefined</span>'; } html += DebugJS.addPropSep(ctx); html += '\n</pre>'; ctx.sysInfoPanelBody.innerHTML = html; if (DebugJS.LS_AVAILABLE) { ctx.updateStrageInfo(0); } if (DebugJS.SS_AVAILABLE) { ctx.updateStrageInfo(1); } }, clearLocalStrage: function() { localStorage.clear(); DebugJS.ctx.updateStrageInfo(0); }, removeLocalStrage: function(key) { localStorage.removeItem(key); DebugJS.ctx.updateStrageInfo(0); }, clearSessionStrage: function() { sessionStorage.clear(); DebugJS.ctx.updateStrageInfo(1); }, removeSessionStrage: function(key) { sessionStorage.removeItem(key); DebugJS.ctx.updateStrageInfo(1); }, updateStrageInfo: function(type) { var ctx = DebugJS.ctx; var strg, nm, rmvFn, id; if (type == 0) { strg = localStorage; nm = 'localStorage'; rmvFn = 'removeLocalStrage'; id = 'ls'; } else { strg = sessionStorage; nm = 'sessionStorage'; rmvFn = 'removeSessionStrage'; id = 'ss'; } var html = ' <span style="color:' + DebugJS.ITEM_NAME_COLOR + '">length</span> = ' + strg.length + '\n' + ' <span style="color:' + DebugJS.ITEM_NAME_COLOR + '">key</span>'; if (DebugJS.LS_AVAILABLE) { for (var i = 0; i < strg.length; i++) { var key = strg.key(i); if (i != 0) html += '\n '; var getCode = nm + '.getItem(\'' + key + '\')'; var rmvCode = nm + '.removeItem(\'' + key + '\')'; html += '(' + i + ') = ' + '<span class="dbg-btn dbg-btn-wh" onclick="DebugJS.ctx.setStrgEdit(' + type + ', ' + getCode + ', \'' + key + '\');" title="' + getCode + '">' + (key == '' ? ' ' : key) + '</span>' + ' <span class="dbg-btn dbg-btn-red" onclick="DebugJS.ctx.' + rmvFn + '(\'' + key + '\');" title="' + rmvCode + '">x</span>'; } } document.getElementById(ctx.id + '-sys-' + id).innerHTML = html; }, createStorageEditor: function(ctx, type) { return '<textarea id="' + ctx.id + '-strg' + type + '" class="dbg-editor dbg-strg"></textarea>\n' + ' <span class="dbg-btn" onclick="DebugJS.ctx.setStrg(' + type + ');">setItem</span>(\'<input id="' + ctx.id + '-strgkey' + type + '" class="dbg-txtbox dbg-strgkey">\', v);'; }, setStrgEdit: function(type, v, k) { document.getElementById(DebugJS.ctx.id + '-strg' + type).value = v; document.getElementById(DebugJS.ctx.id + '-strgkey' + type).value = k; }, setStrg: function(type) { var v = document.getElementById(DebugJS.ctx.id + '-strg' + type).value; var k = document.getElementById(DebugJS.ctx.id + '-strgkey' + type).value; var strg = localStorage; if (type == 1) strg = sessionStorage; strg.setItem(k, v); DebugJS.ctx.updateStrageInfo(type); }, showHideByName: function(name) { var ctx = DebugJS.ctx; var btn = document.getElementById(ctx.id + '-' + name + '__button'); var partialBody = document.getElementById(ctx.id + '-' + name + '__partial-body'); var body = document.getElementById(ctx.id + '-' + name + '__body'); if ((body) && ((!body.style.display) || (body.style.display == 'none'))) { btn.innerHTML = DebugJS.CLOSEBTN; partialBody.style.display = 'none'; body.style.display = 'block'; if (ctx.elmInfoShowHideStatus[name] != undefined) { ctx.elmInfoShowHideStatus[name] = true; } } else { btn.innerHTML = DebugJS.EXPANDBTN; partialBody.style.display = 'inline'; body.style.display = 'none'; if (ctx.elmInfoShowHideStatus[name] != undefined) { ctx.elmInfoShowHideStatus[name] = false; } } }, createFoldingText: function(obj, name, omitpart, lineMaxLen, style, show) { var ctx = DebugJS.ctx; var DFLT_MAX_LEN = 50; var foldingText; if ((lineMaxLen == undefined) || (lineMaxLen < 0)) lineMaxLen = DFLT_MAX_LEN; if (!style) style = 'color:#aaa'; if (!obj) { foldingText = '<span class="dbg-na">' + obj + '</span>'; } else { var btn = DebugJS.EXPANDBTN; var partDisp = 'inline'; var bodyDisp = 'none'; if (show) { btn = DebugJS.CLOSEBTN; partDisp = 'none'; bodyDisp = 'block'; } foldingText = obj + ''; if ((foldingText.indexOf('\n') >= 1) || (foldingText.length > lineMaxLen)) { partial = DebugJS.trimDownText2(foldingText, lineMaxLen, omitpart, style); foldingText = '<span class="dbg-showhide-btn dbg-nomove" id="' + ctx.id + '-' + name + '__button" onclick="DebugJS.ctx.showHideByName(\'' + name + '\')">' + btn + '</span> ' + '<span id="' + ctx.id + '-' + name + '__partial-body" style="display:' + partDisp + '">' + partial + '</span>' + '<div style="display:' + bodyDisp + '" id="' + ctx.id + '-' + name + '__body">' + obj + '</div>'; } else { foldingText = obj; } } return foldingText; }, toggleElmInfo: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_ELM_INSPECTING) { ctx.closeElmInfo(ctx); } else { ctx.openElmInfo(ctx); } }, openElmInfo: function(ctx) { ctx.status |= DebugJS.ST_ELM_INSPECTING; ctx.featStack.push(DebugJS.ST_ELM_INSPECTING); if (!ctx.elmInfoPanel) ctx.createElmInfoPanel(ctx); ctx.updateElmInfoBtn(ctx); ctx.updateElmSelectBtn(); ctx.updateElmHighlightBtn(); }, createElmInfoPanel: function(ctx) { ctx.elmInfoPanel = document.createElement('div'); if (DebugJS.ELM_INFO_FULL_OVERLAY) { ctx.elmInfoPanel.className = 'dbg-overlay-panel-full'; ctx.addOverlayPanelFull(ctx.elmInfoPanel); } else { ctx.elmInfoPanel.className = 'dbg-overlay-panel'; ctx.addOverlayPanel(ctx, ctx.elmInfoPanel); ctx.expandHightIfNeeded(ctx); } ctx.elmInfoHeaderPanel = document.createElement('div'); ctx.elmInfoPanel.appendChild(ctx.elmInfoHeaderPanel); ctx.elmPrevBtn = ctx.createElmInfoHeadBtn('<<', ctx.showPrevElem); ctx.enablePrevElBtn(ctx, false); ctx.elmTitle = document.createElement('span'); ctx.elmTitle.style.marginLeft = '4px'; ctx.elmTitle.style.marginRight = '4px'; ctx.setStyle(ctx.elmTitle, 'color', DebugJS.DOM_BTN_COLOR); ctx.elmTitle.innerText = 'ELEMENT INFO'; ctx.elmInfoHeaderPanel.appendChild(ctx.elmTitle); ctx.elmNextBtn = ctx.createElmInfoHeadBtn('>>', ctx.showNextElem); ctx.enableNextElBtn(ctx, false); ctx.elmSelectBtn = ctx.createElmInfoHeadBtn('SELECT', ctx.toggleElmSelectMode); ctx.elmSelectBtn.style.marginLeft = '8px'; ctx.elmSelectBtn.style.marginRight = '4px'; ctx.elmHighlightBtn = ctx.createElmInfoHeadBtn('HIGHLIGHT', ctx.toggleElmHlMode); ctx.elmHighlightBtn.style.marginLeft = '4px'; ctx.elmHighlightBtn.style.marginRight = '4px'; ctx.elmUpdateBtn = ctx.createElmInfoHeadBtn('UPDATE', ctx.updateElementInfo); ctx.elmUpdateBtn.style.marginLeft = '4px'; ctx.setStyle(ctx.elmUpdateBtn, 'color', DebugJS.COLOR_INACT); var UPDATE_COLOR = '#ccc'; var label1 = DebugJS.ui.addLabel(ctx.elmInfoHeaderPanel, ':'); label1.style.marginRight = '0px'; ctx.setStyle(label1, 'color', UPDATE_COLOR); ctx.elmUpdateInput = DebugJS.ui.addTextInput(ctx.elmInfoHeaderPanel, '30px', 'right', UPDATE_COLOR, ctx.elmUpdateInterval, ctx.onchangeElmUpdateInterval); var label2 = DebugJS.ui.addLabel(ctx.elmInfoHeaderPanel, 'ms'); label2.style.marginLeft = '2px'; ctx.setStyle(label2, 'color', UPDATE_COLOR); ctx.elmNumPanel = document.createElement('span'); ctx.elmNumPanel.style.float = 'right'; ctx.elmNumPanel.style.marginRight = '4px'; ctx.elmInfoHeaderPanel.appendChild(ctx.elmNumPanel); ctx.elmDelBtn = ctx.createElmInfoHeadBtn('DEL', ctx.delTargetElm); ctx.elmDelBtn.style.float = 'right'; ctx.elmDelBtn.style.marginRight = '4px'; ctx.setStyle(ctx.elmDelBtn, 'color', DebugJS.COLOR_INACT); ctx.elmCapBtn = ctx.createElmInfoHeadBtn('CAPTURE', ctx.exportTargetElm); ctx.elmCapBtn.style.float = 'right'; ctx.elmCapBtn.style.marginRight = '4px'; ctx.setStyle(ctx.elmCapBtn, 'color', DebugJS.COLOR_INACT); ctx.elmInfoBodyPanel = document.createElement('div'); ctx.elmInfoBodyPanel.style.width = '100%'; ctx.elmInfoBodyPanel.style.height = 'calc(100% - 1.3em)'; ctx.elmInfoBodyPanel.style.overflow = 'auto'; ctx.elmInfoPanel.appendChild(ctx.elmInfoBodyPanel); ctx.updateElmInfoInterval(); }, createElmInfoHeadBtn: function(label, handler) { return DebugJS.ui.addBtn(DebugJS.ctx.elmInfoHeaderPanel, label, handler); }, closeElmInfo: function(ctx) { if (ctx.targetEl) { if (typeof ctx.targetEl.className == 'string') { DebugJS.removeClass(ctx.targetEl, ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX); } ctx.targetEl = null; } if (ctx.elmInfoPanel) { if (DebugJS.ELM_INFO_FULL_OVERLAY) { ctx.removeOverlayPanelFull(ctx.elmInfoPanel); } else { ctx.removeOverlayPanel(ctx, ctx.elmInfoPanel); ctx.resetExpandedHeightIfNeeded(ctx); } ctx.elmInfoPanel = null; ctx.elmInfoBodyPanel = null; ctx.elmNumPanel = null; } ctx.updateTargetElm(null); ctx.status &= ~DebugJS.ST_ELM_INSPECTING; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_ELM_INSPECTING); ctx.updateElmInfoBtn(ctx); }, inspectElement: function(x, y) { var ctx = DebugJS.ctx; if ((!(ctx.elmInfoStatus & DebugJS.ELMINFO_ST_SELECT)) || (ctx.isOnDbgWin(x, y))) return; var el = document.elementFromPoint(x, y); if (el != ctx.targetEl) { ctx.showElementInfo(el); ctx.updateTargetElm(el); } }, showElementInfo: function(el) { var ctx = DebugJS.ctx; var html = '<pre>'; if (el && el.tagName) { html += ctx.getElmInfo(ctx, el); } html += '</pre>'; ctx.elmInfoBodyPanel.innerHTML = html; ctx.showAllElmNum(); }, getElmInfo: function(ctx, el) { var OMIT_STYLE = 'color:#888'; var OMIT_STYLE2 = 'color:#666'; DebugJS.dom = el; var computedStyle = window.getComputedStyle(el); var rect = el.getBoundingClientRect(); var rectT = Math.round(rect.top); var rectL = Math.round(rect.left); var rectR = Math.round(rect.right); var rectB = Math.round(rect.bottom); var MAX_LEN = 50; var text = ''; if ((el.tagName != 'HTML') && (el.tagName != 'BODY')) { if (el.tagName == 'META') { text = DebugJS.escTags(el.outerHTML); } else { if (el.innerText != undefined) { text = DebugJS.escTags(el.innerText); } } } var txt = ctx.createFoldingText(text, 'text', DebugJS.OMIT_LAST, MAX_LEN, OMIT_STYLE, ctx.elmInfoShowHideStatus.text); var className = el.className + ''; className = className.replace(ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX, '<span style="' + OMIT_STYLE2 + '">' + ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX + '</span>'); var href = (el.href ? ctx.createFoldingText(el.href, 'elHref', DebugJS.OMIT_MID, MAX_LEN, OMIT_STYLE) : DebugJS.setStyleIfObjNA(el.href)); var src = (el.src ? ctx.createFoldingText(el.src, 'elSrc', DebugJS.OMIT_MID, MAX_LEN, OMIT_STYLE) : DebugJS.setStyleIfObjNA(el.src)); var backgroundColor = computedStyle.backgroundColor; var bgColor16 = DebugJS.getElmHexColor(backgroundColor); var color = computedStyle.color; var color16 = DebugJS.getElmHexColor(color); var borderColorT = computedStyle.borderTopColor; var borderColorT16 = DebugJS.getElmHexColor(borderColorT); var borderColorR = computedStyle.borderRightColor; var borderColorR16 = DebugJS.getElmHexColor(borderColorR); var borderColorB = computedStyle.borderBottomColor; var borderColorB16 = DebugJS.getElmHexColor(borderColorB); var borderColorL = computedStyle.borderLeftColor; var borderColorL16 = DebugJS.getElmHexColor(borderColorL); var borderT = 'top : ' + computedStyle.borderTopWidth + ' ' + computedStyle.borderTopStyle + ' ' + borderColorT + ' ' + borderColorT16 + ' ' + DebugJS.getColorBlock(borderColorT); var borderRBL = ' right : ' + computedStyle.borderRightWidth + ' ' + computedStyle.borderRightStyle + ' ' + borderColorR + ' ' + borderColorR16 + ' ' + DebugJS.getColorBlock(borderColorR) + '\n' + ' bottom: ' + computedStyle.borderBottomWidth + ' ' + computedStyle.borderBottomStyle + ' ' + borderColorR + ' ' + borderColorB16 + ' ' + DebugJS.getColorBlock(borderColorB) + '\n' + ' left : ' + computedStyle.borderLeftWidth + ' ' + computedStyle.borderLeftStyle + ' ' + borderColorL + ' ' + borderColorL16 + ' ' + DebugJS.getColorBlock(borderColorL); var allStyles = ''; var MIN_KEY_LEN = 20; for (var k in computedStyle) { if (!(k.match(/^\d.*/))) { if (typeof computedStyle[k] != 'function') { var indent = ''; if (k.length < MIN_KEY_LEN) { for (var i = 0; i < (MIN_KEY_LEN - k.length); i++) { indent += ' '; } } allStyles += ' ' + k + indent + ': ' + computedStyle[k] + '\n'; } } } allStylesFolding = ctx.createFoldingText(allStyles, 'allStyles', DebugJS.OMIT_LAST, 0, OMIT_STYLE, ctx.elmInfoShowHideStatus.allStyles); var name = (el.name == undefined) ? DebugJS.setStyleIfObjNA(el.name) : DebugJS.escTags(el.name); var val = (el.value == undefined) ? DebugJS.setStyleIfObjNA(el.value) : DebugJS.escSpclChr(el.value); var html = '<span style="color:#8f0;display:inline-block;height:14px">#text</span> ' + txt + '\n' + DebugJS.addPropSep(ctx) + 'id : ' + el.id + '\n' + 'className : ' + className + '\n' + DebugJS.addPropSep(ctx) + 'object : ' + Object.prototype.toString.call(el) + '\n' + 'tagName : ' + el.tagName + '\n' + 'type : ' + DebugJS.setStyleIfObjNA(el.type) + '\n' + DebugJS.addPropSep(ctx) + 'display : ' + computedStyle.display + '\n' + 'position : ' + computedStyle.position + '\n' + 'z-index : ' + computedStyle.zIndex + '\n' + 'float : ' + computedStyle.cssFloat + ' / clear: ' + computedStyle.clear + '\n' + 'size : W:' + ((rectR - rectL) + 1) + ' x H:' + ((rectB - rectT) + 1) + ' px\n' + 'margin : ' + computedStyle.marginTop + ' ' + computedStyle.marginRight + ' ' + computedStyle.marginBottom + ' ' + computedStyle.marginLeft + '\n' + 'border : ' + borderT + ' ' + ctx.createFoldingText(borderRBL, 'elBorder', DebugJS.OMIT_LAST, 0, OMIT_STYLE, ctx.elmInfoShowHideStatus.elBorder) + '\n' + 'padding : ' + computedStyle.paddingTop + ' ' + computedStyle.paddingRight + ' ' + computedStyle.paddingBottom + ' ' + computedStyle.paddingLeft + '\n' + 'lineHeight: ' + computedStyle.lineHeight + '\n' + DebugJS.addPropSep(ctx) + 'location : <span style="color:#aaa">winOffset + pageOffset = pos (computedStyle)</span>\n' + ' top : ' + rectT + ' + ' + window.pageYOffset + ' = ' + Math.round(rect.top + window.pageYOffset) + ' px (' + computedStyle.top + ')\n' + ' left : ' + rectL + ' + ' + window.pageXOffset + ' = ' + Math.round(rect.left + window.pageXOffset) + ' px (' + computedStyle.left + ')\n' + ' right : ' + rectR + ' + ' + window.pageXOffset + ' = ' + Math.round(rect.right + window.pageXOffset) + ' px (' + computedStyle.right + ')\n' + ' bottom: ' + rectB + ' + ' + window.pageYOffset + ' = ' + Math.round(rect.bottom + window.pageYOffset) + ' px (' + computedStyle.bottom + ')\n' + 'scroll : top = ' + el.scrollTop + ' / left = ' + el.scrollLeft + '\n' + 'overflow : ' + computedStyle.overflow + '\n' + 'opacity : ' + computedStyle.opacity + '\n' + DebugJS.addPropSep(ctx) + 'bg-color : ' + backgroundColor + ' ' + bgColor16 + ' ' + DebugJS.getColorBlock(backgroundColor) + '\n' + 'bg-image : ' + ctx.createFoldingText(computedStyle.backgroundImage, 'bgimg', DebugJS.OMIT_LAST, -1, OMIT_STYLE) + '\n' + 'color : ' + color + ' ' + color16 + ' ' + DebugJS.getColorBlock(color) + '\n' + 'font : -size : ' + computedStyle.fontSize + '\n' + ' -family: ' + computedStyle.fontFamily + '\n' + ' -weight: ' + computedStyle.fontWeight + '\n' + ' -style : ' + computedStyle.fontStyle + '\n' + DebugJS.addPropSep(ctx) + 'All Styles: window.getComputedStyle(element) ' + allStylesFolding + '\n' + DebugJS.addPropSep(ctx) + 'action : ' + DebugJS.setStyleIfObjNA(el.action) + '\n' + 'method : ' + DebugJS.setStyleIfObjNA(el.method) + '\n' + 'name : ' + name + '\n' + 'value : ' + ctx.createFoldingText(val, 'elValue', DebugJS.OMIT_LAST, MAX_LEN, OMIT_STYLE) + '\n' + 'disabled : ' + DebugJS.setStyleIfObjNA(el.disabled, true) + '\n' + 'hidden : ' + el.hidden + '\n' + 'tabIndex : ' + el.tabIndex + '\n' + 'accessKey : ' + el.accessKey + '\n' + 'maxLength : ' + DebugJS.setStyleIfObjNA(el.maxLength) + '\n' + 'checked : ' + DebugJS.setStyleIfObjNA(el.checked, true) + '\n' + 'htmlFor : ' + DebugJS.setStyleIfObjNA(el.htmlFor) + '\n' + 'selectedIndex: ' + DebugJS.setStyleIfObjNA(el.selectedIndex) + '\n' + 'contentEditable: ' + el.contentEditable + '\n' + DebugJS.addPropSep(ctx) + 'href : ' + href + '\n' + 'src : ' + src + '\n' + DebugJS.addPropSep(ctx) + 'onclick : ' + ctx.getEvtHandlerStr(el.onclick, 'elOnclick') + '\n' + 'ondblclick : ' + ctx.getEvtHandlerStr(el.ondblclick, 'elOnDblClick') + '\n' + 'onmousedown : ' + ctx.getEvtHandlerStr(el.onmousedown, 'elOnMouseDown') + '\n' + 'onmouseup : ' + ctx.getEvtHandlerStr(el.onmouseup, 'elOnMouseUp') + '\n' + 'onmouseover : ' + ctx.getEvtHandlerStr(el.onmouseover, 'elOnMouseOver') + '\n' + 'onmouseout : ' + ctx.getEvtHandlerStr(el.onmouseout, 'elOnMouseOut') + '\n' + 'onmousemove : ' + ctx.getEvtHandlerStr(el.onmousemove, 'elOnMouseMove') + '\n' + 'oncontextmenu: ' + ctx.getEvtHandlerStr(el.oncontextmenu, 'elOnContextmenu') + '\n' + DebugJS.addPropSep(ctx) + 'onkeydown : ' + ctx.getEvtHandlerStr(el.onkeydown, 'elOnKeyDown') + '\n' + 'onkeypress : ' + ctx.getEvtHandlerStr(el.onkeypress, 'elOnKeyPress') + '\n' + 'onkeyup : ' + ctx.getEvtHandlerStr(el.onkeyup, 'elOnKeyUp') + '\n' + DebugJS.addPropSep(ctx) + 'onfocus : ' + ctx.getEvtHandlerStr(el.onfocus, 'elOnFocus') + '\n' + 'onblur : ' + ctx.getEvtHandlerStr(el.onblur, 'elOnBlur') + '\n' + 'onchange : ' + ctx.getEvtHandlerStr(el.onchange, 'elOnChange') + '\n' + 'oninput : ' + ctx.getEvtHandlerStr(el.oninput, 'elOnInput') + '\n' + 'onselect : ' + ctx.getEvtHandlerStr(el.onselect, 'elOnSelect') + '\n' + 'onselectstart: ' + ctx.getEvtHandlerStr(el.onselectstart, 'elOnSelectStart') + '\n' + 'onsubmit : ' + ctx.getEvtHandlerStr(el.onsubmit, 'elOnSubmit') + '\n' + DebugJS.addPropSep(ctx) + 'onscroll : ' + ctx.getEvtHandlerStr(el.onscroll, 'elOnScroll') + '\n' + DebugJS.addPropSep(ctx) + 'dataset (data-*):\n'; if (el.dataset) { html += '{' + ((Object.keys(el.dataset).length > 0) ? '\n' : ''); for (var data in el.dataset) { html += ' ' + data + ': ' + el.dataset[data] + '\n'; } html += '}'; } else { html += '<span style="color:#aaa">' + el.dataset + '</span>'; } var htmlSrc = (el.outerHTML ? el.outerHTML.replace(/</g, '&lt;').replace(/>/g, '&gt;') : DebugJS.setStyleIfObjNA(el.outerHTML)); htmlSrc = ctx.createFoldingText(htmlSrc, 'htmlSrc', DebugJS.OMIT_LAST, 0, OMIT_STYLE, ctx.elmInfoShowHideStatus.htmlSrc); html += DebugJS.addPropSep(ctx) + 'outerHTML: ' + htmlSrc; return html; }, showPrevElem: function() { var ctx = DebugJS.ctx; if (!ctx.targetEl) return; var el = ctx.getPrevElm(ctx, ctx.targetEl); if (el) { ctx.showElementInfo(el); ctx.updateTargetElm(el); } }, showNextElem: function() { var ctx = DebugJS.ctx; if (!ctx.targetEl) return; var el = ctx.getNextElm(ctx, ctx.targetEl); if (el) { ctx.showElementInfo(el); ctx.updateTargetElm(el); } }, getPrevElm: function(ctx, targetElm) { var el = targetElm.previousElementSibling; if ((el != null) && (el.id == ctx.id)) { el = targetElm.previousElementSibling; } if (el == null) { el = targetElm.parentNode; } else { if (el.childElementCount > 0) { var lastChild = el.lastElementChild; while (lastChild.childElementCount > 0) { lastChild = lastChild.lastElementChild; } el = lastChild; } } if (el instanceof HTMLDocument) el = null; return el; }, getNextElm: function(ctx, targetElm) { var el = targetElm.firstElementChild; if ((el == null) || ((el != null) && (el.id == ctx.id))) { el = targetElm.nextElementSibling; if (el == null) { var parent = targetElm.parentNode; if (parent) { do { el = parent.nextElementSibling; if ((el != null) && (el.id != ctx.id)) { break; } parent = parent.parentNode; } while ((parent != null) && (parent.tagName != 'HTML')); } } } return el; }, updateTargetElm: function(el) { var ctx = DebugJS.ctx; if (ctx.elmInfoStatus & DebugJS.ELMINFO_ST_HIGHLIGHT) { ctx.highlightElement(ctx.targetEl, el); } if (el) { ctx.targetEl = el; ctx.enablePrevElBtn(ctx, (ctx.getPrevElm(ctx, el) ? true : false)); ctx.enableNextElBtn(ctx, (ctx.getNextElm(ctx, el) ? true : false)); ctx.setStyle(ctx.elmUpdateBtn, 'color', ctx.opt.btnColor); ctx.setStyle(ctx.elmCapBtn, 'color', ctx.opt.btnColor); ctx.setStyle(ctx.elmDelBtn, 'color', '#a88'); } }, highlightElement: function(removeTarget, setTarget) { if ((removeTarget) && (typeof removeTarget.className == 'string')) { DebugJS.removeClass(removeTarget, DebugJS.ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX); } if ((setTarget) && (typeof setTarget.className == 'string')) { DebugJS.addClass(setTarget, DebugJS.ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX); } }, enablePrevElBtn: function(ctx, f) { ctx.setStyle(ctx.elmPrevBtn, 'color', (f ? ctx.opt.btnColor : DebugJS.COLOR_INACT)); }, enableNextElBtn: function(ctx, f) { ctx.setStyle(ctx.elmNextBtn, 'color', (f ? ctx.opt.btnColor : DebugJS.COLOR_INACT)); }, updateElementInfo: function() { DebugJS.ctx.showAllElmNum(); DebugJS.ctx.showElementInfo(DebugJS.ctx.targetEl); }, showAllElmNum: function() { DebugJS.ctx.elmNumPanel.innerHTML = '(All: ' + document.getElementsByTagName('*').length + ')'; }, onchangeElmUpdateInterval: function() { var ctx = DebugJS.ctx; var v = ctx.elmUpdateInput.value; if (v == '') v = 0; if (isFinite(v)) { ctx.elmUpdateInterval = v; clearTimeout(ctx.elmUpdateTimerId); ctx.elmUpdateTimerId = setTimeout(ctx.updateElmInfoInterval, v); } }, updateElmInfoInterval: function() { var ctx = DebugJS.ctx; if (!(ctx.status & DebugJS.ST_ELM_INSPECTING)) return; ctx.updateElementInfo(); if (ctx.elmUpdateInterval > 0) { ctx.elmUpdateTimerId = setTimeout(ctx.updateElmInfoInterval, ctx.elmUpdateInterval); } }, toggleElmSelectMode: function() { var ctx = DebugJS.ctx; if (ctx.elmInfoStatus & DebugJS.ELMINFO_ST_SELECT) { ctx.elmInfoStatus &= ~DebugJS.ELMINFO_ST_SELECT; } else { ctx.elmInfoStatus |= DebugJS.ELMINFO_ST_SELECT; } ctx.updateElmSelectBtn(); }, updateElmSelectBtn: function() { DebugJS.ctx.setStyle(DebugJS.ctx.elmSelectBtn, 'color', (DebugJS.ctx.elmInfoStatus & DebugJS.ELMINFO_ST_SELECT) ? DebugJS.ctx.opt.btnColor : DebugJS.COLOR_INACT); }, toggleElmHlMode: function() { var ctx = DebugJS.ctx; if (ctx.elmInfoStatus & DebugJS.ELMINFO_ST_HIGHLIGHT) { ctx.elmInfoStatus &= ~DebugJS.ELMINFO_ST_HIGHLIGHT; ctx.highlightElement(ctx.targetEl, null); } else { ctx.elmInfoStatus |= DebugJS.ELMINFO_ST_HIGHLIGHT; ctx.highlightElement(null, ctx.targetEl); } ctx.updateElmHighlightBtn(); }, updateElmHighlightBtn: function() { DebugJS.ctx.setStyle(DebugJS.ctx.elmHighlightBtn, 'color', (DebugJS.ctx.elmInfoStatus & DebugJS.ELMINFO_ST_HIGHLIGHT) ? DebugJS.ctx.opt.btnColor : DebugJS.COLOR_INACT); }, exportTargetElm: function() { if (DebugJS.ctx.targetEl) DebugJS.ctx.captureElm(DebugJS.ctx.targetEl); }, captureElm: function(elm) { DebugJS.el = elm; if (DebugJS.G_EL_AVAILABLE) el = elm; if (DebugJS.ctx.status & DebugJS.ST_ELM_EDIT) { DebugJS.ctx.updateEditable(DebugJS.ctx, elm); } DebugJS._log.s('&lt;' + elm.tagName + '&gt; object has been exported to <span style="color:' + DebugJS.KEYWORD_COLOR + '">' + (DebugJS.G_EL_AVAILABLE ? 'el' : ((dbg == DebugJS) ? 'dbg' : 'DebugJS') + '.el') + '</span>'); }, delTargetElm: function() { var e = DebugJS.ctx.targetEl; if (e) { var p = e.parentNode; if (p) { p.removeChild(e); DebugJS.ctx.showElementInfo(p); DebugJS.ctx.updateTargetElm(p); } } }, updateEditable: function(ctx, el) { if ((ctx.txtChkTargetEl) && (ctx.txtChkTargetEl.contentEditableBak)) { ctx.txtChkTargetEl.contentEditable = ctx.txtChkTargetEl.contentEditableBak; } ctx.txtChkTargetEl = el; ctx.txtChkTargetEl.contentEditableBak = el.contentEditable; ctx.txtChkTargetEl.contentEditable = true; }, getEvtHandlerStr: function(handler, name) { var MAX_LEN = 300; var s = ''; if (handler) { s = handler.toString(); s = s.replace(/\n/g, ''); s = s.replace(/[^.]{1,}\{/, ''); s = s.replace(/\}$/, ''); s = s.replace(/^\s{1,}/, ''); } else { s = '<span style="color:#aaa">null</span>'; } s = DebugJS.ctx.createFoldingText(s, name, DebugJS.OMIT_LAST, MAX_LEN, 'color:#888'); return s; }, toggleHtmlSrc: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_HTML_SRC) { ctx.closeHtmlSrc(ctx); } else { ctx.openHtmlSrc(ctx); } }, openHtmlSrc: function(ctx) { ctx.status |= DebugJS.ST_HTML_SRC; ctx.featStack.push(DebugJS.ST_HTML_SRC); if (!ctx.htmlSrcPanel) ctx.createHtmlSrcPanel(ctx); ctx.updateHtmlSrcBtn(ctx); ctx.showHtmlSrc(); }, createHtmlSrcPanel: function(ctx) { ctx.htmlSrcPanel = document.createElement('div'); if (DebugJS.HTML_SRC_FULL_OVERLAY) { ctx.htmlSrcPanel.className = 'dbg-overlay-panel-full'; ctx.addOverlayPanelFull(ctx.htmlSrcPanel); } else { ctx.htmlSrcPanel.className = 'dbg-overlay-panel'; ctx.addOverlayPanel(ctx, ctx.htmlSrcPanel); } if (DebugJS.HTML_SRC_EXPAND_H) ctx.expandHightIfNeeded(ctx); ctx.htmlSrcHeaderPanel = document.createElement('div'); ctx.htmlSrcPanel.appendChild(ctx.htmlSrcHeaderPanel); ctx.htmlSrcTitle = document.createElement('span'); ctx.setStyle(ctx.htmlSrcTitle, 'color', DebugJS.HTML_BTN_COLOR); ctx.htmlSrcTitle.innerText = 'HTML SOURCE'; ctx.htmlSrcHeaderPanel.appendChild(ctx.htmlSrcTitle); var UPDATE_COLOR = '#fff'; ctx.htmlSrcUpdInpLbl2 = document.createElement('span'); ctx.htmlSrcUpdInpLbl2.style.float = 'right'; ctx.htmlSrcUpdInpLbl2.style.marginLeft = '2px'; ctx.setStyle(ctx.htmlSrcUpdInpLbl2, 'color', UPDATE_COLOR); ctx.htmlSrcUpdInpLbl2.innerText = 'ms'; ctx.htmlSrcHeaderPanel.appendChild(ctx.htmlSrcUpdInpLbl2); ctx.htmlSrcUpdateInput = DebugJS.ui.addTextInput(ctx.htmlSrcHeaderPanel, '50px', 'right', UPDATE_COLOR, ctx.htmlSrcUpdateInterval, ctx.onchangeHtmlSrcUpdateInterval); ctx.htmlSrcUpdateInput.style.float = 'right'; ctx.htmlSrcUpdInpLbl = document.createElement('span'); ctx.htmlSrcUpdInpLbl.style.float = 'right'; ctx.setStyle(ctx.htmlSrcUpdInpLbl, 'color', UPDATE_COLOR); ctx.htmlSrcUpdInpLbl.innerText = ':'; ctx.htmlSrcHeaderPanel.appendChild(ctx.htmlSrcUpdInpLbl); ctx.htmlSrcUpdBtn = DebugJS.ui.addBtn(ctx.htmlSrcHeaderPanel, 'UPDATE', ctx.showHtmlSrc); ctx.htmlSrcUpdBtn.style.float = 'right'; ctx.htmlSrcUpdBtn.style.marginLeft = '4px'; ctx.setStyle(ctx.htmlSrcUpdBtn, 'color', ctx.opt.btnColor); ctx.htmlSrcBodyPanel = document.createElement('div'); ctx.htmlSrcBodyPanel.style.width = '100%'; ctx.htmlSrcBodyPanel.style.height = 'calc(100% - 1.3em)'; ctx.htmlSrcBodyPanel.style.overflow = 'auto'; ctx.htmlSrcPanel.appendChild(ctx.htmlSrcBodyPanel); ctx.htmlSrcBody = document.createElement('pre'); ctx.htmlSrcBodyPanel.appendChild(ctx.htmlSrcBody); }, closeHtmlSrc: function(ctx) { if (ctx.htmlSrcPanel) { if (DebugJS.HTML_SRC_FULL_OVERLAY) { ctx.removeOverlayPanelFull(ctx.htmlSrcPanel); } else { ctx.removeOverlayPanel(ctx, ctx.htmlSrcPanel); } if (DebugJS.HTML_SRC_EXPAND_H) ctx.resetExpandedHeightIfNeeded(ctx); ctx.htmlSrcPanel = null; } ctx.status &= ~DebugJS.ST_HTML_SRC; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_HTML_SRC); ctx.updateHtmlSrcBtn(ctx); }, showHtmlSrc: function() { var ctx = DebugJS.ctx; ctx.htmlSrcBodyPanel.removeChild(ctx.htmlSrcBody); var html = document.getElementsByTagName('html')[0].outerHTML.replace(/</g, '&lt;').replace(/>/g, '&gt;'); ctx.htmlSrcBodyPanel.appendChild(ctx.htmlSrcBody); ctx.htmlSrcBody.innerHTML = html; }, onchangeHtmlSrcUpdateInterval: function() { var ctx = DebugJS.ctx; var interval = ctx.htmlSrcUpdateInput.value; if (interval == '') interval = 0; if (isFinite(interval)) { ctx.htmlSrcUpdateInterval = interval; clearTimeout(ctx.htmlSrcUpdateTimerId); ctx.htmlSrcUpdateTimerId = setTimeout(ctx.updateHtmlSrcInterval, ctx.htmlSrcUpdateInterval); } }, updateHtmlSrcInterval: function() { var ctx = DebugJS.ctx; if (!(ctx.status & DebugJS.ST_HTML_SRC)) return; ctx.showHtmlSrc(); if (ctx.htmlSrcUpdateInterval > 0) { ctx.elmUpdateTimerId = setTimeout(ctx.updateHtmlSrcInterval, ctx.htmlSrcUpdateInterval); } }, toggleJs: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_JS) { ctx.closeJsEditor(); } else { ctx.openJsEditor(ctx); } }, openJsEditor: function(ctx) { ctx.status |= DebugJS.ST_JS; ctx.featStack.push(DebugJS.ST_JS); if (!ctx.jsPanel) ctx.createJsPanel(ctx); ctx.updateJsBtn(ctx); ctx.jsEditor.focus(); }, createJsPanel: function(ctx) { ctx.jsPanel = document.createElement('div'); ctx.jsPanel.className = 'dbg-overlay-panel'; var html = '<div class="dbg-btn dbg-nomove" ' + 'style="position:relative;top:-1px;float:right;' + 'font-size:' + (18 * ctx.opt.zoom) + 'px;color:#888 !important" ' + 'onclick="DebugJS.ctx.closeJsEditor();" ' + 'onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'#d88\');" ' + 'onmouseout="DebugJS.ctx.setStyle(this, \'color\', \'#888\');">x</div>' + '<span style="color:#ccc">JS Editor</span>' + DebugJS.ui.createBtnHtml('[EXEC]', 'DebugJS.ctx.execJavaScript();', 'float:right;margin-right:4px') + DebugJS.ui.createBtnHtml('[CLR]', 'DebugJS.ctx.insertJsSnippet();', 'margin-left:4px;margin-right:4px'); for (var i = 0; i < 5; i++) { html += ctx.createJsSnippetBtn(ctx, i); } ctx.jsPanel.innerHTML = html; ctx.addOverlayPanel(ctx, ctx.jsPanel); ctx.jsEditor = document.createElement('textarea'); ctx.jsEditor.className = 'dbg-editor'; ctx.jsEditor.onblur = ctx.saveJsBuf; ctx.jsEditor.value = ctx.jsBuf; ctx.enableDnDFileLoad(ctx.jsEditor, ctx.onDropOnJS); ctx.jsPanel.appendChild(ctx.jsEditor); }, createJsSnippetBtn: function(ctx, i) { return DebugJS.ui.createBtnHtml('{CODE' + (i + 1) + '}', 'DebugJS.ctx.insertJsSnippet(' + i + ');', 'margin-left:4px'); }, insertJsSnippet: function(n) { var editor = DebugJS.ctx.jsEditor; if (n == undefined) { editor.value = ''; editor.focus(); } else { var code = DebugJS.JS_SNIPPET[n]; var buf = editor.value; var posCursor = editor.selectionStart; var bufL = buf.substr(0, posCursor); var bufR = buf.substr(posCursor, buf.length); buf = bufL + code + bufR; DebugJS.ctx.jsEditor.focus(); DebugJS.ctx.jsEditor.value = buf; editor.selectionStart = editor.selectionEnd = posCursor + code.length; } }, saveJsBuf: function() { DebugJS.ctx.jsBuf = DebugJS.ctx.jsEditor.value; }, execJavaScript: function() { DebugJS.ctx.execCode(DebugJS.ctx.jsBuf, true); }, execCode: function(code, echo) { if (code == '') return; try { var r = eval(code); var res = r; if (typeof r == 'string') { res = DebugJS.quoteStr(r); } if (echo) DebugJS._log.res(res); return r; } catch (e) { DebugJS._log.e(e); } }, closeJsEditor: function() { var ctx = DebugJS.ctx; if (ctx.jsPanel) { ctx.removeOverlayPanel(ctx, ctx.jsPanel); ctx.jsPanel = null; } ctx.status &= ~DebugJS.ST_JS; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_JS); ctx.updateJsBtn(ctx); }, toggleTools: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_TOOLS) { ctx.closeTools(ctx); } else { ctx.openTools(ctx); } }, openTools: function(ctx) { ctx.status |= DebugJS.ST_TOOLS; ctx.featStack.push(DebugJS.ST_TOOLS); if (!ctx.toolsPanel) ctx.createToolsPanel(ctx); ctx.addOverlayPanelFull(ctx.toolsPanel); ctx.resizeImgPreview(); ctx.switchToolsFunction(ctx.toolsActiveFnc); ctx.updateToolsBtns(); ctx.updateToolsBtn(ctx); }, isAvailableTools: function(ctx) { return (ctx.win && ctx.opt.useTools); }, createToolsPanel: function(ctx) { var p = ctx.createSubBasePanel(ctx); ctx.toolsPanel = p.base; ctx.toolsHeaderPanel = p.head; ctx.toolsBodyPanel = p.body; ctx.timerBtn = ctx.createToolsHeaderBtn('TIMER', 'TOOLS_FNC_TIMER', 'timerBtn'); ctx.txtChkBtn = ctx.createToolsHeaderBtn('TEXT', 'TOOLS_FNC_TEXT', 'txtChkBtn'); ctx.htmlPrevBtn = ctx.createToolsHeaderBtn('HTML', 'TOOLS_FNC_HTML', 'htmlPrevBtn'); ctx.fileVwrBtn = ctx.createToolsHeaderBtn('FILE', 'TOOLS_FNC_FILE', 'fileVwrBtn'); ctx.batBtn = ctx.createToolsHeaderBtn('BAT', 'TOOLS_FNC_BAT', 'batBtn'); }, createToolsHeaderBtn: function(label, state, btnObj) { var fn = new Function('DebugJS.ctx.switchToolsFunction(DebugJS.' + state + ');'); var btn = DebugJS.ui.addBtn(DebugJS.ctx.toolsHeaderPanel, '<' + label + '>', fn); btn.style.marginRight = '4px'; btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', DebugJS.SBPNL_COLOR_ACTIVE);'); btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', (DebugJS.ctx.toolsActiveFnc & DebugJS.' + state + ') ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT);'); return btn; }, closeTools: function(ctx) { if (ctx.toolsPanel) { ctx.removeOverlayPanelFull(ctx.toolsPanel); ctx.switchToolsFunction(0); } ctx.status &= ~DebugJS.ST_TOOLS; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_TOOLS); ctx.updateToolsBtn(ctx); }, updateToolsBtns: function() { var ctx = DebugJS.ctx; ctx.setStyle(ctx.timerBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_TIMER) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); ctx.setStyle(ctx.txtChkBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_TEXT) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); ctx.setStyle(ctx.htmlPrevBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_HTML) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); ctx.setStyle(ctx.fileVwrBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_FILE) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); ctx.setStyle(ctx.batBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_BAT) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); }, switchToolsFunction: function(kind, param) { var ctx = DebugJS.ctx; if (kind & DebugJS.TOOLS_FNC_TIMER) { ctx.openTimer(param); } else { ctx.closeTimer(); } if (kind & DebugJS.TOOLS_FNC_TEXT) { ctx.openTextChecker(); } else { ctx.closeTextChecker(); } if (kind & DebugJS.TOOLS_FNC_HTML) { ctx.openHtmlEditor(); } else { ctx.closeHtmlEditor(); } if (kind & DebugJS.TOOLS_FNC_FILE) { ctx.openFileLoader(param); } else { ctx.closeFileLoader(); } if (kind & DebugJS.TOOLS_FNC_BAT) { ctx.openBatEditor(); } else { ctx.closeBatEditor(); } if (kind) ctx.toolsActiveFnc = kind; ctx.updateToolsBtns(); }, removeToolFuncPanel: function(ctx, panel) { if (panel.parentNode) { ctx.toolsBodyPanel.removeChild(panel); } }, openTimer: function(mode) { var ctx = DebugJS.ctx; if (!ctx.timerBasePanel) { ctx.createTimerBasePanel(ctx); } else { ctx.toolsBodyPanel.appendChild(ctx.timerBasePanel); } ctx.setIntervalH(ctx); if ((mode != undefined) && (mode !== '')) { ctx.switchTimerMode(mode); } else { switch (ctx.toolTimerMode) { case DebugJS.TOOL_TIMER_MODE_CLOCK: ctx.updateTimerClock(); break; case DebugJS.TOOL_TIMER_MODE_SW_CU: ctx.updateTimerStopwatchCu(); break; case DebugJS.TOOL_TIMER_MODE_SW_CD: ctx.updateTimerStopwatchCd(); } } }, createTimerBasePanel: function(ctx) { var baseFontSize = ctx.computedFontSize; var fontSize = baseFontSize * 6.5; ctx.timerBasePanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); ctx.timerBasePanel.style.position = 'absolute'; ctx.timerBasePanel.style.height = baseFontSize * 21 + 'px'; ctx.timerBasePanel.style.top = '0'; ctx.timerBasePanel.style.bottom = '0'; ctx.timerBasePanel.style.margin = 'auto'; ctx.setStyle(ctx.timerBasePanel, 'font-size', fontSize + 'px'); ctx.timerBasePanel.style.lineHeight = '1em'; ctx.timerBasePanel.style.textAlign = 'center'; ctx.toolsBodyPanel.appendChild(ctx.timerBasePanel); ctx.createTimerClockSubPanel(); ctx.createTimerStopwatchCuSubPanel(); ctx.createTimerStopwatchCdSubPanel(); ctx.createTimerStopwatchCdInpSubPanel(); if (!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) && !(ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED)) { ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_RST; } ctx.switchTimerMode(ctx.toolTimerMode); }, createTimerClockSubPanel: function() { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize; var btnFontSize = fontSize * 3; ctx.timerClockSubPanel = document.createElement('div'); var marginB = 20 * ctx.opt.zoom; ctx.timerClockLabel = document.createElement('div'); ctx.timerClockLabel.style.marginBottom = marginB + 'px'; ctx.timerClockSubPanel.appendChild(ctx.timerClockLabel); var btns = document.createElement('div'); btns.style.borderTop = 'solid 2px ' + ctx.opt.timerLineColor; btns.style.paddingTop = fontSize + 'px'; btns.style.lineHeight = btnFontSize + 'px'; ctx.timerClockSubPanel.appendChild(btns); ctx.createTimerBtn(btns, 'MODE', ctx.toggleTimerMode, false, btnFontSize); ctx.createTimerBtn(btns, 'RESET', null, true, btnFontSize); ctx.createTimerBtn(btns, '>>', null, true, btnFontSize); ctx.createTimerBtn(btns, 'SPLIT', null, true, btnFontSize); ctx.clockSSSbtn = ctx.createTimerBtn(btns, 'sss', ctx.toggleSSS, false, (fontSize * 1.5)); ctx.updateSSS(ctx); }, toggleSSS: function() { var ctx = DebugJS.ctx; ctx.timerClockSSS = (ctx.timerClockSSS ? false : true); ctx.updateSSS(ctx); }, updateSSS: function(ctx) { var color = (ctx.timerClockSSS ? DebugJS.TOOL_TIMER_BTN_COLOR : '#888'); ctx.setStyle(ctx.clockSSSbtn, 'color', color); }, createTimerStopwatchSubPanel: function(ctx, handlers) { var panel = { basePanel: null, stopWatchLabel: null, btns: null, startStopBtn: null, splitBtn: null }; var fontSize = ctx.computedFontSize; var btnFontSize = fontSize * 3; panel.basePanel = document.createElement('div'); var marginT = 40 * ctx.opt.zoom; var marginB = 39 * ctx.opt.zoom; panel.stopWatchLabel = document.createElement('div'); panel.stopWatchLabel.style.margin = marginT + 'px 0 ' + marginB + 'px 0'; panel.basePanel.appendChild(panel.stopWatchLabel); var btns = document.createElement('div'); btns.style.borderTop = 'solid 2px ' + ctx.opt.timerLineColor; btns.style.paddingTop = fontSize + 'px'; btns.style.lineHeight = btnFontSize + 'px'; panel.basePanel.appendChild(btns); ctx.createTimerBtn(btns, 'MODE', ctx.toggleTimerMode, false, btnFontSize); ctx.createTimerBtn(btns, 'RESET', handlers.reset, false, btnFontSize); panel.startStopBtn = ctx.createTimerBtn(btns, '>>', handlers.startStop, false, btnFontSize); panel.splitBtn = ctx.createTimerBtn(btns, 'SPLIT', handlers.split, false, btnFontSize); panel.btns = btns; return panel; }, createTimerStopwatchCuSubPanel: function() { var ctx = DebugJS.ctx; var handlers = { reset: ctx.resetTimerStopwatchCu, startStop: ctx.startStopTimerStopwatchCu, split: ctx.splitTimerStopwatchCu }; var panel = ctx.createTimerStopwatchSubPanel(ctx, handlers); ctx.timerStopwatchCuSubPanel = panel.basePanel; ctx.timerStopwatchCuLabel = panel.stopWatchLabel; ctx.timerStartStopBtnCu = panel.startStopBtn; ctx.timerSplitBtnCu = panel.splitBtn; }, createTimerStopwatchCdSubPanel: function() { var ctx = DebugJS.ctx; var handlers = { reset: ctx.resetTimerStopwatchCd, startStop: ctx.startStopTimerStopwatchCd, split: ctx.splitTimerStopwatchCd }; var panel = ctx.createTimerStopwatchSubPanel(ctx, handlers); ctx.timerStopwatchCdSubPanel = panel.basePanel; ctx.timerStopwatchCdLabel = panel.stopWatchLabel; ctx.timerStartStopBtnCd = panel.startStopBtn; ctx.timerSplitBtnCd = panel.splitBtn; ctx.timer0CntBtnCd1 = ctx.createTimerBtn(panel.btns, '0=>', ctx.toggle0ContinueTimerStopwatchCd, false, (ctx.computedFontSize * 1.5)); ctx.update0ContinueBtnTimerStopwatchCd(); }, createTimerStopwatchCdInpSubPanel: function() { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize; var baseFontSize = fontSize * 6.5; var btnFontSize = fontSize * 3; var msFontSize = baseFontSize * 0.65; var basePanel = document.createElement('div'); var timerUpBtns = document.createElement('div'); timerUpBtns.style.margin = '0 0 -' + fontSize * 0.8 + 'px 0'; timerUpBtns.style.lineHeight = btnFontSize + 'px'; basePanel.appendChild(timerUpBtns); ctx.createTimerUpDwnBtn(true, 'hh', timerUpBtns, btnFontSize, 3); ctx.createTimerUpDwnBtn(true, 'mi', timerUpBtns, btnFontSize, 3); ctx.createTimerUpDwnBtn(true, 'ss', timerUpBtns, btnFontSize, 2.5); ctx.createTimerUpDwnBtn(true, 'sss', timerUpBtns, btnFontSize, 0); ctx.timerStopwatchCdInput = document.createElement('div'); ctx.timerStopwatchCdInput.style.margin = '0'; ctx.timerStopwatchCdInput.style.lineHeight = baseFontSize + 'px'; basePanel.appendChild(ctx.timerStopwatchCdInput); ctx.timerTxtHH = ctx.createTimerInput(ctx.timerStopwatchCdInput, DebugJS.timestr2struct(ctx.props.timer).hh, baseFontSize); ctx.createTimerInputLabel(ctx.timerStopwatchCdInput, ':', baseFontSize); ctx.timerTxtMI = ctx.createTimerInput(ctx.timerStopwatchCdInput, DebugJS.timestr2struct(ctx.props.timer).mi, baseFontSize); ctx.createTimerInputLabel(ctx.timerStopwatchCdInput, ':', baseFontSize); ctx.timerTxtSS = ctx.createTimerInput(ctx.timerStopwatchCdInput, DebugJS.timestr2struct(ctx.props.timer).ss, baseFontSize); ctx.createTimerInputLabel(ctx.timerStopwatchCdInput, '.', msFontSize); ctx.timerTxtSSS = ctx.createTimerInput(ctx.timerStopwatchCdInput, DebugJS.timestr2struct(ctx.props.timer).sss, msFontSize, '2em'); var timerDwnBtns = document.createElement('div'); var marginT = fontSize * 2; var marginB = fontSize * 1.2; timerDwnBtns.style.margin = '-' + marginT + 'px 0 ' + marginB + 'px 0'; timerDwnBtns.style.lineHeight = btnFontSize + 'px'; ctx.createTimerUpDwnBtn(false, 'hh', timerDwnBtns, btnFontSize, 3); ctx.createTimerUpDwnBtn(false, 'mi', timerDwnBtns, btnFontSize, 3); ctx.createTimerUpDwnBtn(false, 'ss', timerDwnBtns, btnFontSize, 2.5); ctx.createTimerUpDwnBtn(false, 'sss', timerDwnBtns, btnFontSize, 0); basePanel.appendChild(timerDwnBtns); var btns = document.createElement('div'); btns.style.borderTop = 'solid 2px ' + ctx.opt.timerLineColor; btns.style.paddingTop = fontSize + 'px'; btns.style.lineHeight = btnFontSize + 'px'; ctx.createTimerBtn(btns, 'MODE', ctx.toggleTimerMode, false, btnFontSize); ctx.createTimerBtn(btns, 'RESET', ctx.resetTimerStopwatchCd, false, btnFontSize); ctx.timerStartStopBtnCdInp = ctx.createTimerBtn(btns, '>>', ctx.startStopTimerStopwatchCd, false, btnFontSize); ctx.createTimerBtn(btns, 'SPLIT', null, true, btnFontSize); ctx.timer0CntBtnCd2 = ctx.createTimerBtn(btns, '0=>', ctx.toggle0ContinueTimerStopwatchCd, false, (fontSize * 1.5)); basePanel.appendChild(btns); ctx.timerStopwatchCdInpSubPanel = basePanel; }, createTimerInput: function(base, val, fontSize, width) { var ctx = DebugJS.ctx; var el = document.createElement('input'); el.className = 'dbg-timer-inp'; ctx.setStyle(el, 'margin-top', '-' + fontSize * 0.5 + 'px'); ctx.setStyle(el, 'font-size', fontSize + 'px'); if (width) ctx.setStyle(el, 'width', width); el.value = val; el.oninput = ctx.updatePropTimer; base.appendChild(el); return el; }, createTimerInputLabel: function(base, label, fontSize) { var el = document.createElement('span'); el.innerText = label; DebugJS.ctx.setStyle(el, 'font-size', fontSize + 'px'); base.appendChild(el); }, createTimerBtn: function(base, label, handler, disabled, fontSize) { var btn = DebugJS.ui.addBtn(base, label, handler); btn.style.marginRight = '0.5em'; DebugJS.ctx.setStyle(btn, 'color', (disabled ? '#888' : DebugJS.TOOL_TIMER_BTN_COLOR)); if (fontSize) DebugJS.ctx.setStyle(btn, 'font-size', fontSize + 'px'); return btn; }, createTimerUpDwnBtn: function(up, part, area, fontSize, margin) { var lbl = (up ? '+' : '-'); var fn = new Function('DebugJS.ctx.timerUpDwn(\'' + part + '\', ' + up + ')'); var btn = DebugJS.ui.addBtn(area, lbl, fn); btn.style.marginRight = margin + 'em'; DebugJS.ctx.setStyle(btn, 'color', DebugJS.TOOL_TIMER_BTN_COLOR); DebugJS.ctx.setStyle(btn, 'font-size', fontSize + 'px'); return btn; }, timerUpDwn: function(part, up) { var val = DebugJS.ctx.calcTimeupTimeInp(); var ms = {'hh': 3600000, 'mi': 60000, 'ss': 1000, 'sss': 1}; var v = (ms[part] === undefined ? 0 : ms[part]); if (up) { val += v; } else { if (val >= v) val -= v; } DebugJS.ctx.updateTimeupTimeInp(val); DebugJS.ctx.drawStopwatchCd(); }, updatePropTimer: function(v) { var ctx = DebugJS.ctx; ctx.props.timer = ctx.timerTxtHH.value + ':' + ctx.timerTxtMI.value + ':' + ctx.timerTxtSS.value + '.' + ctx.timerTxtSSS.value; }, calcTimeupTimeInp: function() { var ctx = DebugJS.ctx; var h = (ctx.timerTxtHH.value | 0) * 3600000; var m = (ctx.timerTxtMI.value | 0) * 60000; var s = (ctx.timerTxtSS.value | 0) * 1000; var ms = (ctx.timerTxtSSS.value | 0); return h + m + s + ms; }, updateTimeupTimeInp: function(v) { var ctx = DebugJS.ctx; var tm = DebugJS.ms2struct(v, true); ctx.timerTxtHH.value = tm.hh; ctx.timerTxtMI.value = tm.mi; ctx.timerTxtSS.value = tm.ss; ctx.timerTxtSSS.value = tm.sss; ctx.updatePropTimer(); }, toggleTimerMode: function() { var a = [DebugJS.TOOL_TIMER_MODE_CLOCK, DebugJS.TOOL_TIMER_MODE_SW_CU, DebugJS.TOOL_TIMER_MODE_SW_CD]; var nextMode = DebugJS.nextArr(a, DebugJS.ctx.toolTimerMode); DebugJS.ctx.switchTimerMode(nextMode); }, switchTimerMode: function(mode) { if (mode == DebugJS.TOOL_TIMER_MODE_SW_CU) { DebugJS.ctx.switchTimerModeStopwatchCu(); } else if (mode == DebugJS.TOOL_TIMER_MODE_SW_CD) { DebugJS.ctx.switchTimerModeStopwatchCd(); } else { DebugJS.ctx.switchTimerModeClock(); } }, switchTimerModeClock: function() { var ctx = DebugJS.ctx; ctx.replaceTimerSubPanel(ctx.timerClockSubPanel); ctx.toolTimerMode = DebugJS.TOOL_TIMER_MODE_CLOCK; ctx.updateTimerClock(); }, switchTimerModeStopwatchCu: function() { var ctx = DebugJS.ctx; ctx.toolTimerMode = DebugJS.TOOL_TIMER_MODE_SW_CU; ctx.replaceTimerSubPanel(ctx.timerStopwatchCuSubPanel); ctx.drawStopwatchCu(); ctx.updateTimerStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, switchTimerModeStopwatchCd: function() { var ctx = DebugJS.ctx; ctx.toolTimerMode = DebugJS.TOOL_TIMER_MODE_SW_CD; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RST) { ctx.replaceTimerSubPanel(ctx.timerStopwatchCdInpSubPanel); } else { ctx.replaceTimerSubPanel(ctx.timerStopwatchCdSubPanel); ctx.drawStopwatchCd(); ctx.updateTimerStopwatchCd(); } ctx.updateTimerSwBtnsCd(); }, replaceTimerSubPanel: function(panel) { var ctx = DebugJS.ctx; for (var i = ctx.timerBasePanel.childNodes.length - 1; i >= 0; i--) { ctx.timerBasePanel.removeChild(ctx.timerBasePanel.childNodes[i]); } ctx.timerBasePanel.appendChild(panel); }, updateTimerClock: function() { var ctx = DebugJS.ctx; if ((!(ctx.status & DebugJS.ST_TOOLS)) || (ctx.toolTimerMode != DebugJS.TOOL_TIMER_MODE_CLOCK)) return; var tm = DebugJS.getDateTime(); ctx.timerClockLabel.innerHTML = ctx.createClockStr(tm); setTimeout(ctx.updateTimerClock, ctx.clockUpdInt); }, createClockStr: function(tm) { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize * 8; var dtFontSize = fontSize * 0.45; var ssFontSize = fontSize * 0.65; var msFontSize = fontSize * 0.45; var marginT = 20 * ctx.opt.zoom; var marginB = 10 * ctx.opt.zoom; var dot = '.'; if (tm.sss > 500) dot = '&nbsp;'; var date = tm.yyyy + '-' + tm.mm + '-' + tm.dd + ' <span style="color:#' + DebugJS.WDAYS_COLOR[tm.wday] + ' !important;font-size:' + dtFontSize + 'px !important">' + DebugJS.WDAYS[tm.wday] + '</span>'; var time = tm.hh + ':' + tm.mi + '<span style="margin-left:' + (ssFontSize / 5) + 'px;color:' + ctx.opt.fontColor + ' !important;font-size:' + ssFontSize + 'px !important">' + tm.ss + dot + '</span>'; if (ctx.timerClockSSS) { time += '<span style="font-size:' + msFontSize + 'px !important">' + tm.sss + '</span>'; marginB -= 16 * ctx.opt.zoom; } var s = '<div style="color:' + ctx.opt.fontColor + ' !important;font-size:' + dtFontSize + 'px !important">' + date + '</div>' + '<div style="color:' + ctx.opt.fontColor + ' !important;font-size:' + fontSize + 'px !important;margin:-' + marginT + 'px 0 ' + marginB + 'px 0">' + time + '</div>'; return s; }, startStopTimerStopwatchCu: function() { var ctx = DebugJS.ctx; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END) { ctx.resetTimerStopwatchCu(); } if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) { ctx.stopTimerStopwatchCu(); } else { ctx.startTimerStopwatchCu(); } }, startStopTimerStopwatchCd: function() { var ctx = DebugJS.ctx; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) { ctx.stopTimerStopwatchCd(); } else { ctx.startTimerStopwatchCd(); } }, startTimerStopwatchCu: function() { var ctx = DebugJS.ctx; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END) { ctx.resetTimerStopwatchCu(); } ctx.toolStatus |= DebugJS.TOOL_ST_SW_CU_RUNNING; DebugJS.time.restart(DebugJS.TIMER_NAME_SW_CU); ctx.updateTimerStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, stopTimerStopwatchCu: function() { var ctx = DebugJS.ctx; ctx.updateTimerStopwatchCu(); DebugJS.time.pause(DebugJS.TIMER_NAME_SW_CU); ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CU_RUNNING; ctx.drawStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, endTimerStopwatchCu: function() { var ctx = DebugJS.ctx; ctx.updateTimerStopwatchCu(); ctx.toolStatus |= DebugJS.TOOL_ST_SW_CU_END; ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CU_RUNNING; ctx.updateTimerStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, splitTimerStopwatchCu: function() { if (DebugJS.ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) { DebugJS.time._split(DebugJS.TIMER_NAME_SW_CU); } }, resetTimerStopwatchCu: function() { var ctx = DebugJS.ctx; ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CU_END; DebugJS.time.reset(DebugJS.TIMER_NAME_SW_CU); ctx.drawStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, updateTimerStopwatchCu: function() { var ctx = DebugJS.ctx; if ((!(ctx.status & DebugJS.ST_TOOLS)) || (ctx.toolTimerMode != DebugJS.TOOL_TIMER_MODE_SW_CU) || ((!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING)) && (!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END)))) return; if (!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END)) { DebugJS.time.updateCount(DebugJS.TIMER_NAME_SW_CU); } ctx.drawStopwatchCu(); setTimeout(ctx.updateTimerStopwatchCu, DebugJS.UPDATE_INTERVAL_H); }, drawStopwatchCu: function() { var ctx = DebugJS.ctx; var tm = DebugJS.ms2struct(DebugJS.time.getCount(DebugJS.TIMER_NAME_SW_CU), true); ctx.timerStopwatchCuLabel.innerHTML = ctx.createTimeStrCu(tm); }, updateTimerSwBtnsCu: function() { var ctx = DebugJS.ctx; if (!ctx.timerStartStopBtnCu) return; var btn = (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) ? '||' : '>>'; ctx.timerStartStopBtnCu.innerText = btn; ctx.updateTimerLapBtnCu(); }, updateTimerLapBtnCu: function() { var ctx = DebugJS.ctx; var color = '#888'; var fn = null; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) { color = DebugJS.TOOL_TIMER_BTN_COLOR; fn = ctx.splitTimerStopwatchCu; } ctx.setStyle(ctx.timerSplitBtnCu, 'color', color); ctx.timerSplitBtnCu.onclick = fn; }, toggle0ContinueTimerStopwatchCd: function() { var ctx = DebugJS.ctx; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) return; ctx.timerSwTimeCdContinue = (ctx.timerSwTimeCdContinue ? false : true); ctx.update0ContinueBtnTimerStopwatchCd(); }, update0ContinueBtnTimerStopwatchCd: function() { var ctx = DebugJS.ctx; var color = DebugJS.TOOL_TIMER_BTN_COLOR; if (ctx.timerSwTimeCdContinue) { if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { color = ctx.opt.timerColorExpr; } } else { color = '#888'; } ctx.setStyle(ctx.timer0CntBtnCd1, 'color', color); if (ctx.timer0CntBtnCd2) ctx.setStyle(ctx.timer0CntBtnCd2, 'color', color); }, startTimerStopwatchCd: function() { var ctx = DebugJS.ctx; var now = (new Date()).getTime(); if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_END) { ctx.resetTimerStopwatchCd(); } if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RST) { ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_RST; var timeup = ctx.calcTimeupTimeInp(); ctx.timerTimeUpTime = now + timeup; ctx.replaceTimerSubPanel(ctx.timerStopwatchCdSubPanel); } else { if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { ctx.timerTimeUpTime = now - ctx.timerSwTimeCd; } else { ctx.timerTimeUpTime = now + ctx.timerSwTimeCd; } } ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_RUNNING; ctx.updateTimerStopwatchCd(); ctx.updateTimerSwBtnsCd(); }, stopTimerStopwatchCd: function() { var ctx = DebugJS.ctx; ctx.updateTimerStopwatchCd(); ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_RUNNING; ctx.drawStopwatchCd(); ctx.updateTimerSwBtnsCd(); }, splitTimerStopwatchCd: function() { var ctx = DebugJS.ctx; var color = '#fff'; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { color = ctx.opt.timerColorExpr; } var t = DebugJS.TIMER_NAME_SW_CD + ': ' + '<span style="color:' + color + '">' + DebugJS.getTimerStr(ctx.timerSwTimeCd) + '</span>'; DebugJS._log(t); }, resetTimerStopwatchCd: function() { var ctx = DebugJS.ctx; ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_EXPIRED; ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_END; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) { var timeup = ctx.calcTimeupTimeInp(); ctx.timerTimeUpTime = (new Date()).getTime() + timeup; ctx.updateTimerStopwatchCd(); } else { ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_RST; ctx.replaceTimerSubPanel(ctx.timerStopwatchCdInpSubPanel); } ctx.updateTimerSwBtnsCd(); }, updateTimerStopwatchCd: function() { var ctx = DebugJS.ctx; if ((!(ctx.status & DebugJS.ST_TOOLS)) || (ctx.toolTimerMode != DebugJS.TOOL_TIMER_MODE_SW_CD) || ((!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING)) && (!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_END)))) return; var now = (new Date()).getTime(); if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { if (ctx.timerSwTimeCdContinue) { ctx.timerSwTimeCd = now - ctx.timerTimeUpTime; } } else { ctx.timerSwTimeCd = ctx.timerTimeUpTime - now; } if (ctx.timerSwTimeCd < 0) { ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_EXPIRED; ctx.update0ContinueBtnTimerStopwatchCd(); if (ctx.timerSwTimeCdContinue) { ctx.timerSwTimeCd *= -1; } else { ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_RUNNING; ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_END; ctx.updateTimerSwBtnsCd(); ctx.timerSwTimeCd = 0; } } ctx.drawStopwatchCd(); setTimeout(ctx.updateTimerStopwatchCd, DebugJS.UPDATE_INTERVAL_H); }, drawStopwatchCd: function() { var ctx = DebugJS.ctx; var tm = DebugJS.ms2struct(ctx.timerSwTimeCd, true); ctx.timerStopwatchCdLabel.innerHTML = ctx.createTimeStrCd(tm); }, updateTimerSwBtnsCd: function() { var ctx = DebugJS.ctx; if (!ctx.timerStartStopBtnCd) return; var btn = (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) ? '||' : '>>'; ctx.timerStartStopBtnCd.innerText = btn; ctx.timerStartStopBtnCdInp.innerText = btn; ctx.updateTimerLapBtnCd(); ctx.update0ContinueBtnTimerStopwatchCd(); }, updateTimerLapBtnCd: function() { var ctx = DebugJS.ctx; var color = '#888'; var fn = null; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) { color = DebugJS.TOOL_TIMER_BTN_COLOR; fn = ctx.splitTimerStopwatchCd; } ctx.setStyle(ctx.timerSplitBtnCd, 'color', color); ctx.timerSplitBtnCd.onclick = fn; }, createTimeStrCu: function(tm) { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize * 7; var msFontSize = fontSize * 0.65; var str; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END) { var now = DebugJS.getDateTime(); if (now.sss > 500) { str = '&nbsp;<span style="font-size:' + msFontSize + 'px !important">' + '&nbsp;</span>'; } else { str = tm.hh + ':' + tm.mi + ':' + tm.ss + '<span style="color:' + ctx.opt.fontColor + ' !important;font-size:' + msFontSize + 'px !important">.' + tm.sss + '</span>'; } } else { var dot = (((ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) && (tm.sss > 500)) ? '&nbsp;' : '.'); str = tm.hh + ':' + tm.mi + ':' + tm.ss + '<span style="color:' + ctx.opt.fontColor + ' !important;font-size:' + msFontSize + 'px !important">' + dot + tm.sss + '</span>'; } return '<div style="color:' + ctx.opt.fontColor + ' !important;font-size:' + fontSize + 'px !important">' + str + '</div>'; }, createTimeStrCd: function(tm) { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize * 7; var msFontSize = fontSize * 0.65; var color = ctx.opt.fontColor; var str; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_END) { var now = DebugJS.getDateTime(); if (now.sss > 500) { str = '&nbsp;<span style="font-size:' + msFontSize + 'px !important">' + '&nbsp;</span>'; } else { str = tm.hh + ':' + tm.mi + ':' + tm.ss + '<span style="color:' + color + ' !important;font-size:' + msFontSize + 'px !important">.' + tm.sss + '</span>'; } } else { var dot; var styleS = ''; var styleE = ''; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { color = ctx.opt.timerColorExpr; dot = (((ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) && (tm.sss > 500)) ? '&nbsp;' : '.'); styleS = '<span style="color:' + color + ' !important;font-size:' + fontSize + 'px !important">'; styleE = '</span>'; } else { dot = (((ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) && (tm.sss < 500)) ? '&nbsp;' : '.'); } str = styleS + tm.hh + ':' + tm.mi + ':' + tm.ss + '<span style="color:' + color + ' !important;font-size:' + msFontSize + 'px !important">' + dot + tm.sss + '</span>' + styleE; } return '<div style="color:' + color + ' !important;font-size:' + fontSize + 'px !important">' + str + '</div>'; }, closeTimer: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_TIMER) && (ctx.timerBasePanel)) { ctx.removeToolFuncPanel(ctx, ctx.timerBasePanel); ctx.setIntervalL(ctx); } }, openTextChecker: function() { var ctx = DebugJS.ctx; if (!ctx.txtChkPanel) { ctx.createTxtChkPanel(ctx); } else { ctx.toolsBodyPanel.appendChild(ctx.txtChkPanel); } }, createTxtChkPanel: function(ctx) { var dfltFontSize = ctx.computedFontSize; var dfltFontFamily = 'Consolas'; var dfltFontWeight = 400; var dfltFgRGB16 = 'fff'; var dfltBgRGB16 = '000'; var panelPadding = 2; ctx.txtChkPanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); var txtPadding = 4; var txtChkTxt = document.createElement('input'); ctx.setStyle(txtChkTxt, 'width', 'calc(100% - ' + ((txtPadding + panelPadding) * 2) + 'px)'); ctx.setStyle(txtChkTxt, 'min-height', (20 * ctx.opt.zoom) + 'px'); ctx.setStyle(txtChkTxt, 'margin-bottom', '8px'); ctx.setStyle(txtChkTxt, 'padding', txtPadding + 'px'); ctx.setStyle(txtChkTxt, 'border', '0'); ctx.setStyle(txtChkTxt, 'border-radius', '0'); ctx.setStyle(txtChkTxt, 'outline', 'none'); ctx.setStyle(txtChkTxt, 'font-size', dfltFontSize + 'px'); ctx.setStyle(txtChkTxt, 'font-family', dfltFontFamily); txtChkTxt.value = 'ABCDEFG.abcdefg 12345-67890_!?'; ctx.txtChkPanel.appendChild(txtChkTxt); ctx.txtChkTxt = txtChkTxt; ctx.txtChkTargetEl = txtChkTxt; ctx.txtChkCtrl = document.createElement('div'); ctx.txtChkPanel.appendChild(ctx.txtChkCtrl); var html = 'font-size: <input type="range" min="0" max="128" step="1" id="' + ctx.id + '-fontsize-range" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeFontSize(true);" onchange="DebugJS.ctx.onChangeFontSize(true);">' + '<input value="' + dfltFontSize + '" id="' + ctx.id + '-font-size" class="dbg-txtbox" style="width:30px;text-align:right" oninput="DebugJS.ctx.onChangeFontSizeTxt()">' + '<input value="px" id="' + ctx.id + '-font-size-unit" class="dbg-txtbox" style="width:20px;" oninput="DebugJS.ctx.onChangeFontSizeTxt()">' + '<span class="dbg-btn dbg-nomove" style="margin-left:5px;color:' + DebugJS.COLOR_INACT + ' !important;font-style:italic;" onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'' + ctx.opt.btnColor + '\');" onmouseout="DebugJS.ctx.updateTxtItalicBtn(this);" onclick="DebugJS.ctx.toggleTxtItalic(this);"> I </span>' + '<span class="dbg-btn dbg-nomove" style="margin-left:5px;color:' + DebugJS.COLOR_INACT + ' !important;" onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'' + ctx.opt.btnColor + '\');" onmouseout="DebugJS.ctx.updateElBtn(this);" onclick="DebugJS.ctx.toggleElmEditable(this);">(el)</span>' + '<br>' + 'font-family: <input value="' + dfltFontFamily + '" class="dbg-txtbox" style="width:110px" oninput="DebugJS.ctx.onChangeFontFamily(this)">&nbsp;&nbsp;' + 'font-weight: <input type="range" min="100" max="900" step="100" value="' + dfltFontWeight + '" id="' + ctx.id + '-fontweight-range" class="dbg-txt-range" style="width:80px !important" oninput="DebugJS.ctx.onChangeFontWeight();" onchange="DebugJS.ctx.onChangeFontWeight();"><span id="' + ctx.id + '-font-weight"></span> ' + '<table class="dbg-txt-tbl">' + '<tr><td colspan="2">FG #<input id="' + ctx.id + '-fg-rgb" class="dbg-txtbox" value="' + dfltFgRGB16 + '" style="width:80px" oninput="DebugJS.ctx.onChangeFgRGB()"></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_R + '">R</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-fg-range-r" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeFgColor(true);" onchange="DebugJS.ctx.onChangeFgColor(true);"></td><td><span id="' + ctx.id + '-fg-r"></span></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_G + '">G</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-fg-range-g" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeFgColor(true);" onchange="DebugJS.ctx.onChangeFgColor(true);"></td><td><span id="' + ctx.id + '-fg-g"></span></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_B + '">B</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-fg-range-b" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeFgColor(true);" onchange="DebugJS.ctx.onChangeFgColor(true);"></td><td><span id="' + ctx.id + '-fg-b"></span></td></tr>' + '<tr><td colspan="2">BG #<input id="' + ctx.id + '-bg-rgb" class="dbg-txtbox" value="' + dfltBgRGB16 + '" style="width:80px" oninput="DebugJS.ctx.onChangeBgRGB()"></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_R + '">R</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-bg-range-r" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeBgColor(true);" onchange="DebugJS.ctx.onChangeBgColor(true);"></td><td><span id="' + ctx.id + '-bg-r"></span></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_G + '">G</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-bg-range-g" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeBgColor(true);" onchange="DebugJS.ctx.onChangeBgColor(true);"></td><td><span id="' + ctx.id + '-bg-g"></span></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_B + '">B</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-bg-range-b" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeBgColor(true);" onchange="DebugJS.ctx.onChangeBgColor(true);"></td><td><span id="' + ctx.id + '-bg-b"></span></td></tr>' + '</tbale>'; ctx.txtChkCtrl.innerHTML = html; ctx.txtChkFontSizeRange = document.getElementById(ctx.id + '-fontsize-range'); ctx.txtChkFontSizeInput = document.getElementById(ctx.id + '-font-size'); ctx.txtChkFontSizeUnitInput = document.getElementById(ctx.id + '-font-size-unit'); ctx.txtChkFontWeightRange = document.getElementById(ctx.id + '-fontweight-range'); ctx.txtChkFontWeightLabel = document.getElementById(ctx.id + '-font-weight'); ctx.txtChkInputFgRGB = document.getElementById(ctx.id + '-fg-rgb'); ctx.txtChkRangeFgR = document.getElementById(ctx.id + '-fg-range-r'); ctx.txtChkRangeFgG = document.getElementById(ctx.id + '-fg-range-g'); ctx.txtChkRangeFgB = document.getElementById(ctx.id + '-fg-range-b'); ctx.txtChkLabelFgR = document.getElementById(ctx.id + '-fg-r'); ctx.txtChkLabelFgG = document.getElementById(ctx.id + '-fg-g'); ctx.txtChkLabelFgB = document.getElementById(ctx.id + '-fg-b'); ctx.txtChkInputBgRGB = document.getElementById(ctx.id + '-bg-rgb'); ctx.txtChkRangeBgR = document.getElementById(ctx.id + '-bg-range-r'); ctx.txtChkRangeBgG = document.getElementById(ctx.id + '-bg-range-g'); ctx.txtChkRangeBgB = document.getElementById(ctx.id + '-bg-range-b'); ctx.txtChkLabelBgR = document.getElementById(ctx.id + '-bg-r'); ctx.txtChkLabelBgG = document.getElementById(ctx.id + '-bg-g'); ctx.txtChkLabelBgB = document.getElementById(ctx.id + '-bg-b'); ctx.onChangeFontSizeTxt(); ctx.onChangeFontWeight(); ctx.onChangeFgRGB(); ctx.onChangeBgRGB(); }, toggleTxtItalic: function(btn) { var ctx = DebugJS.ctx; var style = ''; if (ctx.txtChkItalic) { ctx.txtChkItalic = false; } else { ctx.txtChkItalic = true; style = 'italic'; } ctx.setStyle(ctx.txtChkTargetEl, 'font-style', style); ctx.updateTxtItalicBtn(btn); }, updateTxtItalicBtn: function(btn) { var ctx = DebugJS.ctx; var c = (ctx.txtChkItalic ? ctx.opt.btnColor : DebugJS.COLOR_INACT); ctx.setStyle(btn, 'color', c); }, toggleElmEditable: function(btn) { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_ELM_EDIT) { ctx.status &= ~DebugJS.ST_ELM_EDIT; ctx.updateEditable(ctx, ctx.txtChkTxt); } else { ctx.status |= DebugJS.ST_ELM_EDIT; if (DebugJS.el) { ctx.updateEditable(ctx, DebugJS.el); } } ctx.updateElBtn(btn); }, updateElBtn: function(btn) { var ctx = DebugJS.ctx; var c = (ctx.status & DebugJS.ST_ELM_EDIT ? ctx.opt.btnColor : DebugJS.COLOR_INACT); ctx.setStyle(btn, 'color', c); }, onChangeFgRGB: function() { var ctx = DebugJS.ctx; var rgb16 = '#' + ctx.txtChkInputFgRGB.value; var rgb10 = DebugJS.convRGB16to10(rgb16); ctx.txtChkRangeFgR.value = rgb10.r; ctx.txtChkRangeFgG.value = rgb10.g; ctx.txtChkRangeFgB.value = rgb10.b; ctx.onChangeFgColor(null); ctx.setStyle(ctx.txtChkTargetEl, 'color', rgb16); }, onChangeBgRGB: function() { var ctx = DebugJS.ctx; var rgb16 = '#' + ctx.txtChkInputBgRGB.value; var rgb10 = DebugJS.convRGB16to10(rgb16); ctx.txtChkRangeBgR.value = rgb10.r; ctx.txtChkRangeBgG.value = rgb10.g; ctx.txtChkRangeBgB.value = rgb10.b; ctx.onChangeBgColor(null); ctx.setStyle(ctx.txtChkTargetEl, 'background', rgb16); }, onChangeFgColor: function(callFromRange) { var ctx = DebugJS.ctx; var fgR = ctx.txtChkRangeFgR.value; var fgG = ctx.txtChkRangeFgG.value; var fgB = ctx.txtChkRangeFgB.value; var rgb16 = DebugJS.convRGB10to16(fgR + ' ' + fgG + ' ' + fgB); ctx.txtChkLabelFgR.innerText = fgR; ctx.txtChkLabelFgG.innerText = fgG; ctx.txtChkLabelFgB.innerText = fgB; if (callFromRange) { ctx.txtChkInputFgRGB.value = rgb16.r + rgb16.g + rgb16.b; ctx.setStyle(ctx.txtChkTargetEl, 'color', 'rgb(' + fgR + ',' + fgG + ',' + fgB + ')'); } }, onChangeBgColor: function(callFromRange) { var ctx = DebugJS.ctx; var bgR = ctx.txtChkRangeBgR.value; var bgG = ctx.txtChkRangeBgG.value; var bgB = ctx.txtChkRangeBgB.value; var rgb16 = DebugJS.convRGB10to16(bgR + ' ' + bgG + ' ' + bgB); ctx.txtChkLabelBgR.innerText = bgR; ctx.txtChkLabelBgG.innerText = bgG; ctx.txtChkLabelBgB.innerText = bgB; if (callFromRange) { ctx.txtChkInputBgRGB.value = rgb16.r + rgb16.g + rgb16.b; ctx.setStyle(ctx.txtChkTargetEl, 'background', 'rgb(' + bgR + ',' + bgG + ',' + bgB + ')'); } }, onChangeFontSizeTxt: function() { var ctx = DebugJS.ctx; var fontSize = ctx.txtChkFontSizeInput.value; var unit = ctx.txtChkFontSizeUnitInput.value; ctx.txtChkFontSizeRange.value = fontSize; ctx.onChangeFontSize(null); ctx.setStyle(ctx.txtChkTargetEl, 'font-size', fontSize + unit); }, onChangeFontSize: function(callFromRange) { var ctx = DebugJS.ctx; var fontSize = ctx.txtChkFontSizeRange.value; var unit = ctx.txtChkFontSizeUnitInput.value; if (callFromRange) { ctx.txtChkFontSizeInput.value = fontSize; ctx.setStyle(ctx.txtChkTargetEl, 'font-size', fontSize + unit); } }, onChangeFontWeight: function() { var ctx = DebugJS.ctx; var fontWeight = ctx.txtChkFontWeightRange.value; ctx.setStyle(ctx.txtChkTargetEl, 'font-weight', fontWeight); if (fontWeight == 400) { fontWeight += '(normal)'; } else if (fontWeight == 700) { fontWeight += '(bold)'; } ctx.txtChkFontWeightLabel.innerText = fontWeight; }, onChangeFontFamily: function(font) { DebugJS.ctx.setStyle(DebugJS.ctx.txtChkTargetEl, 'font-family', font.value); }, closeTextChecker: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_TEXT) && (ctx.txtChkPanel)) { ctx.removeToolFuncPanel(ctx, ctx.txtChkPanel); } }, openFileLoader: function(fmt) { var ctx = DebugJS.ctx; if (!ctx.fileVwrPanel) { ctx.createFileVwrPanel(ctx); ctx.clearFile(); } else { ctx.toolsBodyPanel.appendChild(ctx.fileVwrPanel); } if (fmt && (ctx.fileVwrMode != fmt)) { ctx.switchFileScreen(); } }, createFileVwrPanel: function(ctx) { var opt = ctx.opt; var fontSize = ctx.computedFontSize + 'px'; ctx.fileVwrPanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); var fileInput = document.createElement('input'); fileInput.type = 'file'; ctx.setStyle(fileInput, 'width', 'calc(100% - ' + (ctx.computedFontSize * 19) + 'px)'); ctx.setStyle(fileInput, 'min-height', (20 * opt.zoom) + 'px'); ctx.setStyle(fileInput, 'margin', '0 0 4px 0'); ctx.setStyle(fileInput, 'padding', '1px'); ctx.setStyle(fileInput, 'border', '0'); ctx.setStyle(fileInput, 'border-radius', '0'); ctx.setStyle(fileInput, 'outline', 'none'); ctx.setStyle(fileInput, 'font-size', fontSize); fileInput.addEventListener('change', ctx.onFileSelected, false); ctx.fileVwrPanel.appendChild(fileInput); ctx.fileInput = fileInput; ctx.fileVwrRadioB64 = document.createElement('input'); ctx.fileVwrRadioB64.type = 'radio'; ctx.fileVwrRadioB64.id = ctx.id + '-load-type-b64'; ctx.fileVwrRadioB64.name = ctx.id + '-load-type'; ctx.fileVwrRadioB64.style.marginLeft = (ctx.computedFontSize * 0.8) + 'px'; ctx.fileVwrRadioB64.value = 'base64'; ctx.fileVwrRadioB64.checked = true; ctx.fileVwrRadioB64.onchange = ctx.openViewerB64; ctx.fileVwrPanel.appendChild(ctx.fileVwrRadioB64); ctx.fileVwrLabelB64 = document.createElement('label'); ctx.fileVwrLabelB64.htmlFor = ctx.id + '-load-type-b64'; ctx.fileVwrLabelB64.innerText = 'Base64'; ctx.fileVwrPanel.appendChild(ctx.fileVwrLabelB64); ctx.fileVwrRadioBin = document.createElement('input'); ctx.fileVwrRadioBin.type = 'radio'; ctx.fileVwrRadioBin.id = ctx.id + '-load-type-bin'; ctx.fileVwrRadioBin.name = ctx.id + '-load-type'; ctx.fileVwrRadioBin.style.marginLeft = (ctx.computedFontSize * 0.8) + 'px'; ctx.fileVwrRadioBin.value = 'binary'; ctx.fileVwrRadioBin.onchange = ctx.openViewerBin; ctx.fileVwrPanel.appendChild(ctx.fileVwrRadioBin); ctx.fileVwrLabelBin = document.createElement('label'); ctx.fileVwrLabelBin.htmlFor = ctx.id + '-load-type-bin'; ctx.fileVwrLabelBin.innerText = 'Binary'; ctx.fileVwrPanel.appendChild(ctx.fileVwrLabelBin); ctx.fileReloadBtn = DebugJS.ui.addBtn(ctx.fileVwrPanel, 'Reload', ctx.reloadFile); ctx.fileReloadBtn.style.marginLeft = (ctx.computedFontSize * 0.8) + 'px'; ctx.fileClrBtn = DebugJS.ui.addBtn(ctx.fileVwrPanel, 'Clear', ctx.clearFile); ctx.fileClrBtn.style.marginLeft = (ctx.computedFontSize * 0.8) + 'px'; ctx.filePreviewWrapper = document.createElement('div'); ctx.setStyle(ctx.filePreviewWrapper, 'width', 'calc(100% - ' + (DebugJS.WIN_ADJUST + 2) + 'px)'); ctx.setStyle(ctx.filePreviewWrapper, 'height', 'calc(100% - ' + ((ctx.computedFontSize * 4) + 10) + 'px)'); ctx.setStyle(ctx.filePreviewWrapper, 'margin-bottom', '4px'); ctx.setStyle(ctx.filePreviewWrapper, 'padding', '2px'); ctx.setStyle(ctx.filePreviewWrapper, 'border', '1px dotted #ccc'); ctx.setStyle(ctx.filePreviewWrapper, 'font-size', fontSize); ctx.setStyle(ctx.filePreviewWrapper, 'overflow', 'auto'); ctx.enableDnDFileLoad(ctx.filePreviewWrapper, ctx.onDropOnFileVwr); ctx.fileVwrPanel.appendChild(ctx.filePreviewWrapper); ctx.filePreview = document.createElement('pre'); ctx.setStyle(ctx.filePreview, 'min-height', 'calc(50% + 10px)'); ctx.setStyle(ctx.filePreview, 'background', 'transparent'); ctx.setStyle(ctx.filePreview, 'color', opt.fontColor); ctx.setStyle(ctx.filePreview, 'font-size', fontSize); ctx.filePreviewWrapper.appendChild(ctx.filePreview); ctx.fileVwrFooter = document.createElement('div'); ctx.fileVwrFooter.style.width = 'calc(100% - ' + (DebugJS.WIN_ADJUST + DebugJS.WIN_SHADOW) + 'px)'; ctx.fileVwrFooter.style.height = (ctx.computedFontSize + 3) + 'px'; ctx.fileVwrFooter.style.opacity = 0; ctx.fileVwrFooter.style.transition = 'opacity 0.5s linear'; ctx.fileVwrPanel.appendChild(ctx.fileVwrFooter); ctx.fileLoadProgBar = document.createElement('div'); ctx.fileLoadProgBar.style.display = 'inline-block'; ctx.fileLoadProgBar.style.width = 'calc(100% - ' + (ctx.computedFontSize * 5) + 'px)'; ctx.fileLoadProgBar.style.height = 'auto'; ctx.fileLoadProgBar.style.padding = 0; ctx.fileLoadProgBar.style.border = '1px solid #ccc'; ctx.fileVwrFooter.appendChild(ctx.fileLoadProgBar); ctx.fileLoadProg = document.createElement('div'); ctx.fileLoadProg.style.width = 'calc(100% - ' + (DebugJS.WIN_BORDER * 2) + 'px)'; ctx.fileLoadProg.style.height = 'auto'; ctx.fileLoadProg.style.padding = '1px'; ctx.fileLoadProg.style.border = 'none'; ctx.fileLoadProg.style.background = '#00f'; ctx.setStyle(ctx.fileLoadProg, 'font-size', (ctx.computedFontSize * 0.8) + 'px'); ctx.fileLoadProg.style.fontFamily = opt.fontFamily + 'px'; ctx.fileLoadProg.innerText = '0%'; ctx.fileLoadProgBar.appendChild(ctx.fileLoadProg); ctx.fileLoadCancelBtn = DebugJS.ui.addBtn(ctx.fileVwrFooter, '[CANCEL]', ctx.cancelLoadFile); ctx.fileLoadCancelBtn.style.position = 'relative'; ctx.fileLoadCancelBtn.style.top = '2px'; ctx.fileLoadCancelBtn.style.float = 'right'; ctx.fileVwrDtUrlWrp = document.createElement('div'); ctx.setStyle(ctx.fileVwrDtUrlWrp, 'height', 'calc(50% - ' + (ctx.computedFontSize + ctx.computedFontSize * 0.5) + 'px)'); ctx.filePreviewWrapper.appendChild(ctx.fileVwrDtUrlWrp); ctx.fileVwrDtUrlScheme = DebugJS.ui.addTextInput(ctx.fileVwrDtUrlWrp, 'calc(100% - 15.5em)', null, ctx.opt.fontColor, '', null); var decodeBtn = DebugJS.ui.addBtn(ctx.fileVwrDtUrlWrp, 'Decode', ctx.decodeFileVwrData); decodeBtn.style.float = 'right'; decodeBtn.style.marginRight = '4px'; ctx.fileVwrDecModeBtn = DebugJS.ui.addBtn(ctx.fileVwrDtUrlWrp, '[B64]', ctx.toggleDecMode); ctx.fileVwrDecModeBtn.style.float = 'right'; ctx.fileVwrDecModeBtn.style.marginRight = (ctx.computedFontSize * 0.5) + 'px'; var imgBtn = DebugJS.ui.addBtn(ctx.fileVwrDtUrlWrp, '<image>', ctx.setDtSchmImg); imgBtn.style.float = 'right'; imgBtn.style.marginRight = (ctx.computedFontSize * 0.5) + 'px'; var txtBtn = DebugJS.ui.addBtn(ctx.fileVwrDtUrlWrp, '<text>', ctx.setDtSchmTxt); txtBtn.style.float = 'right'; txtBtn.style.marginRight = (ctx.computedFontSize * 0.2) + 'px'; ctx.fileVwrDtTxtArea = document.createElement('textarea'); ctx.fileVwrDtTxtArea.className = 'dbg-editor'; ctx.setStyle(ctx.fileVwrDtTxtArea, 'height', 'calc(100% - ' + (ctx.computedFontSize + ctx.computedFontSize * 0.5) + 'px)'); ctx.enableDnDFileLoad(ctx.fileVwrDtTxtArea, ctx.onDropOnFileVwrTxt); ctx.fileVwrDtUrlWrp.appendChild(ctx.fileVwrDtTxtArea); }, closeFileLoader: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_FILE) && (ctx.fileVwrPanel)) { ctx.removeToolFuncPanel(ctx, ctx.fileVwrPanel); } }, enableDnDFileLoad: function(target, cb) { target.addEventListener('dragover', DebugJS.file.onDragOver, false); target.addEventListener('drop', cb, false); }, onFileSelected: function(e) { if (e.target.files.length > 0) { DebugJS.ctx.clearFile(); DebugJS.ctx.loadFile(e.target.files[0], DebugJS.ctx.fileVwrMode); } }, handleDroppedFile: function(ctx, e, fmt, cb) { ctx.clearFile(); try { if (e.dataTransfer.files) { if (e.dataTransfer.files.length > 0) { ctx.fileVwrSysCb = cb; ctx.loadFile(e.dataTransfer.files[0], fmt); } else { DebugJS._log.w('handleDroppedFile() e.dataTransfer.files.length == 0'); if (cb) { cb(ctx, false, null, null); } } } } catch (e) {DebugJS._log.e('handleDroppedFile() ' + e);} }, onDrop: function(e) { e.stopPropagation(); e.preventDefault(); }, onDropOnFileVwr: function(e) { var ctx = DebugJS.ctx; ctx.onDrop(e); ctx.stopErrCb = true; try { var d = e.dataTransfer.getData('text'); if (d) { var s = DebugJS.delAllNL(d.trim()); if (DebugJS.isDataURL(s)) { ctx.decodeDataURL(ctx, s); } else if (DebugJS.isBase64(s)) { var tp = DebugJS.Base64.getMimeType(s); var mime = (tp ? tp.type + '/' + tp.subtype : 'text/plain'); ctx.decodeDataURL(ctx, 'data:' + mime + ';base64,' + s); } } else { ctx.handleDroppedFile(ctx, e, ctx.fileVwrMode, null); } } catch (e) {DebugJS._log.e(e);} ctx.stopErrCb = false; }, onDropOnFileVwrTxt: function(e) { var ctx = DebugJS.ctx; ctx.onDrop(e); ctx.stopErrCb = true; try { var d = e.dataTransfer.getData('text'); if (d) { ctx.fileVwrDtTxtArea.value = d; } else { ctx.handleDroppedFile(ctx, e, ctx.fileVwrMode, null); } } catch (e) {DebugJS._log.e(e);} ctx.stopErrCb = false; }, onDropOnLogPanel: function(e) { var ctx = DebugJS.ctx; ctx.onDrop(e); ctx.stopErrCb = true; try { if (!DebugJS.callEvtListeners('drop', e)) return; var d = e.dataTransfer.getData('text'); if (d) { ctx.onTxtDrop(ctx, d); } else { ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'file', 'b64'); ctx.handleDroppedFile(ctx, e, 'b64', ctx.onFileLoadedAuto); } } catch (e) {DebugJS._log.e(e);} ctx.stopErrCb = false; }, onTxtDrop: function(ctx, t) { if (DebugJS.isBat(t)) { ctx.openBat(ctx, t); } else { var s = DebugJS.delAllNL(t.trim()); if (DebugJS.isDataURL(s)) { ctx.decodeDataURL(ctx, s); } else { if (ctx.decB64(ctx, s)) return; ctx._execCmd('json ' + t, true, false, true); ctx.scrollLogBtm(ctx); } } }, decB64: function(ctx, s) { if (!DebugJS.isBase64(s)) return 0; if (DebugJS.isB64Bat(s)) { var b = DebugJS.decodeB64(s); if (b) { ctx.openBat(ctx, b); return 1; } else { return 0; } } var tp = DebugJS.Base64.getMimeType(s); var mime = (tp ? tp.type + '/' + tp.subtype : 'text/plain'); if (tp || (s.length > 102400)) { ctx.decodeDataURL(ctx, 'data:' + mime + ';base64,' + s); return 1; } ctx._execCmd('base64 -d ' + s, true, false, true); ctx.scrollLogBtm(ctx); return 1; }, openBat: function(ctx, s) { ctx.openFeature(ctx, DebugJS.ST_TOOLS); ctx.onBatLoaded(ctx, null, s); }, onFileLoadedAuto: function(ctx, file, cnt) { if (DebugJS.wBOM(cnt)) cnt = cnt.substr(1); if (DebugJS.isBat(cnt) || DebugJS.isB64Bat(cnt)) { ctx.onBatLoaded(ctx, file, cnt); } else if (file.name.match(/\.js$/)) { ctx.onJsLoaded(ctx, file, cnt); } else if (file.name.match(/\.json$/)) { DebugJS._cmdJson(cnt, true); ctx.closeFeature(ctx, DebugJS.ST_TOOLS); } }, _onDropOnFeat: function(ctx, e, fn) { ctx.onDrop(e); var d = e.dataTransfer.getData('text'); if (d) { fn(ctx, null, d); } else { ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'file', 'b64'); ctx.handleDroppedFile(ctx, e, 'b64', fn); } }, onDropOnBat: function(e) { var ctx = DebugJS.ctx; ctx._onDropOnFeat(ctx, e, ctx.onBatLoaded); }, onBatLoaded: function(ctx, file, cnt) { DebugJS.bat.set(cnt); ctx.switchToolsFunction(DebugJS.TOOLS_FNC_BAT); }, onDropOnJS: function(e) { var ctx = DebugJS.ctx; ctx._onDropOnFeat(ctx, e, ctx.onJsLoaded); }, onJsLoaded: function(ctx, file, cnt) { ctx.closeFeature(ctx, DebugJS.ST_TOOLS); ctx.openFeature(ctx, DebugJS.ST_JS); ctx.jsEditor.value = ctx.jsBuf = cnt; }, loadFile: function(file, fmt) { var ctx = DebugJS.ctx; ctx.fileVwrDataSrcType = 'file'; ctx.fileVwrFile = file; if (!file) return; if ((file.size == 0) && (file.type == '')) { var html = ctx.getFileInfo(file); ctx.updateFilePreview(html); return; } ctx.fileLoadProg.style.width = '0%'; ctx.fileLoadProg.textContent = '0%'; ctx.fileReader = new FileReader(); ctx.fileReader.onloadstart = ctx.onFileLoadStart; ctx.fileReader.onprogress = ctx.onFileLoadProg; ctx.fileReader.onload = ctx.onFileLoaded; ctx.fileReader.onabort = ctx.onAbortLoadFile; ctx.fileReader.onerror = ctx.onFileLoadError; ctx.fileReader.file = file; if (fmt == 'bin') { ctx.fileReader.readAsArrayBuffer(file); } else { ctx.fileReader.readAsDataURL(file); } }, cancelLoadFile: function() { if (DebugJS.ctx.fileReader) DebugJS.ctx.fileReader.abort(); }, onFileLoadStart: function(e) { DebugJS.addClass(DebugJS.ctx.fileVwrFooter, 'dbg-loading'); DebugJS.ctx.updateFilePreview('LOADING...'); }, onFileLoadProg: function(e) { if (e.lengthComputable) { var total = e.total; var loaded = e.loaded; var pct = (total == 0) ? 100 : Math.round((loaded / total) * 100); DebugJS.ctx.fileLoadProg.style.width = 'calc(' + pct + '% - ' + (DebugJS.WIN_BORDER * 2) + 'px)'; DebugJS.ctx.fileLoadProg.textContent = pct + '%'; DebugJS.ctx.updateFilePreview('LOADING...\n' + DebugJS.formatDec(loaded) + ' / ' + DebugJS.formatDec(total) + ' bytes'); } }, onFileLoaded: function(e) { var ctx = DebugJS.ctx; var file = ctx.fileReader.file; var content = ''; try { if (ctx.fileReader.result != null) content = ctx.fileReader.result; } catch (e) { DebugJS._log.e('onFileLoaded: ' + e); } if (ctx.fileVwrMode == 'bin') { ctx.onFileLoadedBin(ctx, file, content); } else { ctx.onFileLoadedB64(ctx, file, content); } setTimeout(ctx.fileLoadFinalize, 1000); var isB64 = (ctx.fileVwrMode == 'b64'); DebugJS.callEvtListeners('fileloaded', file, content, isB64); ctx.fileVwrSysCb = null; DebugJS.file.finalize(); }, onAbortLoadFile: function(e) { DebugJS.ctx.fileVwrSysCb = null; DebugJS.file.finalize(); DebugJS.ctx.updateFilePreview('File read cancelled.'); setTimeout(DebugJS.ctx.fileLoadFinalize, 1000); }, onFileLoadError: function(e) { DebugJS.ctx.fileVwrSysCb = null; DebugJS.file.finalize(); var te = e.target.error; var err; switch (te.code) { case te.NOT_FOUND_ERR: err = 'NOT_FOUND_ERR'; break; case te.SECURITY_ERR: err = 'SECURITY_ERR'; break; case te.NOT_READABLE_ERR: err = 'NOT_READABLE_ERR'; break; case te.ABORT_ERR: err = 'ABORT_ERR'; break; default: err = 'FILE_READ_ERROR (' + te.code + ')'; } DebugJS.ctx.updateFilePreview(err); }, openViewerB64: function() { var ctx = DebugJS.ctx; ctx.fileVwrMode = 'b64'; ctx.filePreviewWrapper.appendChild(ctx.fileVwrDtUrlWrp); var dtSrc = ctx.dataSrcType(); switch (dtSrc) { case 'file': if (ctx.fileVwrByteArray) { ctx.viewBinAsB64(ctx); } else { ctx.loadFile(ctx.fileVwrFile, 'b64'); } break; case 'b64': ctx.showB64Preview(ctx, null, ctx.fileVwrDataSrc.scheme, ctx.fileVwrDataSrc.data); break; case 'bin': case 'hex': ctx.viewBinAsB64(ctx); } }, openViewerBin: function() { var ctx = DebugJS.ctx; ctx.fileVwrMode = 'bin'; if (DebugJS.isChild(ctx.filePreviewWrapper, ctx.fileVwrDtUrlWrp)) { ctx.filePreviewWrapper.removeChild(ctx.fileVwrDtUrlWrp); } var dtSrc = ctx.dataSrcType(); switch (dtSrc) { case 'file': if (ctx.fileVwrDataSrc) { ctx.decodeB64dataAsB(ctx.fileVwrDataSrc.data); } else { ctx.loadFile(ctx.fileVwrFile, 'bin'); } break; case 'b64': case 'bin': case 'hex': ctx.decodeB64dataAsB(ctx.fileVwrDataSrc.data); break; default: ctx.updateFilePreview(''); } }, decodeFileVwrData: function() { var ctx = DebugJS.ctx; var mode = ctx.fileVwrDecMode; var scheme = ctx.fileVwrDtUrlScheme.value; var data = ctx.fileVwrDtTxtArea.value; ctx.clearFile(); if (mode != 'txt') { data = DebugJS.delAllNL(DebugJS.delAllSP(data)); } ctx.fileVwrDataSrc = {scheme: scheme, data: data}; ctx.setDataUrl(ctx, scheme, data); switch (mode) { case 'bin': ctx.fileVwrDataSrcType = 'bin'; ctx.decodeBin(ctx, data); break; case 'hex': ctx.fileVwrDataSrcType = 'hex'; ctx.decodeHex(ctx, data); break; default: if (mode == 'txt') { data = DebugJS.encodeBase64(data); ctx.fileVwrDtTxtArea.value = ctx.fileVwrDataSrc.data = data; } ctx.fileVwrDataSrcType = 'b64'; ctx.showB64Preview(ctx, null, scheme, data); } }, decodeBin: function(ctx, bin) { ctx.fileVwrByteArray = DebugJS.str2binArr(bin, 8, '0b'); ctx.viewBinAsB64(ctx); }, decodeHex: function(ctx, hex) { ctx.fileVwrByteArray = DebugJS.str2binArr(hex, 2, '0x'); ctx.viewBinAsB64(ctx); }, decodeB64dataAsB: function(b64) { var a = DebugJS.Base64.decode(b64); DebugJS.ctx.fileVwrByteArray = a; DebugJS.ctx.showBinDump(DebugJS.ctx, a); }, viewBinAsB64: function(ctx) { var file = ctx.fileVwrFile; var scheme; if (file) { scheme = 'data:' + file.type + ';base64'; } else { scheme = ctx.fileVwrDataSrc.scheme; } var lm = ctx.props.prevlimit; if (file && (file.size > lm)) { ctx.showFileSizeExceeds(ctx, file, lm); } else { var data = DebugJS.Base64.encode(ctx.fileVwrByteArray); ctx.fileVwrDataSrc = {scheme: scheme, data: data}; ctx.setDataUrl(ctx, scheme, data); ctx.showB64Preview(ctx, file, scheme, data); } }, onFileLoadedB64: function(ctx, file, dturl) { if (file) { var LIMIT = ctx.props.prevlimit; if (file.size > LIMIT) { ctx.showFileSizeExceeds(ctx, file, LIMIT); return; } else if (file.size == 0) { ctx.updateFilePreview(ctx.getFileInfo(file)); return; } } var b64cnt = DebugJS.splitDataUrl(dturl); ctx.fileVwrDataSrc = b64cnt; var cType = DebugJS.getContentType(null, file, b64cnt.data); if (cType == 'text') { if (ctx.fileVwrSysCb) { var decoded = DebugJS.decodeB64(b64cnt.data); ctx.fileVwrSysCb(ctx, file, decoded); } } DebugJS.file.onLoaded(file, dturl); ctx.setDataUrl(ctx, b64cnt.scheme, b64cnt.data); ctx.showB64Preview(ctx, file, b64cnt.scheme, b64cnt.data); }, onFileLoadedBin: function(ctx, file, content) { var buf = new Uint8Array(content); ctx.fileVwrByteArray = buf; DebugJS.file.onLoaded(file, buf); ctx.showBinDump(ctx, buf); }, switchFileScreen: function() { var ctx = DebugJS.ctx; if (ctx.fileVwrMode == 'b64') { ctx.fileVwrRadioBin.checked = true; ctx.openViewerBin(); } else { ctx.fileVwrRadioB64.checked = true; ctx.openViewerB64(); } }, toggleDecMode: function() { var ctx = DebugJS.ctx; var a = ['b64', 'hex', 'bin', 'txt']; var mode = DebugJS.nextArr(a, ctx.fileVwrDecMode); ctx.setDecMode(ctx, mode); }, setDecMode: function(ctx, mode) { ctx.fileVwrDecMode = mode; ctx.fileVwrDecModeBtn.innerText = '[' + mode.toUpperCase() + ']'; }, toggleBinMode: function() { var ctx = DebugJS.ctx; var a = ['hex', 'bin', 'dec']; var opt = ctx.fileVwrBinViewOpt; opt.mode = DebugJS.nextArr(a, opt.mode); ctx.showBinDump(ctx, ctx.fileVwrByteArray); }, toggleShowAddr: function() { DebugJS.ctx.toggleBinVwrOpt(DebugJS.ctx, 'addr'); }, toggleShowSpace: function() { DebugJS.ctx.toggleBinVwrOpt(DebugJS.ctx, 'space'); }, toggleShowAscii: function() { DebugJS.ctx.toggleBinVwrOpt(DebugJS.ctx, 'ascii'); }, toggleBinVwrOpt: function(ctx, key) { var ctx = DebugJS.ctx; var opt = ctx.fileVwrBinViewOpt; opt[key] = (opt[key] ? false : true); var file = ctx.fileVwrFile; var html = ''; if (file) html += ctx.getFileInfo(file); html += ctx.getBinDumpHtml(ctx.fileVwrByteArray, opt.mode, opt.addr, opt.space, opt.ascii); ctx.updateFilePreview(html); }, showBinDump: function(ctx, buf) { var file = ctx.fileVwrFile; var opt = ctx.fileVwrBinViewOpt; var html = ''; if (file) html += ctx.getFileInfo(file); html += ctx.getBinDumpHtml(buf, opt.mode, opt.addr, opt.space, opt.ascii); ctx.updateFilePreview(html); }, showB64Preview: function(ctx, file, scheme, data) { var html = ''; if (file) { var LIMIT = ctx.props.prevlimit; if (file.size > LIMIT) { ctx.showFileSizeExceeds(ctx, file, LIMIT); return; } else if (file.size == 0) { ctx.updateFilePreview(html); return; } html += ctx.getFileInfo(file); } var cType = DebugJS.getContentType(scheme, file, data); if (cType == 'image') { html += ctx.getImgPreview(ctx, scheme, data); } else { var decoded = DebugJS.decodeB64(data); html += ctx.getTextPreview(decoded); } ctx.updateFilePreview(html); }, setDataUrl: function(ctx, scheme, data) { scheme = scheme.replace(/,$/, ''); ctx.fileVwrDtUrlScheme.value = scheme + ','; ctx.fileVwrDtTxtArea.value = data; }, getFileInfo: function(file) { var lastMod = (file.lastModified ? file.lastModified : file.lastModifiedDate); var dt = DebugJS.getDateTime(lastMod); var fileDate = DebugJS.convDateTimeStr(dt); var s = '<span style="color:#cff">' + 'file : ' + file.name + '\n' + 'type : ' + file.type + '\n' + 'size : ' + DebugJS.formatDec(file.size) + ' ' + DebugJS.plural('byte', file.size) + '\n' + 'modified: ' + fileDate + '</span>\n'; return s; }, showFileSizeExceeds: function(ctx, file, lm) { var html = ctx.getFileInfo(file) + '<span style="color:' + ctx.opt.logColorW + '">The file size exceeds the limit allowed. (limit=' + lm + ')</span>'; ctx.updateFilePreview(html); }, getTextPreview: function(decoded) { if (decoded.length == 0) return ''; var txt = DebugJS.escTags(decoded); txt = txt.replace(/\r\n/g, DebugJS.CHR_CRLF_S + '\n'); txt = txt.replace(/([^>])\n/g, '$1' + DebugJS.CHR_LF_S + '\n'); txt = txt.replace(/\r/g, DebugJS.CHR_CR_S + '\n'); return (txt + DebugJS.EOF + '\n'); }, toggleShowHideCC: function() { var el = document.getElementsByClassName('dbg-cc'); for (var i = 0; i < el.length; i++) { DebugJS.toggleElShowHide(el[i]); } }, getImgPreview: function(ctx, scheme, data) { var ctxSizePos = ctx.getSelfSizePos(); return '<img src="' + DebugJS.buildDataUrl(scheme, data) + '" id="' + ctx.id + '-img-preview" style="max-width:' + (ctxSizePos.w - 32) + 'px;max-height:' + (ctxSizePos.h - (ctx.computedFontSize * 13) - 8) + 'px">\n'; }, resizeImgPreview: function() { var ctx = DebugJS.ctx; if ((!(ctx.status & DebugJS.ST_TOOLS)) || (!(ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_FILE)) || (!(ctx.fileVwrMode == 'b64'))) { return; } var imgPreview = document.getElementById(ctx.id + '-img-preview'); if (imgPreview == null) return; var ctxSizePos = ctx.getSelfSizePos(); var maxW = (ctxSizePos.w - 32); if (maxW < 100) maxW = 100; var maxH = (ctxSizePos.h - (ctx.computedFontSize * 13) - 8); if (maxH < 100) maxH = 100; imgPreview.style.maxWidth = maxW + 'px'; imgPreview.style.maxHeight = maxH + 'px'; }, getBinDumpHtml: function(buf, mode, showAddr, showSp, showAscii) { if (buf == null) return ''; var ctx = DebugJS.ctx; var lm = ctx.props.hexdumplimit | 0; var lastRows = ctx.props.hexdumplastrows | 0; var lastLen = 0x10 * lastRows; var bLen = buf.length; if (lm == 0) lm = bLen; var len = ((bLen > lm) ? lm : bLen); if (len % 0x10 != 0) { len = (((len / 0x10) + 1) | 0) * 0x10; } var html = '<pre style="white-space:pre !important">'; html += DebugJS.ui.createBtnHtml('[' + mode.toUpperCase() + ']', 'DebugJS.ctx.toggleBinMode()') + ' '; html += DebugJS.ui.createBtnHtml('[ADDR]', 'DebugJS.ctx.toggleShowAddr()', (showAddr ? '' : 'color:' + DebugJS.COLOR_INACT)) + ' '; html += DebugJS.ui.createBtnHtml('[SP]', 'DebugJS.ctx.toggleShowSpace()', (showSp ? '' : 'color:' + DebugJS.COLOR_INACT)) + ' '; html += DebugJS.ui.createBtnHtml('[ASCII]', 'DebugJS.ctx.toggleShowAscii()', (showAscii ? '' : 'color:' + DebugJS.COLOR_INACT)); html += '\n<span style="background:#0cf;color:#000">'; if (showAddr) { html += 'Address '; } if (mode == 'bin') { if (showSp) { html += '+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F '; } else { html += '+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F '; } } else if (mode == 'dec') { if (showSp) { html += ' +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F'; } else { html += ' +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F'; } } else { if (showSp) { html += '+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F'; } else { html += '+0+1+2+3+4+5+6+7+8+9+A+B+C+D+E+F'; } } if (showAscii) { html += ' ASCII '; } html += '</span>\n'; if (showAddr) { html += DebugJS.dumpAddr(0); } for (var i = 0; i < len; i++) { html += ctx.getDump(mode, i, buf, len, showSp, showAddr, showAscii); } if (bLen > lm) { if (bLen - lm > (0x10 * lastRows)) { html += '\n<span style="color:#ccc">...</span>'; } if (lastRows > 0) { var rem = (bLen % 0x10); var start = (rem == 0 ? (bLen - lastLen) : ((bLen - rem) - (0x10 * (lastRows - 1)))); if (start < len) { rem = ((len - start) % 0x10); start = len + rem; } var end = bLen + (rem == 0 ? 0 : (0x10 - rem)); html += '\n'; if (showAddr) { html += DebugJS.dumpAddr(start); } for (i = start; i < end; i++) { html += ctx.getDump(mode, i, buf, end, showSp, showAddr, showAscii); } } } html += '</pre>'; return html; }, getDump: function(mode, i, buf, len, showSp, showAddr, showAscii) { var b; if (mode == 'bin') { b = DebugJS.dumpBin(i, buf); } else if (mode == 'dec') { b = DebugJS.dumpDec(i, buf); } else { b = DebugJS.dumpHex(i, buf); } if ((i + 1) % 0x10 == 0) { if (showAscii) { b += ' ' + DebugJS.dumpAscii(((i + 1) - 0x10), buf, len); } if ((i + 1) < len) { b += '\n'; if (showAddr) { b += DebugJS.dumpAddr(i + 1); } } } else if (showSp) { if ((i + 1) % 8 == 0) { b += ' '; } else { b += ' '; } } return b; }, updateFilePreview: function(html) { DebugJS.ctx.filePreview.innerHTML = html + '\n'; DebugJS.ctx.filePreviewWrapper.scrollTop = 0; }, fileLoadFinalize: function() { DebugJS.removeClass(DebugJS.ctx.fileVwrFooter, 'dbg-loading'); }, reloadFile: function() { DebugJS.ctx.loadFile(DebugJS.ctx.fileVwrFile, DebugJS.ctx.fileVwrMode); }, clearFile: function() { var ctx = DebugJS.ctx; ctx.fileVwrDataSrcType = null; ctx.fileVwrFile = null; ctx.fileVwrDataSrc = null; ctx.fileVwrByteArray = null; ctx.fileReader = null; if (ctx.fileVwrPanel) { ctx.filePreview.innerText = 'Drop a file here'; ctx.setDtSchmTxt(); ctx.fileVwrDtTxtArea.value = ''; } }, dataSrcType: function() { return DebugJS.ctx.fileVwrDataSrcType; }, setDtSchm: function(type) { DebugJS.ctx.fileVwrDtUrlScheme.value = 'data:' + type + ';base64,'; }, setDtSchmTxt: function() { DebugJS.ctx.setDtSchm('text/plain'); }, setDtSchmImg: function() { DebugJS.ctx.setDtSchm('image/jpeg'); }, decodeDataURL: function(ctx, s) { ctx.clearFile(); ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'file', 'b64'); ctx.openViewerB64(); var d = DebugJS.splitDataUrl(s); ctx.setDataUrl(ctx, d.scheme, d.data); ctx.setDecMode(ctx, 'b64'); ctx.decodeFileVwrData(); }, openHtmlEditor: function() { var ctx = DebugJS.ctx; if (!ctx.htmlPrevBasePanel) { ctx.createHtmlPrevBasePanel(ctx); } else { ctx.toolsBodyPanel.appendChild(ctx.htmlPrevBasePanel); } ctx.htmlPrevEditor.focus(); }, createHtmlPrevBasePanel: function(ctx) { ctx.htmlPrevBasePanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); ctx.htmlPrevPrevPanel = document.createElement('div'); ctx.htmlPrevPrevPanel.style.height = '50%'; ctx.htmlPrevPrevPanel.innerHTML = 'HTML PREVIEWER'; ctx.htmlPrevBasePanel.appendChild(ctx.htmlPrevPrevPanel); ctx.htmlPrevEditorPanel = document.createElement('div'); var html = '<span style="color:#ccc">HTML Editor</span>' + DebugJS.ui.createBtnHtml('[DRAW]', 'DebugJS.ctx.drawHtml();DebugJS.ctx.htmlPrevEditor.focus();', 'float:right;margin-right:4px') + DebugJS.ui.createBtnHtml('[CLR]', 'DebugJS.ctx.insertHtmlSnippet();', 'margin-left:4px;margin-right:4px'); for (var i = 0; i < 5; i++) { html += ctx.createHtmlSnippetBtn(ctx, i); } ctx.htmlPrevEditorPanel.innerHTML = html; ctx.htmlPrevBasePanel.appendChild(ctx.htmlPrevEditorPanel); ctx.htmlPrevEditor = document.createElement('textarea'); ctx.htmlPrevEditor.className = 'dbg-editor'; ctx.setStyle(ctx.htmlPrevEditor, 'height', 'calc(50% - ' + (ctx.computedFontSize + 10) + 'px)'); ctx.htmlPrevEditor.onblur = ctx.saveHtmlBuf; ctx.htmlPrevEditor.value = ctx.htmlPrevBuf; ctx.htmlPrevBasePanel.appendChild(ctx.htmlPrevEditor); }, createHtmlSnippetBtn: function(ctx, i) { return DebugJS.ui.createBtnHtml('&lt;CODE' + (i + 1) + '&gt;', 'DebugJS.ctx.insertHtmlSnippet(' + i + ');', 'margin-left:4px'); }, insertHtmlSnippet: function(n) { var editor = DebugJS.ctx.htmlPrevEditor; if (n == undefined) { editor.value = ''; editor.focus(); } else { var code = DebugJS.HTML_SNIPPET[n]; var buf = editor.value; var posCursor = editor.selectionStart; var bufL = buf.substr(0, posCursor); var bufR = buf.substr(posCursor, buf.length); buf = bufL + code + bufR; DebugJS.ctx.htmlPrevEditor.focus(); DebugJS.ctx.htmlPrevEditor.value = buf; editor.selectionStart = editor.selectionEnd = posCursor + code.length; } }, saveHtmlBuf: function() { DebugJS.ctx.htmlPrevBuf = DebugJS.ctx.htmlPrevEditor.value; }, drawHtml: function() { DebugJS.ctx.htmlPrevPrevPanel.innerHTML = DebugJS.ctx.htmlPrevBuf; }, closeHtmlEditor: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_HTML) && (ctx.htmlPrevBasePanel)) { ctx.removeToolFuncPanel(ctx, ctx.htmlPrevBasePanel); } }, openBatEditor: function() { var ctx = DebugJS.ctx; if (!ctx.batBasePanel) { ctx.createBatBasePanel(ctx); } else { ctx.toolsBodyPanel.appendChild(ctx.batBasePanel); } ctx.batTextEditor.focus(); }, createBatBasePanel: function(ctx) { var basePanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); ctx.batResumeBtn = DebugJS.ui.addBtn(basePanel, '[RESUME]', null); ctx.batResumeBtn.style.float = 'right'; ctx.batRunBtn = DebugJS.ui.addBtn(basePanel, '[ RUN ]', ctx.startPauseBat); ctx.batStopBtn = DebugJS.ui.addBtn(basePanel, '[STOP]', DebugJS.bat.terminate); DebugJS.ui.addLabel(basePanel, ' FROM:'); ctx.batStartTxt = DebugJS.ui.addTextInput(basePanel, '45px', 'left', ctx.opt.fontColor, '', null); DebugJS.ui.addLabel(basePanel, ' TO:'); ctx.batEndTxt = DebugJS.ui.addTextInput(basePanel, '45px', 'left', ctx.opt.fontColor, '', null); DebugJS.ui.addLabel(basePanel, ' Arg:'); ctx.batArgTxt = DebugJS.ui.addTextInput(basePanel, '80px', 'left', ctx.opt.fontColor, '', null); DebugJS.ui.addLabel(basePanel, ' L:'); ctx.batCurPc = DebugJS.ui.addLabel(basePanel, '0'); DebugJS.ui.addLabel(basePanel, '/').style.color = '#ccc'; ctx.batTotalLine = DebugJS.ui.addLabel(basePanel, DebugJS.bat.cmds.length); DebugJS.ui.addLabel(basePanel, ' N:'); ctx.batNestLv = DebugJS.ui.addLabel(basePanel, '0'); ctx.batTextEditor = document.createElement('textarea'); ctx.batTextEditor.className = 'dbg-editor'; ctx.setStyle(ctx.batTextEditor, 'height', 'calc(100% - ' + (ctx.computedFontSize * 2) + 'px)'); ctx.enableDnDFileLoad(ctx.batTextEditor, ctx.onDropOnBat); basePanel.appendChild(ctx.batTextEditor); ctx.batBasePanel = basePanel; ctx.setBatTxt(ctx); ctx.setBatArgTxt(ctx); ctx.updateCurPc(); ctx.updateBatNestLv(); ctx.updateBatRunBtn(); ctx.updateBatResumeBtn(); }, startPauseBat: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_BAT_RUNNING) { if (ctx.status & DebugJS.ST_BAT_PAUSE) { DebugJS.bat._resume(); } else { DebugJS.bat.pause(); } } else { ctx.runBat(ctx); } }, runBat: function(ctx) { var bat = DebugJS.bat; bat.store(ctx.batTextEditor.value); var a = ctx.batArgTxt.value; try { bat.setExecArg(eval(a)); } catch (e) { DebugJS._log.e('BAT ARG ERROR (' + e + ')'); return; } var s = ctx.batStartTxt.value; var e = ctx.batEndTxt.value; if (s == '') s = undefined; if (e == '') e = undefined; bat.run(s, e); }, updateBatRunBtn: function() { var ctx = DebugJS.ctx; if (!ctx.batRunBtn) return; var label = ' RUN '; var color = '#0f0'; if (ctx.status & DebugJS.ST_BAT_RUNNING) { if (!(ctx.status & DebugJS.ST_BAT_PAUSE)) { label = 'PAUSE'; color = '#ff0'; } ctx.setStyle(ctx.batStopBtn, 'color', '#f66'); } else { ctx.setStyle(ctx.batStopBtn, 'color', '#a99'); } ctx.batRunBtn.innerText = '[' + label + ']'; ctx.setStyle(ctx.batRunBtn, 'color', color); }, updateBatResumeBtn: function() { var ctx = DebugJS.ctx; if (!ctx.batResumeBtn) return; var color = DebugJS.COLOR_INACT; var fn = null; if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD_KEY) { color = ctx.opt.btnColor; fn = ctx.batResume; } else if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD) { color = ctx.opt.btnColor; } ctx.setStyle(ctx.batResumeBtn, 'color', color); ctx.batResumeBtn.onclick = fn; }, batResume: function() { DebugJS.bat._resume('cmd-key'); }, setBatTxt: function(ctx) { var b = ''; var cmds = DebugJS.bat.cmds; for (var i = 0; i < cmds.length; i++) { b += cmds[i] + '\n'; } if (ctx.batTextEditor) { ctx.batTextEditor.value = b; } }, setBatArgTxt: function(ctx) { if (ctx.batArgTxt) { var a = DebugJS.bat.ctrl.execArg; if ((typeof a == 'string') && (a != '')) {a = '"' + a + '"';} ctx.batArgTxt.value = a + ''; } }, updateCurPc: function(b) { var pc = DebugJS.bat.ctrl.pc; var df = DebugJS.digits(DebugJS.bat.cmds.length) - DebugJS.digits(pc); var pdng = ''; for (var i = 0; i < df; i++) { pdng += '0'; } if (DebugJS.ctx.batCurPc) { DebugJS.ctx.batCurPc.innerText = pdng + pc; DebugJS.ctx.batCurPc.style.color = (b ? '#f66' : ''); } }, updateTotalLine: function() { if (DebugJS.ctx.batTotalLine) { DebugJS.ctx.batTotalLine.innerText = DebugJS.bat.cmds.length; } }, updateBatNestLv: function() { if (DebugJS.ctx.batNestLv) { DebugJS.ctx.batNestLv.innerText = DebugJS.bat.nestLv(); } }, closeBatEditor: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_BAT) && (ctx.batBasePanel)) { ctx.removeToolFuncPanel(ctx, ctx.batBasePanel); } }, toggleExtPanel: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_EXT_PANEL) { ctx.closeExtPanel(ctx); } else { ctx.openExtPanel(ctx); } }, openExtPanel: function(ctx) { ctx.status |= DebugJS.ST_EXT_PANEL; ctx.featStack.push(DebugJS.ST_EXT_PANEL); ctx.addOverlayPanelFull(ctx.extPanel); var activePanel = ctx.extActPnlIdx; if (activePanel == -1) { var activePanel = ctx.nextValidExtPanelIdx(ctx, activePanel); ctx.switchExtPanel(activePanel); } else { var p = ctx.extPanels[activePanel]; if ((p) && (p.onActive)) ctx.onExtPanelActive(ctx, p); } ctx.updateExtBtns(ctx); ctx.updateExtBtn(ctx); }, createExtHeaderBtn: function(ctx, label, idx) { var MAX_LEN = 20; label = DebugJS.trimDownText(label, MAX_LEN); var fn = new Function('DebugJS.ctx.switchExtPanel(' + idx + ');'); var btn = DebugJS.ui.addBtn(ctx.extHeaderPanel, '<' + label + '>', fn); btn.style.marginRight = '4px'; ctx.setStyle(btn, 'color', DebugJS.SBPNL_COLOR_INACT); btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.extPanels[' + idx + '].btn, \'color\', DebugJS.SBPNL_COLOR_ACTIVE);'); btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.extPanels[' + idx + '].btn, \'color\', (DebugJS.ctx.extActPnlIdx == ' + idx + ') ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT);'); return btn; }, closeExtPanel: function(ctx) { if ((ctx.extPanel) && (ctx.extPanel.parentNode)) { var p = ctx.extPanels[ctx.extActPnlIdx]; if ((p) && (p.onInActive)) ctx.onExtPanelInActive(ctx, p); ctx.removeOverlayPanelFull(ctx.extPanel); } ctx.status &= ~DebugJS.ST_EXT_PANEL; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_EXT_PANEL); ctx.updateExtBtn(ctx); }, switchExtPanel: function(idx) { var ctx = DebugJS.ctx; var pnls = ctx.extPanels; if (ctx.extActPnlIdx == idx) return; if (ctx.extActPnlIdx != -1) { var p2 = pnls[ctx.extActPnlIdx]; if (p2) { if ((ctx.status & DebugJS.ST_EXT_PANEL) && (p2.onInActive)) { ctx.onExtPanelInActive(ctx, p2); } ctx.extBodyPanel.removeChild(p2.base); } } var p1 = pnls[idx]; ctx.extBodyPanel.appendChild(p1.base); if (p1) { if ((ctx.status & DebugJS.ST_EXT_PANEL) && (p1.onActive)) { ctx.onExtPanelActive(ctx, p1); } } ctx.extActPnlIdx = idx; ctx.updateExtBtns(ctx); }, onExtPanelActive: function(ctx, p) { ctx.extActivePanel = p.panel; p.onActive(p.panel); }, onExtPanelInActive: function(ctx, p) { ctx.extActivePanel = null; p.onInActive(p.panel); }, prevValidExtPanelIdx: function(ctx, idx) { if (idx > 0) { for (var i = idx - 1; i >= 0; i--) { if (ctx.extPanels[i] != null) return i; } } return -1; }, nextValidExtPanelIdx: function(ctx, idx) { for (var i = idx + 1; i < ctx.extPanels.length; i++) { if (ctx.extPanels[i] != null) return i; } return -1; }, existsValidExtPanel: function(ctx) { for (var i = 0; i < ctx.extPanels.length; i++) { if (ctx.extPanels[i] != null) return true; } return false; }, updateExtBtns: function(ctx) { var pnls = ctx.extPanels; for (var i = 0; i < pnls.length; i++) { var p = pnls[i]; if (p != null) { ctx.setStyle(p.btn, 'color', (ctx.extActPnlIdx == i) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); } } }, createSubBasePanel: function(ctx) { var base = document.createElement('div'); base.className = 'dbg-overlay-panel-full'; var head = document.createElement('div'); head.style.position = 'relative'; head.style.height = ctx.computedFontSize + 'px'; base.appendChild(head); var body = document.createElement('div'); body.style.position = 'relative'; body.style.height = 'calc(100% - ' + ctx.computedFontSize + 'px)'; base.appendChild(body); return {base: base, head: head, body: body}; }, isOnDbgWin: function(x, y) { var sp = DebugJS.ctx.getSelfSizePos(); return (((x >= sp.x1) && (x <= sp.x2)) && ((y >= sp.y1) && (y <= sp.y2))); }, getSelfSizePos: function() { var ctx = DebugJS.ctx; var rect = ctx.win.getBoundingClientRect(); var resizeBoxSize = 6; var sp = {}; sp.w = ctx.win.clientWidth; sp.h = ctx.win.clientHeight; sp.x1 = rect.left - resizeBoxSize / 2; sp.y1 = rect.top - resizeBoxSize / 2; sp.x2 = sp.x1 + ctx.win.clientWidth + resizeBoxSize + DebugJS.WIN_BORDER; sp.y2 = sp.y1 + ctx.win.clientHeight + resizeBoxSize + DebugJS.WIN_BORDER; return sp; }, setSelfSizeW: function(ctx, w) { ctx.win.style.width = w + 'px'; ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, setSelfSizeH: function(ctx, h) { ctx.win.style.height = h + 'px'; ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, expandHight: function(ctx, height) { if (!(ctx.uiStatus & DebugJS.UI_ST_DYNAMIC)) return; ctx.saveExpandModeOrgSizeAndPos(ctx); var clientH = document.documentElement.clientHeight; var sp = ctx.getSelfSizePos(); if (sp.h >= height) { return; } else if (clientH <= height) { height = clientH; } ctx.setSelfSizeH(ctx, height); sp = ctx.getSelfSizePos(); if (ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) { ctx.adjustDbgWinPos(ctx); } else { if (sp.y2 > clientH) { if (clientH < (height + ctx.opt.adjustY)) { ctx.win.style.top = 0; } else { var top = clientH - height - ctx.opt.adjustY; ctx.win.style.top = top + 'px'; } } } }, expandHightIfNeeded: function(ctx) { if (ctx.winExpandCnt == 0) ctx.expandHight(ctx, ctx.winExpandHeight); ctx.winExpandCnt++; }, resetExpandedHeight: function(ctx) { if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { ctx.win.style.width = ctx.expandModeOrg.w + 'px'; ctx.win.style.height = ctx.expandModeOrg.h + 'px'; ctx.resizeMainHeight(); ctx.resizeImgPreview(); ctx.scrollLogBtm(ctx); if (ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) { ctx.adjustDbgWinPos(ctx); } } }, resetExpandedHeightIfNeeded: function(ctx) { ctx.winExpandCnt--; if (ctx.winExpandCnt == 0) ctx.resetExpandedHeight(ctx); }, saveExpandModeOrgSizeAndPos: function(ctx) { var shadow = (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) ? (DebugJS.WIN_SHADOW / 2) : 0; ctx.expandModeOrg.w = (ctx.win.offsetWidth + DebugJS.WIN_BORDER - shadow); ctx.expandModeOrg.h = (ctx.win.offsetHeight + DebugJS.WIN_BORDER - shadow); ctx.expandModeOrg.t = ctx.win.offsetTop; ctx.expandModeOrg.l = ctx.win.offsetLeft; }, turnLed: function(pos, active) { var ctx = DebugJS.ctx; var bit = DebugJS.LED_BIT[pos]; if (active) { ctx.led |= bit; } else { ctx.led &= ~bit; } ctx.updateLedPanel(); }, setLed: function(val) { try { DebugJS.ctx.led = eval(val); DebugJS.ctx.updateLedPanel(); } catch (e) { DebugJS._log.e('Invalid value'); } }, setMsg: function(m) { DebugJS.ctx.msgStr = m; DebugJS.ctx.updateMsgLabel(); }, execCmd: function(ctx) { var cl = ctx.cmdLine.value; ctx.cmdLine.value = ''; if (cl == '') { DebugJS._log(''); return; } if (cl.substr(0, 2) == '!!') { var ev = ctx.getLastHistory(); if (ev == '') { DebugJS._log.w('!!: event not found'); return; } cl = ev + cl.substr(2); } else if (cl.substr(0, 1) == '!') { var s = cl.substr(1).match(/(\d*)(.*)/); var num = s[1]; var arg = s[2]; if (num != '') { var ev = ctx.getHistory((num | 0) - 1); if (ev == '') { DebugJS._log.w('!' + num + ': event not found'); return; } cl = ev + arg; } else if (arg != '') { cl = '!' + arg; } } ctx._execCmd(cl, ctx.cmdEchoFlg, false, true); }, _execCmd: function(str, echo, recho, sv) { var ctx = DebugJS.ctx; if (sv) ctx.saveHistory(ctx, str); var setValName = null; var cmdline = str; if (str.match(/^\s*@/)) { echo = false; cmdline = str.substr(str.indexOf('@') + 1); } if (echo) { var echoStr = str; echoStr = DebugJS.escTags(echoStr); echoStr = DebugJS.trimDownText(echoStr, DebugJS.CMD_ECHO_MAX_LEN, 'color:#aaa'); DebugJS._log.s(echoStr); } var cmds = DebugJS.splitCmdLineInTwo(cmdline); var cmd = cmds[0]; var valName = DebugJS.getCmdValName(cmd, '\\$', true); if (valName != null) { var vStartPos = cmdline.indexOf(valName); var restCmd = cmdline.substr(vStartPos + valName.length + 1); if (restCmd.match(/^\s*=/)) { setValName = valName; cmdline = restCmd.substr(restCmd.indexOf('=') + 1); } } var ret; echo = echo || recho; cmds = DebugJS.splitCmdLineInTwo(cmdline); if (cmds[0] == 'code') { ret = ctx.execCode(cmds[1], echo); } else { cmdline = DebugJS.replaceCmdVals(cmdline); ret = ctx.__execCmd(ctx, cmdline, echo); } if (setValName != null) { DebugJS.setCmdVal(setValName, ret); } return ret; }, __execCmd: function(ctx, cmdline, echo, aliased) { cmdline = DebugJS.escCtrlChr(cmdline); var cmds = DebugJS.splitCmdLineInTwo(cmdline); var cmd = cmds[0]; var arg = cmds[1]; if (!aliased) { for (var key in ctx.CMD_ALIAS) { if (cmd == key) { var cl = cmdline.replace(new RegExp(cmd), ctx.CMD_ALIAS[key]); return ctx.__execCmd(ctx, cl, echo, true); } } } for (var i = 0; i < ctx.CMD_TBL.length; i++) { if (cmd == ctx.CMD_TBL[i].cmd) { return ctx.CMD_TBL[i].fn(arg, ctx.CMD_TBL[i], echo); } } if (ctx.opt.disableAllCommands) return; for (i = 0; i < ctx.EXT_CMD_TBL.length; i++) { if (cmd == ctx.EXT_CMD_TBL[i].cmd) { return ctx.EXT_CMD_TBL[i].fn(arg, ctx.EXT_CMD_TBL[i], echo); } } if (cmdline.match(/^\s*http/)) { DebugJS.ctx.doHttpRequest('GET', cmdline); return; } var ret = ctx.cmdRadixConv(cmdline, echo); if (ret) return cmd | 0; ret = ctx.cmdTimeCalc(cmdline, echo); if (ret != null) return ret; ret = ctx.cmdDateCalc(cmdline, echo); if (ret != null) return ret; ret = ctx.cmdDateDiff(cmdline, echo); if (!isNaN(ret)) return ret; ret = ctx.cmdDateConv(cmdline, echo); if (ret != null) return ret; if (DebugJS.isTmStr(cmdline)) { ret = DebugJS.str2ms(cmdline); if (echo) DebugJS._log.res(ret); return ret; } if (cmdline.match(/^\s*U\+/i)) { return ctx.cmdUnicode('-d ' + cmdline, null, echo); } return ctx.execCode(cmdline, echo); }, cmdAlias: function(arg, tbl) { var ctx = DebugJS.ctx; if (DebugJS.countArgs(arg) == 0) { var lst = DebugJS.getKeys(ctx.CMD_ALIAS); return ctx._cmdAliasList(ctx, lst); } var p = arg.indexOf('='); if (p == -1) { return ctx._cmdAliasList(ctx, DebugJS.splitCmdLine(arg)); } var al = arg.substr(0, p).trim(); var v = arg.substring(p + 1, arg.length).trim(); var c = DebugJS.getQuotedStr(v); if (c == null) { c = DebugJS.splitArgs(v)[0]; } ctx.CMD_ALIAS[al] = c; }, _cmdAliasList: function(ctx, lst) { var s = ''; for (var i = 0; i < lst.length; i++) { if (i > 0) s += '\n'; s += ctx._cmdAliasDisp(ctx, lst[i]); } DebugJS._log.mlt(s); }, _cmdAliasDisp: function(ctx, al) { var s = 'alias ' + al; var c = ctx.CMD_ALIAS[al]; if (c == undefined) { s += ': not found'; } else { s += "='" + c + "'"; } return s; }, cmdBase64: function(arg, tbl, echo) { var iIdx = 0; if ((DebugJS.hasOpt(arg, 'd')) || (DebugJS.hasOpt(arg, 'e'))) iIdx++; return DebugJS.ctx.execEncAndDec(arg, tbl, echo, true, DebugJS.encodeB64, DebugJS.decodeB64, iIdx); }, cmdBat: function(arg, tbl, echo) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); var bat = DebugJS.bat; var ret; switch (a[0]) { case 'run': if ((ctx.status & DebugJS.ST_BAT_RUNNING) && (ctx.status & DebugJS.ST_BAT_PAUSE)) { bat._resume(); } else { if (ctx.batTextEditor) bat.store(ctx.batTextEditor.value); var s = DebugJS.getOptVal(arg, 's'); var e = DebugJS.getOptVal(arg, 'e'); var ag = DebugJS.getOptVal(arg, 'arg'); if ((s == null) && (e == null) && (a[1] != '-arg')) { s = a[1]; if ((s != undefined) && (!isNaN(s))) { return bat.exec1(s); } } if (ag == null) ag = undefined; bat.run(s, e, ag); } break; case 'symbols': var t = a[1]; if ((t != 'label') && (t != 'function')) { DebugJS.printUsage('bat symbols label|function "pattern"'); return; } var p = DebugJS.getArgsFrom(arg, 2); try { p = eval(p); } catch (e) { DebugJS._log.e('bat symbols: ' + e); return; } ret = bat.getSymbols(t, p); if (echo) DebugJS._log.p(ret); return ret; case 'list': if (bat.cmds.length == 0) { DebugJS._log('No batch script'); break; } var s = bat.list(a[1], a[2]); DebugJS._log.mlt(s); break; case 'status': var key = a[1]; if (key == undefined) { var st = '\n'; if (bat.cmds.length == 0) { st += 'No batch script'; } else { st += ((ctx.status & DebugJS.ST_BAT_RUNNING) ? '<span style="color:#0f0">RUNNING</span>' : '<span style="color:#f44">STOPPED</span>'); st += '\nNest Lv: ' + bat.nestLv(); } DebugJS._log.p(bat.ctrl, 0, st, false); } else { ret = bat.ctrl[key]; DebugJS._log(ret); } return ret; case 'pc': DebugJS._log.res(bat.ctrl.pc); return bat.ctrl.pc; break; case 'pause': case 'clear': bat[a[0]](); break; case 'set': ctx._cmdBatSet(DebugJS.getArgsFrom(arg, 1), echo); break; case 'stop': bat.terminate(); break; case 'exec': if (a[1] != undefined) { var b = DebugJS.decodeB64(a[1], true); if (b != '') { var ag = DebugJS.getArgsFrom(arg, 2); try { bat(b, eval(ag)); } catch (e) { DebugJS._log.e('BAT ERROR: Illegal argument (' + e + ')'); } } else { DebugJS._log.e('BAT ERROR: script must be encoded in Base64.'); } break; } default: DebugJS.printUsage(tbl.help); } }, _cmdBatSet: function(arg, echo) { var a = DebugJS.splitCmdLine(arg); var key = a[0]; var v = a[1]; if (!v) {DebugJS.printUsage('bat set break|delay val'); return;} try { v = eval(v); } catch (e) { DebugJS._log.e(e); return; } switch (key) { case 'b': case 'break': DebugJS.bat.ctrl.breakP = v; break; case 'delay': break; case 'pc': DebugJS.bat.setPc(v); break; default: DebugJS.printUsage('bat set b|break|delay|pc val'); return; } DebugJS.bat.ctrl[key] = v; if (echo) DebugJS._log.res(v); }, cmdBin: function(arg, tbl) { var data = DebugJS.ctx.radixCmd(arg, tbl); if (data == null) return; var r = DebugJS.convertBin(data); if (r) DebugJS._log(r); }, cmdBSB64: function(arg, tbl, echo) { var iIdx = 0; if ((DebugJS.hasOpt(arg, 'd')) || (DebugJS.hasOpt(arg, 'e'))) iIdx++; var toR = false; var n = DebugJS.getOptVal(arg, 'n'); if (n == null) { n = 1; } else { iIdx += 2; if (n.length > 1) { var d = n.charAt(n.length - 1); if (isNaN(d)) { if (d == 'R') toR = true; n = n.substr(0, n.length - 1); } } } return DebugJS.ctx.execEncAndDec(arg, tbl, echo, true, DebugJS.encodeBSB64, DebugJS.decodeBSB64, iIdx, n | 0, toR); }, cmdCall: function(arg, tbl) { if (DebugJS.bat.isCmdExecutable()) { DebugJS.ctx._cmdJump(DebugJS.ctx, arg, true, 'func'); } }, cmdClose: function(arg, tbl) { var ctx = DebugJS.ctx; var fn = DebugJS.splitArgs(arg)[0]; if (fn == 'all') { ctx.closeAllFeatures(ctx); return; } var d = { 'measure': DebugJS.ST_MEASURE, 'sys': DebugJS.ST_SYS_INFO, 'html': DebugJS.ST_HTML_SRC, 'dom': DebugJS.ST_ELM_INSPECTING, 'js': DebugJS.ST_JS, 'tool': DebugJS.ST_TOOLS, 'ext': DebugJS.ST_EXT_PANEL }; if (d[fn] === undefined) { DebugJS.printUsage(tbl.help); } else { ctx.closeFeature(ctx, d[fn]); } }, cmdClock: function(arg, tbl) { var ctx = DebugJS.ctx; ctx.launchFnc(ctx, 'tool', 'timer', 'clock'); ctx.timerClockSSS = DebugJS.hasOpt(arg, 'sss'); ctx.updateSSS(ctx); }, cmdCls: function(arg, tbl) { DebugJS.ctx.clearLog(); }, cmdCondWait: function(arg, tbl) { var bat = DebugJS.bat; var op = DebugJS.splitCmdLine(arg)[0]; switch (op) { case 'init': bat._initCond(); break; case 'set': var key = DebugJS.getOptVal(arg, 'key'); bat.ctrl.condKey = (key ? DebugJS.delAllSP(key) : key); break; case 'pause': if (bat.ctrl.condKey) { var to = DebugJS.getOptVal(arg, 'timeout'); DebugJS.ctx._cmdPause('key', bat.ctrl.condKey, to); } break; default: DebugJS.printUsage(tbl.help); } }, cmdDbgWin: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); switch (a[0]) { case 'hide': ctx.closeDbgWin(); break; case 'show': ctx.showDbgWin(); break; case 'opacity': var v = a[1]; if ((v <= 1) && (v >= 0.1)) { DebugJS.opacity(v); } else { DebugJS.printUsage('dbgwin opacity 0.1-1'); } break; case 'pos': ctx._cmdDbgWinPos(ctx, a[1], a[2]); break; case 'size': ctx._cmdDbgWinSize(ctx, a[1], a[2]); break; case 'status': ctx._cmdDbgWinStatus(ctx); break; case 'lock': ctx._cmdDbgWinLock(ctx, a); break; default: DebugJS.printUsage(tbl.help); } }, _cmdDbgWinPos: function(ctx, x, y) { if (!(ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) || (ctx.opt.mode == 'kiosk')) { return; } var sp; switch (x) { case 'n': case 'ne': case 'e': case 'se': case 's': case 'sw': case 'w': case 'nw': case 'c': sp = ctx.getSelfSizePos(); ctx.setWinPos(x, sp.w, sp.h); break; default: if (isNaN(x) || isNaN(y)) { sp = ctx.getSelfSizePos(); DebugJS._log('x=' + (sp.x1 + 3) + ' y=' + (sp.y1 + 3)); DebugJS.printUsage('dbgwin pos n|ne|e|se|s|sw|w|nw|c|x y'); break; } x |= 0; y |= 0; DebugJS.ctx.setDbgWinPos(y, x); } }, _cmdDbgWinSize: function(ctx, w, h) { if (!(ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) || (ctx.opt.mode == 'kiosk')) { return; } if (isNaN(w) || isNaN(h)) { var sp = ctx.getSelfSizePos(); DebugJS._log('w=' + (sp.w) + ' h=' + (sp.h)); DebugJS.printUsage('dbgwin size width height'); return; } w |= 0; h |= 0; if (w < ctx.computedMinW) w = ctx.computedMinW; if (h < ctx.computedMinH) h = ctx.computedMinH; ctx.setDbgWinSize(w, h); }, _cmdDbgWinStatus: function(ctx) { var sp = ctx.getSelfSizePos(); var s = 'width : ' + sp.w + '\n' + 'height: ' + sp.h + '\n' + 'posX1 : ' + sp.x1 + '\n' + 'posY1 : ' + sp.y1 + '\n' + 'posX2 : ' + sp.x2 + '\n' + 'posY2 : ' + sp.y2 + '\n'; DebugJS._log.mlt(s); }, _cmdDbgWinLock: function(ctx, a) { var c = a[1]; if (ctx.opt.lockCode == null) { if (c == undefined) { DebugJS.printUsage('dbgwin lock [code]'); return; } ctx.opt.lockCode = c; } ctx.lockDbgWin(ctx); }, cmdDate: function(arg, tbl) { var val = arg; var iso = false; var idx = DebugJS.indexOfOptVal(arg, '-iso'); if (idx >= 0) { iso = true; val = arg.substr(idx); } var d = DebugJS.date(val, iso); if (d == null) { DebugJS.printUsage(tbl.help); } else { if (!DebugJS.hasOpt(arg, 'q')) DebugJS._log.res(d); } return d; }, cmdDateConv: function(arg, echo) { var d = arg.trim(); if (!(DebugJS.isDateFormat(d) || DebugJS.isDateTimeFormat(d) || DebugJS.isDateTimeFormatIso(d) || (d == 'today'))) { return null; } if (d == 'today') d = DebugJS.today('/'); var r = DebugJS.date(d); if (r != null) { if (echo) DebugJS._log.res(r); } return r; }, cmdDateCalc: function(arg, echo) { var ret = null; arg = arg.trim(); if ((!DebugJS.isBasicDateFormat(arg, true)) && (!DebugJS.isDateFormat(arg, true)) && (!DebugJS.startsWith(arg, 'today'))) { return ret; } arg = DebugJS.delAllSP(arg); var sp = arg.charAt(4); if ((sp != '-') && (sp != '/')) sp = '-'; arg = arg.replace(/(\d{4})-(\d{1,})-(\d{1,})/g, '$1/$2/$3'); var op; if (arg.indexOf('+') >= 0) { op = '+'; } else if (arg.indexOf('-') >= 0) { op = '-'; } var v = arg.split(op); if (v.length < 2) return ret; var d1 = DebugJS.ctx._cmdFmtDate(v[0]); if (!DebugJS.isDateFormat(d1)) return ret; var d2 = v[1]; var t1 = DebugJS.getDateTime(d1).time; var t2 = (d2 | 0) * 86400000; var t; if (op == '-') { t = t1 - t2; } else { t = t1 + t2; } var d = DebugJS.getDateTime(t); if (isNaN(d.time)) return ret; ret = DebugJS.convDateStr(d, sp); if (echo) DebugJS._log.res(ret); return ret; }, cmdDateDiff: function(arg, echo) { var ret = NaN; var a = DebugJS.splitArgs(arg); if (a.length < 2) return ret; var d1 = DebugJS.ctx._cmdFmtDate(a[0]); var d2 = DebugJS.ctx._cmdFmtDate(a[1]); if ((!DebugJS.isDateFormat(d1)) || (!DebugJS.isDateFormat(d2))) return ret; d1 = d1.replace(/-/g, '/'); d2 = d2.replace(/-/g, '/'); ret = DebugJS.diffDate(d1, d2); if (echo && !isNaN(ret)) DebugJS._log.res(ret); return ret; }, _cmdFmtDate: function(d) { if ((d.length == 8) && (!isNaN(d))) { d = DebugJS.num2date(d); } else if (d == 'today') { d = DebugJS.today('/'); } return d; }, cmdDelay: function(arg, tbl) { var ctx = DebugJS.ctx; var d = DebugJS.splitArgs(arg)[0]; if (d == '-c') { ctx._cmdDelayCancel(ctx); return; } else if (d.match(/\|/)) { d = DebugJS.calcNextTime(d).t; d = DebugJS.calcTargetTime(d); } else if (DebugJS.isTimeFormat(d)) { d = DebugJS.calcTargetTime(d); } else if (DebugJS.isTmStr(d)) { d = DebugJS.str2ms(d); } else if ((d == '') || (isNaN(d))) { DebugJS.printUsage(tbl.help); return; } var c = DebugJS.getArgsFrom(arg, 1); ctx.cmdDelayData.cmd = c; ctx._cmdDelayCancel(ctx); ctx.cmdDelayData.tmid = setTimeout(ctx._cmdDelayExec, d | 0); }, _cmdDelayExec: function() { var ctx = DebugJS.ctx; ctx.cmdDelayData.tmid = 0; var c = ctx.cmdDelayData.cmd; if (c == '') { DebugJS._log(c); } else { ctx._execCmd(c, false, ctx.cmdEchoFlg); } ctx.cmdDelayData.cmd = null; }, _cmdDelayCancel: function(ctx) { if (ctx.cmdDelayData.tmid > 0) { clearTimeout(ctx.cmdDelayData.tmid); ctx.cmdDelayData.tmid = 0; DebugJS._log('command delay execution has been canceled.'); } }, cmdEcho: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg)[0]; if (a == '') { DebugJS._log(ctx.cmdEchoFlg ? 'on' : 'off');return; } else if (a == 'off') { ctx.cmdEchoFlg = false;return; } else if (a == 'on') { ctx.cmdEchoFlg = true;return; } arg = DebugJS.decodeEsc(arg); try { var s = eval(arg) + ''; DebugJS._log(s); } catch (e) { DebugJS._log.e(e); } }, cmdElements: function(arg, tbl) { arg = arg.trim(); if ((arg == '-h') || (arg == '--help')) { DebugJS.printUsage(tbl.help); } else { return DebugJS.countElements(arg, true); } }, cmdEvent: function(arg, tbl) { var a = DebugJS.splitCmdLine(arg); var op = a[0]; switch (op) { case 'create': if (a[1]) { DebugJS.event.create(a[1]); return; } break; case 'set': if (a[1]) { try { DebugJS.event.set(a[1], eval(a[2])); } catch (e) { DebugJS._log.e(e); } return; } break; case 'dispatch': var target = a[1]; if (target) { if (target.charAt(0) == '(') { target = target.substr(1, target.length - 2); } DebugJS.event.dispatch(target, a[2]); return; } break; case 'clear': DebugJS.event.clear(); return; } DebugJS.printUsage(tbl.help); }, cmdExit: function(arg, tbl) { var ctx = DebugJS.ctx; DebugJS.bat.exit(); ctx._cmdDelayCancel(ctx); ctx.CMDVALS = {}; ctx.finalizeFeatures(ctx); ctx.toolsActiveFnc = DebugJS.TOOLS_DFLT_ACTIVE_FNC; if (ctx.opt.useSuspendLogButton) { ctx.status &= ~DebugJS.ST_LOG_SUSPENDING; ctx.updateSuspendLogBtn(ctx); } if (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { ctx.stopStopwatch(); } ctx.resetStopwatch(); if (ctx.timerBasePanel) { ctx.stopTimerStopwatchCu(); ctx.resetTimerStopwatchCu(); ctx.stopTimerStopwatchCd(); ctx.resetTimerStopwatchCd(); ctx.switchTimerModeClock(); } ctx.setLed(0); ctx.setMsg(''); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (ctx.opt.usePinButton) { ctx.enableDraggable(ctx); } if (ctx.opt.mode != 'kiosk') { ctx.resetDbgWinSizePos(); } } ctx.jsBuf = ''; ctx.fltrText = ''; if (ctx.fltrInput) ctx.fltrInput.value = ''; ctx.closeDbgWin(); ctx.clearLog(); ctx.logFilter = DebugJS.LOG_FLTR_ALL; ctx.updateLogFilterBtns(); }, cmdGoto: function(arg, tbl) { var ctrl = DebugJS.bat.ctrl; if (DebugJS.bat.isCmdExecutable()) { var lbl = DebugJS.splitArgs(arg)[0]; DebugJS.ctx._cmdJump(DebugJS.ctx, arg, false, 'label'); } }, cmdHelp: function(arg, tbl) { var ctx = DebugJS.ctx; var a = arg.trim(); var t1 = ctx.CMD_TBL; var t2 = ctx.EXT_CMD_TBL; if (ctx._cmdHelp(ctx, t1, a)) return; if (ctx._cmdHelp(ctx, t2, a)) return; var s = 'Available Commands:\n<table>' + ctx._cmdHelpTbl(ctx, t1); if (!ctx.opt.disableAllCommands) { if (t2.length > 0) { s += '<tr><td colspan="2">' + '---- ---- ---- ---- ---- ---- ---- ----</td></tr>'; } s += ctx._cmdHelpTbl(ctx, t2); } s += '</table>'; DebugJS._log.mlt(s); }, _cmdHelp: function(ctx, tbl, c) { for (var i = 0; i < tbl.length; i++) { var t = tbl[i]; if ((t.cmd == c) && !(t.attr & DebugJS.CMD_ATTR_HIDDEN) && !(t.attr & DebugJS.CMD_ATTR_DISABLED)) { if (t.help) { DebugJS.printUsage(t.help); } else { DebugJS._log('No help message for this command'); } return true; } } return false; }, _cmdHelpTbl: function(ctx, tbl) { var s = ''; for (var i = 0; i < tbl.length; i++) { if (!(tbl[i].attr & DebugJS.CMD_ATTR_HIDDEN)) { var style1 = ''; var style2 = ''; if (tbl[i].attr & DebugJS.CMD_ATTR_DISABLED) { style1 = '<span style="color:#aaa">'; style2 = '</span>'; } s += '<tr><td class="dbg-cmdtd">' + style1 + tbl[i].cmd + style2 + '</td><td>' + style1 + tbl[i].desc + style2 + '</td></tr>'; } } return s; }, cmdHex: function(arg, tbl) { var data = DebugJS.ctx.radixCmd(arg, tbl); if (data == null) return; try { var v2 = ''; var v16 = ''; var val = eval(data.exp); if (val < 0) { for (var i = (DebugJS.DFLT_UNIT - 1); i >= 0; i--) { v2 += (val & 1 << i) ? '1' : '0'; } v16 = parseInt(v2, 2).toString(16); } else { v16 = parseInt(val).toString(16); } var hex = DebugJS.formatHex(v16, true, false); var ret = hex; if (data.digit > 0) { if (hex.length > data.digit) { ret = hex.slice(data.digit * -1); var omit = hex.substr(0, hex.length - data.digit); ret = '<span style="color:#888">' + omit + '</span>' + ret; } else if (hex.length < data.digit) { var padding = data.digit - hex.length; var zero = ''; for (i = 0; i < padding; i++) { zero += ((val < 0) ? 'F' : '0'); } ret = zero + hex; } } ret = '0x' + ret; DebugJS._log(ret); } catch (e) { DebugJS._log.e('Invalid value'); } }, radixCmd: function(arg, tbl) { var args = DebugJS.splitArgs(arg); if (args[0] == '') { DebugJS.printUsage(tbl.help); return null; } var argLen = args.length; var digit = 0; var exp = args[0]; var expLen; if (argLen == 2) { digit = args[1]; } else if (argLen >= 3) { if (args[0].match(/^\(/)) { if (args[argLen - 2].match(/\)$/)) { digit = args[argLen - 1]; expLen = argLen - 1; } else if (args[argLen - 1].match(/\)$/)) { expLen = argLen; } else { DebugJS._log.e('Invalid value'); return null; } exp = ''; for (var i = 0; i < expLen; i++) { exp += ((i >= 1) ? ' ' : '') + args[i]; } } else { DebugJS._log.e('Invalid value'); return null; } } var data = {exp: exp, digit: (digit | 0)}; return data; }, cmdHistory: function(arg, tbl) { var ctx = DebugJS.ctx; try { if (DebugJS.countArgs(arg) == 0) { ctx.showHistory(); } else if (DebugJS.hasOpt(arg, 'c')) { ctx.clearHistory(); } else { var d = DebugJS.getOptVal(arg, 'd'); if (d != null) { ctx.delHistory(ctx, d | 0); } else { DebugJS.printUsage(tbl.help); } } } catch (e) { DebugJS._log.e(e); } }, initHistory: function(ctx) { if (ctx.cmdHistoryBuf == null) { ctx.CMD_HISTORY_MAX = ctx.opt.cmdHistoryMax; ctx.cmdHistoryBuf = new DebugJS.RingBuffer(ctx.CMD_HISTORY_MAX); } if (DebugJS.LS_AVAILABLE) ctx.loadHistory(ctx); }, showHistory: function() { var bf = DebugJS.ctx.cmdHistoryBuf.getAll(); var s = '<table>'; for (var i = 0; i < bf.length; i++) { var cmd = bf[i]; cmd = DebugJS.escTags(cmd); cmd = DebugJS.trimDownText(cmd, DebugJS.CMD_ECHO_MAX_LEN, 'color:#aaa'); s += '<tr><td class="dbg-cmdtd" style="text-align:right">' + (i + 1) + '</td><td>' + cmd + '</td></tr>'; } s += '</table>'; DebugJS._log.mlt(s); }, saveHistory: function(ctx, cmd) { if (!ctx.cmdHistoryBuf) return; ctx.cmdHistoryBuf.add(cmd); ctx.cmdHistoryIdx = (ctx.cmdHistoryBuf.count() < ctx.CMD_HISTORY_MAX) ? ctx.cmdHistoryBuf.count() : ctx.CMD_HISTORY_MAX; if (DebugJS.LS_AVAILABLE) { var bf = ctx.cmdHistoryBuf.getAll(); var cmds = ''; for (var i = 0; i < bf.length; i++) { cmds += bf[i] + '\n'; } localStorage.setItem('DebugJS-history', cmds); } }, loadHistory: function(ctx) { if (DebugJS.LS_AVAILABLE) { var bf = localStorage.getItem('DebugJS-history'); if (bf != null) { var cmds = bf.split('\n'); for (var i = 0; i < (cmds.length - 1); i++) { ctx.cmdHistoryBuf.add(cmds[i]); ctx.cmdHistoryIdx = (ctx.cmdHistoryBuf.count() < ctx.CMD_HISTORY_MAX) ? ctx.cmdHistoryBuf.count() : ctx.CMD_HISTORY_MAX; } } } }, getHistory: function(idx) { var cmds = DebugJS.ctx.cmdHistoryBuf.getAll(); var c = cmds[idx]; return ((c == undefined) ? '' : c); }, getLastHistory: function() { var cmds = DebugJS.ctx.cmdHistoryBuf.getAll(); var c = cmds[cmds.length - 1]; return ((c == undefined) ? '' : c); }, delHistory: function(ctx, idx) { var cmds = ctx.cmdHistoryBuf.getAll(); ctx.clearHistory(); for (var i = 0; i < cmds.length; i++) { if (cmds.length < ctx.opt.cmdHistoryMax) { if (i != (idx - 1)) { ctx.saveHistory(ctx, cmds[i]); } } else if (cmds.length >= ctx.opt.cmdHistoryMax) { if (i != (idx - 2)) { ctx.saveHistory(ctx, cmds[i]); } } } }, clearHistory: function() { DebugJS.ctx.cmdHistoryBuf.clear(); if (DebugJS.LS_AVAILABLE) localStorage.removeItem('DebugJS-history'); }, cmdHttp: function(arg, tbl) { var a = DebugJS.splitCmdLineInTwo(arg); var method = a[0]; var data = a[1]; if (method == '') { DebugJS.printUsage(tbl.help); return; } else if (method.match(/^\s*http/)) { method = 'GET'; data = arg; } DebugJS.ctx.doHttpRequest(method, data); }, cmdJs: function(arg, tbl) { var a = DebugJS.splitArgs(arg); if (a[0] == 'exec') { DebugJS.ctx.execJavaScript(); } else { DebugJS.printUsage(tbl.help); } }, cmdJson: function(arg, tbl) { if (arg == '') { DebugJS.printUsage(tbl.help); return; } var json = DebugJS.delLeadingSP(arg); var lv = 0; var jsnFlg = true; if (json.charAt(0) == '-') { var opt = json.match(/-p\s/); if (opt != null) jsnFlg = false; opt = json.match(/-l(\d+)/); if (opt) lv = opt[1]; json = json.match(/(\{.*)/); if (json) { json = json[1]; } } if (json) { return DebugJS._cmdJson(json, jsnFlg, lv); } else { DebugJS.printUsage(tbl.help); } }, cmdJump: function(arg, tbl) { if (DebugJS.bat.isCmdExecutable()) { DebugJS.ctx._cmdJump(DebugJS.ctx, arg, true, 'label'); } }, _cmdJump: function(ctx, arg, lnk, type) { var bat = DebugJS.bat; var ctrl = bat.ctrl; var fnArg; var a = DebugJS.splitCmdLineInTwo(arg); var lbl = a[0]; if (lbl.match(/^".+?"$/)) { try { lbl = eval(lbl); } catch (e) { DebugJS._log.e('L' + ctrl.pc + ': Illegal argument (' + lbl + ')'); return; } } var tbl = (type == 'func' ? bat.fncs : bat.labels); var idx = tbl[lbl]; if (idx == undefined) { DebugJS._log.e('L' + ctrl.pc + ': No such ' + type + ' (' + lbl + ')'); return; } if (lnk) { try { fnArg = eval(a[1]); } catch (e) { DebugJS._log.e('L' + ctrl.pc + ': Illegal argument (' + e + ')'); return; } delete ctx.CMDVALS['%RET%']; var fnCtx = { lr: ctrl.pc, fnArg: ctrl.fnArg, block: ctrl.block, label: ctrl.label, fnnm: ctrl.fnnm }; ctrl.stack.push(fnCtx); ctrl.fnArg = fnArg; ctx.CMDVALS['%ARG%'] = fnArg; ctrl.lr = ctrl.pc; } ctrl.startPc = 0; ctrl.block = []; if (type == 'func') { bat.setFnNm(lbl); } else { bat.setLabel(lbl); } ctrl.pc = idx + 1; ctx.updateCurPc(); }, cmdKeyPress: function(arg, tbl) { var keyCode = DebugJS.splitArgs(arg)[0]; if ((keyCode == '') || isNaN(keyCode)) { DebugJS.printUsage(tbl.help); return; } var s = (DebugJS.getOptVal(arg, 'shift') == null ? false : true); var c = (DebugJS.getOptVal(arg, 'ctrl') == null ? false : true); var a = (DebugJS.getOptVal(arg, 'alt') == null ? false : true); var m = (DebugJS.getOptVal(arg, 'meta') == null ? false : true); var opt = {keyCode: keyCode | 0, shift: s, ctrl: c, alt: a, meta: m}; DebugJS.keyPress(opt); }, cmdKeys: function(arg, tbl) { arg = DebugJS.unifySP(arg); if (arg == '') { DebugJS.printUsage(tbl.help); return; } var ags = arg.split(' '); for (var i = 0; i < ags.length; i++) { if (ags[i] == '') continue; var cmd = 'DebugJS.tmp="' + ags[i] + ' = ";DebugJS.tmp+=DebugJS.getKeysStr(' + ags[i] + ');DebugJS._log.mlt(DebugJS.tmp);'; try { eval(cmd); } catch (e) { DebugJS._log.e(e); } } }, cmdLaptime: function(arg, tbl) { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_STOPWATCH_LAPTIME) { ctx.stopStopwatch(); } else { if (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { ctx.stopStopwatch(); ctx.resetStopwatch(); } ctx.status |= DebugJS.ST_STOPWATCH_LAPTIME; ctx.startStopwatch(); } }, cmdLed: function(arg, tbl) { if (arg == '') { var v = DebugJS.ctx.led; var h = DebugJS.formatHex(DebugJS.toHex(v), true, true); DebugJS._log.res(v + '(' + h + ')'); DebugJS.printUsage(tbl.help); } else { DebugJS.ctx.setLed(arg); } return DebugJS.ctx.led; }, cmdLog: function(arg, tbl, echo) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); var fn = { bufsize: ctx._cmdLogBufsize, dump: ctx._cmdLogDump, filter: ctx._cmdLogFilter, html: ctx._cmdLogHtml, load: ctx._cmdLogLoad, preserve: ctx._cmdLogPreserve, suspend: ctx._cmdLogSuspend, lv: ctx._cmdLogLv }; if (fn[a[0]]) {return fn[a[0]](ctx, arg, echo);} DebugJS.printUsage(tbl.help); }, _cmdLogBufsize: function(ctx, arg) { var n = DebugJS.splitArgs(arg)[1] | 0; if (n > 0) { ctx.initBuf(ctx, n); } else { n = ctx.logBuf.size(); DebugJS._log.res(n); DebugJS.printUsage('log bufsize [size]'); } return n; }, _cmdLogDump: function(ctx, arg) { arg = DebugJS.splitCmdLineInTwo(arg)[1]; var f = (arg.trim() == '-b64' ? true : false); var l = DebugJS.dumpLog('json', f); DebugJS._log.res(l); }, _cmdLogFilter: function(ctx, arg) { var a = DebugJS.getArgsFrom(arg, 1); var s = DebugJS.getOptVal(a, 'case'); if (!s) s = DebugJS.getOptVal(a, 'fl'); if (!s) s = DebugJS.getOptVal(a, '')[0]; if (s == '') { DebugJS.printUsage('log filter [-case] [-fl] "string"'); return; } try { s = eval(s); } catch (e) { DebugJS._log.e(e); return; } ctx.setLogFilter(ctx, s, DebugJS.hasOpt(arg, 'case'), DebugJS.hasOpt(arg, 'fl')); }, _cmdLogHtml: function(ctx, arg) { var op = DebugJS.splitArgs(arg)[1]; if (op == 'on') { ctx.setFilterTxtHtml(ctx, true); } else if (op == 'off') { ctx.setFilterTxtHtml(ctx, false); } else { var st = ctx.fltrTxtHtml; DebugJS.printUsage('log html on|off'); return st; } }, _cmdLogLoad: function(ctx, arg) { arg = DebugJS.splitCmdLineInTwo(arg)[1]; var data = DebugJS.getOptVal(arg, 'b64'); if (DebugJS.countArgs(arg) == 0) { DebugJS.printUsage('log load [-b64] log-buf-json'); } else { try { if (data != null) { DebugJS.loadLog(data, true); } else { DebugJS.loadLog(arg); } ctx.printLogs(); } catch (e) { DebugJS._log.e(e); } } }, _cmdLogPreserve: function(ctx, arg, echo) { var op = DebugJS.splitArgs(arg)[1]; if (op == 'on') { ctx.setLogPreserve(ctx, true); } else if (op == 'off') { ctx.setLogPreserve(ctx, false); } else { var st = ((ctx.status & DebugJS.ST_LOG_PRESERVED) ? true : false); if (echo) { DebugJS._log.res(st); DebugJS.printUsage('log preserve on|off'); } return st; } }, _cmdLogSuspend: function(ctx, arg) { var op = DebugJS.splitArgs(arg)[1]; if (op == 'on') { DebugJS.ctx.suspendLog(); } else if (op == 'off') { DebugJS.ctx.resumeLog(); } else { var st = ((ctx.status & DebugJS.ST_LOG_SUSPENDING) ? true : false); DebugJS.printUsage('log suspend on|off'); return st; } }, _cmdLogLv: function(ctx, arg) { var a = DebugJS.delAllSP(DebugJS.getArgsFrom(arg, 1)); var lv = a.split('|'); if (lv[0] == '') { DebugJS.printUsage('log lv LOG|VRB|DBG|INF|WRN|ERR|ALL|NONE'); return; } var FLT = { LOG: DebugJS.LOG_FLTR_LOG, VRB: DebugJS.LOG_FLTR_VRB, DBG: DebugJS.LOG_FLTR_DBG, INF: DebugJS.LOG_FLTR_INF, WRN: DebugJS.LOG_FLTR_WRN, ERR: DebugJS.LOG_FLTR_ERR, ALL: DebugJS.LOG_FLTR_ALL }; ctx.logFilter = 0; for (var i = 0; i < lv.length; i++) { var f = FLT[lv[i]]; if (f != undefined) ctx.logFilter |= f; } ctx.updateLogFilterBtns(); ctx.printLogs(); }, cmdMsg: function(arg, tbl) { var m = ((DebugJS.hasOpt(arg, 'c') || (arg.trim() == '')) ? '""' : arg); try { DebugJS.ctx.setMsg(eval(m)); } catch (e) { DebugJS._log.e(e); DebugJS.printUsage(tbl.help); } }, cmdNextTime: function(arg, tbl) { var t, ms; var v = arg; var p = true; var idx = DebugJS.indexOfOptVal(arg, '-q'); if (idx >= 0) { p = false; v = arg.substr(idx); } v = v.trim(); if ((v.match(/^T\d{4,6}/))) { t = DebugJS.calcNextTime(v); } else if (ms = DebugJS.parseToMillis(v)) { var dt = DebugJS.getDateTime((new Date()).getTime() + ms); t = {time: dt.time, t: 'T' + dt.hh + dt.mi + dt.ss}; } else if (DebugJS.isNum(v)) { var dt = DebugJS.getDateTime((new Date()).getTime() + (v | 0)); t = {time: dt.time, t: 'T' + dt.hh + dt.mi + dt.ss}; } else { DebugJS.printUsage(tbl.help); return ''; } if (p) { DebugJS.log.res(DebugJS.convDateTimeStr(DebugJS.getDateTime(t.time))); } return t.t; }, cmdNow: function(arg, tbl, echo) { var t = (new Date()).getTime(); if (echo) DebugJS._log.res(t); return t; }, cmdOpen: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var fn = a[0]; var subfn = a[1]; var opt = a[2]; if ((fn == '') || (!DebugJS.ctx.launchFnc(DebugJS.ctx, fn, subfn, opt))) { DebugJS.printUsage(tbl.help); } }, cmdP: function(arg, tbl) { DebugJS._cmdP(arg, tbl); }, cmdPause: function(arg, tbl) { var op = ''; var opts = ['s', 'key']; for (var i = 0; i < opts.length; i++) { if (DebugJS.getOptVal(arg, opts[i]) != null) { op = opts[i]; break; } } var key = DebugJS.getOptVal(arg, 'key'); var to = DebugJS.getOptVal(arg, 'timeout'); if (!(DebugJS.ctx._cmdPause(op, key, to))) { DebugJS.printUsage(tbl.help); } }, _cmdPause: function(op, key, tout) { var ctx = DebugJS.ctx; if (DebugJS.isTmStr(tout)) tout = DebugJS.str2ms(tout); tout |= 0; ctx.CMDVALS['%RESUMED_KEY%'] = null; if (op == 's') { ctx.status |= DebugJS.ST_BAT_PAUSE_CMD; DebugJS._log('Click or press any key to continue...'); } else { if (op == '') { DebugJS._log('Type "resume" to continue...' + ((tout > 0) ? ' (timeout=' + tout + ')' : '')); } else if (op == 'key') { if (key == undefined) key = ''; DebugJS.bat.ctrl.pauseKey = key; DebugJS._log('Type "resume" or "resume -key' + ((key == '') ? '' : ' ' + key) + '" to continue...' + ((tout > 0) ? ' (timeout=' + tout + ')' : '')); } else { return false; } if (tout > 0) { DebugJS.bat.ctrl.pauseTimeout = (new Date()).getTime() + tout; } ctx.status |= DebugJS.ST_BAT_PAUSE_CMD_KEY; } ctx.updateBatResumeBtn(); return true; }, cmdPin: function(arg, tbl) { var op = DebugJS.splitArgs(arg)[0]; if ((op != 'on') && (op != 'off')) { var st = ((DebugJS.ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) ? false : true); DebugJS.printUsage(tbl.help); return st; } else { DebugJS.pin(op == 'on'); } }, cmdPoint: function(arg, tbl, echo) { var ctx = DebugJS.ctx; var args = DebugJS.splitCmdLine(arg); var point = DebugJS.point; var ret; var op = args[0]; var alignX = DebugJS.getOptVal(arg, 'alignX'); var alignY = DebugJS.getOptVal(arg, 'alignY'); if (op == 'init') { point.init(); } else if (op == 'move') { ctx._cmdPointMove(ctx, arg, tbl, args); } else if (op == 'label') { ctx._cmdPointLabel(args, alignX, alignY); } else if (op == 'scroll') { ctx._cmdPointScroll(args); } else if (op == 'selectoption') { ret = ctx._cmdPointSelectOpt(ctx, args); } else if (op == 'getprop') { ret = point.getProp(args[1]); } else if (op == 'setprop') { point.setProp(args[1], DebugJS.getArgsFrom(arg, 2), echo); } else if (op == 'text') { ctx._cmdPointText(arg); } else if (op == 'verify') { ret = ctx._cmdPointVerify(arg); } else if (op == 'event') { ret = point.event(DebugJS.getArgsFrom(arg, 1)); } else if (op == 'cursor') { ctx._cmdPointCursor(args, tbl); } else if (op == 'show') { point.show(); } else if (op == 'hide') { point.hide(); } else if (op == 'hint') { ctx._cmdPointHint(ctx, arg, point, args[1]); } else if (op == 'drag') { point.drag(DebugJS.getArgsFrom(arg, 1)); } else if ((op == 'click') || (op == 'cclick') || (op == 'rclick') || (op == 'dblclick')) { var speed = DebugJS.getOptVal(arg, 'speed'); point.simpleEvent(op, speed); } else if ((op == 'blur') || (op == 'change') || (op == 'contextmenu') || (op == 'focus') || (op == 'mousedown') || (op == 'mouseup')) { point.simpleEvent(op, args[1]); } else if ((op == 'keydown') || (op == 'keypress') || (op == 'keyup')) { if (args[1] != undefined) { point.keyevt(args); } else { DebugJS.printUsage('point keydown|keypress|keyup -keyCode n -code c -key k [-s] [-c] [-a] [-m]'); } } else { ctx._cmdPointJmp(ctx, arg, tbl, args); } return ret; }, _cmdPointJmp: function(ctx, arg, tbl, args) { var point = DebugJS.point; var x, y; if (args[0] == '') { DebugJS._log('x=' + point.x + ', y=' + point.y); DebugJS.printUsage(tbl.help); return; } var p = ctx._cmdPointCalcPos(ctx, args[0], args[1]); if (p) { point(p.x, p.y); } else if (isNaN(args[0])) { var target = args[0]; var idx = args[1]; if (target.charAt(0) == '(') { target = target.substr(1, target.length - 2); } var alignX = DebugJS.getOptVal(arg, 'alignX'); var alignY = DebugJS.getOptVal(arg, 'alignY'); DebugJS.pointBySelector(target, idx, alignX, alignY); } else { x = args[0]; y = args[1]; point(x, y); } }, _cmdPointMove: function(ctx, arg, tbl, args) { var point = DebugJS.point; var target = args[1]; if (target == undefined) { DebugJS.printUsage(tbl.help); return; } var idx; var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); var alignX = DebugJS.getOptVal(arg, 'alignX'); var alignY = DebugJS.getOptVal(arg, 'alignY'); var p = ctx._cmdPointCalcPos(ctx, args[1], args[2]); if (p) { point.move(p.x, p.y, speed, step); } else if (target == 'label') { var label = args[2]; idx = args[3] | 0; try { label = eval(label); } catch (e) { DebugJS._log.e(e); return; } point.moveToLabel(label, idx, speed, step, alignX, alignY); } else if (isNaN(target)) { idx = args[2]; if (target.charAt(0) == '(') { target = target.substr(1, target.length - 2); } point.moveToSelector(target, idx, speed, step, alignX, alignY); } else { var x = args[1]; var y = args[2]; point.move(x, y, speed, step); } }, _cmdPointCalcPos: function(ctx, a1, a2) { var x = a1; var y = a2; if (a1 == 'mouse') { x = ctx.mousePos.x; y = ctx.mousePos.y; } else if (a1 == 'center') { var p = DebugJS.getScreenCenter(); x = p.x; if (a2 == undefined) y = p.y; } else if (a1 == 'left') { x = 0; if (a2 == undefined) y = '+0'; } else if (a1 == 'right') { x = document.documentElement.clientWidth; if (a2 == undefined) y = '+0'; } if (a2 == 'top') { y = 0; } else if (a2 == 'middle') { y = DebugJS.getScreenCenter().y; } else if (a2 == 'bottom') { y = document.documentElement.clientHeight; } if ((x == a1) && (y == a2)) { return null; } return {x: x, y: y}; }, _cmdPointHint: function(ctx, arg, point, op) { var a = DebugJS.getArgsFrom(arg, 2); if (op == 'msg') { if (!a) { DebugJS.printUsage('point hint msg "str"'); } else { point.hint(a, 0, 0); } } else if (op == 'msgseq') { ctx._cmdPointHintMsgSeq(ctx, arg, point); } else if (op == 'hide') { point.hint.hide(); } else if (op == 'show') { point.hint.show(); } else if (op == 'clear') { point.hint.clear(); } else { DebugJS.printUsage('point hint msg|msgseq "str"|show|hide|clear'); } }, _cmdPointHintMsgSeq: function(ctx, arg, point) { var a = DebugJS.splitCmdLine(arg); var m = a[2]; var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); var start = DebugJS.getOptVal(arg, 'start'); var end = DebugJS.getOptVal(arg, 'end'); if (speed == null) speed = ctx.props.textspeed; if (step == null) step = ctx.props.textstep; if (!m) { DebugJS.printUsage('point hint msgseq "str"'); } else { point.hint(m, speed, step, start, end); } }, _cmdPointCursor: function(args, tbl) { var src = args[1]; var w = args[2]; var h = args[3]; if (src == undefined) { DebugJS.printUsage(tbl.help); return; } if (src == 'default') src = ''; DebugJS.point.cursor(src, w, h); }, _cmdPointText: function(arg) { var el = DebugJS.point.getElementFromCurrentPos(); if ((!el) || (!DebugJS.isTxtInp(el))) { DebugJS._log.e('Pointed area is not an input element (' + (el ? el.nodeName : 'null') + ')'); return; } var txt = DebugJS.getArgVal(arg, 1); var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); var start = DebugJS.getOptVal(arg, 'start'); var end = DebugJS.getOptVal(arg, 'end'); try { DebugJS.setText(el, txt, speed, step, start, end); } catch (e) { DebugJS._log.e(e); } }, _cmdPointSelectOpt: function(ctx, args) { var ret; var el = DebugJS.point.getElementFromCurrentPos(); if ((el) && (el.nodeName == 'SELECT')) { var method = args[1]; var type = args[2]; if (((method == 'get') || (method == 'set')) && ((type == 'text') || (type == 'texts') || (type == 'value') || (type == 'values'))) { var val = args[3]; ret = ctx._cmdSelect(el, method, type, val); } else { DebugJS._log.e('Usage: point selectoption get|set text|texts|value|values val'); } } else { DebugJS._log.e('Pointed area is not a select element (' + (el ? el.nodeName : 'null') + ')'); } return ret; }, _cmdPointLabel: function(args, alignX, alignY) { var label = args[1]; try { label = eval(label); } catch (e) { DebugJS._log.e(e); return; } var idx = args[2] | 0; DebugJS.pointByLabel(label, idx, alignX, alignY); }, _cmdPointScroll: function(args) { var x = args[1]; var y = args[2]; var el = DebugJS.point.getElementFromCurrentPos(); if (el) { DebugJS.scrollElTo(el, x, y); } else { DebugJS._log.e('Failed to get element'); } }, _cmdPointVerify: function(arg) { var a = DebugJS.splitCmdLine(arg); var prop = a[1]; var method = a[2]; var exp = DebugJS.getArgsFrom(arg, 3); var label = DebugJS.getOptVal(a, 'label'); if (label != null) { prop = a[3]; method = a[4]; exp = DebugJS.getArgsFrom(arg, 5); } return DebugJS.point.verify(prop, method, exp, label); }, cmdProp: function(arg, tbl) { arg = DebugJS.delLeadingSP(arg); if (arg == '') { DebugJS.printUsage(tbl.help); } else { var v = DebugJS.ctx.props[arg]; if (v != undefined) { DebugJS._log.res(v); return v; } else { DebugJS._log.e(arg + ' is invalid property name.'); } } }, cmdProps: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); if (a[0] == '-reset') { DebugJS.copyProp(ctx.PROPS_DFLT_VALS, ctx.props); DebugJS._log('debug properties have been reset.'); return; } else if (a[0] != '') { DebugJS.printUsage(tbl.help); return; } var s = 'Available properties:\n<table>'; for (var k in ctx.props) { s += '<tr><td>' + k + '</td><td>' + ctx.props[k] + '</td></tr>'; } s += '</table>'; DebugJS._log.mlt(s); }, cmdRandom: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var type = a[0] || DebugJS.RND_TYPE_NUM; var min, max; if (a[0] == '') { type = DebugJS.RND_TYPE_NUM; } else { if ((a[0] == DebugJS.RND_TYPE_NUM) || (a[0] == DebugJS.RND_TYPE_STR)) { type = a[0]; min = a[1]; max = a[2]; } else if (a[0].match(/[0-9]{1,}/)) { type = DebugJS.RND_TYPE_NUM; min = a[0]; max = a[1]; } else { DebugJS.printUsage(tbl.help); return; } } var rnd = DebugJS.getRandom(type, min, max); DebugJS._log(rnd); return rnd; }, cmdRadixConv: function(v, echo) { v = v.trim(); var rdx = DebugJS.checkRadix(v); if ((rdx == 10) || (rdx == 16) || (rdx == 2)) { DebugJS.ctx._cmdRadixConv(v, echo); return true; } else { return false; } }, _cmdRadixConv: function(v, echo) { if (!echo) return; var rdx = DebugJS.checkRadix(v); if (rdx == 10) { v = v.replace(/,/g, ''); DebugJS.convRadixFromDEC(v); } else if (rdx == 16) { DebugJS.convRadixFromHEX(v.substr(2)); } else if (rdx == 2) { DebugJS.convRadixFromBIN(v.substr(2)); } }, cmdResume: function(arg, tbl) { var k = DebugJS.getOptVal(arg, 'key'); if (arg == '') { DebugJS.bat._resume('cmd-key'); } else if (k != null) { DebugJS.bat.resume(k); } else { DebugJS.printUsage(tbl.help); } }, cmdReturn: function(arg, tbl) { DebugJS.bat.ret(arg); }, cmdRGB: function(arg, tbl) { arg = DebugJS.unifySP(arg.trim()); if (arg == '') { DebugJS.printUsage(tbl.help); } else { return DebugJS.convRGB(arg); } }, cmdROT: function(arg, tbl, echo) { var x = DebugJS.splitArgs(arg)[0]; var a = DebugJS.getArgsFrom(arg, 1); var fnE, fnD; switch (x) { case '5': fnE = DebugJS.encodeROT5; fnD = DebugJS.decodeROT5; break; case '13': fnE = DebugJS.encodeROT13; fnD = DebugJS.decodeROT13; break; case '47': fnE = DebugJS.encodeROT47; fnD = DebugJS.decodeROT47; break; default: DebugJS.printUsage(tbl.help); return; } var iIdx = 0; if ((DebugJS.hasOpt(a, 'd')) || (DebugJS.hasOpt(a, 'e'))) { iIdx++; } var n = DebugJS.getOptVal(a, 'n'); if (n == null) { n = x | 0; } else { n = n.replace(/\(|\)/g, '') | 0; iIdx += 2; } return DebugJS.ctx.execEncAndDec(a, tbl, echo, true, fnE, fnD, iIdx, n); }, cmdScrollTo: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); var target = a[0]; if (target == '') { DebugJS.printUsage(tbl.help); } else if (target == 'log') { var pos = a[1]; ctx._cmdScrollToLog(ctx, tbl, pos); } else if (target == 'window') { ctx._cmdScrollToWin(ctx, arg, tbl); } else { var x = a[1]; var y = a[2]; DebugJS.scrollElTo(target, x, y); } }, _cmdScrollToLog: function(ctx, tbl, pos) { if (pos == 'top') { pos = 0; } else if (pos == 'bottom') { pos = ctx.logPanel.scrollHeight; } if ((pos === '') || isNaN(pos)) { DebugJS.printUsage(tbl.help); } else { ctx.logPanel.scrollTop = pos; } }, _cmdScrollToWin: function(ctx, arg, tbl) { var a = DebugJS.getOptVal(arg, ''); var posX = a[1]; var posY = a[2]; var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); if (posX == undefined) { posX = DebugJS.splitCmdLine(arg)[1]; if (posX == undefined) { DebugJS.printUsage(tbl.help); return; } } if (speed == undefined) speed = ctx.props.scrollspeed; if (step == undefined) step = ctx.props.scrollstep; if (isNaN(posX)) { var slct = a[1]; var idx = a[2]; var ps = DebugJS.getElPosSize(slct, idx); if (ps) { var adjX = DebugJS.getOptVal(arg, 'adjX'); var adjY = DebugJS.getOptVal(arg, 'adjY'); try { if (adjX) ps.x += eval(adjX); if (adjY) ps.y += eval(adjY); } catch (e) { DebugJS.log.e('scollto window: ' + e); } DebugJS.scrollWinToTarget(ps, speed, step, null, null, true); return; } } if (posY == undefined) { posY = DebugJS.splitCmdLine(arg)[2]; if (posY == undefined) { DebugJS.printUsage(tbl.help); return; } } var y = ctx._cmdScrollWinGetY(posY); if (y == undefined) { DebugJS.printUsage(tbl.help); return; } var x = ctx._cmdScrollWinGetX(posX); if (x == undefined) { DebugJS.printUsage(tbl.help); return; } if ((speed == '0') || (step == '0')) { window.scroll(x, y); } else { DebugJS.scrollWinTo(x, y, speed, step); } }, _cmdScrollWinGetX: function(posX) { var x; var scrollX = (window.scrollX != undefined ? window.scrollX : window.pageXOffset); if (posX == 'left') { x = 0; } else if (posX == 'center') { x = document.body.clientWidth / 2; } else if (posX == 'right') { x = document.body.clientWidth; } else if (posX == 'current') { x = scrollX; } else if (posX.charAt(0) == '+') { x = scrollX + (posX.substr(1) | 0); } else if (posX.charAt(0) == '-') { x = scrollX - (posX.substr(1) | 0); } else if ((posX == '') || isNaN(posX)) { x = undefined; } else { x = posX; } return x; }, _cmdScrollWinGetY: function(posY) { var y; var scrollY = (window.scrollY != undefined ? window.scrollY : window.pageYOffset); if (posY == 'top') { y = 0; } else if (posY == 'middle') { y = (document.body.clientHeight - document.documentElement.clientHeight) / 2; } else if (posY == 'bottom') { y = document.body.clientHeight; } else if (posY == 'current') { y = scrollY; } else if (posY.charAt(0) == '+') { y = scrollY + (posY.substr(1) | 0); } else if (posY.charAt(0) == '-') { y = scrollY - (posY.substr(1) | 0); } else if ((posY == '') || isNaN(posY)) { y = undefined; } else { y = posY; } return y; }, cmdSelect: function(arg, tbl) { var a = DebugJS.splitCmdLine(arg); var sel = a[0]; var method = a[1]; var type = a[2]; var val = a[3]; if ((sel != '') && (((method == 'set') && (a.length >= 4)) || ((method == 'get') && (a.length >= 3))) && ((type == 'text') || (type == 'texts') || (type == 'value') || (type == 'values'))) { return DebugJS.ctx._cmdSelect(sel, method, type, val); } DebugJS.printUsage(tbl.help); }, _cmdSelect: function(sel, method, type, val) { try { var val = eval(val) + ''; var r = DebugJS.selectOption(sel, method, type, val); if (method == 'get') { if ((type == 'values') || (type == 'texts')) { DebugJS._log.p(r); } else { DebugJS._log.res(r); } } return r; } catch (e) { DebugJS._log.e(e); } }, cmdSet: function(arg, tbl, echo) { var a = DebugJS.splitCmdLine(arg); var nm = a[0]; var v = ((a[1] == undefined) ? '' : a[1]); if ((nm == '') || (v == '')) { DebugJS.printUsage(tbl.help); return; } DebugJS.ctx._cmdSet(DebugJS.ctx, nm, v, echo); }, _cmdSet: function(ctx, nm, val, echo) { var props = ctx.props; if (!props[nm]) { DebugJS._log.e(nm + ' is invalid property name.'); return; } var restriction = ctx.PROPS_RESTRICTION[nm]; if (restriction) { if (!(val + '').match(restriction)) { DebugJS._log.e(val + ' is invalid. (' + restriction + ')'); return; } } var r; if (ctx.PROPS_CB[nm]) { var r = ctx.PROPS_CB[nm](ctx, val); if (r != undefined) props[nm] = r; } props[nm] = (r === undefined ? val : r); if (echo) DebugJS._log.res(props[nm]); }, setPropBatContCb: function(ctx, v) { if (DebugJS.bat.isRunning()) { if (v == 'on') { ctx.status |= DebugJS.ST_BAT_CONT; } else { ctx.status &= ~DebugJS.ST_BAT_CONT; } } }, setPropIndentCb: function(ctx, v) { DebugJS.INDENT_SP = DebugJS.repeatCh(' ', v); }, setPropPointMsgSizeCb: function(ctx, v) { var s; try { s = eval(v); } catch (e) { DebugJS._log.e(e); return ctx.props.pointmsgsize; } ctx.props.pointmsgsize = s; var el = DebugJS.point.hint.pre; if (el) ctx.setStyle(el, 'font-size', s); }, setPropTimerCb: function(ctx, v) { var tm = DebugJS.timestr2struct(v); if (ctx.timerStopwatchCdInput) { ctx.timerTxtHH.value = tm.hh; ctx.timerTxtMI.value = tm.mi; ctx.timerTxtSS.value = tm.ss; ctx.timerTxtSSS.value = tm.sss; } return DebugJS.convTimeStr(tm); }, setPropConsoleLogCb: function(ctx, v) { DebugJS.setConsoleLogOut((v == 'me')); }, cmdSetAttr: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var sel = a[0]; var idx = 0; var nm = a[1]; var vl = a[2]; if (a[3] != undefined) { idx = a[1]; nm = a[2]; vl = a[3]; } if ((sel == '') || (nm == undefined) || (vl == undefined)) { DebugJS.printUsage(tbl.help); return; } var el = DebugJS.getElement(sel, idx); if (!el) { DebugJS._log.e('Element not found: ' + sel); return; } el.setAttribute(nm, vl); }, cmdSleep: function(arg, tbl) { var ms = DebugJS.splitArgs(arg)[0]; if ((ms == '') || isNaN(ms)) { DebugJS.printUsage(tbl.help); return; } DebugJS.sleep(ms); }, cmdTimeCalc: function(arg, echo) { var ret = null; arg = DebugJS.unifySP(arg.trim()); if (!arg.match(/^\d{1,}:{1}\d{2}/)) { return ret; } arg = DebugJS.delAllSP(arg); var op; if (arg.indexOf('-') >= 0) { op = '-'; } else if (arg.indexOf('+') >= 0) { op = '+'; } var vals = arg.split(op); if (vals.length < 2) { return ret; } var timeL = DebugJS.tmStr2ms(vals[0]); var timeR = DebugJS.tmStr2ms(vals[1]); if ((timeL == null) || (timeR == null)) { ret = 'Invalid time format'; DebugJS._log.e(ret); return ret; } var byTheDay = (vals[2] == undefined); if (op == '-') { ret = DebugJS.subTime(timeL, timeR, byTheDay); } else { ret = DebugJS.addTime(timeL, timeR, byTheDay); } if (echo) DebugJS._log.res(ret); return ret; }, cmdTest: function(arg, tbl) { var args = DebugJS.splitCmdLine(arg, 4); var op = args[0]; var test = DebugJS.test; switch (op) { case 'init': var nm = DebugJS.getOptVal(arg, 'name'); try { nm = eval(nm); test.init(nm); DebugJS._log('Test has been initialized.' + (nm == undefined ? '' : ' (' + nm + ')')); } catch (e) { DebugJS._log.e(e); } break; case 'set': DebugJS.ctx._cmdTestSet(arg); break; case 'count': var c = test.data.cnt; if (args[1] != '-d') c = test.getSumCount(); DebugJS._log(test.getCountStr(c)); break; case 'last': var st = test.getLastResult(); DebugJS._log(test.getStyledStStr(st)); return st; case 'result': DebugJS._log(test.result()); break; case 'ttlresult': var st = test.getTotalResult(); DebugJS._log(test.getStyledStStr(st)); return st; case 'status': DebugJS._log.p(test.getStatus(), 0, null, false); break; case 'verify': return DebugJS.ctx._CmdTestVerify(arg); case 'fin': test.fin(); DebugJS._log('Test completed.'); break; default: DebugJS.printUsage(tbl.help); } }, _cmdTestSet: function(arg) { var test = DebugJS.test; var args = DebugJS.splitCmdLine(arg, 3); var target = args[1]; var fn; switch (target) { case 'name': fn = test.setName; break; case 'desc': fn = test.setDesc; break; case 'id': fn = test.setId; break; case 'comment': fn = test.setCmnt; break; case 'result': DebugJS.ctx._cmdTestSetRslt(DebugJS.getArgsFrom(arg, 2)); return; case 'seq': fn = test.setSeq; break; default: DebugJS.printUsage('test set name|desc|id|comment|result|seq val'); return; } try { var v = eval(args[2]); if (v == undefined) v = ''; fn(v + ''); } catch (e) { DebugJS._log.e(e); } }, _CmdTestVerify: function(arg) { var a = DebugJS.splitCmdLine(arg); var got = a[1]; var method = a[2]; var exp = DebugJS.getArgsFrom(arg, 3); var label = DebugJS.getOptVal(a, 'label'); if (label != null) { got = a[3]; method = a[4]; exp = DebugJS.getArgsFrom(arg, 5); } return DebugJS.test.verify(got, method, exp, true, label); }, _cmdTestSetRslt: function(a) { var st = DebugJS.getArgVal(a, 0); var label = DebugJS.getOptVal(a, 'label'); var info = DebugJS.getOptVal(a, 'info'); try { var inf = eval(info); } catch (e) { DebugJS._log.e('Illegal info opt: ' + info); return; } DebugJS.test.setResult(st, label, inf); }, cmdText: function(arg, tbl) { var a = DebugJS.splitCmdLine(arg); var slctr = a[0]; var txt = a[1]; if (txt == undefined) { DebugJS.printUsage(tbl.help); return; } var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); var start = DebugJS.getOptVal(arg, 'start'); var end = DebugJS.getOptVal(arg, 'end'); DebugJS.setText(slctr, txt, speed, step, start, end); }, cmdTime: function(arg, tbl, echo) { if (DebugJS.countArgs(arg) == 0) { DebugJS.printUsage(tbl.help); return; } var t1 = DebugJS.getOptVal(arg, 't1'); var t2 = DebugJS.getOptVal(arg, 't2'); if (((t1 == null) || (t1 == '')) && (t2 == null)) { t1 = arg; } try { t1 = eval(t1); t2 = eval(t2); var s = DebugJS.getTimeDurationStr(t1, t2); if (echo) DebugJS._log.res(s); return s; } catch (e) { DebugJS.printUsage(tbl.help); return; } }, cmdTimer: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var op = a[0]; var tmrNm = a[1]; if (tmrNm == undefined) tmrNm = DebugJS.DFLT_TIMER_NAME; switch (op) { case 'start': DebugJS.time.start(tmrNm); break; case 'split': DebugJS.time._split(tmrNm, false); break; case 'stop': DebugJS.time.end(tmrNm); break; case 'list': DebugJS.time.list(); break; default: DebugJS.printUsage(tbl.help); } }, cmdStopwatch: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); var n = 0; var op = a[0]; if (a[0].substr(0, 2) == 'sw') { n = a[0].charAt(2) | 0; op = a[1]; } var r = -1; if ((n == 0) || (n == 1)) { r = ctx._cmdStopwatch(op, n); } else if (n == 2) { r = ctx._cmdStopwatch2(ctx, op); } if (r == -1) DebugJS.printUsage(tbl.help); return r; }, _cmdStopwatch: function(op, n) { var stopwatch = DebugJS.stopwatch; var elps = stopwatch.val(n); switch (op) { case 'start': stopwatch.start(n); break; case 'stop': stopwatch.stop(n); break; case 'reset': stopwatch.reset(n); break; case 'split': stopwatch.split(n); break; case 'end': stopwatch.end(n); break; case 'val': DebugJS._log('sw' + n + ': ' + DebugJS.getTimerStr(elps)); break; default: return -1; } return elps; }, _cmdStopwatch2: function(ctx, op) { if (!ctx.isAvailableTools(ctx)) return false; switch (op) { case 'start': ctx.startTimerStopwatchCd(); break; case 'stop': ctx.stopTimerStopwatchCd(); break; case 'reset': ctx.resetTimerStopwatchCd(); break; case 'split': ctx.splitTimerStopwatchCd(); break; case 'val': DebugJS._log(DebugJS.TIMER_NAME_SW_CD + ': ' + DebugJS.getTimerStr(ctx.timerSwTimeCd)); break; default: return -1; } return 0; }, cmdUnAlias: function(arg, tbl, echo) { var nm = DebugJS.splitArgs(arg); if (nm[0] == '') { DebugJS.printUsage(tbl.help); return; } if (nm[0] == '-a') { DebugJS.ctx.CMD_ALIAS = {}; return; } var tbl = DebugJS.ctx.CMD_ALIAS; for (var i = 0; i < nm.length; i++) { if (tbl[nm[i]] == undefined) { DebugJS._log(nm[i] + ': not found'); } else { delete tbl[nm[i]]; } } }, cmdUnicode: function(arg, tbl, echo) { var iIdx = 0; if ((DebugJS.hasOpt(arg, 'd')) || (DebugJS.hasOpt(arg, 'e'))) iIdx++; return DebugJS.ctx.execEncAndDec(arg, tbl, echo, false, DebugJS.getUnicodePoints, DebugJS.decodeUnicode, iIdx); }, cmdUri: function(arg, tbl, echo) { var iIdx = 0; if ((DebugJS.hasOpt(arg, 'd')) || (DebugJS.hasOpt(arg, 'e'))) iIdx++; return DebugJS.ctx.execEncAndDec(arg, tbl, echo, true, DebugJS.encodeUri, DebugJS.decodeUri, iIdx); }, cmdUtf8: function(arg, tbl, echo) { try { var s = eval(arg); if (typeof s == 'string') { var bf = DebugJS.UTF8.toByte(s); if (echo) DebugJS.ctx._dumpByteSeq(s, bf.length); return bf; } else { DebugJS.printUsage(tbl.help); } } catch (e) { DebugJS._log.e(e); DebugJS.printUsage(tbl.help); } }, _dumpByteSeq: function(str, len) { var s = ''; var cnt = 0; for (var i = 0; i < str.length; i++) { var ch = str.charAt(i); var a = DebugJS.UTF8.toByte(ch); for (var j = 0; j < a.length; j++) { var v = a[j]; s += '[' + DebugJS.strPadding(cnt, ' ', DebugJS.digits(len), 'L') + '] '; s += DebugJS.strPadding(v, ' ', 3, 'L') + ' '; s += DebugJS.toHex(v, true, true, 2) + ' '; s += DebugJS.toBin(v); if (j == 0) { s += ' ' + DebugJS.getUnicodePoints(ch); s += ' ' + DebugJS.hlCtrlChr(ch, true); } s += '\n'; cnt++; } } DebugJS._log.mlt(s); }, cmdV: function(arg, tbl) { DebugJS._log(DebugJS.ctx.v); return DebugJS.ctx.v; }, cmdVals: function(arg, tbl) { var ctx = DebugJS.ctx; var o = DebugJS.getOptVal(arg, 'c'); if (o == null) { ctx._cmdVals(ctx); } else { ctx._cmdValsC(ctx); } }, _cmdVals: function(ctx) { var v = ''; for (var k in ctx.CMDVALS) { v += '<tr><td class="dbg-cmdtd">' + k + '</td><td>' + DebugJS.objDump(ctx.CMDVALS[k], false) + '</td></tr>'; } if (v == '') { DebugJS._log('no variables'); } else { v = '<table>' + v + '</table>'; DebugJS._log.mlt(v); } }, _cmdValsC: function(ctx) { for (var n in ctx.CMDVALS) { if (!DebugJS.isSysVal(n)) delete ctx.CMDVALS[n]; } }, cmdWatchdog: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var op = a[0]; var time = a[1]; switch (op) { case 'start': DebugJS.wd.start(time); break; case 'stop': DebugJS.wd.stop(); break; default: if (DebugJS.ctx.status & DebugJS.ST_WD) { DebugJS._log('Running ' + DebugJS.ctx.props.wdt + 'ms: ' + DebugJS.wd.cnt); } else { DebugJS._log('Not Running'); } DebugJS.printUsage(tbl.help); } }, cmdWin: function(arg, tbl) { var size = arg.trim(); switch (size) { case 'min': case 'normal': case 'full': case 'expand': case 'center': case 'restore': case 'reset': DebugJS.ctx.setWinSize(size); break; default: DebugJS.printUsage(tbl.help); } }, setWinSize: function(opt) { var ctx = DebugJS.ctx; switch (opt) { case 'min': ctx.saveSize(ctx); ctx.savePosNone(ctx); ctx.setDbgWinSize(ctx.computedMinW, ctx.computedMinH); ctx.scrollLogBtm(ctx); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.sizeStatus = DebugJS.SIZE_ST_MIN; ctx.updateWinCtrlBtnPanel(); break; case 'normal': var w = (ctx.initWidth - (DebugJS.WIN_SHADOW / 2) + DebugJS.WIN_BORDER); var h = (ctx.initHeight - (DebugJS.WIN_SHADOW / 2) + DebugJS.WIN_BORDER); ctx.setDbgWinSize(w, h); ctx.sizeStatus = DebugJS.SIZE_ST_NORMAL; ctx.updateWinCtrlBtnPanel(); ctx.scrollLogBtm(ctx); break; case 'restore': if (ctx.sizeStatus != DebugJS.SIZE_ST_NORMAL) { ctx.restoreDbgWin(); ctx.updateWinCtrlBtnPanel(); } break; case 'reset': ctx.resetDbgWinSizePos(); break; case 'center': case 'full': case 'expand': ctx.expandDbgWin(opt); ctx.updateWinCtrlBtnPanel(); } }, cmdZoom: function(arg, tbl) { var zm = arg.trim(); if (zm == '') { DebugJS.printUsage(tbl.help); } else if (zm != DebugJS.ctx.opt.zoom) { DebugJS.zoom(zm); } return DebugJS.zoom(); }, cmdNop: function(arg, tbl) {}, execEncAndDec: function(arg, tbl, echo, esc, encFnc, decFnc, iIdx, a1, a2) { if (DebugJS.countArgs(arg) == 0) { DebugJS.printUsage(tbl.help); return; } var fn = encFnc; if (DebugJS.hasOpt(arg, 'd')) { fn = decFnc; } else if (DebugJS.hasOpt(arg, 'e')) { fn = encFnc; } var i = DebugJS.getOptVal(arg, 'i'); try { if (i == null) { i = DebugJS.getArgsFrom(arg, iIdx); } else { i = eval(i); } var ret = fn(i, a1, a2); var r = (esc ? DebugJS.escTags(ret) : ret); if (echo) DebugJS._log.res(DebugJS.quoteStrIfNeeded(r)); return ret; } catch (e) { DebugJS._log.e(e); } }, doHttpRequest: function(method, arg) { var a = DebugJS.splitCmdLineInTwo(arg); var url = a[0]; var data = a[1]; var user = ''; var pass = ''; if (url == '--user') { var parts = DebugJS.splitCmdLineInTwo(data); var auth = parts[0]; var auths = auth.split(':'); if (auths.length > 1) { user = auths[0]; pass = auths[1]; parts = DebugJS.splitCmdLineInTwo(parts[1]); url = parts[0]; data = parts[1]; } } data = DebugJS.encodeURIString(data); method = method.toUpperCase(); var req = 'Sending a request.\n' + method + ' ' + url + '\n' + 'Body: ' + ((data == '') ? '<span style="color:#ccc">null</span>' : data); if (user || pass) { req += '\nuser: ' + user + ':' + (pass ? '*' : ''); } DebugJS._log(req); var request = { url: url, method: method, data: data, async: true, cache: false, user: user, pass: pass //userAgent: 'Mozilla/5.0' }; try { DebugJS.http(request, DebugJS.onHttpRequestDone); } catch (e) { DebugJS._log.e(e); var baseURI = document.baseURI; var reg = new RegExp('^' + baseURI + '(.*?)'); if (!url.match(reg)) { DebugJS._log.w('Cross-Origin Request\nsource : ' + baseURI + '\nrequest: ' + url); } } }, initExtension: function(ctx) { ctx.initExtPanel(ctx); }, initExtPanel: function(ctx) { if (ctx.extPanel == null) { var bp = ctx.createSubBasePanel(ctx); ctx.extPanel = bp.base; ctx.extHeaderPanel = bp.head; ctx.extBodyPanel = bp.body; ctx.extBodyPanel.style.overflow = 'auto'; } var pnls = ctx.extPanels; if (pnls.length > 0) { if (ctx.extBtn) ctx.extBtn.style.display = ''; for (var i = 0; i < pnls.length; i++) { var p = pnls[i]; if ((p != null) && (p.base == null)) { ctx.createExtPanel(ctx, p, i); } DebugJS.x.addFileLdr(p); } } }, redrawExtPanelBtn: function(ctx) { for (var i = ctx.extHeaderPanel.childNodes.length - 1; i >= 0; i--) { ctx.extHeaderPanel.removeChild(ctx.extHeaderPanel.childNodes[i]); } var pnls = ctx.extPanels; if (pnls.length > 0) { for (i = 0; i < pnls.length; i++) { var p = pnls[i]; if (p != null) { ctx.extHeaderPanel.appendChild(p.btn); } } } else { ctx.extBtn.style.display = 'none'; } }, createExtPanel: function(ctx, p, idx) { p.base = document.createElement('div'); p.base.className = 'dbg-sbpnl'; p.btn = ctx.createExtHeaderBtn(ctx, p.name, idx); if (p.panel) { p.base.appendChild(p.panel); } else { p.panel = p.base; } if (p.onCreate) p.onCreate(p.panel); }, existsCmd: function(cmd, tbl) { for (var i = 0; i < tbl.length; i++) { if (tbl[i].cmd == cmd) return true; } return false; } }; DebugJS.addSubPanel = function(base) { var el = document.createElement('div'); el.className = 'dbg-sbpnl'; base.appendChild(el); return el; }; DebugJS.addPropSep = function(ctx) { return '<div class="dbg-sep"></div>'; }; DebugJS.addSysInfoPropH = function(n) { return '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '">' + n + '.</span>\n'; }; DebugJS.addSysInfoProp = function(n, v, id) { var s = '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '"> ' + n + '</span>: '; if (id == undefined) { s += v; } else { s += '<span' + (id == undefined ? '' : ' id="' + DebugJS.ctx.id + '-' + id + '"') + '>' + v + '</span>'; } s += '\n'; return s; }; DebugJS.getColorBlock = function(color) { var w = DebugJS.ctx.computedFontSize / 2; var h = DebugJS.ctx.computedFontSize; return '<span style="background:' + color + ';width:' + w + 'px;height:' + h + 'px;display:inline-block"> </span>'; }; DebugJS.getElmHexColor = function(color) { var hex = ''; if ((color) && (color != 'transparent')) { var color10 = color.replace('rgba', '').replace('rgb', '').replace('(', '').replace(')', '').replace(',', ''); var color16 = DebugJS.convRGB10to16(color10); hex = '#' + color16.r + color16.g + color16.b; } return hex; }; DebugJS.RingBuffer = function(len) { this.buffer = new Array(len); this.len = len; this.cnt = 0; }; DebugJS.RingBuffer.prototype = { add: function(data) { var idx = this.cnt % this.len; this.buffer[idx] = data; this.cnt++; }, set: function(idx, data) { this.buffer[idx] = data; }, get: function(idx) { if (this.len < this.cnt) { idx += this.cnt; } idx %= this.len; return this.buffer[idx]; }, getAll: function() { var buf = []; var len = this.len; var pos = 0; if (this.cnt > len) { pos = (this.cnt % len); } for (var i = 0; i < len; i++) { if (pos >= len) { pos = 0; } if (this.buffer[pos] == undefined) { break; } else { buf[i] = this.buffer[pos]; pos++; } } return buf; }, clear: function() { this.buffer = new Array(this.len); this.cnt = 0; }, count: function() { return this.cnt; }, size: function() { return this.len; }, lastIndex: function() { return ((this.cnt - 1) % this.len); } }; DebugJS.TextBuffer = function(s) { this.b = (s == undefined ? '' : s + '\n'); }; DebugJS.TextBuffer.prototype = { add: function(s) { this.b += s + '\n'; }, toString: function() { return this.b; } }; DebugJS.getCmdValName = function(v, pfix, head) { var m = pfix + '\\{(.+?)\\}'; if (head) m = '^' + m; var re = new RegExp(m); var r = re.exec(v); if (r == null) return null; var idx = r.index; if ((idx > 0) && ((v.charAt(idx - 1) == '\\'))) { return null; } return r[1]; }; DebugJS.replaceCmdVals = function(s) { s = DebugJS._replaceCmdVals(s, true); s = DebugJS._replaceCmdVals(s); return s; }; DebugJS._replaceCmdVals = function(s, il) { var prevN; var pfix = (il ? '%' : '\\$'); while (true) { var name = DebugJS.getCmdValName(s, pfix); if (name == null) return s; if (name == prevN) { DebugJS._log.e('(bug) replaceCmdVals(): ' + name); return s; } prevN = name; var reNm = name; if (name == '?') reNm = '\\?'; var re = new RegExp(pfix + '\\{' + reNm + '\\}', 'g'); var r; if (il) { r = DebugJS.ctx.CMDVALS[name] + ''; } else { r = 'DebugJS.ctx.CMDVALS[\'' + name + '\']'; } s = s.replace(re, r); } }; // " 1 2 3 4 " -> [0]="1" [1]="2" [2]="3" [3]="4" DebugJS.splitArgs = function(arg) { return DebugJS.unifySP(arg.trim()).split(' '); }; // ' 1 "abc" "d ef" "g\"hi" 2 ("jkl" + 3) 4 ' // -> [0]=1 [1]="abc" [2]="d ef" [3]="g\"hi" [4]=2 [5]=("jkl" + 3) [6]=4 DebugJS.splitCmdLine = function(arg, limit) { var args = []; var start = 0; var len = 0; var srch = true; var quoted = null; var paren = 0; var ch = ''; var str = ''; limit = (limit == undefined ? 0 : limit); for (var i = 0; i < arg.length; i++) { len++; ch = arg.charAt(i); switch (ch) { case ' ': if (srch || quoted || (paren > 0)) { continue; } else { srch = true; str = arg.substr(start, len); args.push(str); if (args.length + 1 == limit) { if (i < arg.length - 1) { start = i + 1; len = arg.length - start; str = arg.substr(start, len); args.push(str); i = arg.length; } } } break; case '(': if (srch) { start = i; len = 0; srch = false; } if (!quoted) { paren++; } break; case ')': if (srch) { start = i; len = 0; srch = false; } else if (paren > 0) { if ((i > 0) && (arg.charAt(i - 1) == '\\')) { continue; } paren--; } break; case '"': case "'": if (paren > 0) { continue; } else if (srch) { start = i; len = 0; srch = false; quoted = ch; } else if (ch == quoted) { if ((i > 0) && (arg.charAt(i - 1) == '\\')) { continue; } quoted = null; } break; default: if (srch) { start = i; len = 0; srch = false; } } } len++; if (!srch) { str = arg.substr(start, len); args.push(str); } if (args.length == 0) { args = ['']; } return args; }; // " 1 2 3 4 " -> [0]="1" [1]=" 2 3 4 " DebugJS.splitCmdLineInTwo = function(s) { var r = []; s = DebugJS.delLeadingSP(s); var two = DebugJS.splitCmdLine(s); if (two.length == 1) { r[0] = two[0]; r[1] = ''; } else { r[0] = two[0]; r[1] = s.substr(two[0].length + 1); } return r; }; // " 1 2 3 4 " (2)-> " 3 4 " DebugJS.getArgsFrom = function(s, n) { var r = s; for (var i = 0; i < n; i++) { r = DebugJS.splitCmdLineInTwo(r)[1]; } return r; }; DebugJS.countArgs = function(a) { var b = DebugJS.splitCmdLine(a); var c = b.length; if (b[0] == '') c = 0; return c; }; DebugJS.getArgVal = function(a, idx) { return DebugJS.splitCmdLine(a)[idx]; }; DebugJS.getOptVal = function(args, opt) { var v = DebugJS.getOptVals(args); return (v[opt] == undefined ? null : v[opt]); }; DebugJS.getOptVals = function(args) { var i, k, v; var o = {'': []}; if (typeof args == 'string') { args = DebugJS.splitCmdLine(args); } for (i = 0; i < args.length; i++) { if ((args[i].charAt(0) == '-') && ((k = args[i].substring(1)) != '')) { if ((args[i + 1] != undefined) && (args[i + 1].charAt(0) != '-')) { i++; v = args[i]; } else { v = ''; } o[k] = v; } else { o[''].push(args[i]); } } return o; }; DebugJS.hasOpt = function(arg, opt) { var b = false; var v = DebugJS.getOptVal(arg, opt); if (opt == '') { if (v.length > 0) b = true; } else { if (v != null) b = true; } return b; }; DebugJS.indexOfOptVal = function(a, o) { var r = -1; var i = a.indexOf(o); if (i >= 0) { r = i + o.length + 1; } return r; }; DebugJS.getQuotedStr = function(str) { var r = null; var start = 0; var len = 0; var srch = true; var quoted = null; var ch = ''; for (var i = 0; i < str.length; i++) { len++; ch = str.charAt(i); if ((ch == '"') || (ch == "'")) { if (srch) { start = i; len = 0; srch = false; quoted = ch; } else if (ch == quoted) { if ((i > 0) && (str.charAt(i - 1) == '\\')) { continue; } r = str.substr(start + 1, len - 1); break; } } } return r; }; DebugJS.encodeEsc = function(s) { return s.replace(/\\/g, '\\\\'); }; DebugJS.decodeEsc = function(s) { return s.replace(/\\\\/g, '\\'); }; DebugJS.isNumeric = function(ch) { var c = ch.charCodeAt(); return ((c >= 0x30) && (c <= 0x39)); }; DebugJS.isAlphabetic = function(ch) { var c = ch.charCodeAt(); return (((c >= 0x41) && (c <= 0x5A)) || ((c >= 0x61) && (c <= 0x7A))); }; DebugJS.isUpperCase = function(ch) { var c = ch.charCodeAt(); return ((c >= 0x41) && (c <= 0x5A)); }; DebugJS.isLowerCase = function(ch) { var c = ch.charCodeAt(); return ((c >= 0x61) && (c <= 0x7A)); }; DebugJS.isPunctuation = function(ch) { var c = ch.charCodeAt(); if (((c >= 0x20) && (c <= 0x2F)) || ((c >= 0x3A) && (c <= 0x40)) || ((c >= 0x5B) && (c <= 0x60)) || ((c >= 0x7B) && (c <= 0x7E))) { return true; } return false; }; DebugJS.isNumAlpha = function(ch) { var c = ch.charCodeAt(); return (DebugJS.isNumeric(ch) || DebugJS.isAlphabetic(ch)); }; DebugJS.isTypographic = function(ch) { var c = ch.charCodeAt(); return (DebugJS.isNumAlpha(ch) || DebugJS.isPunctuation(ch)); }; DebugJS.isNum = function(s) { return (s.match(/^\d+$/) ? true : false); }; DebugJS.wBOM = function(s) { return s.charCodeAt(0) == 65279; }; DebugJS.getContentType = function(mime, file, dturlData) { var t = ''; var ext = ['bat', 'csv', 'ini', 'java', 'js', 'json', 'log', 'md']; var re = ''; for (var i = 0; i < ext.length; i++) { if (i > 0) {re += '|';} re += '.' + ext[i] + '$'; } var xmlHead = 'PD94bWw'; if (mime) { if (mime.match(/image\//)) { t = 'image'; } else if (mime.match(/text\//)) { t = 'text'; } } else if (file) { if (file.type.match(/image\//)) { t = 'image'; } else if ((file.type.match(/text\//)) || ((new RegExp(re)).test(file.name)) || DebugJS.startsWith(dturlData, xmlHead)) { t = 'text'; } } return t; }; DebugJS.KEYCH = { Spacebar: ' ', Enter: '\n', Add: '+', Subtract: '-', Multiply: '*', Divide: '/', Del: '.' }; DebugJS.key2ch = function(k) { return (DebugJS.KEYCH[k] == undefined ? k : DebugJS.KEYCH[k]); }; DebugJS.unifySP = function(s) { return s.replace(/\s{2,}/g, ' '); }; DebugJS.delAllSP = function(s) { return s.replace(/\s/g, ''); }; DebugJS.delLeadingSP = function(s) { return s.replace(/^\s{1,}/, ''); }; DebugJS.delTrailingSP = function(s) { return s.replace(/\s+$/, ''); }; DebugJS.delAllNL = function(s) { s = s.replace(/\r/g, ''); s = s.replace(/\n/g, ''); return s; }; DebugJS.quoteStr = function(s) { return '<span style="color:#0ff">"</span>' + s + '<span style="color:#0ff">"</span>'; }; DebugJS.quoteStrIfNeeded = function(s) { s += ''; if ((s.match(/^\s|^&#x3000/)) || (s.match(/\s$|&#x3000$/))) { s = DebugJS.quoteStr(s); } return s; }; DebugJS.escEncString = function(s) { s = DebugJS.escTags(s); s = DebugJS.quoteStr(s); return s; }; DebugJS.styleValue = function(v) { var s = v; if (typeof s == 'string') { s = DebugJS.escTags(s); s = DebugJS.quoteStr(s); } else { s = DebugJS.setStyleIfObjNA(s); } return s; }; DebugJS.getDateTime = function(dt) { if ((dt == undefined) || (dt === '')) { dt = new Date(); } else if (!(dt instanceof Date)) { dt = new Date(dt); } var time = dt.getTime(); var offset = dt.getTimezoneOffset(); var yyyy = dt.getFullYear(); var mm = dt.getMonth() + 1; var dd = dt.getDate(); var hh = dt.getHours(); var mi = dt.getMinutes(); var ss = dt.getSeconds(); var ms = dt.getMilliseconds(); var wd = dt.getDay(); if (mm < 10) mm = '0' + mm; if (dd < 10) dd = '0' + dd; if (hh < 10) hh = '0' + hh; if (mi < 10) mi = '0' + mi; if (ss < 10) ss = '0' + ss; if (ms < 10) {ms = '00' + ms;} else if (ms < 100) {ms = '0' + ms;} var dateTime = {time: time, offset: offset, yyyy: yyyy, mm: mm, dd: dd, hh: hh, mi: mi, ss: ss, sss: ms, wday: wd}; return dateTime; }; DebugJS.getDateTimeIso = function(s) { var p = s.split('T'); var d = p[0]; var t = p[1]; var yyyy = d.substr(0, 4); var mm = d.substr(4, 2); var dd = d.substr(6, 2); var hh = (t.substr(0, 2) + '00').substr(0, 2); var mi = (t.substr(2, 2) + '00').substr(0, 2); var ss = (t.substr(4, 2) + '00').substr(0, 2); var sss = (t.substr(7, 3) + '000').substr(0, 3); var dt = new Date(yyyy, (mm | 0) - 1, dd, hh, mi, ss, sss); return DebugJS.getDateTime(dt); }; DebugJS.getDateTimeEx = function(s) { if (DebugJS.isDateTimeFormatIso(s)) { return DebugJS.getDateTimeIso(s); } if (typeof s == 'string') { s = s.replace(/-/g, '/'); var dec = s.split('.'); if (dec.length > 0) s = dec[0]; s = (new Date(s)).getTime(); if (dec.length > 0) s += (dec[1] | 0); } return DebugJS.getDateTime(s); }; DebugJS.date = function(val, iso) { val += ''; val = val.trim(); var s = null; var dt; if ((val == '') || isNaN(val)) { if (DebugJS.isDateTimeFormatIso(val)) { dt = DebugJS.getDateTimeIso(val); } else { val = val.replace(/(\d{4})-(\d{1,})-(\d{1,})/g, '$1/$2/$3'); dt = DebugJS.getDateTime(val); } var tm = dt.time; if (!isNaN(tm)) { if (iso) { s = DebugJS.date(tm, iso); } else { s = DebugJS.date(tm) + ' (' + tm + ')'; } } } else { val = DebugJS.parseInt(val); dt = DebugJS.getDateTime(val); if (iso) { s = DebugJS.getDateTimeStrIso(dt); } else { s = DebugJS.convDateTimeStr(dt) + ' ' + DebugJS.getTimeOffsetStr(dt.offset); } } return s; }; DebugJS.diffDate = function(d1, d2) { var dt1 = DebugJS.getDateTime(d1); var dt2 = DebugJS.getDateTime(d2); return (dt2.time - dt1.time) / 86400000; }; DebugJS.isDateFormat = function(s, p) { if (s == null) return false; var r = '^\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}'; if (!p) r += '$'; return (s.match(new RegExp(r)) ? true : false); }; DebugJS.isBasicDateFormat = function(s, p) { if (s == null) return false; var r = '^\\d{4}[0-1][0-9][0-3][0-9]'; if (!p) r += '$'; return (s.match(new RegExp(r)) ? true : false); }; DebugJS.isDateTimeFormat = function(s, p) { if (s == null) return false; var r = '^\\d{4}[-/]\\d{1,2}[-/]\\d{1,2} {1,}\\d{1,2}:\\d{2}:?\\d{0,2}.?\\d{0,3}'; if (!p) r += '$'; return (s.match(new RegExp(r)) ? true : false); }; DebugJS.isDateTimeFormatIso = function(s, p) { if (typeof s != 'string') return false; var r = '^\\d{8}T\\d{0,6}.?\\d{0,3}'; if (!p) r += '$'; return (s.match(new RegExp(r)) ? true : false); }; DebugJS.isTimeFormat = function(s) { return ((s.match(/^\d{8}T\d{4,6}$/)) || (s.match(/^T\d{4,6}$/))); }; DebugJS.num2date = function(s) { var d = null; if (DebugJS.isBasicDateFormat(s)) { d = s.substr(0, 4) + '/' + s.substr(4, 2) + '/' + s.substr(6, 2); } return d; }; DebugJS.today = function(s) { return DebugJS.convDateStr(DebugJS.getDateTime(), (s === undefined ? '-' : s)); }; DebugJS.convDateTimeStr = function(d) { return (d.yyyy + '-' + d.mm + '-' + d.dd + ' ' + DebugJS.WDAYS[d.wday] + ' ' + d.hh + ':' + d.mi + ':' + d.ss + '.' + d.sss); }; DebugJS.getDateTimeStrIso = function(d) { return (d.yyyy + d.mm + d.dd + 'T' + d.hh + d.mi + d.ss + '.' + d.sss); }; DebugJS.convDateStr = function(d, s) { return d.yyyy + s + d.mm + s + d.dd; }; DebugJS.convTimeStr = function(d) { return d.hh + ':' + d.mi + ':' + d.ss + '.' + d.sss; }; DebugJS.getTimeStr = function(t) { var d = DebugJS.getDateTime(t); return d.hh + ':' + d.mi + ':' + d.ss + '.' + d.sss; }; DebugJS.getDateTimeStr = function(t) { var d = DebugJS.getDateTime(t); return d.yyyy + '-' + d.mm + '-' + d.dd + ' ' + d.hh + ':' + d.mi + ':' + d.ss + '.' + d.sss; }; DebugJS.getTimerStr = function(ms) { var tm = DebugJS.ms2struct(ms, true); return tm.hh + ':' + tm.mi + ':' + tm.ss + '.' + tm.sss; }; DebugJS.ms2struct = function(ms, fmt) { var wk = ms; var sign = false; if (ms < 0) { sign = true; wk *= (-1); } var d = (wk / 86400000) | 0; var hh = 0; if (wk >= 3600000) { hh = (wk / 3600000) | 0; wk -= (hh * 3600000); } var mi = 0; if (wk >= 60000) { mi = (wk / 60000) | 0; wk -= (mi * 60000); } var ss = (wk / 1000) | 0; var sss = wk - (ss * 1000); var tm = { sign: sign, d: d, hr: hh - d * 24, hh: hh, mi: mi, ss: ss, sss: sss }; if (fmt) { if (tm.hh < 10) tm.hh = '0' + tm.hh; if (tm.mi < 10) tm.mi = '0' + tm.mi; if (tm.ss < 10) tm.ss = '0' + tm.ss; if (tm.sss < 10) { tm.sss = '00' + tm.sss; } else if (tm.sss < 100) { tm.sss = '0' + tm.sss; } } return tm; }; DebugJS.timestr2struct = function(str) { var wk = str.split(':'); var h = wk[0]; var mi = (wk[1] == undefined ? '' : wk[1]); var s = (wk[2] == undefined ? '' : wk[2]); var ss = s.split('.')[0]; var sss = s.split('.')[1]; if (sss == undefined) sss = ''; mi = DebugJS.nan2zero(mi); ss = DebugJS.nan2zero(ss); sss = DebugJS.nan2zero(sss); var st = { hh: DebugJS.nan2zero(h), mi: ('00' + mi).slice(-2), ss: ('00' + ss).slice(-2), sss: ('000' + sss).slice(-3) }; return st; }; DebugJS.getTimeOffsetStr = function(v, e) { var s = '-'; if (v <= 0) { v *= (-1); s = '+'; } var h = (v / 60) | 0; var m = v - h * 60; var str = s + ('0' + h).slice(-2) + (e ? ':' : '') + ('0' + m).slice(-2); return str; }; DebugJS.getTimeDurationStr = function(t1, t2) { var dec; if (isNaN(t1)) t1 = DebugJS.getDateTimeEx(t1).time; var ms = t1; if (t2 != undefined) { if (isNaN(t2)) t2 = DebugJS.getDateTimeEx(t2).time; ms = t2 - t1; } var s = ''; var t = DebugJS.ms2struct(ms); if (t.d) s += t.d + 'd '; if (t.d || t.hr) s += t.hr + 'h '; if (t.d || t.hr || t.mi) s += t.mi + 'm '; if (t.d || t.hr || t.mi || t.ss) { s += t.ss + 's'; if (t.sss) s += ' ' + t.sss + 'ms'; } else { if (t.sss) { s = '0.' + ('00' + t.sss).slice(-3).replace(/0+$/, ''); } else { s = '0'; } s += 's'; } return s; }; DebugJS.calcTargetTime = function(tgt) { var yyyy, mm, dd, t1; var now = DebugJS.getDateTime(); var dt = tgt.split('T'); var date = dt[0]; var t = dt[1]; var hh = t.substr(0, 2); var mi = t.substr(2, 2); var ss = t.substr(4, 2); if (ss == '') ss = '00'; if (date == '') { yyyy = now.yyyy; mm = now.mm; dd = now.dd; var tgt = DebugJS.getDateTime(now.yyyy + '/' + now.mm + '/' + now.dd + ' ' + hh + ':' + mi + ':' + ss); if (now.time > tgt.time) { t1 = tgt.time + 86400000; } else { t1 = tgt.time; } } else { yyyy = date.substr(0, 4); mm = date.substr(4, 2); dd = date.substr(6, 2); var sd = yyyy + '/' + mm + '/' + dd + ' ' + hh + ':' + mi + ':' + ss; t1 = (new Date(sd)).getTime(); } return (t1 - now.time); }; DebugJS.calcNextTime = function(times) { var now = DebugJS.getDateTime(); ts = times.split('|'); ts.sort(); var ret = {t: ts[0]}; var yyyy = now.yyyy; var mm = now.mm; var dd = now.dd; for (var i = 0; i < ts.length; i++) { var t = ts[i]; t = t.replace(/T/, ''); var hh = t.substr(0, 2); var mi = t.substr(2, 2); var ss = t.substr(4, 2); if (ss == '') ss = '00'; var tgt = DebugJS.getDateTime(now.yyyy + '/' + now.mm + '/' + now.dd + ' ' + hh + ':' + mi + ':' + ss); if (i == 0) ret.time = tgt.time; if (now.time <= tgt.time) { ret.t = ts[i]; ret.time = tgt.time; return ret; } } ret.t = ts[0]; ret.time += 86400000; return ret; }; DebugJS.parseToMillis = function(v) { var d = 0, h = 0, m = 0, s = 0; var a = v.split('d'); if (a.length > 1) { d = a[0]; v = a[1]; } else { v = a[0]; } var a = v.split('h'); if (a.length > 1) { h = a[0]; v = a[1]; } else { v = a[0]; } var a = v.split('m'); if (a.length > 1) { m = a[0]; v = a[1]; } else { v = a[0]; } var a = v.split('s'); if (a.length > 1) { s = a[0]; } return (d * 86400000 + h * 3600000 + m * 60000 + s * 1000) | 0; }; DebugJS.nan2zero = function(v) { return (isNaN(v) ? 0 : v); }; DebugJS.checkModKey = function(e) { var shift = e.shiftKey ? DebugJS.COLOR_ACTIVE : DebugJS.COLOR_INACT; var ctrl = e.ctrlKey ? DebugJS.COLOR_ACTIVE : DebugJS.COLOR_INACT; var alt = e.altKey ? DebugJS.COLOR_ACTIVE : DebugJS.COLOR_INACT; var meta = e.metaKey ? DebugJS.COLOR_ACTIVE : DebugJS.COLOR_INACT; var metaKey = '<span style="color:' + shift + '">S</span><span style="color:' + ctrl + '">C</span><span style="color:' + alt + '">A</span><span style="color:' + meta + '">M</span>'; return metaKey; }; DebugJS._cmdP = function(_arg, _tbl) { var _obj; var _jsn = false; var _dmpLmt = DebugJS.ctx.props.dumplimit; var _vlLen = DebugJS.ctx.props.dumpvallen; var _lvLmt = 0; var _opt = DebugJS.getOptVals(_arg); for (var _k in _opt) { if ((_k == '') && (_opt[_k].length > 0)) { _obj = _opt[_k][0]; } var _lv = _k.match(/l(\d+)/); if (_lv != null) { _lvLmt = _lv[1]; if (!_obj) _obj = _opt[_k]; } if (_k == 'json') { _jsn = true; if (!_obj) _obj = _opt[_k]; } if (_k == 'a') { _dmpLmt = _vlLen = 0; if (!_obj) _obj = _opt[_k]; } } if (!_obj) { DebugJS.printUsage(_tbl.help); return; } var _cl = 'DebugJS.buf=DebugJS.objDump(' + _obj + ', _jsn, ' + _lvLmt + ', ' + _dmpLmt + ', ' + _vlLen + ');DebugJS._log.mlt(DebugJS.buf);'; try { eval(_cl); } catch (e) { DebugJS._log.e(e); } }; DebugJS.INDENT_SP = ' '; DebugJS.objDump = function(obj, toJson, levelLimit, limit, valLenLimit) { if (levelLimit == undefined) levelLimit = 0; if (limit == undefined) limit = DebugJS.ctx.props.dumplimit; if (valLenLimit == undefined) valLenLimit = 0; var arg = {lv: 0, cnt: 0, dump: ''}; if (typeof obj === 'function') { arg.dump += (toJson ? 'function' : '<span style="color:#4c4">function</span>') + '()\n'; } var ret = DebugJS._objDump(obj, arg, toJson, levelLimit, limit, valLenLimit); if ((limit > 0) && (ret.cnt > limit)) { DebugJS._log.w('The object is too large. (>=' + ret.cnt + ')'); } ret.dump = ret.dump.replace(/: {2,}\{/g, ': {'); ret.dump = ret.dump.replace(/\[\n {2,}\]/g, '[]'); return ret.dump; }; DebugJS._objDump = function(obj, arg, toJson, levelLimit, limit, valLenLimit) { var SNIP = (toJson ? '...' : '<span style="color:#aaa">...</span>'); var sibling = 0; try { if ((levelLimit > 0) && (arg.lv > levelLimit)) return arg; if ((limit > 0) && (arg.cnt > limit)) { if ((typeof obj !== 'function') || (Object.keys(obj).length > 0)) { arg.dump += SNIP; arg.cnt++; } return arg; } var indent = ''; for (var i = 0; i < arg.lv; i++) { indent += DebugJS.INDENT_SP; } if ((obj instanceof Array) || (obj instanceof Set)) { arg.cnt++; var len = ((obj instanceof Set) ? obj.size : obj.length); if (toJson) { arg.dump += '['; if (len > 0) { arg.dump += '\n'; } } else { if (obj instanceof Set) { arg.dump += '<span style="color:#6cf">[Set][' + len + ']</span>'; } else { arg.dump += '<span style="color:#e4b">[Array][' + len + ']</span>'; } } if ((levelLimit == 0) || ((levelLimit >= 1) && (arg.lv < levelLimit))) { var avil = true; for (i = 0; i < len; i++) { arg.lv++; indent += DebugJS.INDENT_SP; v = obj[i]; if (obj instanceof Set) { try { var it = obj.entries(); for (var j = 0; j <= i; j++) { v = it.next().value[0]; } } catch (e) {avil = false;} } if (toJson) { if (sibling > 0) { arg.dump += ',\n'; } if ((typeof v == 'number') || (typeof v == 'string') || (typeof v == 'boolean') || (v instanceof Array)) { arg.dump += indent; } } else { arg.dump += '\n' + indent + '[' + i + '] '; } if (avil) { arg = DebugJS._objDump(v, arg, toJson, levelLimit, limit, valLenLimit); } else { arg.dump += 'N/A'; } arg.lv--; indent = indent.replace(DebugJS.INDENT_SP, ''); sibling++; } } if (toJson) { if (sibling > 0) { arg.dump += '\n'; } if (len > 0) { if ((levelLimit >= 1) && (arg.lv >= levelLimit)) { arg.dump += indent + DebugJS.INDENT_SP + SNIP + '\n'; } arg.dump += indent; } arg.dump += ']'; } } else if (obj instanceof Object) { arg.cnt++; if ((typeof obj !== 'function') && (Object.prototype.toString.call(obj) !== '[object Date]') && ((window.ArrayBuffer) && !(obj instanceof ArrayBuffer))) { if (toJson) { arg.dump += indent; } else { arg.dump += '<span style="color:#49f">[Object]</span> '; } if ((toJson) || (levelLimit == 0) || ((levelLimit >= 1) && (arg.lv < levelLimit))) { arg.dump += '{\n'; } } if ((levelLimit == 0) || ((levelLimit >= 1) && (arg.lv < levelLimit))) { indent += DebugJS.INDENT_SP; for (var key in obj) { if (sibling > 0) { if (toJson) { arg.dump += ','; } arg.dump += '\n'; } if (typeof obj[key] === 'function') { arg.dump += indent + (toJson ? 'function' : '<span style="color:#4c4">function</span>'); if (obj[key].toString().match(/\[native code\]/)) { arg.dump += ' [native]'; } arg.dump += ' ' + DebugJS.escTags(key) + '()'; arg.cnt++; if ((levelLimit == 0) || ((levelLimit >= 1) && ((arg.lv + 1) < levelLimit))) { if (Object.keys(obj[key]).length > 0) { arg.dump += ' {\n'; } } } else if (Object.prototype.toString.call(obj[key]) === '[object Date]') { arg.dump += indent; if (toJson) {arg.dump += '"';} arg.dump += (toJson ? key : DebugJS.escTags(key)); if (toJson) {arg.dump += '"';} var dt = DebugJS.getDateTime(obj[key]); var date = dt.yyyy + '-' + dt.mm + '-' + dt.dd + ' ' + DebugJS.WDAYS[dt.wday] + ' ' + dt.hh + ':' + dt.mi + ':' + dt.ss + '.' + dt.sss + ' (' + obj[key].getTime() + ')'; arg.dump += ': '; if (toJson) { arg.dump += '"' + obj[key].toISOString() + '"'; } else { arg.dump += '<span style="color:#f80">[Date]</span> ' + date; } sibling++; continue; } else if ((window.ArrayBuffer) && (obj[key] instanceof ArrayBuffer)) { arg.dump += indent; if (toJson) {arg.dump += '"';} arg.dump += (toJson ? key : DebugJS.escTags(key)); if (toJson) {arg.dump += '"';} arg.dump += ': '; if (toJson) { arg.dump += '{}'; } else { arg.dump += '<span style="color:#d4c">[ArrayBuffer]</span> (byteLength = ' + obj[key].byteLength + ')'; } sibling++; continue; } else { arg.dump += indent; if (toJson) {arg.dump += '"';} arg.dump += (toJson ? key : DebugJS.escTags(key)); if (toJson) {arg.dump += '"';} arg.dump += ': '; } var hasChildren = false; for (var cKey in obj[key]) { hasChildren = true; break; } if ((typeof obj[key] !== 'function') || (hasChildren)) { arg.lv++; arg = DebugJS._objDump(obj[key], arg, toJson, levelLimit, limit, valLenLimit); arg.lv--; } if (typeof obj[key] === 'function') { if ((levelLimit == 0) || ((levelLimit >= 1) && ((arg.lv + 1) < levelLimit))) { if (Object.keys(obj[key]).length > 0) { arg.dump += '\n' + indent + '}'; } } } sibling++; } var empty = false; if (sibling == 0) { if (typeof obj === 'function') { arg.dump += '<span style="color:#4c4">function</span>()'; if (obj.toString().match(/\[native code\]/)) { arg.dump += ' [native]'; } } else if (Object.prototype.toString.call(obj) === '[object Date]') { var dt = DebugJS.getDateTime(obj); var date = dt.yyyy + '-' + dt.mm + '-' + dt.dd + ' ' + DebugJS.WDAYS[dt.wday] + ' ' + dt.hh + ':' + dt.mi + ':' + dt.ss + '.' + dt.sss + ' (' + obj.getTime() + ')'; if (toJson) { arg.dump += '"' + obj.toISOString() + '"'; } else { arg.dump += '<span style="color:#f80">[Date]</span> ' + date; } } else if ((window.ArrayBuffer) && (obj instanceof ArrayBuffer)) { if (toJson) { arg.dump += '{}'; } else { arg.dump += '<span style="color:#d4c">[ArrayBuffer]</span> (byteLength = ' + obj.byteLength + ')'; } } else { empty = true; arg.dump = arg.dump.replace(/\n$/, ''); arg.dump += '}'; } arg.cnt++; } indent = indent.replace(DebugJS.INDENT_SP, ''); if ((typeof obj !== 'function') && (Object.prototype.toString.call(obj) !== '[object Date]') && ((window.ArrayBuffer) && !(obj instanceof ArrayBuffer) && (!empty))) { arg.dump += '\n' + indent + '}'; } } if ((toJson) && (levelLimit >= 1) && (arg.lv >= levelLimit)) { arg.dump += indent + DebugJS.INDENT_SP + SNIP + '\n' + indent + '}'; } } else if (obj === null) { if (toJson) { arg.dump += 'null'; } else { arg.dump += '<span style="color:#ccc">null</span>'; } arg.cnt++; } else if (obj === undefined) { if (toJson) { arg.dump += 'undefined'; } else { arg.dump += '<span style="color:#ccc">undefined</span>'; } arg.cnt++; } else if (typeof obj == 'string') { var str; if ((valLenLimit > 0) && (obj.length > valLenLimit)) { str = obj.substr(0, valLenLimit); if (toJson) { str += '...'; } else { str = DebugJS.escTags(str) + SNIP; } } else { str = (toJson ? obj : DebugJS.escTags(obj)); } str = str.replace(/\\/g, '\\\\'); if (toJson) { str = str.replace(/\n/g, '\\n'); str = str.replace(/\r/g, '\\r'); } else { str = DebugJS.hlCtrlChr(str); } arg.dump += (toJson ? '"' + str.replace(/"/g, '\\"') + '"' : DebugJS.quoteStr(str)); arg.cnt++; } else { arg.dump += obj; arg.cnt++; } } catch (e) { arg.dump += '<span style="color:#f66">parse error: ' + e + '</span>'; arg.cnt++; } return arg; }; DebugJS.getKeys = function(o) { var keys = []; for (var k in o) { keys.push(k); } return keys; }; DebugJS.getKeysStr = function(o) { var keys = ''; for (var k in o) { keys += k + '\n'; } return keys; }; DebugJS.countElements = function(selector, showDetail) { if (!selector) selector = '*'; var cnt = {}; var el = null; var els = []; var total = 0; if (selector.charAt(0) == '#') { el = document.getElementById(selector.substr(1)); } else { if (selector.charAt(0) == '(') { selector = selector.substr(1, selector.length - 2); } els = document.querySelectorAll(selector); } if (el) { DebugJS.getChildElements(el, els); } if (els) { for (var i = 0; i < els.length; i++) { if (!cnt[els[i].tagName]) { cnt[els[i].tagName] = 1; } else { cnt[els[i].tagName]++; } total++; } } if (showDetail) { var l = '<table>'; for (var k in cnt) { l += '<tr><td>' + k + '</td><td style="text-align:right">' + cnt[k] + '</td></tr>'; } l += '<tr><td>Total</td><td style="text-align:right">' + total + '</td></tr></table>'; DebugJS._log.mlt(l); } return total; }; DebugJS.getChildElements = function(el, list) { if (!el.tagName) return; list.push(el); var children = el.childNodes; if (children) { for (var i = 0; i < children.length; i++) { DebugJS.getChildElements(children[i], list); } } }; DebugJS.isDescendant = function(el, t) { if (el) { var p = el.parentNode; while (p) { if (p == t) { return true; } p = p.parentNode; } } return false; }; DebugJS.isChild = function(p, el) { if (el) { var c = p.childNodes; for (var i = 0; i < c.length; i++) { if (c[i] == el) return true; } } return false; }; DebugJS.getHTML = function(b64) { var ctx = DebugJS.ctx; var el = document.getElementsByTagName('html').item(0); var cmdActive = false; if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { cmdActive = (document.activeElement == ctx.cmdLine); ctx.bodyEl.removeChild(ctx.win); } var html = el.outerHTML; if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { ctx.bodyEl.appendChild(ctx.win); ctx.scrollLogBtm(ctx); if (cmdActive) ctx.cmdLine.focus(); } if (b64) html = DebugJS.encodeB64(html); return html; }; DebugJS.formatJSON = function(s) { return DebugJS.fmtJSON(s, true, 0, 0, 0); }; DebugJS.fmtJSON = function(s, f, lv, lmt, vlen) { if (s) s = s.replace(/\\r\\n|\\r|\\n$/g, ''); var j = JSON.parse(s); return DebugJS.objDump(j, f, lv, lmt, vlen); }; DebugJS._cmdJson = function(s, f, lv) { var p = DebugJS.ctx.props; try { var j = DebugJS.fmtJSON(s, f, lv, p.dumplimit, p.dumpvallen); if (f) j = DebugJS.escTags(j); DebugJS._log.mlt(j); return j; } catch (e) { DebugJS._log.e('JSON format error: ' + DebugJS.hlJsonErr(s)); } }; DebugJS.hlJsonErr = function(json) { var jsn = json.trim().split('\\'); var cnt = 0; var res = ''; for (var i = 0; i < jsn.length; i++) { var chnk = jsn[i]; if (chnk == '') { cnt++; } else { if (i == 0) { res += chnk; continue; } if (cnt >= 1) { res += '\\'; for (var j = 0; j < (cnt - 1); j++) { res += '\\'; } if (cnt % 2 == 0) { res += '<span class="dbg-txt-hl">\\</span>'; } else { res += '\\'; } res += chnk; cnt = 0; } else { if (chnk.match(/^n|^r|^t|^b|^"/)) { res += '\\' + chnk; } else { res += '<span class="dbg-txt-hl">\\</span>' + chnk; } } } } res = res.replace(/\t/g, '<span class="dbg-txt-hl">\\t</span>'); res = res.replace(/\r\n/g, '<span class="dbg-txt-hl">\\r\\n</span>'); res = res.replace(/([^\\])\r/g, '$1<span class="dbg-txt-hl">\\r</span>'); res = res.replace(/([^\\])\n/g, '$1<span class="dbg-txt-hl">\\n</span>'); if (!res.match(/^\{/)) { res = '<span class="dbg-txt-hl"> </span>' + res; } res = res.replace(/\}([^}]+)$/, '}<span class="dbg-txt-hl">$1</span>'); if (!res.match(/\}$/)) { res = res + '<span class="dbg-txt-hl"> </span>'; } return res; }; DebugJS.fromJSON = function(j, r) { return JSON.parse(j, r); }; DebugJS.toJSON = function(o, r, s) { return JSON.stringify(o, r, s); }; DebugJS.obj2json = function(o) { return DebugJS.objDump(o, true, 0, 0, 0); }; DebugJS.digits = function(x) { var d = 0; if (x == 0) { d = 1; } else { while (x != 0) { x = (x / 10) | 0; d++; } } return d; }; DebugJS.parseInt = function(v) { var rdx = DebugJS.checkRadix(v); if (rdx == 10) { return parseInt(v, 10); } else if (rdx == 16) { return parseInt(v, 16); } else if (rdx == 2) { v = v.substr(2); return parseInt(v, 2); } return 0; }; DebugJS.checkRadix = function(v) { if (v.match(/^\-{0,1}[0-9,]+$/)) { return 10; } else if (v.match(/^\-{0,1}0x[0-9A-Fa-f]+$/)) { return 16; } else if (v.match(/^\-{0,1}0b[01\s]+$/)) { return 2; } return 0; }; DebugJS.arr2set = function(a, f) { var s = []; for (var i = 0; i < a.length; i++) { var v = a[i]; if (DebugJS.findArrVal(s, v, f) < 0) { s.push(v); } } return s; }; DebugJS.findArrVal = function(a, v, f) { var r = -1; for (var i = 0; i < a.length; i++) { if ((!f && (a[i] == v)) || (f && (a[i] === v))) { r = i; break; } } return r; }; DebugJS.countArrVal = function(a, v, f) { var c = 0; for (var i = 0; i < a.length; i++) { if ((!f && (a[i] == v)) || (f && (a[i] === v))) c++; } return c; }; DebugJS.delArrVal = function(arr, v) { for (var i = 0; i < arr.length; i++) { if (arr[i] == v) { arr.splice(i--, 1); } } }; DebugJS.nextArr = function(a, v) { var r = a[0]; for (var i = 0; i < a.length; i++) { if ((a[i] == v) && (i < (a.length - 1))) { r = a[i + 1];break; } } return r; }; DebugJS.printUsage = function(m) { DebugJS._log('Usage: ' + m); }; DebugJS.convRGB = function(v) { var r, rgb; if (v.indexOf('#') == 0) { rgb = DebugJS.convRGB16to10(v); r = 'rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')'; } else { v = v.replace(/rgb\(/, ''); v = v.replace(/\)/, ''); v = v.replace(/,/g, ' '); v = v.trim(); v = DebugJS.unifySP(v); rgb = DebugJS.convRGB10to16(v); r = '#' + rgb.r + rgb.g + rgb.b; } DebugJS._log(rgb.rgb); return r; }; DebugJS.convRGB16to10 = function(rgb16) { var boxSize = '0.7em'; var r16, g16, b16, r10, g10, b10; rgb16 = rgb16.replace(/\s/g, ''); if (rgb16.length == 7) { r16 = rgb16.substr(1, 2); g16 = rgb16.substr(3, 2); b16 = rgb16.substr(5, 2); } else if (rgb16.length == 4) { r16 = rgb16.substr(1, 1); g16 = rgb16.substr(2, 1); b16 = rgb16.substr(3, 1); r16 += r16; g16 += g16; b16 += b16; } else { return {rgb: '<span style="color:' + DebugJS.ctx.opt.logColorE + '">invalid value</span>'}; } r10 = parseInt(r16, 16); g10 = parseInt(g16, 16); b10 = parseInt(b16, 16); var rgb10 = '<span style="vertical-align:top;display:inline-block;height:1em"><span style="background:rgb(' + r10 + ',' + g10 + ',' + b10 + ');width:' + boxSize + ';height:' + boxSize + ';margin-top:0.2em;display:inline-block"> </span></span> <span style="color:' + DebugJS.COLOR_R + '">' + r10 + '</span> <span style="color:' + DebugJS.COLOR_G + '">' + g10 + '</span> <span style="color:' + DebugJS.COLOR_B + '">' + b10 + '</span>'; var rgb = {r: r10, g: g10, b: b10, rgb: rgb10}; return rgb; }; DebugJS.convRGB10to16 = function(rgb10) { var boxSize = '0.7em'; rgb10 = DebugJS.unifySP(rgb10); var rgb10s = rgb10.split(' ', 3); if ((rgb10s.length != 3) || ((rgb10s[0] < 0) || (rgb10s[0] > 255)) || ((rgb10s[1] < 0) || (rgb10s[1] > 255)) || ((rgb10s[2] < 0) || (rgb10s[2] > 255))) { return {rgb: '<span style="color:' + DebugJS.ctx.opt.logColorE + '">invalid value</span>'}; } var r16 = ('0' + parseInt(rgb10s[0]).toString(16)).slice(-2); var g16 = ('0' + parseInt(rgb10s[1]).toString(16)).slice(-2); var b16 = ('0' + parseInt(rgb10s[2]).toString(16)).slice(-2); if ((r16.charAt(0) == r16.charAt(1)) && (g16.charAt(0) == g16.charAt(1)) && (b16.charAt(0) == b16.charAt(1))) { r16 = r16.substring(0, 1); g16 = g16.substring(0, 1); b16 = b16.substring(0, 1); } var rgb16 = '<span style="vertical-align:top;display:inline-block;height:1em"><span style="background:#' + r16 + g16 + b16 + ';width:' + boxSize + ';height:' + boxSize + ';margin-top:0.2em;display:inline-block"> </span></span> #<span style="color:' + DebugJS.COLOR_R + '">' + r16 + '</span><span style="color:' + DebugJS.COLOR_G + '">' + g16 + '</span><span style="color:' + DebugJS.COLOR_B + '">' + b16 + '</span>'; var rgb = {r: r16, g: g16, b: b16, rgb: rgb16}; return rgb; }; DebugJS.convRadixFromHEX = function(v16) { var v10 = parseInt(v16, 16).toString(10); var bin = DebugJS.convertBin({exp: v10, digit: DebugJS.DFLT_UNIT}); if (v10 > 0xffffffff) { var v2 = parseInt(v10).toString(2); bin = DebugJS.formatBin(v2, true, DebugJS.DISP_BIN_DIGITS_THR); } var hex = DebugJS.formatHex(v16, true, false); if (hex.length >= 2) { hex = '0x' + hex; } DebugJS.printRadixConv(v10, hex, bin); }; DebugJS.convRadixFromDEC = function(v10) { var unit = DebugJS.DFLT_UNIT; var bin = DebugJS.convertBin({exp: v10, digit: DebugJS.DFLT_UNIT}); var v16 = parseInt(v10).toString(16); var v2 = ''; if (v10 < 0) { for (var i = (unit - 1); i >= 0; i--) { v2 += (v10 & 1 << i) ? '1' : '0'; } v16 = parseInt(v2, 2).toString(16); } else if (v10 > 0xffffffff) { v2 = parseInt(v10).toString(2); bin = DebugJS.formatBin(v2, true, DebugJS.DISP_BIN_DIGITS_THR); } var hex = DebugJS.formatHex(v16, true, false); if (hex.length >= 2) { hex = '0x' + hex; } DebugJS.printRadixConv(v10, hex, bin); }; DebugJS.convRadixFromBIN = function(v2) { v2 = v2.replace(/\s/g, ''); var v10 = parseInt(v2, 2).toString(10); var v16 = parseInt(v2, 2).toString(16); var bin = DebugJS.convertBin({exp: v10, digit: DebugJS.DFLT_UNIT}); if (v10 > 0xffffffff) { v2 = parseInt(v10).toString(2); bin = DebugJS.formatBin(v2, true, DebugJS.DISP_BIN_DIGITS_THR); } var hex = DebugJS.formatHex(v16, true, false); if (hex.length >= 2) { hex = '0x' + hex; } DebugJS.printRadixConv(v10, hex, bin); }; DebugJS.printRadixConv = function(v10, hex, bin) { var rdx = DebugJS.ctx.props.radix; var s = ''; if (DebugJS.hasKeyWd(rdx, 'dec', '|')) s += 'DEC ' + DebugJS.formatDec(v10) + '\n'; if (DebugJS.hasKeyWd(rdx, 'hex', '|')) s += 'HEX ' + hex + '\n'; if (DebugJS.hasKeyWd(rdx, 'bin', '|')) s += 'BIN ' + bin + '\n'; DebugJS._log.mlt(s); }; DebugJS.toBin = function(v) { return ('0000000' + v.toString(2)).slice(-8); }; DebugJS.toHex = function(v, uc, pFix, d) { var hex = parseInt(v).toString(16); return DebugJS.formatHex(hex, uc, pFix, d); }; DebugJS.convertBin = function(data) { var digit = data.digit; if (digit == 0) digit = DebugJS.DFLT_UNIT; var val; try { val = eval(data.exp); } catch (e) { DebugJS._log.e('Invalid value: ' + e); return; } var v2 = parseInt(val).toString(2); var v2len = v2.length; var loop = ((digit > v2len) ? digit : v2len); v2 = ''; for (var i = (loop - 1); i >= 0; i--) { v2 += (val & 1 << i) ? '1' : '0'; } var hldigit = v2len; var overflow = false; if (val < 0) { hldigit = digit; } else if ((data.digit > 0) && (v2len > data.digit)) { overflow = true; hldigit = data.digit; } return DebugJS.formatBin(v2, true, DebugJS.DISP_BIN_DIGITS_THR, hldigit, overflow); }; DebugJS.formatBin = function(v2, grouping, n, highlight, overflow) { var len = v2.length; var bin = ''; if (grouping) { if ((highlight > 0) && (len > highlight)) { bin += '<span style="color:#888">'; } for (var i = 0; i < len; i++) { if ((i != 0) && ((len - i) % 4 == 0)) { bin += ' '; } bin += v2.charAt(i); if ((highlight > 0) && ((len - i) == (highlight + 1))) { bin += '</span>'; } } } else { bin = v2; } if (n) { if (len >= n) { var digits = len; if (overflow == false) { digits = highlight; } bin += ' (' + digits + ' bits)'; } } return bin; }; DebugJS.formatDec = function(v10) { v10 += ''; var len = v10.length; var dec = ''; for (var i = 0; i < len; i++) { if ((i != 0) && ((len - i) % 3 == 0)) { if (!((i == 1) && (v10.charAt(0) == '-'))) { dec += ','; } } dec += v10.charAt(i); } return dec; }; DebugJS.formatHex = function(hex, uc, pFix, d) { if (uc) hex = hex.toUpperCase(); if ((d) && (hex.length < d)) { hex = (DebugJS.repeatCh('0', d) + hex).slice(d * (-1)); } if (pFix) hex = '0x' + hex; return hex; }; DebugJS.bit8 = {}; DebugJS.bit8.rotateL = function(v, n) { n = n % 8; return ((v << n) | (v >> (8 - n))) & 255; }; DebugJS.bit8.rotateR = function(v, n) { n = n % 8; return ((v >> n) | (v << (8 - n))) & 255; }; DebugJS.bit8.invert = function(v) { return (~v) & 255; }; DebugJS.UTF8 = {}; DebugJS.UTF8.toByte = function(s) { var a = []; if (!s) return a; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c <= 0x7F) { a.push(c); } else if (c <= 0x07FF) { a.push(((c >> 6) & 0x1F) | 0xC0); a.push((c & 0x3F) | 0x80); } else { a.push(((c >> 12) & 0x0F) | 0xE0); a.push(((c >> 6) & 0x3F) | 0x80); a.push((c & 0x3F) | 0x80); } } return a; }; DebugJS.UTF8.fmByte = function(a) { if (!a) return null; var s = ''; var i, c; while (i = a.shift()) { if (i <= 0x7F) { s += String.fromCharCode(i); } else if (i <= 0xDF) { c = ((i & 0x1F) << 6); c += a.shift() & 0x3F; s += String.fromCharCode(c); } else if (i <= 0xE0) { c = ((a.shift() & 0x1F) << 6) | 0x800; c += a.shift() & 0x3F; s += String.fromCharCode(c); } else { c = ((i & 0x0F) << 12); c += (a.shift() & 0x3F) << 6; c += a.shift() & 0x3F; s += String.fromCharCode(c); } } return s; }; DebugJS.encodeB64 = function(s) { if (!window.btoa) return ''; return DebugJS.encodeBase64(s); }; DebugJS.decodeB64 = function(s, q) { var r = ''; if (!window.btoa) return r; try { r = DebugJS.decodeBase64(s); } catch (e) { if (!q) DebugJS._log.e('decodeB64(): ' + e); } return r; }; DebugJS.encodeBase64 = function(s) { var r; try { r = btoa(s); } catch (e) { r = btoa(encodeURIComponent(s).replace(/%([0-9A-F]{2})/g, function(match, p1) {return String.fromCharCode('0x' + p1);})); } return r; }; DebugJS.decodeBase64 = function(s) { var r = ''; if (!window.atob) return r; try { r = decodeURIComponent(Array.prototype.map.call(atob(s), function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); } catch (e) { r = atob(s); } return r; }; DebugJS.Base64 = {}; DebugJS.Base64.encode = function(arr) { var len = arr.length; if (len == 0) return ''; var tbl = {64: 61, 63: 47, 62: 43}; for (var i = 0; i < 62; i++) { tbl[i] = (i < 26 ? i + 65 : (i < 52 ? i + 71 : i - 4)); } var str = ''; for (i = 0; i < len; i += 3) { str += String.fromCharCode( tbl[arr[i] >>> 2], tbl[(arr[i] & 3) << 4 | arr[i + 1] >>> 4], tbl[(i + 1) < len ? (arr[i + 1] & 15) << 2 | arr[i + 2] >>> 6 : 64], tbl[(i + 2) < len ? (arr[i + 2] & 63) : 64] ); } return str; }; DebugJS.Base64.decode = function(str) { var arr = []; if (str.length == 0) return arr; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); if (!(((c >= 0x30) && (c <= 0x39)) || ((c >= 0x41) && (c <= 0x5A)) || ((c >= 0x61) && (c <= 0x7A)) || (c == 0x2B) || (c == 0x2F) || (c == 0x3D))) { DebugJS._log.e('invalid b64 char: 0x' + c.toString(16).toUpperCase() + ' at ' + i); return arr; } } var tbl = {61: 64, 47: 63, 43: 62}; for (i = 0; i < 62; i++) { tbl[i < 26 ? i + 65 : (i < 52 ? i + 71 : i - 4)] = i; } var buf = []; for (i = 0; i < str.length; i += 4) { for (var j = 0; j < 4; j++) { buf[j] = tbl[str.charCodeAt(i + j) || 0]; } arr.push( buf[0] << 2 | (buf[1] & 63) >>> 4, (buf[1] & 15) << 4 | (buf[2] & 63) >>> 2, (buf[2] & 3) << 6 | buf[3] & 63 ); } if (buf[3] == 64) { arr.pop(); if (buf[2] == 64) { arr.pop(); } } return arr; }; DebugJS.Base64.getMimeType = function(s) { var h = {image: {jpeg: '/9', png: 'iVBORw0KGgo', gif: 'R0lGO', bmp: 'Qk0'}}; for (var tp in h) { for (stp in h[tp]) { if (DebugJS.startsWith(s, h[tp][stp])) { return {type: tp, subtype: stp}; } } } return null; }; DebugJS.isBase64 = function(s) { return (s && s.match(/^[A-Za-z0-9\/+]*=*$/) ? true : false); }; DebugJS.encodeBSB64 = function(s, n, toR) { var a = DebugJS.UTF8.toByte(s); return DebugJS.BSB64.encode(a, n, toR); }; DebugJS.decodeBSB64 = function(s, n, toR) { var a = DebugJS.BSB64.decode(s, n, (toR ? false : true)); return DebugJS.UTF8.fmByte(a); }; DebugJS.BSB64 = {}; DebugJS.BSB64.encode = function(a, n, toR) { var fn = (toR ? DebugJS.bit8.rotateR : DebugJS.bit8.rotateL); if (n % 8 == 0) fn = DebugJS.bit8.invert; var b = []; for (var i = 0; i < a.length; i++) { b.push(fn(a[i], n)); } return DebugJS.Base64.encode(b); }; DebugJS.BSB64.decode = function(s, n, toR) { var fn = (toR ? DebugJS.bit8.rotateR : DebugJS.bit8.rotateL); if (n % 8 == 0) fn = DebugJS.bit8.invert; var b = DebugJS.Base64.decode(s); var a = []; for (var i = 0; i < b.length; i++) { a.push(fn(b[i], n)); } return a; }; DebugJS.encodeROT5 = function(s, n) { if ((n < -9) || (n > 9)) n = n % 10; var r = ''; for (var i = 0; i < s.length; i++) { var c = s.charAt(i); var cc = c.charCodeAt(); if (DebugJS.isNumeric(c)) { cc += n; if (cc > 0x39) { cc = 0x2F + (cc - 0x39); } else if (cc < 0x30) { cc = 0x3A - (0x30 - cc); } r += String.fromCharCode(cc); } else { r += c; } } return r; }; DebugJS.decodeROT5 = function(s, n) { return DebugJS.encodeROT5(s, ((n | 0) * (-1))); }; DebugJS.encodeROT13 = function(s, n) { if ((n < -25) || (n > 25)) n = n % 26; var r = ''; for (var i = 0; i < s.length; i++) { var c = s.charAt(i); var cc = c.charCodeAt(); if (DebugJS.isAlphabetic(c)) { cc += n; if (DebugJS.isUpperCase(c)) { if (cc > 0x5A) { cc = 0x40 + (cc - 0x5A); } else if (cc < 0x41) { cc = 0x5B - (0x41 - cc); } } else if (DebugJS.isLowerCase(c)) { if (cc > 0x7A) { cc = 0x60 + (cc - 0x7A); } else if (cc < 0x61) { cc = 0x7B - (0x61 - cc); } } r += String.fromCharCode(cc); } else { r += c; } } return r; }; DebugJS.decodeROT13 = function(s, n) { return DebugJS.encodeROT13(s, ((n | 0) * (-1))); }; DebugJS.encodeROT47 = function(s, n) { if ((n < -93) || (n > 93)) n = n % 94; var r = ''; for (var i = 0; i < s.length; i++) { var c = s.charAt(i); var cc = c.charCodeAt(); if ((cc >= 0x21) && (cc <= 0x7E)) { if (n < 0) { cc += n; if (cc < 0x21) cc = 0x7F - (0x21 - cc); } else { cc = ((cc - 0x21 + n) % 94) + 0x21; } r += String.fromCharCode(cc); } else { r += c; } } return r; }; DebugJS.decodeROT47 = function(s, n) { return DebugJS.encodeROT47(s, ((n | 0) * (-1))); }; DebugJS.buildDataUrl = function(scheme, data) { scheme = scheme.replace(/,$/, ''); return scheme + ',' + data; }; DebugJS.splitDataUrl = function(url) { var a = url.split(','); var b64cnt = {scheme: a[0], data: (a[1] == undefined ? '' : a[1])}; return b64cnt; }; DebugJS.str2binArr = function(str, blkSize, pFix) { var arr = []; for (var i = 0; i < str.length; i += blkSize) { var v = str.substr(i, blkSize); if (v.length == blkSize) { arr.push(DebugJS.parseInt(pFix + v)); } } return arr; }; DebugJS.decodeUnicode = function(arg) { var str = ''; var a = arg.split(' '); for (var i = 0; i < a.length; i++) { if (a[i] == '') continue; var cdpt = a[i].replace(/^U\+/i, ''); if (cdpt == '20') { str += ' '; } else { str += '&#x' + cdpt; } } return str; }; DebugJS.getUnicodePoints = function(str) { var code = ''; for (var i = 0; i < str.length; i++) { var pt = str.charCodeAt(i); if (i > 0) code += ' '; code += 'U+' + DebugJS.toHex(pt, true, '', 4); } return code; }; DebugJS.decodeUri = function(s) { return decodeURIComponent(s); }; DebugJS.encodeUri = function(s) { return encodeURIComponent(s); }; DebugJS.tmStr2ms = function(t) { var hour = min = sec = msec = 0; var s = '0'; var times = t.split(':'); if (times.length == 3) { hour = times[0] | 0; min = times[1] | 0; s = times[2]; } else if (times.length == 2) { hour = times[0] | 0; min = times[1] | 0; } else { return null; } var ss = s.split('.'); sec = ss[0] | 0; if (ss.length >= 2) { msec = ss[1] | 0; } var time = (hour * 3600000) + (min * 60000) + (sec * 1000) + msec; return time; }; DebugJS.str2ms = function(t) { var d = 0, h = 0, m = 0, s = 0, ms = 0; var i = t.indexOf('d'); if (i > 0) { d = t.substr(0, i) | 0; t = t.substr(i + 1); } i = t.indexOf('h'); if (i > 0) { h = t.substr(0, i) | 0; t = t.substr(i + 1); } i = t.indexOf('m'); if (i > 0) { m = t.substr(0, i) | 0; t = t.substr(i + 1); } i = t.indexOf('s'); if (i > 0) { s = t.substr(0, i) | 0; t = t.substr(i + 1); } if (!isNaN(t)) ms = t | 0; return d * 86400000 + h * 3600000 + m * 60000 + s * 1000 + ms; }; DebugJS.isTmStr = function(s) { s = (s + '').trim(); if (!s.match(/^\d/) || s.match(/[^\ddhms]/)) return false; var m = s.match(/\d*d?\d*h?\d*m?\d*s?/); return (isNaN(s) && m && (m != '')); }; DebugJS.subTime = function(tL, tR, byTheDay) { var A_DAY = 86400000; var res = tL - tR; var days = 0; if ((res < 0) && (byTheDay)) { res *= (-1); days = ((res / A_DAY) | 0); if (tL == 0) { days = days + ((res % A_DAY != 0) ? 1 : 0); } else { days = days + ((res < A_DAY) ? 1 : 1); if ((res % A_DAY == 0) && (res != A_DAY)) { days += 1; } } res = A_DAY - (res - days * A_DAY); } return DebugJS.calcTime(res, days, byTheDay, true); }; DebugJS.addTime = function(tL, tR, byTheDay) { var res = tL + tR; var days = 0; if (byTheDay) { days = (res / 86400000) | 0; res -= days * 86400000; } return DebugJS.calcTime(res, days, byTheDay, false); }; DebugJS.calcTime = function(res, days, byTheDay, isSub) { var t = DebugJS.ms2struct(res); var ex = ''; if (days > 0) { ex = ' (' + (isSub ? '-' : '+') + days + ' ' + DebugJS.plural('Day', days) + ')'; } var hh = (byTheDay ? t.hr : t.hh); if (hh < 10) hh = '0' + hh; var r = (t.sign ? '-' : '') + hh + ':' + ('0' + t.mi).slice(-2) + ':' + ('0' + t.ss).slice(-2) + '.' + ('00' + t.sss).slice(-3) + ex; return r; }; DebugJS.getElapsedTimeStr = function(t1, t2) { var delta = t2 - t1; return DebugJS.getTimerStr(delta); }; DebugJS.getRandom = function(type, min, max) { if (min !== undefined) { min |= 0; if (max) { max |= 0; } else { if (type == DebugJS.RND_TYPE_NUM) { max = min; min = 0; } else if (type == DebugJS.RND_TYPE_STR) { max = min; } } if (min > max) { var wk = min; min = max; max = wk; } } else { if (type == DebugJS.RND_TYPE_NUM) { min = 0; max = 0x7fffffff; } else if (type == DebugJS.RND_TYPE_STR) { min = 1; max = DebugJS.RND_STR_DFLT_MAX_LEN; } } var rnd; switch (type) { case DebugJS.RND_TYPE_NUM: rnd = DebugJS.getRndNum(min, max); break; case DebugJS.RND_TYPE_STR: rnd = DebugJS.getRndStr(min, max); } return rnd; }; DebugJS.getRndNum = function(min, max) { min |= 0; max |= 0; var minDigit = (min + '').length; var maxDigit = (max + '').length; var digit = ((Math.random() * (maxDigit - minDigit + 1)) | 0) + minDigit; var rndMin = (digit == 1) ? 0 : Math.pow(10, (digit - 1)); var rndMax = Math.pow(10, digit) - 1; if (min < rndMin) min = rndMin; if (max > rndMax) max = rndMax; var rnd = ((Math.random() * (max - min + 1)) | 0) + min; return rnd; }; DebugJS.getRandomChr = function() { return String.fromCharCode(DebugJS.getRndNum(0x20, 0x7e)); }; DebugJS.RND_STR_DFLT_MAX_LEN = 10; DebugJS.RND_STR_MAX_LEN = 1024; DebugJS.getRndStr = function(min, max) { if (min > DebugJS.RND_STR_MAX_LEN) min = DebugJS.RND_STR_MAX_LEN; if (max > DebugJS.RND_STR_MAX_LEN) max = DebugJS.RND_STR_MAX_LEN; var len = DebugJS.getRndNum(min, max); var ch; var s = ''; for (var i = 0; i < len; i++) { var retry = true; while (retry) { ch = DebugJS.getRandomChr(); if ((!(ch.match(/[!-/:-@[-`{-~]/))) && (!(((i == 0) || (i == (len - 1))) && (ch == ' ')))) { retry = false; } } s += ch; } return s; }; DebugJS.http = function(rq, cb) { if (!rq.method) rq.method = 'GET'; if ((rq.data == undefined) || (rq.data == '')) data = null; if (rq.async == undefined) rq.async = true; if (!rq.user) rq.user = ''; if (!rq.pass) rq.pass = ''; rq.method = rq.method.toUpperCase(); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { if (cb) cb(xhr); } }; xhr.open(rq.method, rq.url, rq.async, rq.user, rq.pass); if (rq.contentType) { xhr.setRequestHeader('Content-Type', rq.contentType); } else { xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } if (!rq.cache) { xhr.setRequestHeader('If-Modified-Since', 'Thu, 01 Jun 1970 00:00:00 GMT'); } if (rq.userAgent) { xhr.setRequestHeader('User-Agent', rq.userAgent); } xhr.send(rq.data); }; DebugJS.http.buildParam = function(p) { var s = ''; var cnt = 0; for (k in p) { if (cnt > 0) s += '&'; s += k + '=' + encodeURIComponent(p[k]); cnt++; } return s; }; DebugJS.onHttpRequestDone = function(xhr) { var stmsg = xhr.status + ' ' + xhr.statusText; if (xhr.status == 0) { DebugJS._log.e('Cannot load: ' + stmsg); } else { DebugJS._log(stmsg); } var head = xhr.getAllResponseHeaders(); var txt = xhr.responseText.replace(/</g, '&lt;'); txt = txt.replace(/>/g, '&gt;'); if (head || txt) { var r = '<span style="color:#5ff">' + head + '</span>' + txt; DebugJS._log.mlt(r); } }; DebugJS.encodeURIString = function(data) { var s = encodeURIComponent(data); s = s.replace(/%20/g, '+'); s = s.replace(/%3D/gi, '='); s = s.replace(/%26/g, '&'); return s; }; DebugJS.getWinZoomRatio = function() { return Math.round(window.devicePixelRatio * 100) + '%'; }; DebugJS.getLanguages = function(indent) { var langs; var navLangs = navigator.languages; if (navLangs) { for (var i = 0; i < navLangs.length; i++) { if (i == 0) { langs = '[' + i + '] ' + navLangs[i]; } else { langs += '\n' + indent + '[' + i + '] ' + navLangs[i]; } } } else { langs = DebugJS.setStyleIfObjNA(navLangs); } return langs; }; DebugJS.getBrowserType = function() { var ua = navigator.userAgent; var ver; var brws = {name: '', version: ''}; if (ua.indexOf('Edge') >= 1) { brws.name = 'Edge'; ver = ua.match(/Edge\/(.*)/); if (ver) brws.version = ver[1]; return brws; } if (ua.indexOf('OPR/') >= 1) { brws.name = 'Opera'; ver = ua.match(/OPR\/(.*)/); if (ver) brws.version = ver[1]; return brws; } if (ua.indexOf('Chrome') >= 1) { brws.name = 'Chrome'; ver = ua.match(/Chrome\/(.*)\s/); if (ver) brws.version = ver[1]; return brws; } if (ua.indexOf('Firefox') >= 1) { brws.name = 'Firefox'; ver = ua.match(/Firefox\/(.*)/); if (ver) brws.version = ver[1]; return brws; } if (ua.indexOf('Trident/7.') >= 1) { brws.name = 'IE11'; brws.family = 'IE'; return brws; } if (ua.indexOf('Trident/6.') >= 1) { brws.name = 'IE10'; brws.family = 'IE'; return brws; } if (ua.indexOf('Trident/5.') >= 1) { brws.name = 'IE9'; brws.family = 'IE'; return brws; } if ((ua.indexOf('Safari/') >= 1) && (ua.indexOf('Version/') >= 1)) { brws.name = 'Safari'; ver = ua.match(/Version\/(.*)\sSafari/); if (ver) brws.version = ver[1]; return brws; } return brws; }; DebugJS.browserColoring = function(nm) { var s = nm; switch (nm) { case 'Chrome': s = '<span style="color:#f44">Ch</span>' + '<span style="color:#ff0">ro</span>' + '<span style="color:#4f4">m</span>' + '<span style="color:#6cf">e</span>'; break; case 'Edge': s = '<span style="color:#0af">' + nm + '</span>'; break; case 'Firefox': s = '<span style="color:#e57f25">' + nm + '</span>'; break; case 'Opera': s = '<span style="color:#f44">' + nm + '</span>'; break; case 'IE11': case 'IE10': case 'IE9': s = '<span style="color:#61d5f8">' + nm + '</span>'; break; case 'Safari': s = '<span style="color:#86c8e8">Safa</span>' + '<span style="color:#dd5651">r</span>' + '<span style="color:#ececec">i</span>'; } return s; }; DebugJS.substr = function(txt, len) { var txtLen = txt.length; var cnt = 0; var str = ''; var i, x; if (len >= 0) { for (i = 0; i < txtLen; i++) { x = encodeURIComponent(txt.charAt(i)); if (x.length <= 3) { cnt++; } else { cnt += 2; } if (cnt > len) break; str += txt.charAt(i); } } else { len *= (-1); for (i = (txtLen - 1); i >= 0; i--) { x = encodeURIComponent(txt.charAt(i)); if (x.length <= 3) { cnt++; } else { cnt += 2; } if (cnt >= len) break; } str = txt.substr(i); } return str; }; DebugJS.startsWith = function(s, p, o) { if (o) s = s.substr(o); if ((s == '') && (p == '')) return true; if (p == '') return false; return (s.substr(0, p.length) == p); }; DebugJS.endsWith = function(s, p) { if ((s == '') && (p == '')) return true; if (p == '') return false; return (s.substr(s.length - p.length) == p); }; DebugJS.needNL = function(s, n) { var nl = '\n'; if (n > 1) nl = DebugJS.repeatCh(nl, n); return ((s != '') && (!DebugJS.endsWith(s, nl))); }; DebugJS.strcount = function(s, p) { var i = 0; var pos = s.indexOf(p); while ((p != '') && (pos != -1)) { i++; pos = s.indexOf(p, pos + p.length); } return i; }; DebugJS.strcmpWOsp = function(s1, s2) { return (s1.trim() == s2.trim()); }; DebugJS.strcatWnl = function(s1, s2) { s1 += s2; if (!DebugJS.endsWith(s2, '\n')) s1 += '\n'; return s1; }; DebugJS.strPadding = function(s, c, l, p) { var t = s + ''; var d = l - t.length; if (d <= 0) return t; var pd = DebugJS.repeatCh(c, d); if (p == 'L') { t = pd + t; } else { t += pd; } return t; }; DebugJS.repeatCh = function(c, n) { var s = ''; for (var i = 0; i < n; i++) s += c; return s; }; DebugJS.crlf2lf = function(s) { return s.replace(/\r\n/g, '\n'); }; DebugJS.isStr = function(s) { return (s + '').match(/\s*\"|'/); }; DebugJS.plural = function(s, n) { return (n >= 2 ? (s + 's') : s); }; DebugJS.trimDownText = function(txt, maxLen, style) { var snip = '...'; if (style) snip = '<span style="' + style + '">' + snip + '</span>'; var s = txt; if (txt.length > maxLen) s = DebugJS.substr(s, maxLen) + snip; return s; }; DebugJS.trimDownText2 = function(txt, maxLen, omitpart, style) { var snip = '...'; if (style) snip = '<span style="' + style + '">' + snip + '</span>'; var str = DebugJS.unifySP(txt.replace(/(\r?\n|\r)/g, ' ').replace(/\t/g, ' ')); if (txt.length > maxLen) { switch (omitpart) { case DebugJS.OMIT_FIRST: str = DebugJS.substr(str, (maxLen * (-1))); str = snip + DebugJS.escTags(str); break; case DebugJS.OMIT_MID: var firstLen = maxLen / 2; var latterLen = firstLen; if ((maxLen % 2) != 0) { firstLen = (firstLen | 0); latterLen = firstLen + 1; } var firstText = DebugJS.substr(str, firstLen); var latterText = DebugJS.substr(str, (latterLen * (-1))); str = DebugJS.escTags(firstText) + snip + DebugJS.escTags(latterText); break; default: str = DebugJS.substr(str, maxLen); str = DebugJS.escTags(str) + snip; } } return str; }; DebugJS.hasKeyWd = function(s, k, d) { if (!s) return false; var a = s.split(d); for (var i = 0; i < a.length; i++) { if (a[i] == k) return true; } return false; }; DebugJS.isEmptyVal = function(o) { return ((o === undefined) || (o === null) || (o === false) || (o === '')); }; DebugJS.setStyleIfObjNA = function(obj, exceptFalse) { var s = obj; if ((exceptFalse && ((obj == undefined) || (obj == null))) || ((!exceptFalse) && (obj !== 0) && (obj !== '') && (!obj))) { s = '<span class="dbg-na">' + obj + '</span>'; } return s; }; DebugJS.dumpAddr = function(i) { return ('0000000' + i.toString(16)).slice(-8).toUpperCase() + ' : '; }; DebugJS.dumpBin = function(i, buf) { return ((buf[i] == undefined) ? ' ' : DebugJS.toBin(buf[i])); }; DebugJS.dumpDec = function(i, buf) { return ((buf[i] == undefined) ? ' ' : (' ' + buf[i].toString()).slice(-3)); }; DebugJS.dumpHex = function(i, buf) { return ((buf[i] == undefined) ? ' ' : ('0' + buf[i].toString(16)).slice(-2).toUpperCase()); }; DebugJS.dumpAscii = function(pos, buf, len) { var b = ''; var end = pos + 0x10; for (var i = pos; i < end; i++) { var code = buf[i]; if (code == undefined) break; switch (code) { case 0x0A: b += DebugJS.CHR_LF_S; break; case 0x0D: b += DebugJS.CHR_CR_S; break; case 0x22: b += '&quot;'; break; case 0x26: b += '&amp;'; break; case 0x3C: b += '&lt;'; break; case 0x3E: b += '&gt;'; break; default: if ((code >= 0x20) && (code <= 0x7E)) { b += String.fromCharCode(code); } else { b += ' '; } } } return b; }; DebugJS.escape = function(s, c) { if (c instanceof Array) { for (var i = 0; i < c.length; i++) { s = DebugJS._escape(s, c[i]); } } else { s = DebugJS._escape(s, c); } return s; }; DebugJS._escape = function(s, c) { return s.replace(new RegExp(c, 'g'), '\\' + c); }; DebugJS.escTags = function(s) { s = s.replace(/&/g, '&amp;'); s = s.replace(/</g, '&lt;'); s = s.replace(/>/g, '&gt;'); s = s.replace(/"/g, '&quot;'); s = s.replace(/'/g, '&#39;'); return s; }; DebugJS.escSpclChr = function(s) { s += ''; s = s.replace(/&/g, '&amp;'); s = s.replace(/</g, '&lt;'); s = s.replace(/>/g, '&gt;'); return s; }; DebugJS.escCtrlChr = function(s) { s = s.replace(/\t/g, '\\t'); s = s.replace(/\v/g, '\\v'); s = s.replace(/\r/g, '\\r'); s = s.replace(/\n/g, '\\n'); s = s.replace(/\f/g, '\\f'); return s; }; DebugJS.decCtrlChr = function(s) { s = s.replace(/\\t/g, '\t'); s = s.replace(/\\v/g, '\v'); s = s.replace(/\\r/g, '\r'); s = s.replace(/\\n/g, '\n'); s = s.replace(/\\f/g, '\f'); return s; }; DebugJS.hlCtrlChr = function(s, sp) { var st = '<span class="dbg-txt-hl">'; var et = '</span>'; if (sp) s = s.replace(/ /g, st + ' ' + et); s = s.replace(/\0/g, st + '\\0' + et); s = s.replace(/\t/g, st + '\\t' + et); s = s.replace(/\v/g, st + '\\v' + et); s = s.replace(/\r/g, st + '\\r' + et); s = s.replace(/\n/g, st + '\\n' + et); s = s.replace(/\f/g, st + '\\f' + et); return s; }; DebugJS.html2text = function(html) { var p = document.createElement('pre'); p.innerHTML = html; return p.innerText; }; DebugJS.addClass = function(el, n) { if (DebugJS.hasClass(el, n)) return; if (el.className == '') { el.className = n; } else { el.className += ' ' + n; } }; DebugJS.removeClass = function(el, n) { var names = el.className.split(' '); var nm = ''; for (var i = 0; i < names.length; i++) { if (names[i] != n) { if (i > 0) nm += ' '; nm += names[i]; } } el.className = nm; }; DebugJS.hasClass = function(el, n) { var names = el.className.split(' '); for (var i = 0; i < names.length; i++) { if (names[i] == n) return true; } return false; }; DebugJS.copyProp = function(src, dst) { for (var k in src) { dst[k] = src[k]; } }; DebugJS.sleep = function(ms) { ms |= 0; var t1 = (new Date()).getTime(); while (true) { var t2 = (new Date()).getTime(); if (t2 - t1 > ms) break; } }; DebugJS.getLogBufSize = function() { return DebugJS.ctx.logBuf.size(); }; DebugJS.setLogBufSize = function(n) { if (n > 0) DebugJS.ctx.initBuf(DebugJS.ctx, n); }; DebugJS.dumpLog = function(fmt, b64, fmtTime) { var buf = DebugJS.ctx.logBuf.getAll(); var b = []; var l = ''; for (var i = 0; i < buf.length; i++) { var data = buf[i]; var type = data.type; var time = (fmtTime ? DebugJS.getDateTimeStr(data.time) : data.time); var msg = data.msg; if (fmt == 'json') { l = {type: type, time: time, msg: DebugJS.encodeB64(msg)}; b.push(l); } else { var lv = 'LOG'; switch (type) { case DebugJS.LOG_TYPE_ERR: lv = 'ERR'; break; case DebugJS.LOG_TYPE_WRN: lv = 'WRN'; break; case DebugJS.LOG_TYPE_INF: lv = 'INF'; break; case DebugJS.LOG_TYPE_DBG: lv = 'DBG'; break; case DebugJS.LOG_TYPE_VRB: lv = 'VRB'; break; case DebugJS.LOG_TYPE_SYS: lv = 'SYS'; break; case DebugJS.LOG_TYPE_RES: case DebugJS.LOG_TYPE_ERES: msg = '> ' + msg; } l += time + '\t' + lv + '\t' + msg + '\n'; } } if (fmt == 'json') l = JSON.stringify(b); if (b64) l = DebugJS.encodeB64(l); return l; }; DebugJS.sendLog = function(url, pName, param, extInfo, flg, cb) { var b = DebugJS.createLogData(extInfo, flg); var data = DebugJS.http.buildParam(param); if (data != '') data += '&'; if (DebugJS.isEmptyVal(pName)) pName = 'data'; data += pName + '=' + encodeURIComponent(b); var r = { url: url, method: 'POST', data: data }; DebugJS.http(r, (cb ? cb : DebugJS.sendLogCb)); }; DebugJS.sendLogCb = function(xhr) { var st = xhr.status; if (st == 200) { DebugJS._log('Send Log OK'); } else { DebugJS._log.e('Send Log ERR (' + st + ')'); } }; DebugJS.createLogData = function(extInfo, flg) { var LINE = '------------------------------------------------------------------------\n'; if (flg == undefined) flg = 'head|log'; var info = ['', '', '', '']; if (extInfo) { if (extInfo.info0) info[0] = extInfo.info0; if (extInfo.info1) info[1] = extInfo.info1; if (extInfo.info2) info[2] = extInfo.info2; if (extInfo.info3) info[3] = extInfo.info3; } var b = ''; if (info[0]) { b = DebugJS.strcatWnl(b, info[0]); } if (DebugJS.hasKeyWd(flg, 'head', '|')) { b += LINE + DebugJS.createLogHeader() + LINE; } if (info[1]) { info[1] = DebugJS.crlf2lf(info[1]); b = DebugJS.strcatWnl(b, info[1]); b += LINE; } if (DebugJS.hasKeyWd(flg, 'log', '|')) { var logTxt = DebugJS.dumpLog('text', false, true); logTxt = DebugJS.html2text(logTxt); logTxt = DebugJS.crlf2lf(logTxt); if (DebugJS.needNL(b, 2)) b += '\n'; b += DebugJS.LOG_HEAD + '\n' + logTxt; if (DebugJS.needNL(logTxt, 1)) b += '\n'; } if (info[2]) { b += '\n'; b = DebugJS.strcatWnl(b, info[2]); } if (DebugJS.hasKeyWd(flg, 'b64buf', '|')) { var b64log = DebugJS.dumpLog('json', true, false); if (DebugJS.needNL(b, 2)) b += '\n'; b += DebugJS.LOG_BOUNDARY_BUF + '\n' + b64log + '\n'; } if (info[3]) { b += '\n'; b = DebugJS.strcatWnl(b, info[3]); } return b; }; DebugJS.createLogHeader = function() { var dt = DebugJS.getDateTime(); var brw = DebugJS.getBrowserType(); var s = 'Sending Time : ' + DebugJS.getDateTimeStr(dt.time) + ' ' + DebugJS.getTimeOffsetStr(dt.offset, true) + ' (' + dt.time + ')\n'; s += 'Browser : ' + brw.name + (brw.version == '' ? '' : ' ' + brw.version) + '\n'; s += 'User Agent : ' + navigator.userAgent + '\n'; s += 'Screen Size : w=' + screen.width + ' h=' + screen.height + '\n'; s += 'Window Size : w=' + document.documentElement.clientWidth + ' h=' + document.documentElement.clientHeight + '\n'; s += 'Body Size : w=' + document.body.clientWidth + ' h=' + document.body.clientHeight + '\n'; s += 'Zoom Ratio : ' + DebugJS.getWinZoomRatio() + '\n'; s += 'Language : ' + navigator.language; var navLangs = navigator.languages; if (navLangs) { s += ' ('; for (var i = 0; i < navLangs.length; i++) { if (i > 0) s += ', '; s += navLangs[i]; } s += ')'; } s += '\n'; return s; }; DebugJS.loadLog = function(json, b64) { var ctx = DebugJS.ctx; if (b64) json = DebugJS.decodeB64(json); var buf = JSON.parse(json); if (ctx.logBuf.size() < buf.length) { ctx.logBuf = new DebugJS.RingBuffer(buf.length); } for (var i = 0; i < buf.length; i++) { var bf = buf[i]; bf.msg = DebugJS.decodeB64(bf.msg); ctx.logBuf.add(bf); } }; DebugJS.preserveLog = function() { if (!DebugJS.LS_AVAILABLE) return; var v = DebugJS.dumpLog('json'); localStorage.setItem('DebugJS-log', v); }; DebugJS.restoreLog = function() { if (!DebugJS.LS_AVAILABLE) return; var s = localStorage.getItem('DebugJS-log'); if (!s) return; localStorage.removeItem('DebugJS-log'); DebugJS.loadLog(s); }; DebugJS.saveStatus = function() { if (!DebugJS.LS_AVAILABLE) return; var ctx = DebugJS.ctx; var data = { status: ctx.status, props: ctx.props, timers: ctx.timers, alias: ctx.CMD_ALIAS }; var st = JSON.stringify(data); localStorage.setItem('DebugJS-st', st); }; DebugJS.loadStatus = function() { if (!DebugJS.LS_AVAILABLE) return 0; var st = localStorage.getItem('DebugJS-st'); if (st == null) return null; localStorage.removeItem('DebugJS-st'); var data = JSON.parse(st); return data; }; DebugJS.file = {}; DebugJS.file.loaders = []; DebugJS.file.ongoingLdr = null; DebugJS.file.onDragOver = function(e) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }; DebugJS.file.onDrop = function(e) { var ctx = DebugJS.ctx; ctx.onDrop(e); var loader = null; for (var i = 0; i < DebugJS.file.loaders.length; i++) { loader = DebugJS.file.loaders[i]; if (DebugJS.isTargetEl(e.target, loader.el)) { DebugJS.file.ongoingLdr = loader; break; } } if (i == DebugJS.file.loaders.length) { DebugJS._log.e('onDrop(): loader not found'); return; } var d = e.dataTransfer.getData('text'); if (d) { if (loader.cb) loader.cb(null, d); } else { var f = (ctx.status & DebugJS.ST_TOOLS ? false : true); ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'file', loader.mode); if (f) ctx.closeFeature(ctx, DebugJS.ST_TOOLS); ctx.handleDroppedFile(ctx, e, loader.mode, null); } }; DebugJS.isTargetEl = function(target, el) { do { if (target == el) return true; target = target.parentNode; } while (target != null); return false; }; DebugJS.file.onLoaded = function(file, cnt) { var loader = DebugJS.file.ongoingLdr; if ((!loader) || (!loader.cb)) return; if ((loader.mode == 'b64') && (loader.decode)) { cnt = DebugJS.decodeB64(DebugJS.splitDataUrl(cnt).data); } loader.cb(file, cnt); }; DebugJS.file.finalize = function() { DebugJS.file.ongoingLdr = null; }; DebugJS.addFileLoader = function(el, cb, mode, decode) { el = DebugJS.getElement(el); if (!el) { DebugJS._log.e('addFileLoader(): target element is ' + el); return; } el.addEventListener('dragover', DebugJS.file.onDragOver, false); el.addEventListener('drop', DebugJS.file.onDrop, false); var loader = { el: el, mode: mode, decode: decode, cb: cb }; DebugJS.file.loaders.push(loader); }; DebugJS.getOptionValue = function(k) { return DebugJS.ctx.opt[k]; }; DebugJS.getStatus = function() { return DebugJS.ctx.status; }; DebugJS.getUiStatus = function() { return DebugJS.ctx.uiStatus; }; DebugJS.getFeatureStack = function() { return DebugJS.ctx.featStack.concat(); }; DebugJS.show = function() { DebugJS.ctx.showDbgWin(); }; DebugJS.hide = function() { DebugJS.ctx.closeDbgWin(); }; DebugJS.opacity = function(v) { if (v > 1) { v = 1; } else if (v < 0.1) { v = 0.1; } DebugJS.ctx.win.style.opacity = v; }; DebugJS.isVisible = function() { if (DebugJS.ctx.uiStatus & DebugJS.UI_ST_VISIBLE) return true; return false; }; DebugJS.pos = function(x, y) { DebugJS.ctx._cmdDbgWinPos(DebugJS.ctx, x, y); }; DebugJS.size = function(w, h) { DebugJS.ctx._cmdDbgWinSize(DebugJS.ctx, w, h); }; DebugJS.pin = function(f) { if (f == undefined) return ((DebugJS.ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) ? false : true); var fn = (f ? 'disableDraggable' : 'enableDraggable'); DebugJS.ctx[fn](DebugJS.ctx); return DebugJS.pin(); }; DebugJS.zoom = function(zm) { var ctx = DebugJS.ctx; if (zm == undefined) return ctx.opt.zoom; var rstrOpt = { cause: DebugJS.INIT_CAUSE_ZOOM, status: ctx.status, sizeStatus: ctx.sizeStatus }; ctx.featStackBak = ctx.featStack.concat(); ctx.finalizeFeatures(ctx); ctx.setWinSize('normal'); ctx.init({zoom: zm}, rstrOpt); return DebugJS.zoom(); }; DebugJS._log = function(m) { if (m instanceof Object) { DebugJS._log.p(m, 0, null, false); } else { DebugJS._log.out(m, DebugJS.LOG_TYPE_LOG); } }; DebugJS._log.e = function(m) { if (DebugJS.bat.hasBatStopCond('error')) { DebugJS.bat.ctrl.stopReq = true; } DebugJS._log.out(m, DebugJS.LOG_TYPE_ERR); DebugJS.ctx.showDbgWinOnError(DebugJS.ctx); if (!DebugJS.ctx.stopErrCb) { DebugJS.callEvtListeners('error'); } }; DebugJS._log.w = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_WRN); }; DebugJS._log.i = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_INF); }; DebugJS._log.d = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_DBG); }; DebugJS._log.v = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_VRB); }; DebugJS._log.s = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_SYS); }; DebugJS._log.p = function(o, l, m, j) { var s = (m ? m : '') + '\n' + DebugJS.objDump(o, j, l, DebugJS.ctx.props.dumplimit, DebugJS.ctx.props.dumpvallen); if (j) s = DebugJS.escTags(s); DebugJS._log.out(s, DebugJS.LOG_TYPE_LOG); }; DebugJS._log.res = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_RES); }; DebugJS._log.res.err = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_ERES); }; DebugJS._log.mlt = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_MLT); }; DebugJS._log.out = function(m, type) { var ctx = DebugJS.ctx; m = DebugJS.setStyleIfObjNA(m); if (typeof m != 'string') {m = m.toString();} var data = {type: type, time: (new Date()).getTime(), msg: m}; ctx.logBuf.add(data); if (!(ctx.status & DebugJS.ST_INITIALIZED)) { if (!DebugJS._init()) return; } ctx.printLogs(); }; DebugJS.stack = function(ldx, q) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; var stk; try { DebugJS.a.b; } catch (e) { stk = e.stack.split('\n'); } ldx |= 0; var cnt = 0, skp = 0; var rslt = ''; for (var i = 0; i < stk.length; i++) { var s = stk[i]; if (s.match(/^TypeError.*/) || s.match(/^DebugJS\.stack@.*/) || s.match(/^\s+at\s.*DebugJS\.stack\s/)) continue; if (skp < ldx) {skp++;continue;} if (cnt > 0) {rslt += '\n';} rslt += DebugJS.delLeadingSP(s).replace(/^at /, '');cnt++; } if (!q) DebugJS._log('Stack:\n' + DebugJS.escTags(rslt)); return rslt; }; DebugJS.stktop = function(idx) { return DebugJS.stack((idx | 0) + 1, true).split('\n')[0]; }; DebugJS.line = function(idx) { return DebugJS._line(DebugJS.stktop((idx | 0) + 1), idx); }; DebugJS._line = function(s, idx) { var a = s.split(':'); var l = a[a.length - 2] | 0; return l; }; DebugJS.funcname = function(idx) { return DebugJS._funcname(DebugJS.stktop((idx | 0) + 1), idx); }; DebugJS._funcname = function(s, idx) { return s.replace(/@/, ' ').replace(/^(.*?)\s.*/, '$1'); }; DebugJS.filename = function(idx, abs) { return DebugJS._filename(DebugJS.stktop((idx | 0) + 1), idx, abs); }; DebugJS._filename = function(s, idx, abs) { if (s == '') return s; var n = s.replace(/@/, ' '); n = n.replace(/^.*?\s/, ''); n = n.replace(/^\(/, ''); n = n.replace(/\)$/, ''); n = n.replace(/:\d+$/, ''); n = n.replace(/:\d+$/, ''); if (!abs) { var p = n.split('/'); n = p[p.length - 1]; if (n == '') { if ((p.length >= 2) && (p.length != 4)) { n = p[p.length - 2]; } n += '/'; } } if ((n == '<anonymous>') || (n == 'Unknown script code')) { n = '&lt;anonymous&gt;'; } else if ((n == 'code (eval code') || (n.match(/> eval$/)) || (n.match(/<anonymous>$/))) { n = '*eval*'; } return n; }; DebugJS.fileline = function(idx, abs) { var s = DebugJS.stktop((idx | 0) + 1); if (s == '') return s; var f = DebugJS._filename(s, idx, abs); var l = DebugJS._line(s, idx); return f + ':' + l; }; DebugJS.time = {}; DebugJS.time.start = function(tmrNm, msg) { var _tmrNm = tmrNm; if ((tmrNm === undefined) || (tmrNm === null)) { _tmrNm = DebugJS.DFLT_TIMER_NAME; } DebugJS.ctx.timers[_tmrNm] = {}; DebugJS.ctx.timers[_tmrNm].start = (new Date()).getTime(); if ((msg === null) || ((tmrNm === null) && (msg === undefined))) { return; } var s; if (msg === undefined) { s = _tmrNm + ': timer started'; } else { s = msg.replace(/%n/g, _tmrNm).replace(/%t/g, '<span style="color:' + DebugJS.ctx.opt.timerColor + '">' + DebugJS.TIME_RST_STR + '</span>'); } DebugJS._log(s); }; DebugJS.time.restart = function(tmrNm) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; if (ctx.timers[tmrNm]) { var paused = now - ctx.timers[tmrNm].pause; ctx.timers[tmrNm].start = now - ctx.timers[tmrNm].count; ctx.timers[tmrNm].pause = 0; ctx.timers[tmrNm].split += paused; } else { ctx.timers[tmrNm] = { start: now, pause: 0, split: 0, count: 0 }; } }; DebugJS.time.split = function(tmrNm, msg) { var t = DebugJS.time._split(tmrNm, false, msg); if ((msg === null) || ((tmrNm === null) && (msg === undefined))) { return t; } }; DebugJS.time._split = function(tmrNm, isEnd, msg) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; var _tmrNm = tmrNm; if ((tmrNm === undefined) || (tmrNm === null)) { _tmrNm = DebugJS.DFLT_TIMER_NAME; } if (!ctx.timers[_tmrNm]) { DebugJS._log.w(_tmrNm + ': timer undefined'); return null; } var prevSplit = ctx.timers[_tmrNm].split; var t = DebugJS.getElapsedTimeStr(ctx.timers[_tmrNm].start, now); var dt = '<span style="color:' + ctx.opt.timerColor + '">' + t + '</span>'; if (isEnd) { delete ctx.timers[_tmrNm]; } else { ctx.timers[_tmrNm].split = now; } if ((msg === null) || ((tmrNm === null) && (msg === undefined))) { return t; } var dtLap = ''; if (prevSplit) { var tLap = DebugJS.getElapsedTimeStr(prevSplit, now); dtLap = '<span style="color:' + ctx.opt.timerColor + '">' + tLap + '</span>'; } else { if (!isEnd) { dtLap = dt; } } var s; if (msg === undefined) { s = _tmrNm + ': ' + dt; if (dtLap != '') { s += '(' + DebugJS.CHR_DELTA + dtLap + ')'; } } else { s = msg.replace(/%n/g, _tmrNm).replace(/%lt/g, dtLap).replace(/%t/g, dt); } DebugJS._log(s); return t; }; DebugJS.time.pause = function(tmrNm) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; if (!ctx.timers[tmrNm]) return; ctx.timers[tmrNm].pause = now; ctx.timers[tmrNm].count = now - ctx.timers[tmrNm].start; }; DebugJS.time.end = function(tmrNm, msg) { var t = DebugJS.time._split(tmrNm, true, msg); if ((msg === null) || ((tmrNm === null) && (msg === undefined))) { return t; } }; DebugJS.time.check = function(tmrNm) { var now = new Date(); if (tmrNm === undefined) tmrNm = DebugJS.DFLT_TIMER_NAME; if (!DebugJS.ctx.timers[tmrNm]) return null; var t = DebugJS.getElapsedTimeStr(DebugJS.ctx.timers[tmrNm].start, now); return t; }; DebugJS.time.list = function() { var l = '<span style="color:#ccc">no timers</span>'; if (Object.keys(DebugJS.ctx.timers).length > 0) { l = '<table>'; for (var k in DebugJS.ctx.timers) { l += '<tr><td>' + k + '</td><td><span style="color:' + DebugJS.ctx.opt.timerColor + '">' + DebugJS.time.check(k) + '</font></td></tr>'; } l += '</table>'; } DebugJS._log.mlt(l); }; DebugJS.time.reset = function(tmrNm) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; ctx.timers[tmrNm] = ctx.timers[tmrNm] || {}; ctx.timers[tmrNm].start = now; ctx.timers[tmrNm].split = now; ctx.timers[tmrNm].pause = now; ctx.timers[tmrNm].count = 0; }; DebugJS.time.getCount = function(tmrNm) { if (!DebugJS.ctx.timers[tmrNm]) { return 0; } else { return DebugJS.ctx.timers[tmrNm].count; } }; DebugJS.time.updateCount = function(tmrNm) { DebugJS.ctx.timers[tmrNm].count = (new Date()).getTime() - DebugJS.ctx.timers[tmrNm].start; }; DebugJS.time.log = function(msg, tmrNm) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; if (!tmrNm) tmrNm = DebugJS.DFLT_TIMER_NAME; var t; var tLap; if (ctx.timers[tmrNm]) { t = DebugJS.getElapsedTimeStr(ctx.timers[tmrNm].start, now); tLap = DebugJS.getElapsedTimeStr(ctx.timers[tmrNm].split, now); ctx.timers[tmrNm].split = now; } else { ctx.timers[tmrNm] = {}; ctx.timers[tmrNm].start = now; ctx.timers[tmrNm].split = now; t = DebugJS.TIME_RST_STR; tLap = t; } var dt = '<span style="color:' + ctx.opt.timerColor + '">' + t + '</span>'; var dtLap = '<span style="color:' + ctx.opt.timerColor + '">' + tLap + '</span>'; var s = dt + ' ' + msg.replace(/%n/g, tmrNm).replace(/%lt/g, dtLap).replace(/%t/g, dt); DebugJS._log(s); }; DebugJS.stopwatch = function() { var ctx = DebugJS.ctx; if (!ctx.isAvailableTools(ctx)) return false; ctx.showDbgWin(); ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'timer', 'cu'); return true; }; DebugJS.stopwatch.tmNm = [DebugJS.TIMER_NAME_SW_0, DebugJS.TIMER_NAME_SW_CU]; DebugJS.stopwatch.start = function(n, m) { if (n == 0) { DebugJS.ctx.startStopwatch(); } else { n = 1; if (DebugJS.stopwatch()) { DebugJS.ctx.startTimerStopwatchCu(); } } if (m) DebugJS.stopwatch.log(n, m); }; DebugJS.stopwatch.stop = function(n) { if (n == 0) { DebugJS.ctx.stopStopwatch(); } else { if (DebugJS.stopwatch()) { DebugJS.ctx.stopTimerStopwatchCu(); } } }; DebugJS.stopwatch.end = function(n, m) { if (n == 0) { DebugJS.ctx.endStopwatch(); } else { n = 1; if (DebugJS.stopwatch()) { DebugJS.ctx.endTimerStopwatchCu(); } } if (m) DebugJS.stopwatch.log(n, m); return DebugJS.stopwatch.val(n); }; DebugJS.stopwatch.split = function(n, m) { if (n != 0) n = 1; var nm = DebugJS.stopwatch.tmNm[n]; if (DebugJS.ctx.isAvailableTools(DebugJS.ctx)) { m = nm + ': %t(' + DebugJS.CHR_DELTA + '%lt)' + (m == undefined ? '' : ' ' + m); DebugJS.time._split(nm, false, m); } }; DebugJS.stopwatch.reset = function(n) { if (n == 0) { DebugJS.ctx.resetStopwatch(); } else { if (DebugJS.stopwatch()) { DebugJS.ctx.resetTimerStopwatchCu(); } } }; DebugJS.stopwatch.val = function(n) { if (n != 0) n = 1; var nm = DebugJS.stopwatch.tmNm[n]; return DebugJS.time.getCount(nm); }; DebugJS.stopwatch.log = function(n, msg) { var nm = DebugJS.stopwatch.tmNm[n]; var t = DebugJS.getTimerStr(DebugJS.time.getCount(nm)); var m = nm + ': <span style="color:' + DebugJS.ctx.opt.timerColor + '">' + t + '</span>'; if (msg != undefined) m += ' ' + msg; DebugJS._log(m); }; DebugJS.addEvtListener = function(type, listener) { var list = DebugJS.ctx.evtListener[type]; if (list) { list.push(listener); } else { DebugJS._log.e('No such event: ' + type); } }; DebugJS.callEvtListeners = function(type, a1, a2, a3) { var list = DebugJS.ctx.evtListener[type]; for (var i = 0; i < list.length; i++) { var cb = list[i]; if (cb) { if (cb(a1, a2, a3) === false) return false; } } return true; }; DebugJS.cmd = function(c, echo, sv) { return DebugJS.ctx._execCmd(c, echo, false, sv); }; DebugJS.cmd.set = function(c) { if (DebugJS.ctx.cmdLine) DebugJS.ctx.cmdLine.value = c; }; DebugJS.cmd.exec = function() { if (DebugJS.ctx.cmdLine) DebugJS.ctx.execCmd(DebugJS.ctx); }; DebugJS.cmd.focus = function() { DebugJS.ctx.focusCmdLine(); }; DebugJS.getCmdVal = function(n) { return DebugJS.ctx.CMDVALS[n]; }; DebugJS.setCmdVal = function(n, v) { if (DebugJS.isSysVal(n)) { DebugJS._log.e('Error: ${' + n + '} is read-only'); } else { DebugJS.ctx.CMDVALS[n] = v; } }; DebugJS.isSysVal = function(n) { return (((n == '?') || (n.match(/^%.*%$/))) ? true : false); }; DebugJS.bat = function(b, a, sl, el) { if (!b) return; var bat = DebugJS.bat; if (!(DebugJS.ctx.status & DebugJS.ST_INITIALIZED)) { bat.q = {b: b, a: a, sl: sl, el: el}; return; } if (DebugJS.ctx.status & DebugJS.ST_BAT_RUNNING) bat.stCtx(); bat.set(b); bat.setExecArg(a); bat.run.arg.s = sl; bat.run.arg.e = el; bat.setRunningSt(true); setTimeout(bat._run, 0); }; DebugJS.bat.q = null; DebugJS.bat.cmds = []; DebugJS.bat.ctrl = { pc: 0, lr: 0, startPc: 0, endPc: 0, breakP: 0, delay: 0, echo: true, tmpEchoOff: false, js: 0, tmid: 0, lock: 0, block: [], fnArg: undefined, condKey: null, pauseKey: null, pauseTimeout: 0, cont: false, stopReq: false, execArg: '', label: '', fnnm: '', stack: [] }; DebugJS.bat.labels = {}; DebugJS.bat.fncs = {}; DebugJS.bat.ctx = []; DebugJS.bat.set = function(b) { var bat = DebugJS.bat; if (DebugJS.ctx.status & DebugJS.ST_BAT_RUNNING) { if (bat.nestLv() == 0) { bat.stop(DebugJS.EXIT_CLEARED); } else { bat.stopNext(); } } if (DebugJS.isB64Bat(b)) b = DebugJS.decodeB64(b); if (DebugJS.ctx.batTextEditor) { DebugJS.ctx.batTextEditor.value = b; } bat.store(b); if (bat.nestLv() > 0) { bat.inheritSt(); } }; DebugJS.bat.inheritSt = function() { var bat = DebugJS.bat; var callerCtrl = bat.ctx[bat.nestLv() - 1].ctrl; bat.ctrl.echo = callerCtrl.echo; }; DebugJS.bat.store = function(b) { var bat = DebugJS.bat; b = b.replace(/(\r?\n|\r)/g, '\n'); bat.cmds = b.split('\n'); var last = bat.cmds.pop(); if (last != '') { bat.cmds.push(last); } bat.parseLabelFncs(); bat.initCtrl(true); DebugJS.ctx.updateTotalLine(); DebugJS.ctx.updateBatNestLv(); }; DebugJS.bat.parseLabelFncs = function() { var bat = DebugJS.bat; var cmnt = 0; bat.labels = {}; bat.fncs = {}; for (var i = 0; i < bat.cmds.length; i++) { var c = DebugJS.delLeadingSP(bat.cmds[i]); if (c.substr(0, 2) == '/*') { cmnt++; continue; } if (DebugJS.delTrailingSP(c).slice(-2) == '*/') { cmnt--; continue; } if (cmnt > 0) continue; if ((c.charAt(0) == DebugJS.BAT_TKN_LABEL) && c.length >= 2) { var label = c.substr(1); bat.labels[label] = i; } else if (DebugJS.startsWith(c, DebugJS.BAT_TKN_FNC)) { var fn = DebugJS.splitArgs(c)[1]; bat.fncs[fn] = i; } } }; DebugJS.bat.run = function(s, e, a) { var bat = DebugJS.bat; bat.run.arg.s = s; bat.run.arg.e = e; if (a != undefined) { bat.setExecArg(a); } bat._run(); }; DebugJS.bat._run = function() { var ctx = DebugJS.ctx; var bat = DebugJS.bat; bat.setRunningSt(false); bat.setExitStatus(DebugJS.EXIT_SUCCESS); if (bat.cmds.length == 0) { DebugJS._log('No batch script'); return; } var s = bat.run.arg.s; var e = bat.run.arg.e; var sl, el; if ((s == undefined) || (s == '*')) { sl = 0; } else if (isNaN(s)) { if (s.charAt(0) == DebugJS.BAT_TKN_LABEL) s = s.substr(1); sl = bat.labels[s]; if (sl == undefined) { DebugJS._log.e('No such label: ' + s); return; } } else { sl = (s | 0) - 1; if (sl < 0) sl = 0; } if (sl >= bat.cmds.length) { DebugJS._log.e('Out of range (1-' + bat.cmds.length + ')'); return; } if ((e == undefined) || (e == '*')) { el = bat.cmds.length - 1; } else if (isNaN(e)) { if (e.charAt(0) == DebugJS.BAT_TKN_LABEL) e = e.substr(1); el = bat.labels[e]; if (el == undefined) { DebugJS._log.e('No such label: ' + e); return; } } else { el = (e | 0) - 1; if (el < 0) el = 0; } if (el < sl) { el = sl; } else if (el >= bat.cmds.length) { el = bat.cmds.length - 1; } bat.setRunningSt(true); ctx.updateBatRunBtn(); bat.initCtrl(false); var ctrl = bat.ctrl; if (bat.nestLv() == 0) { ctrl.echo = ctx.cmdEchoFlg; } ctx.updateCurPc(); ctrl.startPc = sl; ctrl.endPc = el; bat.setExecArg(ctrl.execArg); bat.stopNext(); if (bat.nestLv() == 0) DebugJS.callEvtListeners('batstart'); bat.exec(); }; DebugJS.bat.run.arg = {s: 0, e: 0}; DebugJS.bat.clearTimer = function() { var ctrl = DebugJS.bat.ctrl; clearTimeout(ctrl.tmid); ctrl.tmid = 0; }; DebugJS.bat.exec = function() { var ctx = DebugJS.ctx; var bat = DebugJS.bat; var ctrl = bat.ctrl; ctrl.tmid = 0; if ((ctx.status & DebugJS.ST_BAT_PAUSE) || (ctx.status & DebugJS.ST_BAT_PAUSE_CMD)) { return; } if (ctrl.stopReq) { DebugJS._log.e('BAT ERROR STOPPED (L:' + ctrl.pc + ')'); DebugJS._log.e('--------------------------------'); for (var i = -3; i <= 0; i++) { var pc = ctrl.pc + i; var len = bat.cmds.length; if ((pc >= 0) && (pc < len)) { var n = pc + 1; var df = DebugJS.digits(len) - DebugJS.digits(n); var pdng = ''; for (var j = 0; j < df; j++) { pdng += '0'; } var pre = ((pc == (ctrl.pc - 1)) ? '&gt; ' : ' '); DebugJS._log.e(pre + pdng + n + ': ' + DebugJS.trimDownText(bat.cmds[pc], 98)); } } DebugJS._log.e('--------------------------------'); ctrl.stopReq = false; bat._exit(DebugJS.EXIT_FAILURE); return; } if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD_KEY) { if (ctrl.pauseTimeout > 0) { if ((new Date).getTime() >= ctrl.pauseTimeout) { bat._resume('cmd-key', undefined, true); } else { ctrl.tmid = setTimeout(bat.exec, 50); } } return; } if (!(ctx.status & DebugJS.ST_BAT_RUNNING)) { bat.initCtrl(false); return; } if (ctrl.pc > ctrl.endPc) { if ((ctrl.pc == bat.cmds.length) && (ctrl.stack.length > 0)) { bat.ret(); bat.next(0); return; } bat._exit(DebugJS.EXIT_SUCCESS); return; } if (bat.isLocked()) { ctrl.tmid = setTimeout(bat.exec, 50); return; } if (ctx.status & DebugJS.ST_BAT_BREAK) { ctx.status &= ~DebugJS.ST_BAT_BREAK; bat.setPc(--ctrl.pc); } else { if (ctrl.pc + 1 == ctrl.breakP) { ctx.status |= DebugJS.ST_BAT_BREAK; bat.setPc(++ctrl.pc, true); bat.pause(); ctx.showDbgWin(); return; } } var c = bat.cmds[ctrl.pc]; if (c == undefined) { bat._exit(DebugJS.EXIT_CLEARED); return; } c = DebugJS.delLeadingSP(c); ctrl.pc++; var r = bat.prepro(ctx, c); ctx.updateCurPc(); switch (r) { case 1: ctrl.tmpEchoOff = false; bat.next(0); return; case 2: ctrl.tmpEchoOff = false; return; } var echoFlg = (ctrl.echo && !ctrl.tmpEchoOff); ctrl.tmpEchoOff = false; if (ctrl.pc > ctrl.startPc) { ctx._execCmd(c, echoFlg); } bat.next(1); }; DebugJS.bat.next = function(f) { var d = (f == 1 ? DebugJS.bat.ctrl.delay : 0); DebugJS.bat.ctrl.tmid = setTimeout(DebugJS.bat.exec, d); }; DebugJS.bat.exec1 = function(l) { var cmd = DebugJS.bat.cmds[l - 1]; if (cmd == undefined) return; if (DebugJS.bat.isPpTkn(cmd)) { DebugJS._log(cmd); return; } return DebugJS.ctx._execCmd(cmd, true); }; DebugJS.bat.isPpTkn = function(cmd) { var c = DebugJS.splitCmdLineInTwo(cmd)[0]; if (c.match(/^\s*@/)) { c = c.substr(c.indexOf('@') + 1); } if (((c.charAt(0) == '#') || (c.substr(0, 2) == '//')) || (DebugJS.delLeadingSP(cmd).substr(0, 2) == '/*') || (DebugJS.delTrailingSP(cmd).slice(-2) == '*/') || (c.charAt(0) == DebugJS.BAT_TKN_LABEL)) { return 1; } switch (c) { case DebugJS.BAT_TKN_IF: case DebugJS.BAT_TKN_LOOP: case DebugJS.BAT_TKN_BREAK: case DebugJS.BAT_TKN_CONTINUE: case DebugJS.BAT_TKN_JS: case DebugJS.BAT_TKN_TXT: case DebugJS.BAT_TKN_BLOCK_END: return 1; } if (DebugJS.delAllSP(cmd) == DebugJS.RE_ELSE) { return 1; } return 0; }; DebugJS.bat._exit = function(st) { var bat = DebugJS.bat; bat.setExitStatus(st); if (!bat.ldCtx()) bat._stop(st); }; DebugJS.bat.setExecArg = function(a) { a = ((a === undefined) ? '' : a); DebugJS.ctx.CMDVALS['%%ARG%%'] = a; DebugJS.bat.ctrl.execArg = a; DebugJS.ctx.setBatArgTxt(DebugJS.ctx); }; DebugJS.bat.setLabel = function(s) { s = ((s === undefined) ? '' : s); DebugJS.ctx.CMDVALS['%LABEL%'] = s; DebugJS.bat.ctrl.label = s; }; DebugJS.bat.setFnNm = function(s) { s = ((s === undefined) ? '' : s); DebugJS.ctx.CMDVALS['%FUNCNAME%'] = s; DebugJS.bat.ctrl.fnnm = s; }; DebugJS.bat.setExitStatus = function(st) { if ((st == undefined) || (st == '')) { st = DebugJS.EXIT_SUCCESS; } else { try { st = eval(st); } catch (e) { DebugJS._log.e(e); st = DebugJS.EXIT_FAILURE; } } DebugJS.ctx.CMDVALS['?'] = st; }; DebugJS.bat.prepro = function(ctx, cmd) { var bat = DebugJS.bat; var ctrl = bat.ctrl; if (cmd.match(/^\s*@/)) { ctrl.tmpEchoOff = true; cmd = cmd.substr(cmd.indexOf('@') + 1); } cmd = DebugJS.replaceCmdVals(cmd); var cmds = DebugJS.splitCmdLineInTwo(cmd); var c = cmds[0]; for (var key in ctx.CMD_ALIAS) { if (c == key) { cmd = cmd.replace(new RegExp(c), ctx.CMD_ALIAS[key]); cmd = DebugJS.replaceCmdVals(cmd); cmds = DebugJS.splitCmdLineInTwo(cmd); c = cmds[0]; break; } } var a = DebugJS.splitArgs(cmds[1]); var b; var pc = bat.nextExecLine(ctrl.pc - 1); if (pc != ctrl.pc - 1) { bat.setPc(pc); return 1; } if (c == DebugJS.BAT_TKN_FNC) { if (ctrl.stack.length == 0) { pc = bat.findEndOfFnc(ctrl.pc); bat.setPc(pc + 1); } else { DebugJS.bat.ret(); } return 1; } if (c.charAt(0) == DebugJS.BAT_TKN_LABEL) { bat.setLabel(c.substr(1)); return 1; } switch (c) { case 'nop': DebugJS._log(''); case '': return 1; case 'echo': if (a[0] == 'off') { bat.ppEcho(cmd); ctrl[c] = false; return 1; } else if (a[0] == 'on') { bat.ppEcho(cmd); ctrl[c] = true; return 1; } break; case DebugJS.BAT_TKN_IF: if (ctrl.pc <= ctrl.startPc) return 1; var r = bat.ppIf(c, cmds[1], cmd); if (!r.err) { if (r.cond) { ctrl.block.push({t: DebugJS.BAT_TKN_IF}); } else { bat.ppElIf(ctrl.pc); } } return 1; case DebugJS.BAT_TKN_LOOP: if (ctrl.pc <= ctrl.startPc) return 1; var r = bat.ppIf(c, cmds[1], cmd); var endBlk = bat.findEndOfBlock(DebugJS.BAT_TKN_LOOP, ctrl.pc); if (!r.err) { if (r.cond) { if ((ctrl.block.length == 0) || ((ctrl.block.length > 0) && (ctrl.block[ctrl.block.length - 1].s != (ctrl.pc - 1)))) { ctrl.block.push({t: DebugJS.BAT_TKN_LOOP, s: (ctrl.pc - 1), e: endBlk.l}); } } else { if ((ctrl.block.length > 0) && (ctrl.block[ctrl.block.length - 1].s == (ctrl.pc - 1))) { ctrl.block.pop(); } ctrl.pc = endBlk.l + 1; } } return 1; case DebugJS.BAT_TKN_BREAK: case DebugJS.BAT_TKN_CONTINUE: while (ctrl.block.length > 0) { b = ctrl.block.pop(); if (b.t == DebugJS.BAT_TKN_LOOP) { ctrl.pc = (c == DebugJS.BAT_TKN_BREAK ? (b.e + 1) : b.s); break; } } return 1; case DebugJS.BAT_TKN_JS: if (ctrl.js) { ctrl.js = 0; } else { ctrl.js = ((a[0] == 'pure') ? 1 : 2); bat.execJs(); } return 1; case DebugJS.BAT_TKN_TXT: bat.text(); return 1; } if (DebugJS.unifySP(cmd.trim()).match(DebugJS.RE_ELIF)) { b = ctrl.block.pop(); if (b != undefined) { ctrl.pc = bat.findEndOfBlock(DebugJS.BAT_TKN_BLOCK_END, ctrl.pc).l + 1; return 1; } } else if (DebugJS.delAllSP(cmd) == DebugJS.RE_ELSE) { b = ctrl.block.pop(); if (b != undefined) { ctrl.pc = bat.findEndOfBlock(DebugJS.BAT_TKN_IF, ctrl.pc).l + 1; return 1; } } else if (cmd.trim() == DebugJS.BAT_TKN_BLOCK_END) { if (ctrl.block.length > 0) { b = ctrl.block[ctrl.block.length - 1]; if (b.t == DebugJS.BAT_TKN_LOOP) { if (b.e == (ctrl.pc - 1)) { ctrl.pc = b.s; } } else { ctrl.block.pop(); } return 1; } } if (ctrl.pc <= ctrl.startPc) { return 1; } switch (c) { case 'exit': bat.ppEcho(cmd); bat._exit(cmds[1]); return 2; case 'wait': var w = cmds[1]; if (w == '') { w = ctx.props.wait; } else if (DebugJS.isTmStr(w)) { w = DebugJS.str2ms(w); } else if (!((DebugJS.isTimeFormat(w)) || (w.match(/\|/)))) { try { w = eval(w); } catch (e) { DebugJS._log.e(e); } } w += ''; if (w.match(/\|/)) { w = DebugJS.calcNextTime(w).t; } if (DebugJS.isTimeFormat(w)) { w = DebugJS.calcTargetTime(w); } bat.ppEcho(cmd); ctrl.tmid = setTimeout(bat.exec, w | 0); return 2; } if (ctrl.js) { ctrl.pc--; bat.execJs(); return 1; } return 0; }; DebugJS.bat.nextExecLine = function(pc) { var bat = DebugJS.bat; var cmnt = 0; while (pc <= bat.ctrl.endPc) { pc = DebugJS.bat.nextELOC(pc); var cmd = bat.cmds[pc]; if (cmd == undefined) return pc; pc++; var cmds = DebugJS.splitCmdLineInTwo(cmd); var c = cmds[0]; if ((c == DebugJS.BAT_TKN_FNC) && (bat.ctrl.stack.length == 0)) { pc = bat.findEndOfFnc(pc) + 1; } else { pc--; break; } } return pc; }; DebugJS.bat.nextELOC = function(pc) { var bat = DebugJS.bat; var cmnt = 0; while (pc <= bat.ctrl.endPc) { var cmd = bat.cmds[pc]; pc++; var cmds = DebugJS.splitCmdLineInTwo(cmd); var c = cmds[0]; if ((c == '') || (c.charAt(0) == '#') || (c.substr(0, 2) == '//')) { continue; } if (DebugJS.delLeadingSP(cmd).substr(0, 2) == '/*') { cmnt++; continue; } if (DebugJS.delTrailingSP(cmd).slice(-2) == '*/') { cmnt--; if (cmnt < 0) { bat.syntaxErr(cmd); break; } continue; } if (cmnt == 0) { pc--; break; } } return pc; }; DebugJS.bat.ppIf = function(t, cnd, cmd) { var r = {cond: false, err: true}; var v = cnd.trim(); if (DebugJS.endsWith(v, DebugJS.BAT_TKN_BLOCK_START)) { v = v.substr(0, v.length - 1); if ((t == DebugJS.BAT_TKN_LOOP) && (v == '')) { r.cond = true;r.err = false; return r; } v = DebugJS.replaceCmdVals(v); try { r.cond = eval(v); r.err = false; } catch (e) { DebugJS._log.e(e); } } else { DebugJS.bat.syntaxErr(cmd); } return r; }; DebugJS.bat.ppElIf = function(pc) { var bat = DebugJS.bat; var ctrl = bat.ctrl; while (pc <= ctrl.endPc) { var endBlk = bat.findEndOfBlock(DebugJS.BAT_TKN_ELIF, pc); pc = endBlk.l + 1; if (endBlk.endTkn == DebugJS.BAT_TKN_ELSE) { ctrl.block.push({t: DebugJS.BAT_TKN_ELSE}); break; } else if (endBlk.endTkn == DebugJS.BAT_TKN_BLOCK_END) { break; } var cmd = bat.cmds[pc - 1]; var cnd = DebugJS.getArgsFrom(cmd, 3); var r = bat.ppIf(DebugJS.BAT_TKN_IF, cnd, cmd); if (r.err) break; if (r.cond) { ctrl.block.push({t: DebugJS.BAT_TKN_IF}); break; } } ctrl.pc = pc; }; DebugJS.bat.findEndOfBlock = function(type, pc) { var bat = DebugJS.bat; var l = pc; var ignrBlkLv = 0; var data = {l: 0, endTkn: DebugJS.BAT_TKN_BLOCK_END}; while (l <= bat.ctrl.endPc) { var cmd = bat.cmds[l]; var c = DebugJS.splitCmdLineInTwo(cmd)[0]; if (DebugJS.unifySP(cmd.trim()).match(DebugJS.RE_ELIF)) { if (ignrBlkLv == 0) { if (type == DebugJS.BAT_TKN_ELIF) { data.endTkn = DebugJS.BAT_TKN_ELIF; break; } } } else if (DebugJS.delAllSP(cmd) == DebugJS.RE_ELSE) { if (ignrBlkLv == 0) { if ((type == DebugJS.BAT_TKN_IF) || (type == DebugJS.BAT_TKN_ELIF)) { data.endTkn = DebugJS.BAT_TKN_ELSE; break; } } } else if (cmd.trim() == DebugJS.BAT_TKN_BLOCK_END) { if (ignrBlkLv == 0) { break; } ignrBlkLv--; } else if ((c == DebugJS.BAT_TKN_IF) || (c == DebugJS.BAT_TKN_LOOP)) { ignrBlkLv++; } l++; } if (l > bat.ctrl.endPc) { DebugJS._log.e('End of block "' + DebugJS.BAT_TKN_BLOCK_END + '" not found'); DebugJS._log.e('L' + pc + ': ' + bat.cmds[pc - 1]); } data.l = l; return data; }; DebugJS.bat.findEndOfFnc = function(pc) { var blkLv = 0; while (pc <= DebugJS.bat.ctrl.endPc) { var cmd = DebugJS.bat.cmds[pc]; var c = DebugJS.splitCmdLineInTwo(cmd)[0]; var l = DebugJS.bat.nextELOC(pc); if (l != pc) { pc = l; continue; } if ((c == DebugJS.BAT_TKN_IF) || (c == DebugJS.BAT_TKN_LOOP)) { blkLv++; } else if (cmd.trim() == DebugJS.BAT_TKN_BLOCK_END) { blkLv--; } else if (c == DebugJS.BAT_TKN_RET) { if (blkLv == 0) break; } pc++; } return pc; }; DebugJS.bat.execJs = function() { var bat = DebugJS.bat; var ctrl = bat.ctrl; var pure = (ctrl.js == 1); var js = ''; while ((ctrl.pc >= ctrl.startPc) && (ctrl.pc <= ctrl.endPc)) { c = bat.cmds[ctrl.pc]; ctrl.pc++; if (!DebugJS.strcmpWOsp(c, DebugJS.BAT_TKN_JS)) { if (!pure) { c = DebugJS.replaceCmdVals(c); } js += c + '\n'; } if (DebugJS.strcmpWOsp(c, DebugJS.BAT_TKN_JS) || (ctrl.pc > ctrl.endPc)) { try { eval(js); } catch (e) { DebugJS._log.e(e); } ctrl.js = 0; break; } } }; DebugJS.bat.text = function() { var bat = DebugJS.bat; var ctrl = bat.ctrl; var txt = ''; while ((ctrl.pc >= ctrl.startPc) && (ctrl.pc <= ctrl.endPc)) { c = bat.cmds[ctrl.pc]; ctrl.pc++; if (!DebugJS.strcmpWOsp(c, DebugJS.BAT_TKN_TXT)) { txt += c + '\n'; } if (DebugJS.strcmpWOsp(c, DebugJS.BAT_TKN_TXT) || (ctrl.pc > ctrl.endPc)) { DebugJS.ctx.CMDVALS['%TEXT%'] = txt; break; } } }; DebugJS.bat.ppEcho = function(c) { if (DebugJS.bat.ctrl.echo && !DebugJS.bat.ctrl.tmpEchoOff) DebugJS._log.s(c); }; DebugJS.bat.ret = function(arg) { var bat = DebugJS.bat; var ctrl = bat.ctrl; if (bat.isCmdExecutable()) { var fnCtx = ctrl.stack.pop(); if (!fnCtx) { bat.syntaxErr('Illegal return statement'); return; } try { DebugJS.ctx.CMDVALS['%RET%'] = eval(arg); } catch (e) { DebugJS._log.e(e); return; } DebugJS.ctx.CMDVALS['%ARG%'] = fnCtx.fnArg; ctrl.fnArg = fnCtx.fnArg; ctrl.block = fnCtx.block; ctrl.lr = fnCtx.lr; ctrl.pc = ctrl.lr; bat.setLabel(fnCtx.label); bat.setFnNm(fnCtx.fnnm); } }; DebugJS.bat.syntaxErr = function(c) { DebugJS._log.e('BAT SyntaxError: ' + c); }; DebugJS.bat.lock = function() { DebugJS.bat.ctrl.lock++; }; DebugJS.bat.unlock = function() { var ctrl = DebugJS.bat.ctrl; ctrl.lock--; if (ctrl.lock < 0) { ctrl.lock = 0; } }; DebugJS.bat.isLocked = function() { return (DebugJS.bat.ctrl.lock != 0); }; DebugJS.bat.list = function(s, e) { var l = ''; var pc = DebugJS.bat.ctrl.pc; var js = false; var cmds = DebugJS.bat.cmds; var len = cmds.length; if ((s == undefined) || (s == '*')) { s = 0; e = len; } else { s -= 1; if (s < 0) s = 0; if (e == undefined) { e = s + 1; } } if ((e > len) || (e == '*')) { e = len; } s |= 0; e |= 0; if ((s == 0) && (e == len) && (pc == 0)) {l += '>\n';} for (var i = 0; i < len; i++) { var cmd = cmds[i]; var n = i + 1; var df = DebugJS.digits(len) - DebugJS.digits(n); var pdng = ''; for (var j = 0; j < df; j++) { pdng += '0'; } if (DebugJS.startsWith(DebugJS.delLeadingSP(cmd), DebugJS.BAT_TKN_JS)) { if (!js) { l += '<span style="color:#0ff">'; } } if ((i >= s) && (i < e)) { if (i == pc - 1) { l += '>'; } else { l += ' '; } l += ' ' + pdng + n + ': ' + cmd + '\n'; } if (DebugJS.startsWith(DebugJS.delLeadingSP(cmd), DebugJS.BAT_TKN_JS)) { if (js) { l += '</span>'; js = false; } else { js = true; } } } if (js) l += '</span>'; return l; }; DebugJS.bat.pause = function() { DebugJS.ctx.status |= DebugJS.ST_BAT_PAUSE; DebugJS.ctx.updateBatRunBtn(); }; DebugJS.bat.resume = function(key) { var bat = DebugJS.bat; if (key == undefined) { bat._resume(); } else { if (bat.ctrl.pauseKey == '') { bat._resume('cmd-key', key); } else { if (bat.ctrl.pauseKey != null) { if (DebugJS.hasKeyWd(DebugJS.delAllSP(bat.ctrl.pauseKey), key, '|')) { bat._resume('cmd-key', key); } } } } }; DebugJS.bat._resume = function(trigger, key, to, fmCnd) { var ctx = DebugJS.ctx; var bat = DebugJS.bat; var ctrl = bat.ctrl; if (trigger) { var resumed = false; if (trigger == 'cmd') { if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD) { ctx.status &= ~DebugJS.ST_BAT_PAUSE_CMD; ctx.updateBatResumeBtn(); resumed = true; } } else if (trigger == 'cmd-key') { if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD_KEY) { ctx.status &= ~DebugJS.ST_BAT_PAUSE_CMD_KEY; ctrl.pauseKey = null; ctx.CMDVALS['%RESUMED_KEY%'] = (key == undefined ? '' : key); ctx.updateBatResumeBtn(); resumed = true; } } if (resumed) ctrl.pauseTimeout = 0; var msg; if (resumed) { ctrl.pauseKey = null; msg = 'Resumed.'; if (to) msg += ' (timed out)'; if (key != undefined) msg += ' (' + key + ')'; } else { if (!fmCnd) msg = 'not paused.'; } if (msg) DebugJS._log(msg); } else { ctx.status &= ~DebugJS.ST_BAT_PAUSE; ctx.updateBatRunBtn(); } bat.stopNext(); if (bat.isRunning()) { ctrl.tmid = setTimeout(bat.exec, 0); } }; DebugJS.bat.stopNext = function() { if (DebugJS.bat.ctrl.tmid > 0) { DebugJS.bat.clearTimer(); } }; DebugJS.bat.stop = function(st) { DebugJS.bat._stop(st); DebugJS.bat.resetPc(); }; DebugJS.bat._stop = function(st) { var ctx = DebugJS.ctx; var bat = DebugJS.bat; bat.stopNext(); bat.ctx = []; ctx.updateBatNestLv(); ctx.status &= ~DebugJS.ST_BAT_BREAK; ctx.status &= ~DebugJS.ST_BAT_PAUSE_CMD_KEY; ctx.updateBatResumeBtn(); bat.setRunningSt(false); ctx.status &= ~DebugJS.ST_BAT_PAUSE; ctx.updateBatRunBtn(); delete ctx.CMDVALS['%%ARG%%']; delete ctx.CMDVALS['%ARG%']; delete ctx.CMDVALS['%RET%']; delete ctx.CMDVALS['%LABEL%']; delete ctx.CMDVALS['%FUNCNAME%']; delete ctx.CMDVALS['%TEXT%']; bat.setExitStatus(st); DebugJS.callEvtListeners('batstop', ctx.CMDVALS['?']); }; DebugJS.bat.terminate = function() { DebugJS.bat.stop(DebugJS.EXIT_SIG + DebugJS.SIGTERM); }; DebugJS.bat.cancel = function() { DebugJS._log('Canceled.'); DebugJS.bat.terminate(); DebugJS.point.init(); }; DebugJS.bat.exit = function() { DebugJS.bat.terminate(); DebugJS.point.init(); DebugJS.bat.clear(); }; DebugJS.bat.hasBatStopCond = function(key) { return DebugJS.hasKeyWd(DebugJS.ctx.props.batstop, key, '|'); }; DebugJS.bat.setPc = function(v, b) { DebugJS.bat.ctrl.pc = v; DebugJS.ctx.updateCurPc(b); }; DebugJS.bat.resetPc = function() { DebugJS.bat.setPc(0); }; DebugJS.bat.clear = function() { DebugJS.bat.set(''); }; DebugJS.bat.initCtrl = function(all) { var ctrl = DebugJS.bat.ctrl; ctrl.pc = 0; ctrl.lr = 0; ctrl.fnArg = undefined; ctrl.startPc = 0; ctrl.endPc = 0; ctrl.tmpEchoOff = false; ctrl.block = []; ctrl.js = 0; ctrl.lock = 0; ctrl.conddKey = null; ctrl.pauseKey = null; ctrl.pauseTimeout = 0; ctrl.stopReq = false; ctrl.stack = []; if (all) { ctrl.echo = true; ctrl.execArg = ''; DebugJS.ctx.status &= ~DebugJS.ST_BAT_CONT; } if (ctrl.tmid > 0) { clearTimeout(ctrl.tmid); ctrl.tmid = 0; } DebugJS.bat.setLabel(''); DebugJS.bat.setFnNm(''); DebugJS.ctx.updateCurPc(); }; DebugJS.bat.stCtx = function() { var bat = DebugJS.bat; var ctrl = {}; DebugJS.copyProp(bat.ctrl, ctrl); var cmds = bat.cmds.slice(); var batCtx = { cmds: cmds, ctrl: ctrl, labels: bat.labels, fncs: bat.fncs }; bat.ctx.push(batCtx); }; DebugJS.bat.ldCtx = function() { var ctx = DebugJS.ctx; var bat = DebugJS.bat; var batCtx = bat.ctx.pop(); if (!batCtx) return false; DebugJS.copyProp(batCtx.ctrl, bat.ctrl); bat.setExecArg(bat.ctrl.execArg); bat.setLabel(bat.ctrl.label); bat.setFnNm(bat.ctrl.fnnm); bat.cmds = batCtx.cmds; bat.labels = batCtx.labels; bat.fncs = batCtx.fncs; ctx.setBatTxt(ctx); ctx.updateTotalLine(); ctx.updateBatNestLv(); ctx.updateCurPc(); bat.next(1); return true; }; DebugJS.bat.save = function() { if (!DebugJS.LS_AVAILABLE) return; var bt = { ctrl: DebugJS.bat.ctrl, cmds: DebugJS.bat.cmds, ctx: DebugJS.bat.ctx, vals: DebugJS.ctx.CMDVALS }; var b = JSON.stringify(bt); localStorage.setItem('DebugJS-bat', b); }; DebugJS.bat.load = function() { var bat = DebugJS.bat; if (!DebugJS.LS_AVAILABLE) { if (bat.q) bat.lazyExec(); return; } var b = localStorage.getItem('DebugJS-bat'); localStorage.removeItem('DebugJS-bat'); if (b == null) { if (bat.q) bat.lazyExec(); return; } var bt = JSON.parse(b); bat.ctrl = bt.ctrl; bat.cmds = bt.cmds; bat.ctx = bt.ctx; DebugJS.ctx.CMDVALS = bt.vals; bat.setExecArg(bat.ctrl.execArg); bat.parseLabelFncs(); if (DebugJS.ctx.props.batcont == 'on') { if (bat.ctrl.pauseKey != null) { DebugJS.ctx._cmdPause('key', bat.ctrl.pauseKey, 0); } bat.setRunningSt(true); if (bat.q) { bat.lazyExec(); } else { bat.exec(); } } }; DebugJS.bat.lazyExec = function() { var q = DebugJS.bat.q; DebugJS.bat(q.b, q.a, q.sl, q.el); DebugJS.bat.q = null; }; DebugJS.bat.setRunningSt = function(f) { var ctx = DebugJS.ctx; if (f) { ctx.status |= DebugJS.ST_BAT_RUNNING; if (ctx.props.batcont == 'on') { ctx.status |= DebugJS.ST_BAT_CONT; } } else { ctx.status &= ~DebugJS.ST_BAT_RUNNING; ctx.status &= ~DebugJS.ST_BAT_CONT; } }; DebugJS.bat.isRunning = function() { return ((DebugJS.ctx.status & DebugJS.ST_BAT_RUNNING) ? true : false); }; DebugJS.bat.isCmdExecutable = function() { if (DebugJS.ctx.status & DebugJS.ST_BAT_RUNNING) return true; DebugJS._log('BAT dedicated command'); return false; }; DebugJS.bat.status = function() { var ctx = DebugJS.ctx; var st = 'STOPPED'; if (ctx.status & DebugJS.ST_BAT_PAUSE) { st = 'PAUSED'; } else if ((ctx.status & DebugJS.ST_BAT_PAUSE_CMD) || (ctx.status & DebugJS.ST_BAT_PAUSE_CMD_KEY)) { st = 'PAUSED2'; } else if (ctx.status & DebugJS.ST_BAT_RUNNING) { st = 'RUNNING'; } return st; }; DebugJS.bat.getPauseKey = function() { return DebugJS.bat.ctrl.pauseKey; }; DebugJS.bat.getCondKey = function() { return DebugJS.bat.ctrl.condKey; }; DebugJS.bat.setCond = function(key) { var bat = DebugJS.bat; if (DebugJS.hasKeyWd(bat.ctrl.condKey, key, '|')) { bat._resume('cmd-key', key, false, true); bat.ctrl.condKey = null; } }; DebugJS.bat._initCond = function() { var bat = DebugJS.bat; if (bat.ctrl.condKey == null) return; if (bat.ctrl.pauseKey == bat.ctrl.condKey) { bat._resume('cmd-key'); } bat.ctrl.condKey = null; }; DebugJS.bat.getSymbols = function(t, p) { var a = []; var re = null; if (p) { try { var cnd = eval('/' + p + '/'); } catch (e) { DebugJS._log.e('Get symbols error (' + e + ')'); return a; } re = new RegExp(cnd); } var o = (t == 'function' ? DebugJS.bat.fncs : DebugJS.bat.labels); for (var k in o) { if ((!re) || ((re) && (k.match(re)))) { a.push(k); } } return a; }; DebugJS.bat.nestLv = function() { return DebugJS.bat.ctx.length; }; DebugJS.bat.isAvailable = function() { return DebugJS.bat.cmds.length > 0; }; DebugJS.isBat = function(s) { return DebugJS.startsWith(s, DebugJS.BAT_HEAD); }; DebugJS.isB64Bat = function(s) { return DebugJS.startsWith(s, DebugJS.BAT_HEAD_B64); }; DebugJS.isDataURL = function(s) { return DebugJS.startsWith(s, 'data:'); }; DebugJS.led = function(v) { DebugJS.ctx.setLed(v); }; DebugJS.led.on = function(pos) { DebugJS.ctx.turnLed(pos, true); }; DebugJS.led.off = function(pos) { DebugJS.ctx.turnLed(pos, false); }; DebugJS.led.val = function() { return DebugJS.ctx.led; }; DebugJS.msg = function(v) { DebugJS.ctx.setMsg(v); }; DebugJS.msg.clear = function() { DebugJS.ctx.setMsg(''); }; DebugJS.point = function(x, y) { x += ''; y += ''; var point = DebugJS.point; if (point.ptr == null) point.createPtr(); if (x.charAt(0) == '+') { point.x += (x.substr(1) | 0); } else if (x.charAt(0) == '-') { point.x -= (x.substr(1) | 0); } else { point.x = x | 0; } if (y.charAt(0) == '+') { point.y += (y.substr(1) | 0); } else if (y.charAt(0) == '-') { point.y -= (y.substr(1) | 0); } else { point.y = y | 0; } var ptr = point.ptr; ptr.style.top = point.y + 'px'; ptr.style.left = point.x + 'px'; document.body.appendChild(ptr); point.hint.move(); if (DebugJS.ctx.props.mousemovesim == 'true') { var e = DebugJS.event.create('mousemove'); e.clientX = point.x; e.clientY = point.y; var el = point.getElementFromCurrentPos(); if (el) { el.dispatchEvent(e); } else { window.dispatchEvent(e); } } }; DebugJS.point.ptr = null; DebugJS.point.ptrW = 12; DebugJS.point.ptrH = 19; DebugJS.point.x = 0; DebugJS.point.y = 0; DebugJS.point.d = false; DebugJS.point.CURSOR_DFLT = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAATCAMAAACTKxybAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAD9QTFRFCwsY9PT3S0xX1tbYKCg04eHjLCw4wsLJMzM/zs7S+Pn7Q0ROs7S86OjqLi468PDzYWJsGBgkQkNN////////FEPnZwAAABV0Uk5T//////////////////////////8AK9l96gAAAF5JREFUeNpMzlcOwDAIA1Cyulcw9z9rQ0aLv3iSZUFZ/lBmC7DFL8WniqGGro6mgY0NcLMBTjZA4gpXBjQKRwf2vuZIJqSpotziZ3gFkxYiwlXQvvIByweJzyryCjAA+AIPnHnE+0kAAAAASUVORK5CYII='; DebugJS.point.CURSOR_PTR = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAYCAMAAADAi10DAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJZQTFRF////EhQmHyIzPkBPT1Be+fn68fHywcHHFxorWltovr/E4+PmUlNgLS8//Pz8GRwuqquyFBcpSUtZeHqEa2x35ubo6enrQENRw8TKnJ6lTE5bc3R/9/f3paatRkhWKyw8NThHhoiRtra8lJWdFBYo1dbZKi092NjbFxkrMDJCMjVE0NDUx8jM9PT1ZWZyoqOqOz1M////QATI2QAAADJ0Uk5T/////////////////////////////////////////////////////////////////wANUJjvAAAAoUlEQVR42ozQ1xKDIBAF0GuwYO+a3nvn/38uChGFvOTODrNzXpZdMB7TZTIQ4mxdjfaRRTUyAOM/ehY/lCyKmqjU1NwPCVFo1LyPcqVRq5IosNaoBGzA4xRQTjIGAs/OU5WmY8C5KsSOFVCpxDJrALDO7cTZkPyQf+I1oEQsFJ96Wn53JHYnk+4S7HLjEG1SSSzO7wdnV/f3apO9TdF8BBgAC6AoMWCQ0+8AAAAASUVORK5CYII='; DebugJS.point.CURSOR_TXT = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAQCAMAAADtX5XCAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAZQTFRFAAAA////pdmf3QAAAAJ0Uk5T/wDltzBKAAAAGElEQVR42mJgYGBgZAARjIx0xVB7AQIMABYAAFfcyzDzAAAAAElFTkSuQmCC'; DebugJS.point.createPtr = function() { var point = DebugJS.point; point.x = 0; point.y = 0; var el = document.createElement('img'); var st = el.style; st.position = 'fixed'; st.width = point.ptrW + 'px'; st.height = point.ptrH + 'px'; st.top = point.y; st.left = point.x; st.zIndex = 0x7ffffffe; el.src = point.CURSOR_DFLT; el.onmousedown = point.startDragging; document.body.appendChild(el); point.ptr = el; }; DebugJS.point.init = function() { var point = DebugJS.point; point(0, 0); point.cursor(); point.hint.clear(); point.hide(); }; DebugJS.point.show = function() { var point = DebugJS.point; var ptr = point.ptr; if (ptr == null) { point.createPtr(); } else { document.body.appendChild(ptr); } if (point.hint.st.visible) { point.hint.show(); } }; DebugJS.point.hide = function() { var ptr = DebugJS.point.ptr; if ((ptr != null) && (ptr.parentNode)) { document.body.removeChild(ptr); } DebugJS.point.hint.hide(true); }; DebugJS.point.cursor = function(src, w, h) { var point = DebugJS.point; if (point.ptr == null) { point.createPtr(); } if (!src) { src = point.CURSOR_DFLT; } else if (src == 'pointer') { src = point.CURSOR_PTR; } else if (src == 'text') { src = point.CURSOR_TXT; } else if (src == 'none') { src = point.CURSOR_DFLT; w = 0; h = 0; } if (w == undefined) { w = ''; } else { w += 'px'; } if (h == undefined) { h = ''; } else { h += 'px'; } point.ptr.src = src; point.ptr.style.width = w; point.ptr.style.height = h; }; DebugJS.point.event = function(args) { var el = DebugJS.point.getElementFromCurrentPos(); if (!el) return; var type = DebugJS.getArgVal(args, 0); var opts = DebugJS.getOptVals(args); var e = DebugJS.event.create(type); e.clientX = DebugJS.point.x; e.clientY = DebugJS.point.y; for (var k in opts) { try { e[k] = eval(opts[k]); } catch (e) { DebugJS._log.e('Set property error (' + e + ')'); } } return el.dispatchEvent(e); }; DebugJS.point.simpleEvent = function(type, opt) { var point = DebugJS.point; var el = point.getElementFromCurrentPos(); if (!el) return; switch (type) { case 'click': point.click(0, el, opt); break; case 'cclick': point.click(1, el, opt); break; case 'rclick': point.click(2, el, opt); break; case 'dblclick': point.dblclick(el, opt); break; case 'focus': point.focus(el); break; case 'blur': point.blur(el); break; case 'change': DebugJS.dispatchChangeEvt(el); break; case 'contextmenu': point.contextmenu(el); break; case 'mousedown': case 'mouseup': point.mouseevt(el, type, opt); } }; DebugJS.point.click = function(button, target, speed, cb) { var click = DebugJS.point.click; if (click.tmid[button] > 0) { clearTimeout(click.tmid[button]); click.tmid[button] = 0; DebugJS.point.clickUp(button); } DebugJS.bat.lock(); click.target[button] = target; click.cb = cb; DebugJS.point.mouseevt(target, 'mousedown', button); var el = DebugJS.findFocusableEl(target); if (el != null) el.focus(); if (speed == undefined) speed = 100; click.tmid[button] = setTimeout('DebugJS.point.clickUp(' + button + ')', speed); }; DebugJS.point.dblclick = function(target, speed) { var data = DebugJS.point.dblclick.data; if (data.cnt > 1) { if (data.tmid > 0) { clearTimeout(data.tmid); data.tmid = 0; } data.cnt = 0; DebugJS.bat.unlock(); } if (speed == undefined) speed = 100; var clickcpeed = speed / 2 | 0; data.target = target; data.cnt = 0; data.speed = speed; DebugJS.bat.lock(); DebugJS.point._dblclick(); }; DebugJS.point._dblclick = function() { var data = DebugJS.point.dblclick.data; var clickcpeed = data.speed / 2 | 0; DebugJS.point.click(0, data.target, clickcpeed, DebugJS.point.dblclick.onDone); }; DebugJS.point.dblclick.onDone = function() { var data = DebugJS.point.dblclick.data; data.tmid = 0; data.cnt++; if (data.cnt < 2) { data.tmid = setTimeout(DebugJS.point._dblclick, data.speed); } else { DebugJS.point.mouseevt(data.target, 'dblclick', 0); data.cnt = 0; DebugJS.bat.unlock(); } }; DebugJS.point.dblclick.data = { target: null, tmid: 0, cnt: 0, speed: 0 }; DebugJS.point.clickUp = function(n) { var click = DebugJS.point.click; var target = click.target[n]; click.tmid[n] = 0; DebugJS.point.mouseevt(target, 'mouseup', n); switch (n) { case 0: if (!click.invalid) { target.click(); } click.invalid = false; break; case 1: if (click.tmid[0] > 0) { click.invalid = true; } break; case 2: DebugJS.point.contextmenu(target); if (click.tmid[0] > 0) { click.invalid = true; } } click.target[n] = null; DebugJS.bat.unlock(); if (click.cb) { click.cb(); click.cb = null; } }; DebugJS.point.click.target = [null, null, null]; DebugJS.point.click.tmid = [0, 0, 0]; DebugJS.point.click.invalid = false; DebugJS.point.click.cb = null; DebugJS.point.focus = function(el) { el.focus(); }; DebugJS.point.blur = function(el) { el.blur(); }; DebugJS.point.contextmenu = function(el) { var e = DebugJS.event.create('contextmenu'); el.dispatchEvent(e); }; DebugJS.point.mouseevt = function(el, ev, b) { var e = DebugJS.event.create(ev); e.button = b | 0; e.clientX = DebugJS.point.x; e.clientY = DebugJS.point.y; el.dispatchEvent(e); }; DebugJS.point.keyevt = function(args) { var el = DebugJS.point.getElementFromCurrentPos(); if (!el) return; var ev = args[0]; var e = DebugJS.event.create(ev); var keyCode = DebugJS.getOptVal(args, 'keyCode'); if (keyCode != null) {e.keyCode = keyCode | 0;} var code = DebugJS.getOptVal(args, 'code'); if (code != null) e.code = code; var key = DebugJS.getOptVal(args, 'key'); if (key != null) e.key = key; e.shiftKey = false; e.ctrlKey = false; e.altKey = false; e.metaKey = false; e = DebugJS.point.setKeyFlag(e, args); el.dispatchEvent(e); }; DebugJS.point.setKeyFlag = function(e, a) { for (var i = 0; i < a.length; i++) { if (a[i] == '-s') e.shiftKey = true; if (a[i] == '-c') e.ctrlKey = true; if (a[i] == '-a') e.altKey = true; if (a[i] == '-m') e.metaKey = true; } return e; }; DebugJS.point.getElementFromCurrentPos = function() { var ctx = DebugJS.ctx; var point = DebugJS.point; var ptr = point.ptr; var hide = false; var cmdActive = (document.activeElement == ctx.cmdLine); if ((ptr == null) || (!ptr.parentNode)) { return null; } var hint = point.hint.area; var hintFlg = false; if (hint && (hint.parentNode)) { hintFlg = true; ctx.bodyEl.removeChild(hint); } ctx.bodyEl.removeChild(ptr); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (ctx.isOnDbgWin(point.x, point.y)) { hide = true; ctx.bodyEl.removeChild(ctx.win); } } var el = document.elementFromPoint(point.x, point.y); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (hide) { ctx.bodyEl.appendChild(ctx.win); ctx.scrollLogBtm(ctx); if (cmdActive) ctx.cmdLine.focus(); } } ctx.bodyEl.appendChild(ptr); if (hintFlg) { ctx.bodyEl.appendChild(hint); } return el; }; DebugJS.point.getProp = function(prop) { var el = DebugJS.point.getElementFromCurrentPos(); if (!el) return; var p = prop.split('.'); var v = el; for (var i = 0; i < p.length; i++) { v = v[p[i]]; } DebugJS._log(DebugJS.styleValue(v)); return v; }; DebugJS.point.setProp = function(prop, val, echo) { var el = DebugJS.point.getElementFromCurrentPos(); if (!el) return; try { var v = eval(val); } catch (e) { DebugJS._log.e(e); return; } var p = prop.split('.'); var e = el; for (var i = 0; i < (p.length - 1); i++) { e = e[p[i]]; } e[p[(p.length - 1)]] = v; if (echo) DebugJS._log.res(v); }; DebugJS.point.verify = function(prop, method, exp, label) { var test = DebugJS.test; var st = test.STATUS_ERR; var info; var errPfix = 'Verify error: '; if (prop == undefined) { info = errPfix + 'Property name is undefined'; DebugJS._log.e(info); test.addResult(st, label, exp, undefined, method, info); test.onVrfyAftr(st); return st; } var el = DebugJS.point.getElementFromCurrentPos(); if (!el) { info = errPfix + 'No element (x=' + DebugJS.point.x + ', y=' + DebugJS.point.y + ')'; DebugJS._log.e(info); test.addResult(st, label, exp, undefined, method, info); test.onVrfyAftr(st); return st; } var p = prop.split('.'); var got = el; for (var i = 0; i < p.length; i++) { got = got[p[i]]; } return test.verify(got, method, exp, false, label); }; DebugJS.point.move = function(x, y, speed, step) { x += ''; y += ''; var point = DebugJS.point; var dst = point.move.dstPos; if (x.charAt(0) == '+') { dst.x = point.x + (x.substr(1) | 0); } else if (x.charAt(0) == '-') { dst.x = point.x - (x.substr(1) | 0); } else { dst.x = x | 0; } if (y.charAt(0) == '+') { dst.y = point.y + (y.substr(1) | 0); } else if (y.charAt(0) == '-') { dst.y = point.y - (y.substr(1) | 0); } else { dst.y = y | 0; } if (dst.x < 0) dst.x = 0; if (dst.y < 0) dst.y = 0; if ((speed == null) || (speed == undefined) || (speed == 'auto')) { speed = DebugJS.ctx.props.pointspeed; } speed |= 0; if (speed == 0) { point(x, y); } if ((step == null) || (step == undefined) || (step == 'auto')) { step = DebugJS.ctx.props.pointstep; } step |= 0; point.move.speed = speed; if (dst.x >= point.x) { point.move.mvX = step; } else { point.move.mvX = step * (-1); } if (dst.y >= point.y) { point.move.mvY = step; } else { point.move.mvY = step * (-1); } if (point.move.tmid > 0) { DebugJS.bat.unlock(); clearTimeout(point.move.tmid); point.move.tmid = 0; } DebugJS.bat.lock(); point._move(); }; DebugJS.point.move.dstPos = {x: 0, y: 0}; DebugJS.point.move.speed = 10; DebugJS.point.move.step = 10; DebugJS.point.move.tmid = 0; DebugJS.point.move.cb = null; DebugJS.point._move = function() { var point = DebugJS.point; var move = point.move; move.tmid = 0; if ((move.mvX == 0) && (move.mvY == 0)) { DebugJS.bat.unlock(); return; } var dst = move.dstPos; var mvX = move.mvX; var mvY = move.mvY; var x = point.x + mvX; var y = point.y + mvY; if (mvX < 0) { if (x < dst.x) { x = dst.x; } } else { if (x > dst.x) { x = dst.x; } } if (mvY < 0) { if (y < dst.y) { y = dst.y; } } else { if (y > dst.y) { y = dst.y; } } point(x, y); if ((x == dst.x) && (y == dst.y)) { DebugJS.bat.unlock(); if (move.cb) { setTimeout(move.cb, 10); move.cb = null; } } else { move.tmid = setTimeout(point._move, move.speed); } }; DebugJS.point.move.stop = function() { if (DebugJS.point.move.tmid > 0) { clearTimeout(DebugJS.point.move.tmid); DebugJS.point.move.tmid = 0; DebugJS.bat.unlock(); } }; DebugJS.point.startDragging = function() { DebugJS.point.d = true; DebugJS.point.ptr.style.cursor = 'move'; }; DebugJS.point.endDragging = function() { DebugJS.point.d = false; DebugJS.point.ptr.style.cursor = 'auto'; }; DebugJS.point.drag = function(arg) { var data = DebugJS.point.drag.data; DebugJS.point.drag.cancel(); data.step = 0; data.arg = arg; data.mousemovesim = DebugJS.ctx.props.mousemovesim; DebugJS.ctx.props.mousemovesim = 'true'; DebugJS.bat.lock(); DebugJS.point.drag.proc(); }; DebugJS.point.drag.data = { step: 0, arg: null, mousemovesim: undefined }; DebugJS.point.drag.proc = function() { var point = DebugJS.point; var drag = point.drag; var data = drag.data; drag.data.step++; switch (data.step) { case 1: point.simpleEvent('mousedown', 0); setTimeout(drag.proc, 10); break; case 2: point.move.cb = drag.proc; DebugJS.ctx.cmdPoint('move ' + data.arg); break; case 3: point.simpleEvent('mouseup', 0); drag.stop(); } }; DebugJS.point.drag.cancel = function() { if (DebugJS.point.drag.data.step == 2) { DebugJS.point.move.stop(); } DebugJS.point.drag.stop(); }; DebugJS.point.drag.stop = function() { var data = DebugJS.point.drag.data; data.arg = null; data.step = 0; if (data.mousemovesim != undefined) { DebugJS.ctx.props.mousemovesim = data.mousemovesim; } DebugJS.bat.unlock(); }; DebugJS.pointBySelector = function(selector, idx, alignX, alignY) { var el = DebugJS.getElement(selector, idx); if (!el) { DebugJS._log.e(selector + (selector.charAt(0) == '#' ? '' : (idx == undefined ? '' : ' [' + idx + ']')) + ': Element not found'); return; } var ps = DebugJS.getElPosSize(el); DebugJS.scrollWinToTarget(ps); ps = DebugJS.getElPosSize(selector, idx); DebugJS.pointTarget(ps, alignX, alignY); }; DebugJS.pointByLabel = function(label, idx, alignX, alignY) { var el = DebugJS.getLabelEl(label, idx); if (!el) { DebugJS._log.e(label + ' [' + idx + ']: Element not found'); return; } var ps = DebugJS.getElPosSize(el); DebugJS.scrollWinToTarget(ps); el = DebugJS.getLabelEl(label, idx); ps = DebugJS.getElPosSize(el); DebugJS.pointTarget(ps, alignX, alignY); }; DebugJS.pointTarget = function(ps, alignX, alignY) { if (alignX == undefined) alignX = 0.5; if (alignY == undefined) alignY = 0.5; var p = DebugJS.getAlignedPos(ps, alignX, alignY); DebugJS.point(p.x, p.y); }; DebugJS.getCenterPos = function(ps) { return DebugJS.getAlignedPos(ps, 0.5, 0.5); }; DebugJS.getAlignedPos = function(ps, alignX, alignY) { var x = ps.x; var y = ps.y; if (ps.w > 1) x = x + ps.w * alignX; if (ps.h > 1) y = y + ps.h * alignY; return {x: x, y: y}; }; DebugJS.point.moveToSelector = function(selector, idx, speed, step, alignX, alignY) { var data = { selector: selector, idx: idx, speed: speed, step: step, alignX: alignX, alignY: alignY }; var ps = DebugJS.getElPosSize(selector, idx); if (!ps) { DebugJS._log.e(selector + (selector.charAt(0) == '#' ? '' : (idx == undefined ? '' : ' [' + idx + ']')) + ': Element not found'); return; } if (DebugJS.scrollWinToTarget(ps, DebugJS.ctx.props.scrollspeed, DebugJS.ctx.props.scrollstep, DebugJS.point._moveToSelector, data)) { return; } DebugJS.point._moveToSelector(data); }; DebugJS.point._moveToSelector = function(data) { var el = DebugJS.getElement(data.selector, data.idx); var ps = DebugJS.getElPosSize(el); if (data.alignX == undefined) data.alignX = 0.5; if (data.alignY == undefined) data.alignY = 0.5; DebugJS.point.moveToElement(ps, data.speed, data.step, data.alignX, data.alignY); }; DebugJS.point.moveToLabel = function(label, idx, speed, step, alignX, alignY) { var data = { label: label, idx: idx, speed: speed, step: step, alignX: alignX, alignY: alignY }; var el = DebugJS.getLabelEl(label, idx); if (!el) { DebugJS._log.e(label + ' [' + idx + ']: Element not found'); return; } var ps = DebugJS.getElPosSize(el); if (DebugJS.scrollWinToTarget(ps, DebugJS.ctx.props.scrollspeed, DebugJS.ctx.props.scrollstep, DebugJS.point._moveToLabel, data)) { return; } DebugJS.point._moveToLabel(data); }; DebugJS.point._moveToLabel = function(data) { var el = DebugJS.getLabelEl(data.label, data.idx); var ps = DebugJS.getElPosSize(el); if (data.alignX == undefined) data.alignX = 0.5; if (data.alignY == undefined) data.alignY = 0.5; DebugJS.point.moveToElement(ps, data.speed, data.step, data.alignX, data.alignY); }; DebugJS.point.moveToElement = function(ps, speed, step, alignX, alignY) { if (ps) { var p = DebugJS.getAlignedPos(ps, alignX, alignY); if (p) { DebugJS.point.move(p.x, p.y, speed, step); } } }; DebugJS.point.hint = function(msg, speed, step, start, end) { var hint = DebugJS.point.hint; if (hint.area == null) { hint.createArea(); } var area = hint.area; try { var m = eval(msg) + ''; } catch (e) { m = e + ''; } if (speed && step) { hint.msgseq(msg, m, speed, step, start, end); } else { DebugJS.point.hint.setMsg(DebugJS.point.hint.replaceMsg(m)); } hint.st.hasMsg = true; hint.show(); }; DebugJS.point.hint.area = null; DebugJS.point.hint.pre = null; DebugJS.point.hint.st = {visible: false, hasMsg: false}; DebugJS.point.hint.createArea = function() { var ctx = DebugJS.ctx; var hint = DebugJS.point.hint; var el = document.createElement('div'); el.className = 'dbg-hint'; var sz = ctx.props.pointmsgsize; try { sz = eval(sz); } catch (e) {DebugJS._log.e(e);} var pre = document.createElement('pre'); ctx.setStyle(pre, 'width', 'auto'); ctx.setStyle(pre, 'height', 'auto'); ctx.setStyle(pre, 'margin', 0); ctx.setStyle(pre, 'padding', 0); ctx.setStyle(pre, 'line-height', '1.2'); ctx.setStyle(pre, 'color', ctx.opt.fontColor); ctx.setStyle(pre, 'font-size', sz); ctx.setStyle(pre, 'font-family', ctx.opt.fontFamily); el.appendChild(pre); hint.pre = pre; document.body.appendChild(el); hint.area = el; }; DebugJS.point.hint.setMsg = function(m) { var ctx = DebugJS.ctx; var el = DebugJS.point.hint.pre; ctx.setStyle(el, 'width', 'auto'); ctx.setStyle(el, 'height', 'auto'); el.innerHTML = m; }; DebugJS.point.hint.msgseq = function(msg, m, speed, step, start, end) { var hint = DebugJS.point.hint; var el = hint.pre; var s = window.getComputedStyle(el); DebugJS.point.hint.setMsg(m); DebugJS.ctx.setStyle(el, 'width', s.width); DebugJS.ctx.setStyle(el, 'height', s.height); el.innerHTML = ''; DebugJS.setText(el, msg, speed, step, start, end); }; DebugJS.point.hint.replaceMsg = function(s) { s = s.replace(/\\n/g, '\n'); s = DebugJS.point.hint.rplcBtn(s); if (s.match(/!TEST_COUNT!/)) s = s.replace(/!TEST_COUNT!/g, DebugJS.test.getCountStr(DebugJS.test.getSumCount())); if (s.match(/!TEST_RESULT!/)) s = s.replace(/!TEST_RESULT!/g, DebugJS.test.result()); return s; }; DebugJS.point.hint.rplcBtn = function(s) { var PREFIX = '<span class="dbg-btn dbg-nomove" onclick="DebugJS.'; var SUFFIX = '</span>'; var d = {RESUME: 'ctx.batResume', STOP: 'bat.cancel', CLOSE: 'point.hide'}; for (var k in d) { var re = new RegExp('!' + k + '!', 'g'); if (s.match(re)) { var b = PREFIX + d[k] + '();">[' + k + ']' + SUFFIX; s = s.replace(re, b); } } return s; }; DebugJS.point.hint.move = function() { var point = DebugJS.point; var area = point.hint.area; if (!area) return; var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var ps = DebugJS.getElPosSize(area); var y = (point.y - ps.h - 2); if (y < 0) { if (ps.h > point.y) { y = point.y + point.ptrH; } else { y = 0; } } var x = point.x; if (x < 0) { x = 0; } if ((y + ps.h) > point.y) { x = point.x + point.ptrW; } if ((x + ps.w) > clientW) { if (ps.w < clientW) { x = clientW - ps.w; } else { x = 0; } } if ((y + ps.h) > clientH) { if (ps.h < clientH) { y = clientH - ps.h; } else { y = 0; } } area.style.top = y + 'px'; area.style.left = x + 'px'; }; DebugJS.point.hint.show = function() { var point = DebugJS.point; var hint = point.hint; if (!hint.st.hasMsg) return; var area = hint.area; if (!area) { hint.createArea(); } else { document.body.appendChild(area); } hint.st.visible = true; hint.move(); }; DebugJS.point.hint.hide = function(hold) { var area = DebugJS.point.hint.area; if (area && area.parentNode) document.body.removeChild(area); if (!hold) DebugJS.point.hint.st.visible = false; }; DebugJS.point.hint.clear = function() { var point = DebugJS.point; var area = point.hint.area; if (area) { point.hint.pre.innerHTML = ''; point.hint.hide(); } point.hint.st.hasMsg = false; }; DebugJS.scrollWinTo = function(x, y, speed, step) { var ctx = DebugJS.ctx; var d = DebugJS.scrollWinTo.data; DebugJS.scrollWinTo.stop(); d.dstX = x - ctx.scrollPosX; d.dstY = y - ctx.scrollPosY; if ((speed == undefined) || (speed == null)) { d.speed = ctx.props.scrollspeed | 0; } else { d.speed = speed | 0; } if ((step == undefined) || (step == null)) { d.step = ctx.props.scrollstep | 0; } else { d.step = step | 0; } DebugJS.bat.lock(); DebugJS._scrollWinTo(); return true; }; DebugJS._scrollWinTo = function() { var d = DebugJS.scrollWinTo.data; d.tmid = 0; if (d.speed == 0) d.step = 0; var dX = DebugJS.calcDestPosAndStep(d.dstX, d.step); d.dstX = dX.dest; var dY = DebugJS.calcDestPosAndStep(d.dstY, d.step); d.dstY = dY.dest; window.scrollBy(dX.step, dY.step); if ((d.dstX == 0) && (d.dstY == 0)) { if (d.cb) d.cb(d.arg); DebugJS.scrollWinTo.fin(); } else { d.tmid = setTimeout(DebugJS._scrollWinTo, d.speed); } }; DebugJS.scrollWinTo.data = {}; DebugJS.scrollWinTo.initData = function() { var d = DebugJS.scrollWinTo.data; d.dstX = 0; d.dstY = 0; d.speed = 10; d.step = 100; d.tmid = 0; d.cb = null; d.arg = null; }; DebugJS.scrollWinTo.initData(); DebugJS.scrollWinTo.stop = function() { var tmid = DebugJS.scrollWinTo.data.tmid; if (tmid > 0) { clearTimeout(tmid); DebugJS.scrollWinTo.fin(); } }; DebugJS.scrollWinTo.fin = function() { DebugJS.scrollWinTo.initData(); DebugJS.bat.unlock(); }; DebugJS.scrollWinToTarget = function(ps, speed, step, cb, arg, top) { if (!ps) return false; var d = DebugJS.scrollWinTo.data; if (d.tmid > 0) { clearTimeout(d.tmid); d.tmid = 0; DebugJS.bat.unlock(); } d.dstX = 0; d.dstY = 0; d.speed = speed | 0; d.cb = cb; d.arg = arg; if ((ps.x < 0) || ((ps.x + ps.w) > document.documentElement.clientWidth)) { d.dstX = ps.x; } var clientH = document.documentElement.clientHeight; var bodyH = document.body.clientHeight; var absScreenBottomT = bodyH - clientH; var absScreenBottomB = bodyH; var relTargetPosYinScreen = (ps.y + window.pageYOffset) - absScreenBottomT; var absTargetPosYinDoc = ps.y + window.pageYOffset; var alignY = (top ? 0 : (clientH / 2)); if (top) { d.dstY = ps.y; } else if (ps.y < 0) { if ((ps.y + window.pageYOffset) < (clientH / 2)) { d.dstY = window.pageYOffset * (-1); } else { d.dstY = ps.y - alignY; } } else if ((ps.y + ps.h) > clientH) { if ((absTargetPosYinDoc >= absScreenBottomT) && (absTargetPosYinDoc <= absScreenBottomB)) { d.dstY = absScreenBottomB - DebugJS.ctx.scrollPosY; } else { d.dstY = ps.y - alignY; } } if ((d.dstX != 0) || (d.dstY != 0)) { if (step >= 0) { d.step = step | 0; } else { d.step = DebugJS.ctx.props.scrollstep | 0; } DebugJS.bat.lock(); DebugJS._scrollWinTo(); return true; } DebugJS.scrollWinTo.initData(); return false; }; DebugJS.scrollElTo = function(target, x, y) { x += ''; y += ''; var el = DebugJS.getElement(target); if (!el) { DebugJS._log.e('Element not found: ' + target); return; } if ((x.charAt(0) == '+') || (x.charAt(0) == '-')) { x = el.scrollLeft + (x | 0); } else { switch (x) { case 'left': x = 0; break; case 'center': el.scrollLeft = el.scrollWidth; var wkX = el.scrollLeft; x = wkX / 2; break; case 'right': x = el.scrollWidth; break; case 'current': x = null; } } if ((y.charAt(0) == '+') || (y.charAt(0) == '-')) { y = el.scrollTop + (y | 0); } else { switch (y) { case 'top': y = 0; break; case 'middle': el.scrollTop = el.scrollHeight; var wkY = el.scrollTop; y = wkY / 2; break; case 'bottom': y = el.scrollHeight; break; case 'current': y = null; } } if (x != null) el.scrollLeft = x; if (y != null) el.scrollTop = y; }; DebugJS.calcDestPosAndStep = function(dest, step) { if (dest < 0) { if (((dest * (-1)) < step) || (step == 0)) { step = dest * (-1); } dest += step; step *= (-1); } else { if ((dest < step) || (step == 0)) { step = dest; } dest -= step; } var d = { dest: dest, step: step }; return d; }; DebugJS.setText = function(elm, txt, speed, step, start, end) { if (txt == undefined) return; var data = DebugJS.setText.data; if (data.tmid > 0) { clearTimeout(data.tmid); data.tmid = 0; DebugJS.bat.unlock(); } var el = DebugJS.getElement(elm); if (!el) { DebugJS._log.e('Element not found: ' + elm); return; } try { txt = eval(txt) + ''; } catch (e) { DebugJS._log.e('setText(): ' + e); } txt = DebugJS.decCtrlChr(txt); data.txt = txt; if ((speed == undefined) || (speed == null) || (speed == '')) { speed = DebugJS.ctx.props.textspeed; } if ((step == undefined) || (step == null) || (step == '')) { step = DebugJS.ctx.props.textstep; } start |= 0; if (start > 0) start -= 1; data.speed = speed; data.step = step | 0; data.i = start; data.end = end | 0; data.el = el; data.isInp = DebugJS.isTxtInp(el); DebugJS.bat.lock(); DebugJS._setText(); }; DebugJS._setText = function() { var data = DebugJS.setText.data; var speed = data.speed; var step = data.step; if ((speed == 0) || (step == 0) || (data.end > 0) && (data.i >= data.end)) { data.i = data.txt.length; } else { data.i += step; } data.tmid = 0; var txt = data.txt.substr(0, data.i); if (data.isInp) { data.el.value = txt; var e = DebugJS.event.create('input'); data.el.dispatchEvent(e); } else { data.el.innerText = txt; } if (data.i < data.txt.length) { speed = DebugJS.getSpeed(speed) | 0; data.tmid = setTimeout(DebugJS._setText, speed); } else { DebugJS.setText.stop(); } }; DebugJS.setText.stop = function() { DebugJS.setText.finalize(); DebugJS.bat.unlock(); }; DebugJS.setText.finalize = function() { var data = DebugJS.setText.data; if (data.tmid > 0) { clearTimeout(data.tmid); data.tmid = 0; } data.el = null; data.isInp = false; data.txt = ''; data.speed = 0; data.end = 0; data.i = 0; }; DebugJS.setText.data = {el: null, isInp: false, txt: '', speed: 0, end: 0, i: 0, tmid: 0}; DebugJS.getSpeed = function(v) { v += ''; if (v.indexOf('-') == -1) return v; var a = v.split('-'); var min = a[0]; var max = a[1]; if ((min == '') || (max == '')) return 0; return DebugJS.getRndNum(min, max); }; DebugJS.selectOption = function(elm, method, type, val) { var i; var el = DebugJS.getElement(elm); if (!el) { DebugJS._log.e('Element not found: ' + elm); return; } if (el.tagName != 'SELECT') { DebugJS._log.e('Element is not select (' + el + ')'); return; } if (method == 'set') { if ((type != 'value') && (type != 'text')) return; var prevVal = el.value; for (i = 0; i < el.options.length; i++) { if (((type == 'text') && (el.options[i].innerText == val)) || ((type == 'value') && (el.options[i].value == val))) { el.options[i].selected = true; if (prevVal != val) { DebugJS.dispatchChangeEvt(el); } return; } } } else { var r; var idx = el.selectedIndex; if (type == 'value') { r = el.options[idx].value; } else if (type == 'text') { r = el.options[idx].innerText; } else if ((type == 'values') || (type == 'texts')) { var prop = (type == 'values' ? 'value' : 'innerText'); r = []; for (i = 0; i < el.options.length; i++) { r.push(el.options[i][prop]); } } return r; } DebugJS._log.e('No such option: ' + val); }; DebugJS.dispatchChangeEvt = function(target) { var e = DebugJS.event.create('change'); return target.dispatchEvent(e); }; DebugJS.event = {}; DebugJS.event.evt = null; DebugJS.event.evtDef = { blur: {bubbles: false, cancelable: false}, change: {bubbles: true, cancelable: false}, click: {bubbles: true, cancelable: true}, contextmenu: {bubbles: true, cancelable: true}, dblclick: {bubbles: true, cancelable: true}, dragover: {bubbles: true, cancelable: true}, drop: {bubbles: true, cancelable: true}, focus: {bubbles: false, cancelable: false}, input: {bubbles: true, cancelable: false}, keydown: {bubbles: true, cancelable: true}, keypress: {bubbles: true, cancelable: true}, keyup: {bubbles: true, cancelable: true}, mousedown: {bubbles: true, cancelable: true}, mousemove: {bubbles: true, cancelable: true}, mouseup: {bubbles: true, cancelable: true}, wheel: {bubbles: true, cancelable: true} }; DebugJS.event.create = function(type) { var e = document.createEvent('Events'); e.initEvent(type, true, true); var df = DebugJS.event.evtDef[type]; if (df) { e.bubbles = df.bubbles; e.cancelable = df.cancelable; } DebugJS.event.evt = e; return e; }; DebugJS.event.set = function(prop, v) { var e = DebugJS.event.evt; if (e) { e[prop] = v; } else { DebugJS._log.e('Event is not created'); } }; DebugJS.event.dispatch = function(el, idx) { var target; if (el == 'window') { target = window; } else if (el == 'document') { target = document; } else if (el == 'active') { target = document.activeElement; } else if (el == 'point') { target = DebugJS.point.getElementFromCurrentPos(); } else { target = DebugJS.getElement(el, idx); } if (!target) { DebugJS._log.e('Target is not found'); return false; } var e = DebugJS.event.evt; if (e) { return target.dispatchEvent(e); } else { DebugJS._log.e('Event is not created'); return false; } }; DebugJS.event.clear = function() { DebugJS.event.evt = null; }; DebugJS.keyPress = function(data) { DebugJS.keyPress.data = data; DebugJS.bat.lock(); DebugJS.keyPress.down(); }; DebugJS.keyPress.data = null; DebugJS.keyPress.down = function() { DebugJS.keyPress.send('keydown'); setTimeout(DebugJS.keyPress.up, 10); }; DebugJS.keyPress.up = function() { DebugJS.keyPress.send('keyup'); DebugJS.keyPress.end(); }; DebugJS.keyPress.send = function(type) { var data = DebugJS.keyPress.data; DebugJS.event.create(type); DebugJS.event.set('keyCode', data.keyCode); DebugJS.event.set('shiftKey', data.shift); DebugJS.event.set('ctrlKey', data.ctrl); DebugJS.event.set('altKey', data.alt); DebugJS.event.set('metaKey', data.meta); var target = (DebugJS.isDescendant(document.activeElement, DebugJS.ctx.win) ? 'window' : 'active'); DebugJS.event.dispatch(target); }; DebugJS.keyPress.end = function() { DebugJS.bat.unlock(); }; DebugJS.test = {}; DebugJS.test.STATUS_OK = 'OK'; DebugJS.test.STATUS_NG = 'NG'; DebugJS.test.STATUS_ERR = 'ERR'; DebugJS.test.STATUS_NT = 'NT'; DebugJS.test.COLOR_OK = '#0f0'; DebugJS.test.COLOR_NG = '#f66'; DebugJS.test.COLOR_ERR = '#fa0'; DebugJS.test.STATUS_NT_COLOR = '#fff'; DebugJS.test.data = {}; DebugJS.test.initData = function() { var data = DebugJS.test.data; data.name = ''; data.desc = []; data.running = false; data.startTime = 0; data.endTime = 0; data.seq = 0; data.executingTestId = ''; data.lastRslt = DebugJS.test.STATUS_NT; data.ttlRslt = DebugJS.test.STATUS_NT; data.cnt = {ok: 0, ng: 0, err: 0, nt: 0}; data.results = {}; }; DebugJS.test.initData(); DebugJS.test.init = function(name) { var test = DebugJS.test; test.initData(); DebugJS.ctx.CMDVALS['%TEST_TOTAL_RESULT%'] = test.STATUS_NT; DebugJS.ctx.CMDVALS['%TEST_LAST_RESULT%'] = test.STATUS_NT; var data = test.data; data.name = ((name == undefined) ? '' : name); data.running = true; data.startTime = (new Date()).getTime(); }; DebugJS.test.setName = function(n) { DebugJS.test.data.name = n; DebugJS._log('TestName: ' + n); }; DebugJS.test.setDesc = function(s) { DebugJS.test.data.desc.push(s); DebugJS._log(s); }; DebugJS.test.save = function() { if (!DebugJS.LS_AVAILABLE) return; var d = JSON.stringify(DebugJS.test.data); localStorage.setItem('DebugJS-test', d); }; DebugJS.test.load = function() { if (!DebugJS.LS_AVAILABLE) return; var d = localStorage.getItem('DebugJS-test'); localStorage.removeItem('DebugJS-test'); if (d == null) return; DebugJS.test.data = JSON.parse(d); }; DebugJS.test.fin = function() { DebugJS.test.data.running = false; DebugJS.test.data.endTime = (new Date()).getTime(); }; DebugJS.test.setResult = function(st, label, info) { var test = DebugJS.test; switch (st) { case test.STATUS_OK: case test.STATUS_NG: case test.STATUS_ERR: case test.STATUS_NT: break; default: DebugJS._log.e('Test status must be OK|NG|ERR|NT: ' + st); return; } test.addResult(st, label, null, null, null, info); }; DebugJS.test.addResult = function(st, label, exp, got, method, info) { var ctx = DebugJS.ctx; var test = DebugJS.test; var data = test.data; var lm = ctx.props.testvallimit; switch (st) { case test.STATUS_OK: data.cnt.ok++; break; case test.STATUS_NG: data.cnt.ng++; break; case test.STATUS_ERR: data.cnt.err++; break; case test.STATUS_NT: data.cnt.nt++; } test.setRsltStatus(st); test.setLastResult(st); var id = data.executingTestId; test.prepare(); if (label == null) { label = ''; } else if (label.match(/^".*"$/)) { label = eval(label); } if (typeof exp == 'string') { exp = DebugJS.trimDownText(exp, lm); } if (typeof got == 'string') { got = DebugJS.trimDownText(got, lm); } var rslt = { label: label, status: st, method: method, exp: exp, got: got, info: info }; data.results[id].results.push(rslt); }; DebugJS.test.setRsltStatus = function(st) { var test = DebugJS.test; var data = test.data; switch (st) { case test.STATUS_NT: return; case test.STATUS_OK: if (data.ttlRslt != test.STATUS_NT) return; break; case test.STATUS_NG: if (data.ttlRslt == test.STATUS_ERR) return; } data.ttlRslt = st; DebugJS.ctx.CMDVALS['%TEST_TOTAL_RESULT%'] = st; }; DebugJS.test.setLastResult = function(st) { DebugJS.test.data.lastRslt = st; DebugJS.ctx.CMDVALS['%TEST_LAST_RESULT%'] = st; }; DebugJS.test.getLastResult = function() { return DebugJS.test.data.lastRslt; }; DebugJS.test.getTotalResult = function() { return DebugJS.test.data.ttlRslt; }; DebugJS.test.prepare = function() { DebugJS.test.setId(DebugJS.test.data.executingTestId); }; DebugJS.test.setId = function(id) { if (id.match(/%SEQ%/)) id = id.replace(/%SEQ%/, DebugJS.test.nextSeq()); var data = DebugJS.test.data; if (!data.results[id]) { data.results[id] = {comment: [], results: []}; } data.executingTestId = id; }; DebugJS.test.setSeq = function(v) { if (v != '') DebugJS.test.data.seq = v | 0; }; DebugJS.test.nextSeq = function() { return ++DebugJS.test.data.seq; }; DebugJS.test.setCmnt = function(c) { DebugJS.test.prepare(); DebugJS.test.data.results[DebugJS.test.data.executingTestId].comment.push(c); DebugJS._log('# ' + c); }; DebugJS.test.chkResult = function(results) { var test = DebugJS.test; var r = test.STATUS_NT; for (var i = 0; i < results.length; i++) { var st = results[i].status; if (st == test.STATUS_ERR) { return test.STATUS_ERR; } else if (st == test.STATUS_NG) { r = test.STATUS_NG; } else if ((st == test.STATUS_OK) && (r == test.STATUS_NT)) { r = test.STATUS_OK; } } return r; }; DebugJS.test.getStyledResultStr = function(st, info) { var s = DebugJS.test.getStyledStStr(st); if (info) s += ' ' + info; return s; }; DebugJS.test.getStyledStStr = function(st) { var test = DebugJS.test; var color; switch (st) { case test.STATUS_OK: color = test.COLOR_OK; break; case test.STATUS_NG: color = test.COLOR_NG; break; case test.STATUS_ERR: color = test.COLOR_ERR; break; default: color = test.COLOR_NT; } return '[<span style="color:' + color + '">' + st + '</span>]'; }; DebugJS.test.getStyledInfoStr = function(result) { if (result.info) return result.info; if (!result.method) return ''; var echoExp = result.exp; if (result.method == 'regexp') { echoExp = DebugJS.decodeEsc(echoExp); echoExp = '<span style="color:#0ff">/</span>' + echoExp + '<span style="color:#0ff">/</span>'; } else if (typeof echoExp == 'string') { echoExp = DebugJS.styleValue(echoExp); echoExp = DebugJS.hlCtrlChr(echoExp); } else { echoExp = DebugJS.styleValue(echoExp); } var echoGot = result.got; if (typeof echoGot == 'string') { echoGot = DebugJS.styleValue(echoGot); echoGot = DebugJS.hlCtrlChr(echoGot); } else { echoGot = DebugJS.styleValue(echoGot); } return 'Got=' + echoGot + ' ' + result.method + ' Exp=' + echoExp; }; DebugJS.test.getCountStr = function(cnt) { var test = DebugJS.test; var total = test.countTotal(cnt); return '<span style="color:' + test.COLOR_OK + '">OK</span>:' + cnt.ok + '/' + total + ' <span style="color:' + test.COLOR_NG + '">NG</span>:' + cnt.ng + ' <span style="color:' + test.COLOR_ERR + '">ERR</span>:' + cnt.err + ' <span style="color:' + test.COLOR_NT + '">NT</span>:' + cnt.nt; }; DebugJS.test.getSumCount = function() { var test = DebugJS.test; var cnt = {ok: 0, ng: 0, err: 0, nt: 0}; for (var id in test.data.results) { var st = test.chkResult(test.data.results[id].results); switch (st) { case test.STATUS_OK: cnt.ok++; break; case test.STATUS_NG: cnt.ng++; break; case test.STATUS_ERR: cnt.err++; break; case test.STATUS_NT: cnt.nt++; } } return cnt; }; DebugJS.test.countTotal = function(cnt) { return (cnt.ok + cnt.ng + cnt.err + cnt.nt); }; DebugJS.test.result = function() { var test = DebugJS.test; var data = test.data; var nm = data.name; var ttl = test.getTotalResult(); var cnt = test.getSumCount(); var s = 'Test Result:\n'; if (nm != '') s += '[TEST NAME]\n' + nm + '\n\n'; if (data.desc.length > 0) s += '[DESCRIPTION]\n'; for (var i = 0; i < data.desc.length; i++) { s += data.desc[i] + '\n'; } if (data.desc.length > 0) s += '\n'; if (test.countTotal(cnt) > 0) s += '[RESULTS]\n---------\n'; s += test.getDetailStr(data.results); s += '[SUMMARY]\n' + test.getCountStr(cnt) + ' (' + test.getCountStr(data.cnt) + ')\n'; s += DebugJS.repeatCh('-', ttl.length + 2) + '\n' + test.getStyledStStr(ttl); return s; }; DebugJS.test.getDetailStr = function(results) { var test = DebugJS.test; var M = 16; var n = test.countLongestLabel(); if (n > M) n = M; var details = ''; for (var id in results) { var testId = (id == '' ? '<span style="color:#ccc">&lt;No Test ID&gt;</span>' : id); var st = test.chkResult(results[id].results); var rs = test.getStyledStStr(st); details += rs + ' ' + testId + '\n'; for (var i = 0; i < results[id].comment.length; i++) { var comment = results[id].comment[i]; details += ' # ' + comment + '\n'; } for (i = 0; i < results[id].results.length; i++) { var result = results[id].results[i]; var info = test.getStyledInfoStr(result); details += ' ' + DebugJS.strPadding(result.label, ' ', n, 'R') + ' ' + test.getStyledResultStr(result.status, info) + '\n'; } details += '\n'; } return details; }; DebugJS.test.getResult = function(j) { var data = DebugJS.test.data; var r = { name: data.name, desc: data.desc, startTime: data.startTime, endTime: data.endTime, totalResult: data.ttlRslt, count: data.cnt, results: data.results }; if (j) return DebugJS.toJSON(r); return r; }; DebugJS.test.verify = function(got, method, exp, reqEval, label) { var test = DebugJS.test; var status = test.STATUS_ERR; var info = ''; try { if (method != 'regexp') { exp = eval(exp); if (typeof exp == 'string') { exp = exp.replace(/\r?\n/g, '\n'); } } if (reqEval) { got = eval(got); } if (typeof got == 'string') { got = got.replace(/\r?\n/g, '\n'); } if (method == '==') { if (got == exp) { status = test.STATUS_OK; } else { status = test.STATUS_NG; } } else if (method == '!=') { if (got != exp) { status = test.STATUS_OK; } else { status = test.STATUS_NG; } } else if ((method == 'regexp') || (method == '<') || (method == '<=') || (method == '>') || (method == '>=')) { var evl; if (method == 'regexp') { exp = DebugJS.encodeEsc(exp); var wkGot = got.replace(/\n/g, '\\n'); evl = '(new RegExp(\'' + exp + '\')).test(\'' + wkGot + '\')'; } else { evl = got + method + exp; } try { r = eval(evl); } catch (e) { info = 'Failed to evaluate: ' + e; DebugJS._log.e(info); test.addResult(status, label, exp, got, method, info); test.onVrfyAftr(status); return status; } if (r) { status = test.STATUS_OK; } else { status = test.STATUS_NG; } } else { if (method == undefined) { DebugJS.printUsage('test|point verify [-label:text] got ==|!=|<|>|<=|>=|regexp exp'); } else { info = 'Unknown verify method: ' + method; DebugJS._log.e(info); test.addResult(status, label, exp, got, method, info); test.onVrfyAftr(status); } return status; } } catch (e) { info = e.toString(); } test.addResult(status, label, exp, got, method, info); var s = test.getStyledResultStr(status, info); DebugJS._log(s); test.onVrfyAftr(status); return status; }; DebugJS.test.onVrfyAftr = function(st) { if ((DebugJS.bat.isRunning()) && (DebugJS.bat.hasBatStopCond('test'))) { if (st != DebugJS.test.STATUS_OK) { DebugJS.bat.ctrl.stopReq = true; } } }; DebugJS.test.countLongestLabel = function() { var results = DebugJS.test.data.results; var l = 0; for (var id in results) { for (var i = 0; i < results[id].results.length; i++) { var r = results[id].results[i]; if (r.label.length > l) { l = r.label.length; } } } return l; }; DebugJS.test.getStatus = function() { var data = DebugJS.test.data; var r = { name: data.name, running: data.running, startTime: data.startTime, endTime: data.endTime, seq: data.seq, executingTestId: data.executingTestId, lastRslt: data.lastRslt, ttlRslt: data.ttlRslt, cnt: data.cnt }; return r; }; DebugJS.test.isRunning = function() { return DebugJS.test.data.running; }; DebugJS.getElement = function(selector, idx) { if (typeof selector != 'string') return selector; idx |= 0; var el = null; try { var nodeList = document.querySelectorAll(selector); el = nodeList.item(idx); } catch (e) {} return el; }; DebugJS.getElPosSize = function(el, idx) { el = DebugJS.getElement(el, idx); if (!el) return null; var rect = el.getBoundingClientRect(); var rectT = Math.round(rect.top); var rectL = Math.round(rect.left); var rectR = Math.round(rect.right); var rectB = Math.round(rect.bottom); var ps = { x: rectL, y: rectT, w: ((rectR - rectL) + 1), h: ((rectB - rectT) + 1) }; return ps; }; DebugJS.getScreenCenter = function() { var p = { x: (document.documentElement.clientWidth / 2), y: (document.documentElement.clientHeight / 2) }; return p; }; DebugJS.getLabelEl = function(label, idx) { var el = null; var cnt = 0; var c = document.getElementsByTagName('label'); for (var i = 0; i < c.length; i++) { if (c[i].innerText == label) { if (idx == cnt) { el = c[i]; break; } cnt++; } } return el; }; DebugJS.findFocusableEl = function(e) { var el = e; do { if (el.tagName == 'HTML') { el = null; break; } if (DebugJS.isFocusable(el)) break; el = el.parentNode; } while (el != null); return el; }; DebugJS.isFocusable = function(el) { var a = ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA']; return (a.indexOf(el.tagName) == -1 ? false : true); }; DebugJS.isTxtInp = function(el) { if (el.tagName == 'TEXTAREA') return true; if (el.tagName == 'INPUT') { if ((el.type == 'text') || (el.type == 'password')) return true; } return false; }; DebugJS.toggleElShowHide = function(el) { var v = (el.style.display == 'none' ? '' : 'none'); el.style.display = v; }; DebugJS.random = function(min, max) { return DebugJS.getRandom(DebugJS.RND_TYPE_NUM, min, max); }; DebugJS.randomStr = function(min, max) { return DebugJS.getRandom(DebugJS.RND_TYPE_STR, min, max); }; DebugJS.createResBox = function(m) { return DebugJS._createResBox(m); }; DebugJS.createResBoxErr = function(m) { return DebugJS._createResBox(m, true); }; DebugJS._createResBox = function(m, e) { return '<textarea class="dbg-resbox box ' + (e ? 'err' : 'ok') + '" readonly>' + m + '</textarea>'; }; DebugJS.adjustResBox = function(adj) { DebugJS.adjustResBox.a = adj | 0; setTimeout(DebugJS._adjustResBox, 10); }; DebugJS.adjustResBox.a = 0; DebugJS._adjustResBox = function() { var el = document.getElementsByClassName('dbg-resbox box'); for (var i = 0; i < el.length; i++) { DebugJS.ctx.setStyle(el[i], 'height', (el[i].scrollHeight + DebugJS.adjustResBox.a) + 'px'); } }; DebugJS.getProtocol = function() { return location.protocol; }; DebugJS.getHost = function() { return location.host.split(':')[0]; }; DebugJS.getPort = function() { return location.port; }; DebugJS.getParentPath = function() { return location.href.replace(/(.*\/).*/, '$1'); }; DebugJS.ui = {}; DebugJS.ui.addBtn = function(base, label, onclick) { var el = document.createElement('span'); el.className = 'dbg-btn dbg-nomove'; el.innerText = label; el.onclick = onclick; base.appendChild(el); return el; }; DebugJS.ui.createBtnHtml = function(label, onclick, style) { return '<span class="dbg-btn dbg-nomove" ' + (style == undefined ? '' : 'style="' + style + '" ') + 'onclick="' + onclick + '">' + label + '</span>'; }; DebugJS.ui.addLabel = function(base, label) { var el = document.createElement('span'); el.innerText = label; base.appendChild(el); return el; }; DebugJS.ui.addTextInput = function(base, width, txtAlign, color, val, oninput) { var ctx = DebugJS.ctx; var el = document.createElement('input'); el.className = 'dbg-txtbox'; ctx.setStyle(el, 'width', width); ctx.setStyle(el, 'min-height', ctx.computedFontSize + 'px'); ctx.setStyle(el, 'margin', '0'); ctx.setStyle(el, 'padding', '0'); ctx.setStyle(el, 'color', color); if (txtAlign) ctx.setStyle(el, 'text-align', txtAlign); el.value = val; el.oninput = oninput; base.appendChild(el); return el; }; DebugJS.wd = {}; DebugJS.wd.INTERVAL = 50; DebugJS.wd.wdTmId = 0; DebugJS.wd.wdPetTime = 0; DebugJS.wd.cnt = 0; DebugJS.wd.start = function(interval) { var ctx = DebugJS.ctx; var wd = DebugJS.wd; interval |= 0; if (interval > 0) ctx.props.wdt = interval; ctx.status |= DebugJS.ST_WD; wd.cnt = 0; wd.wdPetTime = (new Date()).getTime(); DebugJS._log.s('Start watchdog (' + ctx.props.wdt + 'ms)'); if (wd.wdTmId > 0) clearTimeout(wd.wdTmId); wd.wdTmId = setTimeout(wd.pet, wd.INTERVAL); }; DebugJS.wd.pet = function() { var ctx = DebugJS.ctx; if (!(ctx.status & DebugJS.ST_WD)) return; var wd = DebugJS.wd; var now = (new Date()).getTime(); var elps = now - wd.wdPetTime; if (elps > ctx.props.wdt) { wd.cnt++; DebugJS._log.w('Watchdog bark! (' + elps + 'ms)'); DebugJS.callEvtListeners('watchdog', elps); } wd.wdPetTime = now; wd.wdTmId = setTimeout(wd.pet, wd.INTERVAL); }; DebugJS.wd.stop = function() { var wd = DebugJS.wd; if (wd.wdTmId > 0) { clearTimeout(wd.wdTmId); wd.wdTmId = 0; } DebugJS.ctx.status &= ~DebugJS.ST_WD; DebugJS._log.s('Stop watchdog'); }; DebugJS.log = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log(m); }; DebugJS.log.e = function(m) { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_LOG_SUSPENDING) return; ctx.errStatus |= DebugJS.ERR_ST_LOG; DebugJS._log.e(m); }; DebugJS.log.w = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.w(m); }; DebugJS.log.i = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.i(m); }; DebugJS.log.d = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.d(m); }; DebugJS.log.v = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.v(m); }; DebugJS.log.t = function(m, n) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS.time.log(m, n); }; DebugJS.log.p = function(o, l, m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.p(o, l, m, false); }; DebugJS.log.json = function(o, l, m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.p(o, l, m, true); }; DebugJS.log.j = DebugJS.log.json; DebugJS.log.res = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.res(m); }; DebugJS.log.res.err = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.res.err(m); }; DebugJS.log.mlt = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.mlt(m); }; DebugJS.log.clear = function() { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS.ctx.clearLog(); }; DebugJS.log.suspend = function() { DebugJS.ctx.suspendLog(); }; DebugJS.log.resume = function() { DebugJS.ctx.resumeLog(); }; DebugJS.log.preserve = function(f) { var ctx = DebugJS.ctx; if (f == undefined) { return ((ctx.status & DebugJS.ST_LOG_PRESERVED) ? true : false); } if (DebugJS.LS_AVAILABLE) ctx.setLogPreserve(ctx, f); }; DebugJS.log.toBottom = function() { DebugJS.ctx.scrollLogBtm(DebugJS.ctx); }; DebugJS.log.root = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; if (window.opener) { window.opener.log.root(m); } else if (window.top.opener) { window.top.opener.log.root(m); } else { window.top.DebugJS._log(m); } }; DebugJS.log.root.fn = function(lv, m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; if (window.opener) { window.opener.log[lv].root(m); } else if (window.top.opener) { window.top.opener.log[lv].root(m); } else { window.top.DebugJS._log[lv](m); } }; DebugJS.rootFncs = function() { var fn = ['v', 'd', 'i', 'w', 'e']; for (var i = 0; i < fn.length; i++) { var lv = fn[i]; DebugJS.log[lv].root = (DebugJS.ENABLE ? DebugJS.log.root.fn.bind(undefined, lv) : DebugJS.f_); } }; DebugJS.setConsoleLogOut = function(f) { if (!window.console) return; if (f) { console.log = function(x) {log(x);}; console.info = function(x) {log.i(x);}; console.warn = function(x) {log.w(x);}; console.error = function(x) {log.e(x);}; console.time = function(x) {DebugJS.time.start(x);}; console.timeEnd = function(x) {DebugJS.time.end(x);}; } else { console.log = DebugJS.bak.console.log; console.info = DebugJS.bak.console.info; console.warn = DebugJS.bak.console.warn; console.error = DebugJS.bak.console.error; console.time = DebugJS.bak.console.time; console.timeEnd = DebugJS.bak.console.timeEnd; } }; DebugJS.restoreStatus = function(ctx) { var data = DebugJS.loadStatus(); if ((data == null) || !((data.status & DebugJS.ST_LOG_PRESERVED) || (data.status & DebugJS.ST_BAT_CONT))) { return; } if (data.status & DebugJS.ST_LOG_PRESERVED) { ctx.status |= DebugJS.ST_LOG_PRESERVED; DebugJS.restoreLog(); } if (data.status & DebugJS.ST_BAT_CONT) { ctx.status |= DebugJS.ST_BAT_CONT; } ctx.timers = data.timers; if (data.status & DebugJS.ST_STOPWATCH_RUNNING) { ctx.startStopwatch(); } else { ctx.updateSwLabel(); } DebugJS.restoreProps(ctx, data.props); DebugJS.ctx.CMD_ALIAS = data.alias; }; DebugJS.restoreProps = function(ctx, props) { for (var k in props) { ctx._cmdSet(ctx, k, props[k], false); } }; DebugJS.ver = function() { return DebugJS.ctx.v; }; DebugJS.x = DebugJS.x || {}; DebugJS.x.addCmdTbl = function(table) { var ctx = DebugJS.ctx; for (var i = 0; i < table.length; i++) { var c = table[i]; if ((ctx.existsCmd(c.cmd, ctx.INT_CMD_TBL)) || (ctx.existsCmd(c.cmd, ctx.EXT_CMD_TBL))) { c.attr |= DebugJS.CMD_ATTR_DISABLED; } ctx.EXT_CMD_TBL.push(c); } }; DebugJS.x.addPanel = function(p) { var ctx = DebugJS.ctx; p.base = null; p.btn = null; var idx = ctx.extPanels.push(p) - 1; if (ctx.status & DebugJS.ST_INITIALIZED) { ctx.initExtPanel(ctx); } return idx; }; DebugJS.x.addFileLdr = function(p) { var d = p.fileloader; if (d) DebugJS.addFileLoader(p.panel, d.cb, d.mode, d.decode); }; DebugJS.x.getPanel = function(idx) { var p = DebugJS.ctx.extPanels[idx]; if (p) return p.panel; return null; }; DebugJS.x.getActivePanel = function() { return DebugJS.x.getPanel(DebugJS.ctx.extActPnlIdx); }; DebugJS.x.removePanel = function(idx) { var ctx = DebugJS.ctx; if (!ctx.extPanels[idx]) return; var nIdx = -1; var p = ctx.extPanels[idx]; ctx.extPanels[idx] = null; if (ctx.extActPnlIdx == idx) { nIdx = ctx.prevValidExtPanelIdx(ctx, idx); if (nIdx == -1) { nIdx = ctx.nextValidExtPanelIdx(ctx, idx); } } if (!(ctx.status & DebugJS.ST_INITIALIZED)) return; if ((ctx.status & DebugJS.ST_EXT_PANEL) && (p.onInActive)) { ctx.onExtPanelInActive(ctx, p); } ctx.redrawExtPanelBtn(ctx); if (ctx.existsValidExtPanel(ctx)) { if (nIdx != -1) { ctx.switchExtPanel(nIdx); } } else { ctx.extActPnlIdx = -1; ctx.extPanels = []; ctx.closeExtPanel(ctx); if (ctx.extBtn) ctx.extBtn.style.display = 'none'; } }; DebugJS.x.setBtnLabel = function(l) { DebugJS.ctx.extBtnLabel = l; if (DebugJS.ctx.extBtn) DebugJS.ctx.extBtn.innerHTML = l; }; DebugJS._init = function() { if (DebugJS.ctx.status & DebugJS.ST_INITIALIZED) { return true; } else { return DebugJS.ctx.init(null, null); } }; DebugJS.init = function(opt) { DebugJS.ctx.init(opt, null); }; DebugJS.onReady = function() { DebugJS._init(); }; DebugJS.onLoad = function() { window.addEventListener('unload', DebugJS.onUnload, true); DebugJS.test.load(); DebugJS.bat.load(); }; DebugJS.onUnload = function() { var ctx = DebugJS.ctx; if (DebugJS.test.data.running) { DebugJS.test.save(); } if ((ctx.status & DebugJS.ST_BAT_RUNNING) && (ctx.props.batcont == 'on')) { DebugJS.bat.save(); } if ((ctx.status & DebugJS.ST_LOG_PRESERVED) || (ctx.status & DebugJS.ST_BAT_CONT)) { DebugJS.saveStatus(); } if (ctx.status & DebugJS.ST_LOG_PRESERVED) { DebugJS.preserveLog(); } }; DebugJS.onError = function(e) { var ctx = DebugJS.ctx; var msg; ctx.errStatus |= DebugJS.ERR_ST_SCRIPT; if (e.error && e.error.stack) { msg = e.error.stack; } else { if ((e.message == undefined) && (e.filename == undefined)) { if (e.target && e.target.outerHTML) { ctx.errStatus |= DebugJS.ERR_ST_LOAD; ctx.errStatus &= ~DebugJS.ERR_ST_SCRIPT; msg = 'LOAD_ERROR: ' + (e.target.outerHTML).replace(/</g, '&lt;').replace(/>/g, '&gt;'); } else { msg = 'UNKNOWN_ERROR'; } } else { msg = e.message + ' ' + e.filename + '(' + e.lineno + ':' + e.colno + ')'; } } DebugJS.log.e(msg); }; DebugJS.balse = function() { var x = DebugJS.f_; DebugJS.boot = x; DebugJS.start = x; DebugJS.log = x; DebugJS.log.e = x; DebugJS.log.w = x; DebugJS.log.i = x; DebugJS.log.d = x; DebugJS.log.v = x; DebugJS.log.t = x; DebugJS.log.p = x; DebugJS.log.json = x; DebugJS.log.mlt = x; DebugJS.log.clear = x; DebugJS.log.res = x; DebugJS.log.res.err = x; DebugJS.log.suspend = x; DebugJS.log.resume = x; DebugJS.log.root = x; DebugJS.addEvtListener = x; DebugJS.addFileLoader = x; DebugJS.adjustResBox = x; DebugJS.cmd = x; DebugJS.bat = x; DebugJS.bat.set = x; DebugJS.bat.run = x; DebugJS.bat.pause = x; DebugJS.bat.resume = x; DebugJS.bat.stop = x; DebugJS.bat.list = x; DebugJS.bat.status = x; DebugJS.bat.isRunning = x; DebugJS.bat.setCond = x; DebugJS.countElements = x; DebugJS.getHTML = x; DebugJS.init = x; DebugJS.dumpLog = x; DebugJS.sendLog = x; DebugJS.show = x; DebugJS.hide = x; DebugJS.http = x; DebugJS.led = x; DebugJS.led.on = x; DebugJS.led.off = x; DebugJS.msg = x; DebugJS.msg.clear = x; DebugJS.opacity = x; DebugJS.stack = x; DebugJS.stopwatch = x; DebugJS.stopwatch.start = x; DebugJS.stopwatch.stop = x; DebugJS.stopwatch.end = x; DebugJS.stopwatch.split = x; DebugJS.stopwatch.reset = x; DebugJS.stopwatch.val = x; DebugJS.time.start = x; DebugJS.time.split = x; DebugJS.time.end = x; DebugJS.time.check = x; DebugJS.ver = x; DebugJS.wd.start = x; DebugJS.wd.stop = x; DebugJS.x.addCmdTbl = x; DebugJS.x.addPanel = x; DebugJS.x.getPanel = x; DebugJS.x.getActivePanel = x; DebugJS.x.removePanel = x; DebugJS.x.setBtnLabel = x; DebugJS._createResBox = x; }; DebugJS.boot = function() { DebugJS.rootFncs(); DebugJS.ctx = DebugJS.ctx || new DebugJS(); DebugJS.el = null; if (window.el === undefined) DebugJS.G_EL_AVAILABLE = true; try { if (typeof window.localStorage != 'undefined') { DebugJS.LS_AVAILABLE = true; } } catch (e) {} try { if (typeof window.sessionStorage != 'undefined') { DebugJS.SS_AVAILABLE = true; } } catch (e) {} window.addEventListener('DOMContentLoaded', DebugJS.onReady, true); window.addEventListener('load', DebugJS.onLoad, true); window.addEventListener('error', DebugJS.onError, true); DebugJS.bak = { console: { log: console.log, info: console.info, warn: console.warn, error: console.error, time: console.time, timeEnd: console.timeEnd } }; DebugJS.restoreStatus(DebugJS.ctx); }; DebugJS.start = function(o) {DebugJS.init(o);DebugJS.show();}; DebugJS.ENABLE = true; if (DebugJS.ENABLE) { DebugJS.boot(); } else { DebugJS.balse(); } DebugJS.time.s = DebugJS.time.start; DebugJS.time.e = DebugJS.time.end; var dbg = (dbg === undefined ? DebugJS : dbg); var log = (log === undefined ? DebugJS.log : log);
debug.js
/*! * debug.js * Copyright 2015 Takashi Harano * Released under the MIT license * https://debugjs.net/ */ var DebugJS = DebugJS || function() { this.v = '201901082111'; this.DEFAULT_OPTIONS = { visible: false, keyAssign: { key: 113, shift: undefined, ctrl: undefined, alt: undefined, meta: undefined }, popupOnError: { scriptError: true, loadError: true, errorLog: true }, lines: 18, bufsize: 300, width: 533, zoom: 1, position: 'se', adjustX: 20, adjustY: 20, fontSize: 12, fontFamily: 'Consolas, monospace', fontColor: '#fff', logColorV: '#99bcc8', logColorD: '#ccc', logColorI: '#9ef', logColorW: '#eee000', logColorE: '#f88', logColorS: '#fff', clockColor: '#8f0', timerColor: '#9ef', timerColorExpr: '#fcc', sysInfoColor: '#ddd', btnColor: '#6cf', btnHoverColor: '#8ef', promptColor: '#0cf', promptColorE: '#f45', background: 'rgba(0,0,0,0.65)', border: 'solid 1px #888', borderRadius: '0', opacity: '1', showLineNums: true, showTimeStamp: true, resizable: true, togglableShowHide: true, useClock: true, useClearButton: true, useSuspendLogButton: true, usePinButton: true, useWinCtrlButton: true, useStopwatch: true, useWindowSizeInfo: true, useMouseStatusInfo: true, useKeyStatusInfo: true, useLed: true, useMsgDisplay: true, msgDisplayPos: 'right', msgDisplayBackground: 'rgba(0,0,0,0.2)', useScreenMeasure: true, useSystemInfo: true, useHtmlSrc: true, useElementInfo: true, useTools: true, useJsEditor: true, useLogFilter: true, useCommandLine: true, cmdHistoryMax: 100, timerLineColor: '#0cf', disableAllCommands: false, disableAllFeatures: false, mode: '', lockCode: null, target: null }; this.DFLT_ELM_ID = '_debug_'; this.id = null; this.bodyEl = null; this.bodyCursor = ''; this.styleEl = null; this.win = null; this.winBody = null; this.headPanel = null; this.infoPanel = null; this.clockLabel = null; this.clockUpdIntHCnt = 0; this.clockUpdInt = DebugJS.UPDATE_INTERVAL_L; this.measBtn = null; this.measBox = null; this.sysInfoBtn = null; this.sysInfoPanel = null; this.htmlSrcBtn = null; this.htmlSrcPanel = null; this.htmlSrcHeaderPanel = null; this.htmlSrcUpdInpLbl = null; this.htmlSrcUpdInpLbl2 = null; this.htmlSrcUpdBtn = null; this.htmlSrcUpdateInput = null; this.htmlSrcBodyPanel = null; this.htmlSrcUpdateInterval = 0; this.htmlSrcUpdateTimerId = 0; this.elmInfoBtn = null; this.elmInfoPanel = null; this.elmInfoHeaderPanel = null; this.elmPrevBtn = null; this.elmTitle = null; this.elmNextBtn = null; this.elmSelectBtn = null; this.elmHighlightBtn = null; this.elmUpdateBtn = null; this.elmCapBtn = null; this.elmDelBtn = null; this.elmUpdateInput = null; this.elmNumPanel = null; this.elmInfoBodyPanel = null; this.elmInfoStatus = DebugJS.ELMINFO_ST_SELECT | DebugJS.ELMINFO_ST_HIGHLIGHT; this.elmUpdateInterval = 0; this.elmUpdateTimerId = 0; this.elmInfoShowHideStatus = {text: false, allStyles: false, elBorder: false, htmlSrc: false}; this.targetEl = null; this.toolsBtn = null; this.toolsPanel = null; this.toolsHeaderPanel = null; this.toolsBodyPanel = null; this.timerBtn = null; this.timerBasePanel = null; this.timerClockSubPanel = null; this.timerClockLabel = null; this.timerClockSSS = false; this.clockSSSbtn = null; this.timerStopwatchCuSubPanel = null; this.timerStopwatchCuLabel = null; this.timerStopwatchCdSubPanel = null; this.timerStopwatchCdLabel = null; this.timerStopwatchCdInpSubPanel = null; this.timerStopwatchCdInput = null; this.timerTimeUpTime = 0; this.timerSwTimeCd = 0; this.timerSwTimeCdContinue = false; this.timerStartStopBtnCu = null; this.timerSplitBtnCu = null; this.timerStartStopBtnCd = null; this.timerSplitBtnCd = null; this.timer0CntBtnCd1 = null; this.timer0CntBtnCd2 = null; this.timerStartStopBtnCdInp = null; this.txtChkBtn = null; this.txtChkPanel = null; this.txtChkTxt = null; this.txtChkFontSizeRange = null; this.txtChkFontSizeInput = null; this.txtChkFontSizeUnitInput = null; this.txtChkFontWeightRange = null; this.txtChkFontWeightLabel = null; this.txtChkInputFgRGB = null; this.txtChkRangeFgR = null; this.txtChkRangeFgG = null; this.txtChkRangeFgB = null; this.txtChkLabelFgR = null; this.txtChkLabelFgG = null; this.txtChkLabelFgB = null; this.txtChkInputBgRGB = null; this.txtChkRangeBgR = null; this.txtChkRangeBgG = null; this.txtChkRangeBgB = null; this.txtChkLabelBgR = null; this.txtChkLabelBgG = null; this.txtChkLabelBgB = null; this.txtChkTargetEl = null; this.txtChkItalic = false; this.fileVwrMode = 'b64'; this.fileVwrBtn = null; this.fileVwrPanel = null; this.fileInput = null; this.fileVwrLabelB64 = null; this.fileVwrRadioB64 = null; this.fileVwrLabelBin = null; this.fileVwrRadioBin = null; this.fileReloadBtn = null; this.fileClrBtn = null; this.fileVwrFooter = null; this.fileLoadProgBar = null; this.fileLoadProg = null; this.fileLoadCancelBtn = null; this.filePreviewWrapper = null; this.filePreview = null; this.fileVwrDtUrlWrp = null; this.fileVwrDtUrlScheme = null; this.fileVwrDtTxtArea = null; this.fileVwrDecMode = 'b64'; this.fileVwrDecModeBtn = null; this.fileVwrDataSrcType = null; this.fileVwrFile = null; this.fileVwrDataSrc = null; this.fileVwrByteArray = null; this.fileVwrBinViewOpt = {mode: 'hex', addr: true, space: true, ascii: true}, this.fileVwrSysCb = null; this.fileReader = null; this.jsBtn = null; this.jsPanel = null; this.jsEditor = null; this.jsBuf = ''; this.htmlPrevBtn = null; this.htmlPrevBasePanel = null; this.htmlPrevPrevPanel = null; this.htmlPrevEditorPanel = null; this.htmlPrevEditor = null; this.htmlPrevBuf = ''; this.batBtn = null; this.batBasePanel = null; this.batEditorPanel = null; this.batTextEditor = null; this.batRunBtn = null; this.batStopBtn = null; this.batResumeBtn = null; this.batStartTxt = null; this.batEndTxt = null; this.batArgTxt = null; this.batCurPc = null; this.batTotalLine = null; this.batNestLv = null; this.swBtnPanel = null; this.swLabel = null; this.clearBtn = null; this.wdBtn = null; this.suspendLogBtn = null; this.preserveLogBtn = null; this.pinBtn = null; this.winCtrlBtnPanel = null; this.closeBtn = null; this.mousePosLabel = null; this.mousePos = {x: '-', y: '-'}; this.mouseClickLabel = null; this.mouseClick0 = DebugJS.COLOR_INACT; this.mouseClick1 = DebugJS.COLOR_INACT; this.mouseClick2 = DebugJS.COLOR_INACT; this.winSizeLabel = null; this.clientSizeLabel = null; this.bodySizeLabel = null; this.pixelRatioLabel = null; this.scrollPosLabel = null; this.scrollPosX = 0; this.scrollPosY = 0; this.keyDownLabel = null; this.keyPressLabel = null; this.keyUpLabel = null; this.keyDownCode = DebugJS.KEY_ST_DFLT; this.keyPressCode = DebugJS.KEY_ST_DFLT; this.keyUpCode = DebugJS.KEY_ST_DFLT; this.ledPanel = null; this.led = 0; this.msgLabel = null; this.msgString = ''; this.mainPanel = null; this.overlayBasePanel = null; this.overlayPanels = []; this.logHeaderPanel = null; this.fltrBtnAll = null; this.fltrBtnStd = null; this.fltrBtnVrb = null; this.fltrBtnDbg = null; this.fltrBtnInf = null; this.fltrBtnWrn = null; this.fltrBtnErr = null; this.fltrInputLabel = null; this.fltrInput = null; this.fltrText = ''; this.fltr = false; this.fltrBtn = null; this.fltrCase = false; this.fltrCaseBtn = null; this.fltrTxtHtml = true; this.fltrTxtHtmlBtn = null; this.logPanel = null; this.logPanelHeightAdjust = ''; this.cmdPanel = null; this.cmdLine = null; this.stopErrCb = false; this.cmdHistoryBuf = null; this.CMD_HISTORY_MAX = this.DEFAULT_OPTIONS.cmdHistoryMax; this.cmdHistoryIdx = this.CMD_HISTORY_MAX; this.cmdTmp = ''; this.cmdEchoFlg = true; this.cmdDelayData = {tmid: 0, cmd: null}; this.timers = {}; this.initWidth = 0; this.initHeight = 0; this.orgSizePos = {w: 0, h: 0, t: 0, l: 0}; this.expandModeOrg = {w: 0, h: 0, t: 0, l: 0}; this.winExpandHeight = DebugJS.DBGWIN_EXPAND_C_H * this.DEFAULT_OPTIONS.zoom; this.winExpandCnt = 0; this.clickedPosX = 0; this.clickedPosY = 0; this.prevOffsetTop = 0; this.prevOffsetLeft = 0; this.savedFunc = null; this.computedFontSize = this.DEFAULT_OPTIONS.fontSize; this.computedWidth = this.DEFAULT_OPTIONS.width; this.computedMinW = DebugJS.DBGWIN_MIN_W; this.computedMinH = DebugJS.DBGWIN_MIN_H; this.featStack = []; this.featStackBak = []; this.status = 0; this.uiStatus = 0; this.toolStatus = 0; this.toolTimerMode = DebugJS.TOOL_TIMER_MODE_CLOCK; this.sizeStatus = 0; this.ptOpTm = 0; this.logFilter = DebugJS.LOG_FLTR_ALL; this.toolsActiveFnc = DebugJS.TOOLS_DFLT_ACTIVE_FNC; this.logBuf = new DebugJS.RingBuffer(this.DEFAULT_OPTIONS.bufsize); this.INT_CMD_TBL = [ {cmd: 'alias', fn: this.cmdAlias, desc: 'Define or display aliases', help: 'alias [name=[\'command\']]'}, {cmd: 'base64', fn: this.cmdBase64, desc: 'Encodes/Decodes Base64', help: 'base64 [-e|-d] str'}, {cmd: 'bat', fn: this.cmdBat, desc: 'Operate BAT Script', help: 'bat run [-s s] [-e e] [-arg arg]|pause|stop|list|status|pc|symbols|clear|exec b64-encoded-bat|set key val'}, {cmd: 'bin', fn: this.cmdBin, desc: 'Convert a number to binary', help: 'bin num digit'}, {cmd: 'bsb64', fn: this.cmdBSB64, desc: 'Encodes/Decodes BSB64(Bit Shifted Base64) reversible encryption string', help: 'bsb64 -e|-d -i "&lt;str&gt;" [-n &lt;n&gt[L|R]]'}, {cmd: 'call', fn: this.cmdCall, attr: DebugJS.CMD_ATTR_SYSTEM | DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'close', fn: this.cmdClose, desc: 'Close a function', help: 'close [measure|sys|html|dom|js|tool|ext]'}, {cmd: 'clock', fn: this.cmdClock, desc: 'Open clock mode'}, {cmd: 'cls', fn: this.cmdCls, desc: 'Clear log message', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'condwait', fn: this.cmdCondWait, desc: 'Suspends processing of batch file until condition key is set', help: 'condwait set -key key | pause [-timeout ms|1d2h3m4s500] | init'}, {cmd: 'dbgwin', fn: this.cmdDbgWin, desc: 'Control the debug window', help: 'dbgwin show|hide|pos|size|opacity|status|lock'}, {cmd: 'date', fn: this.cmdDate, desc: 'Convert ms <--> Date-Time', help: 'date [ms|YYYY/MM/DD HH:MI:SS.sss]'}, {cmd: 'delay', fn: this.cmdDelay, desc: 'Delay command execution', help: 'delay [-c] ms|YYYYMMDDTHHMISS|1d2h3m4s500 command'}, {cmd: 'echo', fn: this.cmdEcho, desc: 'Display the ARGs on the log window'}, {cmd: 'elements', fn: this.cmdElements, desc: 'Count elements by #id / .className / tagName', help: 'elements [#id|.className|tagName]'}, {cmd: 'event', fn: this.cmdEvent, desc: 'Manipulate an event', help: 'event create|set|dispatch|clear type|prop value'}, {cmd: 'exit', fn: this.cmdExit, desc: 'Close the debug window and clear all status', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'goto', fn: this.cmdGoto, attr: DebugJS.CMD_ATTR_SYSTEM | DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'help', fn: this.cmdHelp, desc: 'Displays available command list', help: 'help command', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'hex', fn: this.cmdHex, desc: 'Convert a number to hexadecimal', help: 'hex num digit'}, {cmd: 'history', fn: this.cmdHistory, desc: 'Displays command history', help: 'history [-c] [-d offset]', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'http', fn: this.cmdHttp, desc: 'Send an HTTP request', help: 'http [method] url [--user user:pass] [data]'}, {cmd: 'js', fn: this.cmdJs, desc: 'Operate JavaScript code in JS Editor', help: 'js exec'}, {cmd: 'json', fn: this.cmdJson, desc: 'Parse one-line JSON', help: 'json [-l&lt;n&gt;] [-p] one-line-json'}, {cmd: 'jump', fn: this.cmdJump, attr: DebugJS.CMD_ATTR_SYSTEM | DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'keypress', fn: this.cmdKeyPress, desc: 'Dispatch a key event to active element', help: 'keypress keycode [-shift] [-ctrl] [-alt] [-meta]'}, {cmd: 'keys', fn: this.cmdKeys, desc: 'Displays all enumerable property keys of an object', help: 'keys object'}, {cmd: 'laptime', fn: this.cmdLaptime, desc: 'Lap time test'}, {cmd: 'led', fn: this.cmdLed, desc: 'Set a bit pattern to the indicator', help: 'led bit-pattern'}, {cmd: 'log', fn: this.cmdLog, desc: 'Manipulate log output', help: 'log bufsize|dump|filter|html|load|preserve|suspend|lv'}, {cmd: 'msg', fn: this.cmdMsg, desc: 'Set a string to the message display', help: 'msg message'}, {cmd: 'nexttime', fn: this.cmdNextTime, desc: 'Returns next time from given args', help: 'nexttime T0000|T1200|...|1d2h3m4s|ms'}, {cmd: 'now', fn: this.cmdNow, desc: 'Returns the number of milliseconds elapsed since Jan 1, 1970 00:00:00 UTC'}, {cmd: 'open', fn: this.cmdOpen, desc: 'Launch a function', help: 'open [measure|sys|html|dom|js|tool|ext] [timer|text|file|html|bat]|[idx] [clock|cu|cd]|[b64|bin]'}, {cmd: 'p', fn: this.cmdP, desc: 'Print JavaScript Objects', help: 'p [-l&lt;n&gt;] [-json] object'}, {cmd: 'pause', fn: this.cmdPause, desc: 'Suspends processing of batch file', help: 'pause [-key key [-timeout ms|1d2h3m4s500]|-s]'}, {cmd: 'pin', fn: this.cmdPin, desc: 'Fix the window in its position', help: 'pin on|off'}, {cmd: 'point', fn: this.cmdPoint, desc: 'Show the pointer to the specified coordinate', help: 'point [+|-]x [+|-]y|click|cclick|rclick|dblclick|contextmenu|mousedown|mouseup|keydown|keypress|keyup|focus|blur|change|show|hide|getprop|setprop|verify|init|#id|.class [idx]|tagName [idx]|center|mouse|move|drag|text|selectoption|value|scroll|hint|cursor src [w] [h]'}, {cmd: 'prop', fn: this.cmdProp, desc: 'Displays a property value', help: 'prop property-name'}, {cmd: 'props', fn: this.cmdProps, desc: 'Displays property list', help: 'props [-reset]'}, {cmd: 'random', fn: this.cmdRandom, desc: 'Generate a random number/string', help: 'random [-d|-s] [min] [max]'}, {cmd: 'resume', fn: this.cmdResume, desc: 'Resume a suspended batch process', help: 'resume [-key key]'}, {cmd: 'return', fn: this.cmdReturn, attr: DebugJS.CMD_ATTR_SYSTEM | DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'rgb', fn: this.cmdRGB, desc: 'Convert RGB color values between HEX and DEC', help: 'rgb values (#<span style="color:' + DebugJS.COLOR_R + '">R</span><span style="color:' + DebugJS.COLOR_G + '">G</span><span style="color:' + DebugJS.COLOR_B + '">B</span> | <span style="color:' + DebugJS.COLOR_R + '">R</span> <span style="color:' + DebugJS.COLOR_G + '">G</span> <span style="color:' + DebugJS.COLOR_B + '">B</span>)'}, {cmd: 'rot', fn: this.cmdROT, desc: 'Encodes/Decodes ROTx', help: 'rot 5|13|47 -e|-d -i "&lt;str&gt;" [-n &lt;n&gt]'}, {cmd: 'scrollto', fn: this.cmdScrollTo, desc: 'Set scroll position', help: '\nscrollto log top|px|bottom [+|-]px(x)|left|center|right|current\nscrollto window [+|-]px(y)|top|middle|bottom|current [-speed speed(ms)] [-step step(px)]'}, {cmd: 'select', fn: this.cmdSelect, desc: 'Select an option of select element', help: 'select selectors get|set text|texts|value|values val'}, {cmd: 'set', fn: this.cmdSet, desc: 'Set a property value', help: 'set property-name value'}, {cmd: 'setattr', fn: this.cmdSetAttr, desc: 'Set the value of an attribute on the specified element', help: 'setattr selector [idx] name value'}, {cmd: 'sleep', fn: this.cmdSleep, desc: 'Causes the currently executing thread to sleep', help: 'sleep ms'}, {cmd: 'stopwatch', fn: this.cmdStopwatch, desc: 'Manipulate the stopwatch', help: 'stopwatch [sw0|sw1|sw2] start|stop|reset|split|end|val'}, {cmd: 'test', fn: this.cmdTest, desc: 'Manage unit test', help: 'test init|set|count|result|last|ttlresult|status|verify got-val method expected-val|fin'}, {cmd: 'text', fn: this.cmdText, desc: 'Set text value into an element', help: 'text selector "data" [-speed speed(ms)] [-start seqStartPos] [-end seqEndPos]'}, {cmd: 'time', fn: this.cmdTime, desc: 'Time duration calculator', help: 'time ms|-t1 ms|"datestr" -t2 ms|"datestr"'}, {cmd: 'timer', fn: this.cmdTimer, desc: 'Manipulate the timer', help: 'time start|split|stop|list [timer-name]'}, {cmd: 'unalias', fn: this.cmdUnAlias, desc: 'Remove each NAME from the list of defined aliases', help: 'unalias [-a] name [name ...]'}, {cmd: 'unicode', fn: this.cmdUnicode, desc: 'Displays Unicode code point / Decodes unicode string', help: 'unicode [-e|-d] str|codePoint(s)'}, {cmd: 'uri', fn: this.cmdUri, desc: 'Encodes/Decodes a URI component', help: 'uri [-e|-d] str'}, {cmd: 'utf8', fn: this.cmdUtf8, desc: 'Dump UTF-8 byte sequence', help: 'utf8 "str"'}, {cmd: 'v', fn: this.cmdV, desc: 'Displays version info', attr: DebugJS.CMD_ATTR_SYSTEM}, {cmd: 'vals', fn: this.cmdVals, desc: 'Displays variable list'}, {cmd: 'watchdog', fn: this.cmdWatchdog, desc: 'Start/Stop watchdog timer', help: 'watchdog [start|stop] [time(ms)]'}, {cmd: 'win', fn: this.cmdWin, desc: 'Set the debugger window size/pos', help: 'win min|normal|expand|full|center|restore|reset', attr: DebugJS.CMD_ATTR_DYNAMIC | DebugJS.CMD_ATTR_NO_KIOSK}, {cmd: 'zoom', fn: this.cmdZoom, desc: 'Zoom the debugger window', help: 'zoom ratio', attr: DebugJS.CMD_ATTR_DYNAMIC}, {cmd: 'wait', fn: this.cmdNop, attr: DebugJS.CMD_ATTR_HIDDEN}, {cmd: 'nop', fn: this.cmdNop, attr: DebugJS.CMD_ATTR_HIDDEN} ]; this.CMD_TBL = []; this.EXT_CMD_TBL = []; this.CMD_ALIAS = {b64: 'base64'}; this.CMDVALS = {}; this.opt = null; this.errStatus = DebugJS.ERR_ST_NONE; this.PROPS_RESTRICTION = { batcont: /^on$|^off$/, batstop: /^[^|][a-z|]+[^|]$/, esc: /^enable$|^disable$/, dumplimit: /^[0-9]+$/, dumpvallen: /^[0-9]+$/, prevlimit: /^[0-9]+$/, hexdumplimit: /^[0-9]+$/, hexdumplastrows: /^[0-9]+$/, indent: /^[0-9]+$/, radix: /^[^|][a-z|]+[^|]$/, pointspeed: /^[0-9]+$/, pointstep: /^[0-9]+$/, pointmsgsize: /.*/, scrollspeed: /^[0-9]+$/, scrollstep: /^[0-9]+$/, textspeed: /^[0-9\-]+$/, textstep: /^[0-9\-]+$/, testvallimit: /^[0-9\-]+$/, wait: /^[0-9]+$/, timer: /.*/, wdt: /^[0-9]+$/, mousemovesim: /^true$|^false$/, consolelog: /^native$|^me$/ }; this.PROPS_DFLT_VALS = { batcont: 'off', batstop: 'error', esc: 'enable', dumplimit: 1000, dumpvallen: 4096, prevlimit: 5 * 1024 * 1024, hexdumplimit: 1048576, hexdumplastrows: 16, indent: 1, radix: 'bin|dec|hex', pointspeed: DebugJS.point.move.speed, pointstep: DebugJS.point.move.step, pointmsgsize: '"12px"', scrollspeed: DebugJS.scrollWinTo.data.speed, scrollstep: DebugJS.scrollWinTo.data.step, textspeed: 30, textstep: 1, testvallimit: 4096, wait: 500, timer: '00:03:00.000', wdt: 500, mousemovesim: 'false', consolelog: 'native' }; this.PROPS_CB = { batcont: this.setPropBatContCb, indent: this.setPropIndentCb, pointmsgsize: this.setPropPointMsgSizeCb, timer: this.setPropTimerCb, consolelog: this.setPropConsoleLogCb }; this.props = {}; this.extBtn = null; this.extBtnLabel = 'EXT'; this.extPanel = null; this.extHeaderPanel = null; this.extBodyPanel = null; this.extActivePanel = null; this.extPanels = []; this.extActPnlIdx = -1; this.evtListener = { batstart: [], batstop: [], ctrlc: [], drop: [], error: [], fileloaded: [], unlock: [], watchdog: [] }; this.unlockCode = null; this.setupDefaultOptions(); DebugJS.copyProp(this.PROPS_DFLT_VALS, this.props); }; DebugJS.MAX_SAFE_INT = 0x1FFFFFFFFFFFFF; DebugJS.DFLT_UNIT = 32; DebugJS.INIT_CAUSE_ZOOM = 1; DebugJS.ST_INITIALIZED = 1; DebugJS.ST_MEASURE = 1 << 2; DebugJS.ST_MEASURING = 1 << 3; DebugJS.ST_SYS_INFO = 1 << 4; DebugJS.ST_ELM_INSPECTING = 1 << 5; DebugJS.ST_ELM_EDIT = 1 << 6; DebugJS.ST_TOOLS = 1 << 7; DebugJS.ST_JS = 1 << 8; DebugJS.ST_HTML_SRC = 1 << 9; DebugJS.ST_LOG_SUSPENDING = 1 << 10; DebugJS.ST_LOG_PRESERVED = 1 << 11; DebugJS.ST_STOPWATCH_RUNNING = 1 << 12; DebugJS.ST_STOPWATCH_LAPTIME = 1 << 13; DebugJS.ST_STOPWATCH_END = 1 << 14; DebugJS.ST_WD = 1 << 15; DebugJS.ST_EXT_PANEL = 1 << 16; DebugJS.ST_BAT_RUNNING = 1 << 17; DebugJS.ST_BAT_PAUSE = 1 << 18; DebugJS.ST_BAT_PAUSE_CMD = 1 << 19; DebugJS.ST_BAT_PAUSE_CMD_KEY = 1 << 20; DebugJS.ST_BAT_CONT = 1 << 21; DebugJS.ST_BAT_BREAK = 1 << 22; DebugJS.UI_ST_VISIBLE = 1; DebugJS.UI_ST_DYNAMIC = 1 << 1; DebugJS.UI_ST_SHOW_CLOCK = 1 << 2; DebugJS.UI_ST_DRAGGABLE = 1 << 3; DebugJS.UI_ST_DRAGGING = 1 << 4; DebugJS.UI_ST_RESIZABLE = 1 << 5; DebugJS.UI_ST_RESIZING = 1 << 6; DebugJS.UI_ST_RESIZING_N = 1 << 7; DebugJS.UI_ST_RESIZING_E = 1 << 8; DebugJS.UI_ST_RESIZING_S = 1 << 9; DebugJS.UI_ST_RESIZING_W = 1 << 10; DebugJS.UI_ST_RESIZING_ALL = DebugJS.UI_ST_RESIZING | DebugJS.UI_ST_RESIZING_N | DebugJS.UI_ST_RESIZING_E | DebugJS.UI_ST_RESIZING_S | DebugJS.UI_ST_RESIZING_W; DebugJS.UI_ST_POS_AUTO_ADJUST = 1 << 11; DebugJS.UI_ST_LOG_SCROLL = 1 << 12; DebugJS.UI_ST_PROTECTED = 1 << 13; DebugJS.TOOL_ST_SW_CU_RUNNING = 1; DebugJS.TOOL_ST_SW_CU_END = 1 << 1; DebugJS.TOOL_ST_SW_CD_RUNNING = 1 << 2; DebugJS.TOOL_ST_SW_CD_RST = 1 << 3; DebugJS.TOOL_ST_SW_CD_EXPIRED = 1 << 4; DebugJS.TOOL_ST_SW_CD_END = 1 << 5; DebugJS.TOOL_TIMER_MODE_CLOCK = 0; DebugJS.TOOL_TIMER_MODE_SW_CU = 1; DebugJS.TOOL_TIMER_MODE_SW_CD = 2; DebugJS.TOOL_TIMER_BTN_COLOR = '#eee'; DebugJS.LOG_FLTR_LOG = 0x1; DebugJS.LOG_FLTR_VRB = 0x2; DebugJS.LOG_FLTR_DBG = 0x4; DebugJS.LOG_FLTR_INF = 0x8; DebugJS.LOG_FLTR_WRN = 0x10; DebugJS.LOG_FLTR_ERR = 0x20; DebugJS.LOG_FLTR_ALL = DebugJS.LOG_FLTR_LOG | DebugJS.LOG_FLTR_DBG | DebugJS.LOG_FLTR_INF | DebugJS.LOG_FLTR_WRN | DebugJS.LOG_FLTR_ERR; DebugJS.LOG_TYPE_LOG = 0x1; DebugJS.LOG_TYPE_VRB = 0x2; DebugJS.LOG_TYPE_DBG = 0x4; DebugJS.LOG_TYPE_INF = 0x8; DebugJS.LOG_TYPE_WRN = 0x10; DebugJS.LOG_TYPE_ERR = 0x20; DebugJS.LOG_TYPE_SYS = 0x40; DebugJS.LOG_TYPE_MLT = 0x80; DebugJS.LOG_TYPE_RES = 0x100; DebugJS.LOG_TYPE_ERES = 0x200; DebugJS.ELMINFO_ST_SELECT = 0x1; DebugJS.ELMINFO_ST_HIGHLIGHT = 0x2; DebugJS.ERR_ST_NONE = 0; DebugJS.ERR_ST_SCRIPT = 0x1; DebugJS.ERR_ST_LOAD = 0x2; DebugJS.ERR_ST_LOG = 0x4; DebugJS.TOOLS_FNC_TIMER = 0x1; DebugJS.TOOLS_FNC_TEXT = 0x2; DebugJS.TOOLS_FNC_HTML = 0x4; DebugJS.TOOLS_FNC_FILE = 0x8; DebugJS.TOOLS_FNC_BAT = 0x10; DebugJS.TOOLS_DFLT_ACTIVE_FNC = DebugJS.TOOLS_FNC_TIMER; DebugJS.CMD_ATTR_SYSTEM = 0x1; DebugJS.CMD_ATTR_HIDDEN = 0x2; DebugJS.CMD_ATTR_DYNAMIC = 0x4; DebugJS.CMD_ATTR_NO_KIOSK = 0x8; DebugJS.CMD_ATTR_DISABLED = 0x10; DebugJS.CMD_ECHO_MAX_LEN = 256; DebugJS.DBGWIN_MIN_W = 292; DebugJS.DBGWIN_MIN_H = 155; DebugJS.DBGWIN_EXPAND_C_W = 960; DebugJS.DBGWIN_EXPAND_C_H = 640; DebugJS.DBGWIN_EXPAND_W = 850; DebugJS.DBGWIN_EXPAND_H = 580; DebugJS.SIZE_ST_MIN = -1; DebugJS.SIZE_ST_NORMAL = 0; DebugJS.SIZE_ST_EXPANDED = 1; DebugJS.SIZE_ST_EXPANDED_C = 2; DebugJS.SIZE_ST_FULL_W = 4; DebugJS.SIZE_ST_FULL_H = 5; DebugJS.SIZE_ST_FULL_WH = 6; DebugJS.DBGWIN_POS_NONE = -9999; DebugJS.WIN_SHADOW = 10; DebugJS.WIN_BORDER = 1; DebugJS.WIN_PADDING = 1; DebugJS.WIN_ADJUST = ((DebugJS.WIN_BORDER * 2) + (DebugJS.WIN_PADDING * 2)); DebugJS.OVERLAY_PANEL_HEIGHT = 77; DebugJS.CMD_LINE_PADDING = 3; DebugJS.COLOR_ACTIVE = '#fff'; DebugJS.SBPNL_COLOR_ACTIVE = '#6cf'; DebugJS.SBPNL_COLOR_INACT = '#ccc'; DebugJS.COLOR_INACT = '#999'; DebugJS.MEAS_BTN_COLOR = '#6cf'; DebugJS.SYS_BTN_COLOR = '#3cf'; DebugJS.HTML_BTN_COLOR = '#8f8'; DebugJS.DOM_BTN_COLOR = '#f63'; DebugJS.JS_BTN_COLOR = '#6df'; DebugJS.TOOLS_BTN_COLOR = '#ff0'; DebugJS.EXT_BTN_COLOR = '#f8f'; DebugJS.LOG_PRESERVE_BTN_COLOR = '#0f0'; DebugJS.LOG_SUSPEND_BTN_COLOR = '#f66'; DebugJS.PIN_BTN_COLOR = '#fa0'; DebugJS.FLT_BTN_COLOR = '#eee'; DebugJS.COLOR_R = '#f66'; DebugJS.COLOR_G = '#6f6'; DebugJS.COLOR_B = '#6bf'; DebugJS.KEY_ST_DFLT = '- <span style="color:' + DebugJS.COLOR_INACT + '">SCAM</span>'; DebugJS.WDAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT']; DebugJS.WDAYS_COLOR = ['f74', 'fff', 'fff', 'fff', 'fff', 'fff', '8fd']; DebugJS.UPDATE_INTERVAL_H = 21; DebugJS.UPDATE_INTERVAL_L = 500; DebugJS.DFLT_TIMER_NAME = 'timer0'; DebugJS.TIMER_NAME_SW_0 = 'sw0'; DebugJS.TIMER_NAME_SW_CU = 'sw1'; DebugJS.TIMER_NAME_SW_CD = 'sw2'; DebugJS.LED_BIT = [0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80]; DebugJS.LED_COLOR = ['#4cf', '#0ff', '#6f6', '#ee0', '#f80', '#f66', '#f0f', '#ddd']; DebugJS.LED_COLOR_INACT = '#777'; DebugJS.ITEM_NAME_COLOR = '#cff'; DebugJS.KEYWORD_COLOR = '#0ff'; DebugJS.RND_TYPE_NUM = '-d'; DebugJS.RND_TYPE_STR = '-s'; DebugJS.ELM_HL_CLASS_SUFFIX = '-elhl'; DebugJS.EXPANDBTN = '&gt;'; DebugJS.CLOSEBTN = 'v'; DebugJS.OMIT_LAST = 0; DebugJS.OMIT_MID = 1; DebugJS.OMIT_FIRST = 2; DebugJS.DISP_BIN_DIGITS_THR = 5; DebugJS.TIME_RST_STR = '00:00:00.000'; DebugJS.EXIT_SUCCESS = 0; DebugJS.EXIT_FAILURE = 1; DebugJS.EXIT_SIG = 128; DebugJS.EXIT_CLEARED = -1; DebugJS.SIGINT = 2; DebugJS.SIGTERM = 15; DebugJS.BAT_HEAD = '#!BAT!'; DebugJS.BAT_HEAD_B64 = 'IyFCQVQh'; DebugJS.BAT_TKN_JS = '!__JS__!'; DebugJS.BAT_TKN_TXT = '!__TEXT__!'; DebugJS.BAT_TKN_IF = 'IF'; DebugJS.BAT_TKN_ELIF = 'ELSE IF'; DebugJS.BAT_TKN_ELSE = 'ELSE'; DebugJS.BAT_TKN_LOOP = 'LOOP'; DebugJS.BAT_TKN_BREAK = 'BREAK'; DebugJS.BAT_TKN_CONTINUE = 'CONTINUE'; DebugJS.BAT_TKN_BLOCK_START = '('; DebugJS.BAT_TKN_BLOCK_END = ')'; DebugJS.BAT_TKN_LABEL = ':'; DebugJS.BAT_TKN_FNC = 'FUNCTION'; DebugJS.BAT_TKN_RET = 'return'; DebugJS.RE_ELIF = new RegExp('^\\' + DebugJS.BAT_TKN_BLOCK_END + '\\s?' + DebugJS.BAT_TKN_ELIF + '\\s?\\' + DebugJS.BAT_TKN_BLOCK_START + '?.+'); DebugJS.RE_ELSE = DebugJS.BAT_TKN_BLOCK_END + DebugJS.BAT_TKN_ELSE + DebugJS.BAT_TKN_BLOCK_START; DebugJS.CHR_LED = '&#x25CF;'; DebugJS.CHR_DELTA = '&#x22BF;'; DebugJS.CHR_CRLF = '&#x21b5;'; DebugJS.CHR_LF = '&#x2193;'; DebugJS.CHR_CR = '&#x2190;'; DebugJS.CHR_CRLF_S = '<span style="color:#0cf" class="dbg-cc">' + DebugJS.CHR_CRLF + '</span>'; DebugJS.CHR_LF_S = '<span style="color:#0f0" class="dbg-cc">' + DebugJS.CHR_LF + '</span>'; DebugJS.CHR_CR_S = '<span style="color:#f00" class="dbg-cc">' + DebugJS.CHR_CR + '</span>'; DebugJS.EOF = '<span style="color:#08f" class="dbg-cc">[EOF]</span>'; DebugJS.CHR_WIN_FULL = '&#x25A1;'; DebugJS.CHR_WIN_RST = '&#x2750;'; DebugJS.LOG_HEAD = '[LOG]'; DebugJS.LOG_BOUNDARY_BUF = '-- ORIGINAL LOG BUFFER --'; DebugJS.SYS_INFO_FULL_OVERLAY = true; DebugJS.HTML_SRC_FULL_OVERLAY = true; DebugJS.HTML_SRC_EXPAND_H = false; DebugJS.ELM_INFO_FULL_OVERLAY = false; DebugJS.LS_AVAILABLE = false; DebugJS.SS_AVAILABLE = false; DebugJS.G_EL_AVAILABLE = false; DebugJS.JS_SNIPPET = [ 'dbg.time.s();\nfor (var i = 0; i < 1000000; i++) {\n\n}\ndbg.time.e();\n\'done\';', '', '', ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~', '// Logging performance check\nvar n = 1000;\nvar i = 0;\ndbg.time.s(\'total\');\ntest();\nfunction test() {\n dbg.time.s();\n dbg.time.e();\n i++;\n if (i == n) {\n dbg.msg.clear();\n dbg.time.e(\'total\');\n } else {\n if (i % 100 == 0) {\n dbg.msg(\'i = \' + i + \' / \' + dbg.time.check(\'total\'));\n }\n setTimeout(test, 0);\n }\n}' ]; DebugJS.HTML_SNIPPET = [ '<div style="width:100%; height:100%; background:#fff; color:#000;">\n\n</div>\n', '<img src="data:image/jpeg;base64,">', '<button onclick=""></button>', '<video src="" controls autoplay>', '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="utf-8">\n<meta http-equiv="X-UA-Compatible" content="IE=Edge">\n<title></title>\n<link rel="stylesheet" href="style.css" />\n<script src="script.js"></script>\n<style>\n</style>\n<script>\n</script>\n</head>\n<body>\nhello\n</body>\n</html>\n' ]; DebugJS.FEATURES = [ 'togglableShowHide', 'useClock', 'useClearButton', 'useSuspendLogButton', 'usePinButton', 'useWinCtrlButton', 'useStopwatch', 'useWindowSizeInfo', 'useMouseStatusInfo', 'useKeyStatusInfo', 'useLed', 'useMsgDisplay', 'useScreenMeasure', 'useSystemInfo', 'useElementInfo', 'useHtmlSrc', 'useTools', 'useJsEditor', 'useLogFilter', 'useCommandLine' ]; DebugJS.f_ = function() {}; DebugJS.prototype = { init: function(opt, rstrOpt) { if (!DebugJS.ENABLE) return false; var ctx = DebugJS.ctx; var keepStatus = ((rstrOpt && (rstrOpt.cause == DebugJS.INIT_CAUSE_ZOOM)) ? true : false); ctx.bodyEl = document.body; ctx.finalizeFeatures(ctx); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (ctx.win) { for (var i = ctx.win.childNodes.length - 1; i >= 0; i--) { ctx.win.removeChild(ctx.win.childNodes[i]); } ctx.bodyEl.removeChild(ctx.win); ctx.timerBasePanel = null; ctx.win = null; } } if (!keepStatus) { var preserveStatus = DebugJS.ST_LOG_PRESERVED | DebugJS.ST_STOPWATCH_RUNNING | DebugJS.ST_WD | DebugJS.ST_BAT_RUNNING | DebugJS.ST_BAT_PAUSE | DebugJS.ST_BAT_PAUSE_CMD | DebugJS.ST_BAT_PAUSE_CMD_KEY; ctx.status &= preserveStatus; ctx.uiStatus = 0; ctx.startLogScrolling(); } if ((ctx.opt == null) || ((opt != null) && (!keepStatus)) || (opt === undefined)) { ctx.setupDefaultOptions(); } if (opt) { for (var key1 in opt) { for (var key2 in ctx.opt) { if (key1 == key2) { ctx.opt[key1] = opt[key1]; if ((key1 == 'disableAllFeatures') && (opt[key1])) { ctx.disableAllFeatures(ctx); } break; } } } } if (ctx.logBuf.size() != ctx.opt.bufsize) { if (!(ctx.status & DebugJS.ST_LOG_PRESERVED) || ((ctx.status & DebugJS.ST_LOG_PRESERVED) && (ctx.logBuf.size() < ctx.opt.bufsize))) { ctx.initBuf(ctx, ctx.opt.bufsize); } } if (ctx.opt.mode == 'noui') { ctx.rmvEventHandlers(ctx); ctx.init = DebugJS.f_; DebugJS.init = DebugJS.f_; ctx.status |= DebugJS.ST_INITIALIZED; return false; } if (!ctx.bodyEl) return false; ctx.initUi(ctx, rstrOpt); ctx.initCommandTable(ctx); ctx.status |= DebugJS.ST_INITIALIZED; ctx.initExtension(ctx); ctx.printLogs(); ctx.showDbgWinOnError(ctx); return true; }, initUi: function(ctx, rstrOpt) { ctx.initUiStatus(ctx, ctx.opt, rstrOpt); ctx.computedMinW = DebugJS.DBGWIN_MIN_W * ctx.opt.zoom; ctx.computedMinH = DebugJS.DBGWIN_MIN_H * ctx.opt.zoom; ctx.computedFontSize = Math.round(ctx.opt.fontSize * ctx.opt.zoom); ctx.computedWidth = Math.round(ctx.opt.width * ctx.opt.zoom); if (ctx.opt.target == null) { ctx.id = ctx.DFLT_ELM_ID; ctx.win = document.createElement('div'); ctx.win.id = ctx.id; ctx.win.style.position = 'fixed'; ctx.win.style.zIndex = 0x7fffffff; ctx.win.style.width = ctx.computedWidth + 'px'; ctx.win.style.boxShadow = DebugJS.WIN_SHADOW + 'px ' + DebugJS.WIN_SHADOW + 'px 10px rgba(0,0,0,.3)'; ctx.bodyEl.appendChild(ctx.win); if (ctx.opt.mode == 'kiosk') { ctx.setupKioskMode(ctx); } } else { ctx.id = ctx.opt.target; ctx.win = document.getElementById(ctx.id); ctx.win.style.position = 'relative'; } ctx.win.style.display = 'block'; ctx.win.style.padding = DebugJS.WIN_BORDER + 'px'; ctx.win.style.lineHeight = '1em'; ctx.win.style.boxSizing = 'content-box'; ctx.win.style.border = ctx.opt.border; ctx.win.style.borderRadius = ctx.opt.borderRadius; ctx.win.style.background = ctx.opt.background; ctx.win.style.color = ctx.opt.fontColor; ctx.win.style.fontSize = ctx.computedFontSize + 'px', ctx.win.style.opacity = ctx.opt.opacity; ctx.createPanels(ctx); if (ctx.uiStatus & DebugJS.UI_ST_RESIZABLE) { ctx.initResize(ctx); } ctx.initStyles(ctx); ctx.initDbgWin(ctx); ctx.setupEventHandler(ctx); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (ctx.opt.mode == 'kiosk') { ctx.focusCmdLine(); } else { ctx.setupMove(ctx); ctx.initWidth = ctx.win.offsetWidth; ctx.initHeight = ctx.win.offsetHeight; ctx.resetDbgWinSizePos(); if ((rstrOpt != null) && (rstrOpt.cause == DebugJS.INIT_CAUSE_ZOOM)) { ctx.focusCmdLine(); } if (!(ctx.uiStatus & DebugJS.UI_ST_VISIBLE) || (ctx.uiStatus & DebugJS.UI_ST_PROTECTED)) { ctx.win.style.display = 'none'; } } } else { ctx.initWidth = ctx.win.offsetWidth - DebugJS.WIN_ADJUST; ctx.initHeight = ctx.win.offsetHeight - DebugJS.WIN_ADJUST; } ctx.winExpandHeight = DebugJS.DBGWIN_EXPAND_C_H * ctx.opt.zoom; if ((rstrOpt != null) && (rstrOpt.cause == DebugJS.INIT_CAUSE_ZOOM)) { ctx.resetStylesOnZoom(ctx); ctx.reopenFeatures(ctx); ctx.restoreDbgWinSize(ctx, rstrOpt.sizeStatus); } }, initStyles: function(ctx) { var opt = ctx.opt; var fontSize = ctx.computedFontSize + 'px'; var ltsp = '0'; if (DebugJS.getBrowserType().name == 'Firefox') { ltsp = '-0.35px'; } var styles = {}; styles['#' + ctx.id] = { 'text-align': 'left !important', 'letter-spacing': ltsp + ' !important' }; styles['#' + ctx.id + ' *'] = { 'box-sizing': 'content-box !important', 'color': opt.fontColor, 'font-size': fontSize + ' !important', 'font-family': opt.fontFamily + ' !important' }; styles['#' + ctx.id + ' td'] = { 'width': 'auto !important', 'padding': '0 3px !important', 'border': 'none !important', 'background': 'none !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important' }; styles['#' + ctx.id + ' pre'] = { 'width': 'auto !important', 'height': 'auto !important', 'margin': '0 !important', 'padding': '0 !important', 'line-height': '1em !important', 'border': 'none !important', 'border-radius': '0 !important', 'background': 'none !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important', 'white-space': 'pre-wrap !important', 'word-break': 'break-all !important', 'overflow': 'visible !important' }; styles['.dbg-btn'] = { 'color': opt.btnColor + ' !important' }; styles['.dbg-btn:hover'] = { 'text-shadow': '0 0 3px', 'cursor': 'pointer' }; styles['.dbg-btn-disabled'] = { 'opacity': 0.5 }; styles['.dbg-btn-disabled:hover'] = { 'text-shadow': 'none', 'cursor': 'auto' }; styles['.dbg-btn-red'] = { 'color': '#a88 !important' }; styles['.dbg-btn-wh'] = { 'color': '#fff !important' }; styles['.dbg-sys-info'] = { 'display': 'inline-block', 'margin-right': '10px', 'color': opt.sysInfoColor + ' !important' }; styles['.dbg-resize-corner'] = { 'position': 'absolute', 'width': '6px', 'height': '6px', 'background': 'rgba(0,0,0,0)' }; styles['.dbg-resize-side'] = { 'position': 'absolute', 'background': 'rgba(0,0,0,0)' }; styles['.dbg-overlay-base-panel'] = { 'position': 'relative', 'top': '0', 'left': '0', 'width': 'calc(100% - 2px)', 'height': DebugJS.OVERLAY_PANEL_HEIGHT + '%' }; var overlayPanelBorder = 1; var overlayPanelPadding = 2; styles['.dbg-overlay-panel'] = { 'position': 'absolute', 'top': '0', 'left': '0', 'width': 'calc(100% - ' + ((overlayPanelPadding) * 2) + 'px)', 'height': 'calc(100% - ' + ((overlayPanelPadding) * 2) + 'px)', 'padding': overlayPanelPadding + 'px', 'border': 'solid ' + overlayPanelBorder + 'px #333', 'background': 'rgba(0,0,0,0.5)', 'overflow': 'auto' }; styles['.dbg-overlay-panel pre'] = { 'padding': '0 1px !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important' }; styles['.dbg-overlay-panel-full'] = { 'position': 'absolute', 'top': (ctx.computedFontSize + DebugJS.WIN_ADJUST) + 'px', 'left': '1px', 'width': 'calc(100% - ' + (DebugJS.WIN_SHADOW + DebugJS.WIN_ADJUST - ((overlayPanelPadding * 2) + (overlayPanelBorder * 2))) + 'px)', 'height': 'calc(100% - ' + ((ctx.computedFontSize + DebugJS.WIN_ADJUST) + DebugJS.WIN_SHADOW + ctx.computedFontSize + 10 - (overlayPanelPadding * 2)) + 'px)', 'padding': overlayPanelPadding + 'px', 'border': 'solid ' + overlayPanelBorder + 'px #333', 'background': 'rgba(0,0,0,0.5)', 'overflow': 'auto' }; styles['.dbg-sbpnl'] = { 'position': 'absolute', 'top': 0, 'left': 0, 'width': '100%', 'height': '100%' }; styles['.dbg-sep'] = { 'height': (ctx.computedFontSize * 0.5) + 'px' }; styles['.dbg-na'] = { 'color': '#ccc !important' }; styles['.dbg-showhide-btn'] = { 'color': '#0a0 !important', 'font-size': fontSize + ' !important', 'font-weight': 'bold' }; styles['.dbg-showhide-btn:hover'] = { 'cursor': 'pointer' }; styles['.dbg-cmdtd'] = { 'vertical-align': 'top !important', 'white-space': 'nowrap !important' }; styles['.dbg-txt-range'] = { 'display': 'inline-block !important', 'width': (256 * opt.zoom) + 'px !important', 'height': (15 * opt.zoom) + 'px !important', 'padding': '0 !important', 'border': 'none !important', 'outline': 'none !important', 'box-shadow': 'none !important' }; styles['.dbg-txt-tbl td'] = { 'font-size': fontSize + ' !important', 'line-height': '1em !important' }; styles['.dbg-loading'] = { 'opacity': '1.0 !important' }; styles['#' + ctx.id + ' label'] = { 'display': 'inline !important', 'margin': '0 !important', 'line-height': '1em !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important', 'font-weight': 'normal !important' }; styles['#' + ctx.id + ' input[type="radio"]'] = { 'margin': '0 3px !important', 'width': 13 * opt.zoom + 'px !important', 'height': 13 * opt.zoom + 'px !important' }; styles['.dbg-editor'] = { 'width': 'calc(100% - 6px) !important', 'height': 'calc(100% - ' + (ctx.computedFontSize + 10) + 'px) !important', 'margin': '2px 0 0 0 !important', 'padding': '2px !important', 'border': 'solid 1px #1883d7 !important', 'border-radius': '0 !important', 'outline': 'none !important', 'background': 'transparent !important', 'color': '#fff !important', 'font-size': fontSize + ' !important', 'overflow': 'auto !important', 'resize': 'none !important' }; styles['.dbg-strg'] = { 'display': 'inline-block !important', 'width': 'calc(100% - 1em) !important', 'height': '8em !important', 'margin': '2px 0 0 .5em !important' }; styles['.dbg-strgkey'] = { 'width': 'calc(100% - 10em) !important', 'margin': '0 !important' }; styles['.dbg-txt-hl'] = { 'background': 'rgba(192,192,192,0.5) !important' }; styles['.' + ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX] = { 'outline': 'solid 1px #f00 !important', 'opacity': '0.7 !important' }; styles['.dbg-timer-inp'] = { 'width': '1.1em !important', 'height': '1em !important', 'border': 'none !important', 'outline': 'none !important', 'margin': '0 !important', 'padding': '0 !important', 'text-align': 'center !important', 'vartical-align': 'middle !important', 'background': 'transparent !important', 'color': '#fff !important' }; styles['.dbg-hint'] = { 'position': 'fixed !important', 'display': 'inline-block !important', 'max-width': 'calc(100vw - 35px) !important', 'max-height': 'calc(100vh - 35px) !important', 'overflow': 'auto !important', 'padding': '4px 8px !important', 'box-sizing': 'content-box !important', 'z-index': 0x7ffffffe + ' !important', 'box-shadow': '8px 8px 10px rgba(0,0,0,.3) !important', 'border-radius': '3px !important', 'background': 'rgba(0,0,0,0.65) !important' }; styles['.dbg-txtbox'] = { 'border': 'none !important', 'border-bottom': 'solid 1px #888 !important', 'border-radius': '0 !important', 'outline': 'none !important', 'box-shadow': 'none !important', 'background': 'transparent !important', 'color': opt.fontColor + ' !important', 'font-size': fontSize + ' !important' }; styles['.dbg-resbox.box'] = { 'display': 'inline-block !important', 'min-width': 'calc(100% - 18px) !important', 'height': '1.5em !important', 'margin-top': '4px !important' }; styles['.dbg-resbox'] = { 'padding': '5px !important', 'color': '#fff !important', 'font-size': fontSize + ' !important', 'font-family': 'Consolas !important', 'overflow': 'auto !important', 'cursor': 'text !important', 'resize': 'none !important' }; styles['.dbg-resbox.ok'] = { 'border': '1px solid #2c6cb8 !important', 'background': 'linear-gradient(rgba(8,8,16,0.6),rgba(0,0,68,0.6)) !important' }; styles['.dbg-resbox.err'] = { 'border': '1px solid #c00 !important', 'background': 'linear-gradient(rgba(16,8,8,0.6),rgba(68,0,0,0.6)) !important' }; ctx.applyStyles(ctx, styles); }, initBuf: function(ctx, newSize) { var buf = DebugJS.ctx.logBuf.getAll(); var oldSize = buf.length; if (oldSize == newSize) return; var i = ((oldSize > newSize) ? (oldSize - newSize) : 0); ctx.logBuf = new DebugJS.RingBuffer(newSize); for (; i < oldSize; i++) { ctx.logBuf.add(buf[i]); } }, createResizeSideArea: function(cursor, state, width, height) { var ctx = DebugJS.ctx; var el = document.createElement('div'); el.className = 'dbg-resize-side'; el.style.width = width; el.style.height = height; el.style.cursor = cursor; el.onmousedown = function(e) { if (!(ctx.uiStatus & DebugJS.UI_ST_RESIZABLE)) return; ctx.startResize(ctx, e); ctx.uiStatus |= state; ctx.bodyCursor = ctx.bodyEl.style.cursor; ctx.bodyEl.style.cursor = cursor; }; return el; }, createResizeCornerArea: function(cursor, state) { var ctx = DebugJS.ctx; var el = document.createElement('div'); el.className = 'dbg-resize-corner'; el.style.cursor = cursor; el.onmousedown = function(e) { if (!(ctx.uiStatus & DebugJS.UI_ST_RESIZABLE)) return; ctx.startResize(ctx, e); ctx.uiStatus |= state; ctx.bodyCursor = ctx.bodyEl.style.cursor; ctx.bodyEl.style.cursor = cursor; }; return el; }, setupDefaultOptions: function() { this.opt = {}; DebugJS.copyProp(this.DEFAULT_OPTIONS, this.opt); }, setupEventHandler: function(ctx) { if (!ctx.isAllFeaturesDisabled(ctx)) { window.addEventListener('keydown', ctx.keyHandler, true); } if ((ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) || (ctx.uiStatus & DebugJS.UI_ST_RESIZABLE) || (ctx.opt.useMouseStatusInfo) || (ctx.opt.useScreenMeasure)) { window.addEventListener('mousedown', ctx.onMouseDown, true); window.addEventListener('mousemove', ctx.onMouseMove, true); window.addEventListener('mouseup', ctx.onMouseUp, true); window.addEventListener('touchstart', ctx.onTouchStart, true); window.addEventListener('touchmove', ctx.onTouchMove, true); window.addEventListener('touchend', ctx.onTouchEnd, true); } if (ctx.opt.useWindowSizeInfo) { window.addEventListener('resize', ctx.onResize, true); ctx.onResize(); window.addEventListener('scroll', ctx.onScroll, true); ctx.onScroll(); } window.addEventListener('keydown', ctx.onKeyDown, true); window.addEventListener('keypress', ctx.onKeyPress, true); window.addEventListener('keyup', ctx.onKeyUp, true); if (ctx.opt.useKeyStatusInfo) { ctx.updateKeyDownLabel(); ctx.updateKeyPressLabel(); ctx.updateKeyUpLabel(); } }, rmvEventHandlers: function(ctx) { window.removeEventListener('keydown', ctx.keyHandler, true); window.removeEventListener('mousedown', ctx.onMouseDown, true); window.removeEventListener('mousemove', ctx.onMouseMove, true); window.removeEventListener('mouseup', ctx.onMouseUp, true); window.removeEventListener('resize', ctx.onResize, true); window.removeEventListener('scroll', ctx.onScroll, true); window.removeEventListener('keydown', ctx.onKeyDown, true); window.removeEventListener('keypress', ctx.onKeyPress, true); window.removeEventListener('keyup', ctx.onKeyUp, true); window.removeEventListener('touchstart', ctx.onTouchStart, true); window.removeEventListener('touchmove', ctx.onTouchMove, true); window.removeEventListener('touchend', ctx.onTouchEnd, true); }, initUiStatus: function(ctx, opt, rstrOpt) { if (ctx.opt.target == null) { ctx.uiStatus |= DebugJS.UI_ST_DYNAMIC; ctx.uiStatus |= DebugJS.UI_ST_DRAGGABLE; if ((ctx.opt.lockCode != null) && (!rstrOpt)) { ctx.uiStatus |= DebugJS.UI_ST_PROTECTED; } } if ((ctx.opt.visible) || (ctx.opt.target != null)) { ctx.uiStatus |= DebugJS.UI_ST_VISIBLE; } else if (ctx.errStatus) { if (((ctx.opt.popupOnError.scriptError) && (ctx.errStatus & DebugJS.ERR_ST_SCRIPT)) || ((ctx.opt.popupOnError.loadError) && (ctx.errStatus & DebugJS.ERR_ST_LOAD)) || ((ctx.opt.popupOnError.errorLog) && (ctx.errStatus & DebugJS.ERR_ST_LOG))) { ctx.uiStatus |= DebugJS.UI_ST_VISIBLE; ctx.errStatus = DebugJS.ERR_ST_NONE; } } if (ctx.opt.resizable) ctx.uiStatus |= DebugJS.UI_ST_RESIZABLE; if (ctx.opt.useClock) ctx.uiStatus |= DebugJS.UI_ST_SHOW_CLOCK; }, setupKioskMode: function(ctx) { ctx.sizeStatus = DebugJS.SIZE_ST_FULL_WH; ctx.win.style.top = 0; ctx.win.style.left = 0; ctx.win.style.width = document.documentElement.clientWidth + 'px'; ctx.win.style.height = document.documentElement.clientHeight + 'px'; ctx.opt.togglableShowHide = false; ctx.opt.usePinButton = false; ctx.opt.useWinCtrlButton = false; ctx.opt.useScreenMeasure = false; ctx.opt.useHtmlSrc = false; ctx.opt.useElementInfo = false; ctx.uiStatus |= DebugJS.UI_ST_VISIBLE; ctx.uiStatus &= ~DebugJS.UI_ST_RESIZABLE; }, disableAllFeatures: function(ctx) { for (var i = 0; i < DebugJS.FEATURES.length; i++) { ctx.opt[DebugJS.FEATURES[i]] = false; } }, isAllFeaturesDisabled: function(ctx) { for (var i = 0; i < DebugJS.FEATURES.length; i++) { if (ctx.opt[DebugJS.FEATURES[i]]) return false; } return true; }, createPanels: function(ctx) { var opt = ctx.opt; var fontSize = ctx.computedFontSize + 'px'; ctx.winBody = document.createElement('div'); ctx.win.appendChild(ctx.winBody); if (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) { ctx.winBody.style.cursor = 'default'; } if (!ctx.isAllFeaturesDisabled(ctx)) { ctx.headPanel = document.createElement('div'); ctx.headPanel.style.padding = '2px'; ctx.winBody.appendChild(ctx.headPanel); ctx.infoPanel = document.createElement('div'); ctx.infoPanel.style.padding = '0 2px 1px 2px'; ctx.winBody.appendChild(ctx.infoPanel); } ctx.mainPanel = document.createElement('div'); if (opt.useLogFilter) { ctx.mainPanel.style.height = (opt.lines + 1) + '.1em'; } else { ctx.mainPanel.style.height = opt.lines + '.1em'; } ctx.mainPanel.style.clear = 'both'; ctx.winBody.appendChild(ctx.mainPanel); if (opt.useLogFilter) { ctx.logHeaderPanel = document.createElement('div'); ctx.logHeaderPanel.style.position = 'relative'; ctx.logHeaderPanel.style.height = fontSize; ctx.logHeaderPanel.style.marginBottom = '2px'; ctx.mainPanel.appendChild(ctx.logHeaderPanel); } if (opt.useClearButton) { ctx.clearBtn = DebugJS.ui.addBtn(ctx.headPanel, '[CLR]', ctx.onClr); } if (opt.useLogFilter) ctx.createLogFilter(ctx); if (opt.useLogFilter) { ctx.logPanelHeightAdjust = ' - 1em'; } else { ctx.logPanelHeightAdjust = ''; } ctx.logPanel = document.createElement('div'); ctx.logPanel.style.width = '100%'; ctx.logPanel.style.height = 'calc(100%' + ctx.logPanelHeightAdjust + ')'; ctx.logPanel.style.padding = '0'; ctx.logPanel.style.overflow = 'auto'; ctx.logPanel.addEventListener('scroll', ctx.onLogScroll, true); ctx.enableDnDFileLoad(ctx.logPanel, ctx.onDropOnLogPanel); ctx.mainPanel.appendChild(ctx.logPanel); if (ctx.isAllFeaturesDisabled(ctx)) return; if (opt.useClock) { ctx.clockLabel = document.createElement('span'); ctx.clockLabel.style.marginLeft = '2px'; ctx.setStyle(ctx.clockLabel, 'color', opt.clockColor); ctx.setStyle(ctx.clockLabel, 'font-size', fontSize); ctx.headPanel.appendChild(ctx.clockLabel); ctx.setIntervalL(ctx); } if (opt.togglableShowHide) { ctx.closeBtn = DebugJS.ui.addBtn(ctx.headPanel, 'x', DebugJS.hide); ctx.closeBtn.style.float = 'right'; ctx.closeBtn.style.position = 'relative'; ctx.closeBtn.style.top = '-1px'; ctx.closeBtn.style.marginRight = '2px'; ctx.setStyle(ctx.closeBtn, 'color', '#888'); ctx.setStyle(ctx.closeBtn, 'font-size', (18 * opt.zoom) + 'px'); ctx.closeBtn.onmouseover = new Function('DebugJS.ctx.setStyle(this, \'color\', \'#d88\');'); ctx.closeBtn.onmouseout = new Function('DebugJS.ctx.setStyle(this, \'color\', \'#888\');'); } if ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.uiStatus & DebugJS.UI_ST_RESIZABLE) && (opt.useWinCtrlButton)) { ctx.winCtrlBtnPanel = document.createElement('span'); ctx.headPanel.appendChild(ctx.winCtrlBtnPanel); } if ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (opt.usePinButton)) { ctx.pinBtn = ctx.createHeaderBtn('pinBtn', 'P', 3, fontSize, ctx.toggleDraggable, 'uiStatus', 'UI_ST_DRAGGABLE', 'PIN_BTN_COLOR', true, 'Fix the window in its position'); } if (opt.useSuspendLogButton) { ctx.suspendLogBtn = ctx.createHeaderBtn('suspendLogBtn', '/', 3, fontSize, ctx.toggleLogSuspend, 'status', 'ST_LOG_SUSPENDING', 'LOG_SUSPEND_BTN_COLOR', false, 'Suspend log'); } if (DebugJS.LS_AVAILABLE) { ctx.preserveLogBtn = ctx.createHeaderBtn('preserveLogBtn', '*', 5, fontSize, ctx.toggleLogPreserve, 'status', 'ST_LOG_PRESERVED', 'LOG_PRESERVE_BTN_COLOR', false, 'Preserve log'); } if (opt.useStopwatch) { ctx.swLabel = document.createElement('span'); ctx.swLabel.style.float = 'right'; ctx.swLabel.style.marginLeft = '3px'; ctx.setStyle(ctx.swLabel, 'color', opt.fontColor); ctx.headPanel.appendChild(ctx.swLabel); ctx.swBtnPanel = document.createElement('span'); ctx.swBtnPanel.style.float = 'right'; ctx.swBtnPanel.style.marginLeft = '4px'; ctx.headPanel.appendChild(ctx.swBtnPanel); } ctx.extBtn = ctx.createHeaderBtn('extBtn', ctx.extBtnLabel, 2, null, ctx.toggleExtPanel, 'status', 'ST_EXT_PANEL', 'EXT_BTN_COLOR', false); ctx.extBtn.style.display = 'none'; if (opt.useTools) { ctx.toolsBtn = ctx.createHeaderBtn('toolsBtn', 'TOOL', 2, null, ctx.toggleTools, 'status', 'ST_TOOLS', 'TOOLS_BTN_COLOR', false); } if (opt.useJsEditor) { ctx.jsBtn = ctx.createHeaderBtn('jsBtn', 'JS', 2, null, ctx.toggleJs, 'status', 'ST_JS', 'JS_BTN_COLOR', false); } if (opt.useElementInfo) { ctx.elmInfoBtn = ctx.createHeaderBtn('elmInfoBtn', 'DOM', 3, null, ctx.toggleElmInfo, 'status', 'ST_ELM_INSPECTING', 'DOM_BTN_COLOR', false); } if (opt.useHtmlSrc) { ctx.htmlSrcBtn = ctx.createHeaderBtn('htmlSrcBtn', 'HTM', 3, null, ctx.toggleHtmlSrc, 'status', 'ST_HTML_SRC', 'HTML_BTN_COLOR', false); } if (opt.useSystemInfo) { ctx.sysInfoBtn = ctx.createHeaderBtn('sysInfoBtn', 'SYS', 3, null, ctx.toggleSystemInfo, 'status', 'ST_SYS_INFO', 'SYS_BTN_COLOR', false); } if (opt.useScreenMeasure) { var measBtn = document.createElement('span'); measBtn.className = 'dbg-btn dbg-nomove'; measBtn.style.display = 'inline-block'; measBtn.style.float = 'right'; measBtn.style.marginTop = ((opt.zoom <= 1) ? 1 : (2 * opt.zoom)) + 'px'; measBtn.style.marginLeft = '3px'; measBtn.style.width = (10 * opt.zoom) + 'px'; measBtn.style.height = (7 * opt.zoom) + 'px'; measBtn.innerText = ' '; measBtn.onclick = ctx.toggleMeasure; measBtn.onmouseover = new Function('DebugJS.ctx.measBtn.style.borderColor=\'' + DebugJS.MEAS_BTN_COLOR + '\';'); measBtn.onmouseout = new Function('DebugJS.ctx.measBtn.style.borderColor=(DebugJS.ctx.status & DebugJS.ST_MEASURE) ? DebugJS.MEAS_BTN_COLOR : DebugJS.COLOR_INACT;'); ctx.headPanel.appendChild(measBtn); ctx.measBtn = measBtn; } if (opt.useLed) { ctx.ledPanel = document.createElement('span'); ctx.ledPanel.className = 'dbg-sys-info'; ctx.ledPanel.style.float = 'right'; ctx.ledPanel.style.marginRight = '4px'; ctx.infoPanel.appendChild(ctx.ledPanel); } if (opt.useWindowSizeInfo) { ctx.winSizeLabel = ctx.createSysInfoLabel(); ctx.clientSizeLabel = ctx.createSysInfoLabel(); ctx.bodySizeLabel = ctx.createSysInfoLabel(); ctx.pixelRatioLabel = ctx.createSysInfoLabel(); ctx.scrollPosLabel = ctx.createSysInfoLabel(); } if (opt.useMouseStatusInfo) { ctx.mousePosLabel = ctx.createSysInfoLabel(); ctx.mouseClickLabel = ctx.createSysInfoLabel(); } if ((opt.useWindowSizeInfo) || (opt.useMouseStatusInfo)) { ctx.infoPanel.appendChild(document.createElement('br')); } if (opt.useKeyStatusInfo) { ctx.keyDownLabel = ctx.createSysInfoLabel(); ctx.keyPressLabel = ctx.createSysInfoLabel(); ctx.keyUpLabel = ctx.createSysInfoLabel(); } if (opt.useMsgDisplay) { var msgLabel = ctx.createSysInfoLabel(); msgLabel.style.float = opt.msgDisplayPos; msgLabel.style.position = 'absolute'; msgLabel.style.marginRight = '0'; msgLabel.style.right = '5px'; msgLabel.style.border = '0'; msgLabel.style.padding = '0 1px'; msgLabel.style.background = opt.msgDisplayBackground; ctx.setStyle(msgLabel, 'color', opt.fontColor); msgLabel.style.whiteSpace = 'pre-wrap'; msgLabel.style.wordBreak = 'break-all'; msgLabel.style.overflow = 'hidden'; msgLabel.style.textOverflow = 'ellipsis'; ctx.msgLabel = msgLabel; } if (opt.useCommandLine) { ctx.cmdPanel = document.createElement('div'); ctx.cmdPanel.style.padding = DebugJS.CMD_LINE_PADDING + 'px'; ctx.winBody.appendChild(ctx.cmdPanel); ctx.cmdPanel.innerHTML = '<span style="color:' + opt.promptColor + ' !important">$</span>'; var cmdLine = document.createElement('input'); ctx.setStyle(cmdLine, 'min-height', fontSize); ctx.setStyle(cmdLine, 'width', 'calc(100% - ' + fontSize + ')'); ctx.setStyle(cmdLine, 'margin', '0 0 0 2px'); ctx.setStyle(cmdLine, 'border', '0'); ctx.setStyle(cmdLine, 'border-bottom', 'solid 1px #888'); ctx.setStyle(cmdLine, 'border-radius', '0'); ctx.setStyle(cmdLine, 'outline', 'none'); ctx.setStyle(cmdLine, 'box-shadow', 'none'); ctx.setStyle(cmdLine, 'padding', '1px'); ctx.setStyle(cmdLine, 'background', 'transparent'); ctx.setStyle(cmdLine, 'color', opt.fontColor); ctx.setStyle(cmdLine, 'font-size', fontSize); ctx.cmdPanel.appendChild(cmdLine); ctx.cmdLine = cmdLine; ctx.initHistory(ctx); } }, initResize: function(ctx) { if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { var resizeN = ctx.createResizeSideArea('ns-resize', DebugJS.UI_ST_RESIZING_N, '100%', '6px'); resizeN.style.top = '-3px'; resizeN.style.left = '0'; ctx.win.appendChild(resizeN); } var resizeE = ctx.createResizeSideArea('ew-resize', DebugJS.UI_ST_RESIZING_E, '6px', '100%'); resizeE.style.top = '0'; resizeE.style.right = '-3px'; ctx.win.appendChild(resizeE); var resizeS = ctx.createResizeSideArea('ns-resize', DebugJS.UI_ST_RESIZING_S, '100%', '6px'); resizeS.style.bottom = '-3px'; resizeS.style.left = '0'; ctx.win.appendChild(resizeS); var resizeSE = ctx.createResizeCornerArea('nwse-resize', DebugJS.UI_ST_RESIZING_S | DebugJS.UI_ST_RESIZING_E); resizeSE.style.bottom = '-3px'; resizeSE.style.right = '-3px'; ctx.win.appendChild(resizeSE); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { var resizeW = ctx.createResizeSideArea('ew-resize', DebugJS.UI_ST_RESIZING_W, '6px', '100%'); resizeW.style.top = '0'; resizeW.style.left = '-3px'; ctx.win.appendChild(resizeW); var resizeNW = ctx.createResizeCornerArea('nwse-resize', DebugJS.UI_ST_RESIZING_N | DebugJS.UI_ST_RESIZING_W); resizeNW.style.top = '-3px'; resizeNW.style.left = '-3px'; ctx.win.appendChild(resizeNW); var resizeNE = ctx.createResizeCornerArea('nesw-resize', DebugJS.UI_ST_RESIZING_N | DebugJS.UI_ST_RESIZING_E); resizeNE.style.top = '-3px'; resizeNE.style.right = '-3px'; ctx.win.appendChild(resizeNE); var resizeSW = ctx.createResizeCornerArea('nesw-resize', DebugJS.UI_ST_RESIZING_S | DebugJS.UI_ST_RESIZING_W); resizeSW.style.bottom = '-3px'; resizeSW.style.left = '-3px'; ctx.win.appendChild(resizeSW); ctx.winBody.ondblclick = ctx.onDbgWinDblClick; } }, initDbgWin: function(ctx) { var opt = ctx.opt; if (ctx.isAllFeaturesDisabled(ctx)) return; if (opt.useLogFilter) ctx.updateLogFilterBtns(); if (ctx.uiStatus & DebugJS.UI_ST_SHOW_CLOCK) ctx.updateClockLabel(); if (opt.useScreenMeasure) ctx.updateMeasBtn(ctx); if (opt.useSystemInfo) ctx.updateSysInfoBtn(ctx); if (opt.useElementInfo) ctx.updateElmInfoBtn(ctx); if (opt.useHtmlSrc) ctx.updateHtmlSrcBtn(ctx); if (opt.useJsEditor) ctx.updateJsBtn(ctx); if (opt.useTools) ctx.updateToolsBtn(ctx); if (ctx.extPanel) ctx.updateExtBtn(ctx); if (opt.useStopwatch) { ctx.updateSwBtnPanel(ctx); ctx.updateSwLabel(); } if ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (opt.usePinButton)) { ctx.updatePinBtn(ctx); } if (ctx.preserveLogBtn) ctx.updatePreserveLogBtn(ctx); if (opt.useSuspendLogButton) ctx.updateSuspendLogBtn(ctx); if ((ctx.uiStatus & DebugJS.UI_ST_RESIZABLE) && (opt.useWinCtrlButton)) { ctx.updateWinCtrlBtnPanel(); } if (opt.useMouseStatusInfo) { ctx.updateMousePosLabel(); ctx.updateMouseClickLabel(); } if (opt.useWindowSizeInfo) { ctx.updateWindowSizeLabel(); ctx.updateClientSizeLabel(); ctx.updateBodySizeLabel(); ctx.updateScrollPosLabel(); } if (opt.useLed) ctx.updateLedPanel(); if (opt.useMsgDisplay) ctx.updateMsgLabel(); }, createHeaderBtn: function(btnObj, label, marginLeft, fontSize, handler, status, state, activeColor, reverse, title) { var ctx = DebugJS.ctx; var btn = DebugJS.ui.addBtn(ctx.headPanel, label, handler); btn.style.float = 'right'; btn.style.marginLeft = (marginLeft * ctx.opt.zoom) + 'px'; if (fontSize) ctx.setStyle(btn, 'font-size', fontSize); ctx.setStyle(btn, 'color', DebugJS.COLOR_INACT); btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', DebugJS.' + activeColor + ');'); if (reverse) { btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', (DebugJS.ctx.' + status + ' & DebugJS.' + state + ') ? DebugJS.COLOR_INACT : DebugJS.' + activeColor + ');'); } else { btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', (DebugJS.ctx.' + status + ' & DebugJS.' + state + ') ? DebugJS.' + activeColor + ' : DebugJS.COLOR_INACT);'); } if (title) btn.title = title; return btn; }, createSysInfoLabel: function() { var el = document.createElement('span'); el.className = 'dbg-sys-info'; DebugJS.ctx.infoPanel.appendChild(el); return el; }, createLogFilter: function(ctx) { ctx.fltrBtnAll = ctx.createLogFltBtn('ALL', 'fltrBtnAll', 'btnColor'); ctx.fltrBtnStd = ctx.createLogFltBtn('LOG', 'fltrBtnStd', 'fontColor'); ctx.fltrBtnErr = ctx.createLogFltBtn('ERR', 'fltrBtnErr', 'logColorE'); ctx.fltrBtnWrn = ctx.createLogFltBtn('WRN', 'fltrBtnWrn', 'logColorW'); ctx.fltrBtnInf = ctx.createLogFltBtn('INF', 'fltrBtnInf', 'logColorI'); ctx.fltrBtnDbg = ctx.createLogFltBtn('DBG', 'fltrBtnDbg', 'logColorD'); ctx.fltrBtnVrb = ctx.createLogFltBtn('VRB', 'fltrBtnVrb', 'logColorV'); ctx.fltrInputLabel = document.createElement('span'); ctx.fltrInputLabel.style.marginLeft = '4px'; ctx.setStyle(ctx.fltrInputLabel, 'color', ctx.opt.sysInfoColor); ctx.fltrInputLabel.innerText = 'Search:'; ctx.logHeaderPanel.appendChild(ctx.fltrInputLabel); var fltrW = 'calc(100% - 32.3em)'; ctx.fltrInput = DebugJS.ui.addTextInput(ctx.logHeaderPanel, fltrW, null, ctx.opt.sysInfoColor, ctx.fltrText, DebugJS.ctx.onchangeLogFilter); ctx.setStyle(ctx.fltrInput, 'position', 'relative'); ctx.setStyle(ctx.fltrInput, 'top', '-2px'); ctx.setStyle(ctx.fltrInput, 'margin-left', '2px'); ctx.fltrBtn = ctx.createLogFltBtn2(ctx, 'FL', 'fltrBtn', ctx.fltr, 'fltr', ctx.toggleFilter); ctx.fltrCaseBtn = ctx.createLogFltBtn2(ctx, 'Aa', 'fltrCaseBtn', ctx.fltrCase, 'fltrCase', ctx.toggleFilterCase); ctx.fltrTxtHtmlBtn = ctx.createLogFltBtn2(ctx, '</>', 'fltrTxtHtmlBtn', ctx.fltrTxtHtml, 'fltrTxtHtml', ctx.toggleFilterTxtHtml); }, createLogFltBtn: function(type, btnObj, color) { var ctx = DebugJS.ctx; var lbl = '[' + type + ']'; var fn = new Function('DebugJS.ctx.toggleLogFilter(DebugJS.LOG_FLTR_' + type + ');'); var btn = DebugJS.ui.addBtn(ctx.logHeaderPanel, lbl, fn); btn.style.marginLeft = '2px'; btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', DebugJS.ctx.opt.' + color + ');'); btn.onmouseout = ctx.updateLogFilterBtns; return btn; }, createLogFltBtn2: function(ctx, label, btnNm, flg, flgNm, fn) { var btn = DebugJS.ui.addBtn(ctx.logHeaderPanel, label, fn); btn.style.marginLeft = '2px'; ctx.setStyle(btn, 'color', (flg) ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT); btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnNm + ', \'color\', DebugJS.FLT_BTN_COLOR);'); btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnNm + ', \'color\', (DebugJS.ctx.' + flgNm + ') ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT);'); return btn; }, setLogFilter: function(ctx, s, cs, fl) { ctx.fltrInput.value = s; ctx.setFilterCase(ctx, cs); ctx.setFilter(ctx, fl); ctx.onchangeLogFilter(); }, initCommandTable: function(ctx) { ctx.CMD_TBL = []; for (var i = 0; i < ctx.INT_CMD_TBL.length; i++) { if (ctx.opt.disableAllCommands) { if (ctx.INT_CMD_TBL[i].attr & DebugJS.CMD_ATTR_SYSTEM) { ctx.CMD_TBL.push(ctx.INT_CMD_TBL[i]); } } else { if (!(!(ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.INT_CMD_TBL[i].attr & DebugJS.CMD_ATTR_DYNAMIC)) && (!((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.opt.mode == 'kiosk') && (ctx.INT_CMD_TBL[i].attr & DebugJS.CMD_ATTR_NO_KIOSK)))) { ctx.CMD_TBL.push(ctx.INT_CMD_TBL[i]); } } } }, resetStylesOnZoom: function(ctx) { var fontSize = ctx.computedFontSize + 'px'; if (ctx.toolsPanel) { ctx.toolsHeaderPanel.style.height = fontSize; ctx.toolsBodyPanel.style.height = 'calc(100% - ' + ctx.computedFontSize + 'px)'; } if (ctx.fileVwrPanel) { ctx.setStyle(ctx.fileInput, 'width', 'calc(100% - ' + (ctx.computedFontSize * 12) + 'px)'); ctx.setStyle(ctx.fileInput, 'min-height', (20 * ctx.opt.zoom) + 'px'); ctx.setStyle(ctx.fileInput, 'font-size', fontSize); ctx.setStyle(ctx.filePreviewWrapper, 'height', 'calc(100% - ' + ((ctx.computedFontSize * 4) + 10) + 'px)'); ctx.setStyle(ctx.filePreviewWrapper, 'font-size', fontSize); ctx.setStyle(ctx.filePreview, 'font-size', fontSize); ctx.fileVwrFooter.style.height = (ctx.computedFontSize + 3) + 'px'; ctx.fileLoadProgBar.style.width = 'calc(100% - ' + (ctx.computedFontSize * 5) + 'px)'; ctx.setStyle(ctx.fileLoadProg, 'font-size', (ctx.computedFontSize * 0.8) + 'px'); } if (ctx.extPanel) { ctx.extHeaderPanel.style.height = fontSize; ctx.extBodyPanel.style.height = 'calc(100% - ' + ctx.computedFontSize + 'px)'; } }, reopenFeatures: function(ctx) { while (true) { var f = ctx.featStackBak.shift(); if (f == undefined) break; ctx.openFeature(ctx, f, undefined, true); } }, restoreDbgWinSize: function(ctx, sizeStatus) { if (sizeStatus == DebugJS.SIZE_ST_FULL_WH) { ctx.setWinSize('full'); } else if (sizeStatus == DebugJS.SIZE_ST_EXPANDED_C) { ctx.setWinSize('center'); } else if (sizeStatus == DebugJS.SIZE_ST_EXPANDED) { ctx._expandDbgWin(ctx); } }, setWinPos: function(pos, dbgWinW, dbgWinH) { var ctx = DebugJS.ctx; var opt = ctx.opt; var top = opt.adjustY; var left = opt.adjustX; var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; if (clientW > window.outerWidth) clientW = window.outerWidth; if (clientH > window.outerHeight) clientH = window.outerHeight; switch (pos) { case 'se': top = clientH - dbgWinH - opt.adjustY; left = clientW - dbgWinW - opt.adjustX; break; case 'ne': top = opt.adjustY; left = clientW - dbgWinW - opt.adjustX; break; case 'c': top = (clientH / 2) - (dbgWinH / 2); left = (clientW / 2) - (dbgWinW / 2); break; case 'sw': top = clientH - dbgWinH - opt.adjustY; left = opt.adjustX; break; case 'n': top = opt.adjustY; left = (clientW / 2) - (dbgWinW / 2); break; case 'e': top = (clientH / 2) - (dbgWinH / 2); left = clientW - dbgWinW - opt.adjustX; break; case 's': top = clientH - dbgWinH - opt.adjustY; left = (clientW / 2) - (dbgWinW / 2); break; case 'w': top = (clientH / 2) - (dbgWinH / 2); left = opt.adjustX; } ctx.win.style.top = top + 'px'; ctx.win.style.left = left + 'px'; }, updateClockLabel: function() { var ctx = DebugJS.ctx; var dt = DebugJS.getDateTime(); var t = dt.yyyy + '-' + dt.mm + '-' + dt.dd + ' ' + DebugJS.WDAYS[dt.wday] + ' ' + dt.hh + ':' + dt.mi + ':' + dt.ss; ctx.clockLabel.innerText = t; if (ctx.uiStatus & DebugJS.UI_ST_SHOW_CLOCK) { setTimeout(ctx.updateClockLabel, ctx.clockUpdInt); } }, updateWindowSizeLabel: function() { try { var ctx = DebugJS.ctx; var w = window.outerWidth; var h = window.outerHeight; ctx.winSizeLabel.innerText = 'WIN:w=' + w + ',h=' + h; if (ctx.status & DebugJS.ST_SYS_INFO) { document.getElementById(ctx.id + '-sys-win-w').innerText = w; document.getElementById(ctx.id + '-sys-win-h').innerText = h; } } catch (e) {} }, updateClientSizeLabel: function() { var ctx = DebugJS.ctx; var w = document.documentElement.clientWidth; var h = document.documentElement.clientHeight; ctx.clientSizeLabel.innerText = 'CLI:w=' + w + ',h=' + h; if (ctx.status & DebugJS.ST_SYS_INFO) { document.getElementById(ctx.id + '-sys-cli-w').innerText = w; document.getElementById(ctx.id + '-sys-cli-h').innerText = h; } }, updateBodySizeLabel: function() { var ctx = DebugJS.ctx; var w = this.bodyEl.clientWidth; var h = this.bodyEl.clientHeight; ctx.bodySizeLabel.innerText = 'BODY:w=' + w + ',h=' + h; if (ctx.status & DebugJS.ST_SYS_INFO) { document.getElementById(ctx.id + '-sys-body-w').innerText = w; document.getElementById(ctx.id + '-sys-body-h').innerText = h; } ctx.pixelRatioLabel.innerText = DebugJS.getWinZoomRatio(); }, updateScrollPosLabel: function() { this.scrollPosLabel.innerText = 'SCROLL:x=' + this.scrollPosX + ',y=' + this.scrollPosY; }, updateMousePosLabel: function() { this.mousePosLabel.innerText = 'POS:x=' + this.mousePos.x + ',y=' + this.mousePos.y; }, updateMouseClickLabel: function() { var s = '<span style="color:' + this.mouseClick0 + ' !important;margin-right:2px;">0</span>' + '<span style="color:' + this.mouseClick1 + ' !important;margin-right:2px;">1</span>' + '<span style="color:' + this.mouseClick2 + ' !important">2</span>'; this.mouseClickLabel.innerHTML = 'CLICK:' + s; }, updateKeyDownLabel: function() { this.keyDownLabel.innerHTML = 'Key Down:' + this.keyDownCode; }, updateKeyPressLabel: function() { this.keyPressLabel.innerHTML = 'Press:' + this.keyPressCode; }, updateKeyUpLabel: function() { this.keyUpLabel.innerHTML = 'Up:' + this.keyUpCode; }, updateLedPanel: function() { if (!DebugJS.ctx.ledPanel) return; var SHADOW = 'text-shadow:0 0 5px;'; var led = ''; for (var i = 7; i >= 0; i--) { var color = (DebugJS.ctx.led & DebugJS.LED_BIT[i]) ? 'color:' + DebugJS.LED_COLOR[i] + ' !important;' + SHADOW : 'color:' + DebugJS.LED_COLOR_INACT + ' !important;'; var margin = (i == 0 ? '' : 'margin-right:2px'); led += '<span style="' + color + margin + '">' + DebugJS.CHR_LED + '</span>'; } DebugJS.ctx.ledPanel.innerHTML = led; }, updateMsgLabel: function() { var ctx = DebugJS.ctx; var s = ctx.msgString; if (ctx.msgLabel) { ctx.msgLabel.innerHTML = '<pre>' + s + '</pre>'; var o = (s == '' ? 0 : 1); ctx.msgLabel.style.opacity = o; } }, updateMeasBtn: function(ctx) { ctx.measBtn.style.border = 'solid ' + ctx.opt.zoom + 'px ' + ((ctx.status & DebugJS.ST_MEASURE) ? DebugJS.MEAS_BTN_COLOR : DebugJS.COLOR_INACT); }, updateSysInfoBtn: function(ctx) { ctx.updateBtnActive(ctx.sysInfoBtn, DebugJS.ST_SYS_INFO, DebugJS.SYS_BTN_COLOR); }, updateElmInfoBtn: function(ctx) { ctx.updateBtnActive(ctx.elmInfoBtn, DebugJS.ST_ELM_INSPECTING, DebugJS.DOM_BTN_COLOR); }, updateHtmlSrcBtn: function(ctx) { ctx.updateBtnActive(ctx.htmlSrcBtn, DebugJS.ST_HTML_SRC, DebugJS.HTML_BTN_COLOR); }, updateJsBtn: function(ctx) { ctx.updateBtnActive(ctx.jsBtn, DebugJS.ST_JS, DebugJS.JS_BTN_COLOR); }, updateToolsBtn: function(ctx) { ctx.updateBtnActive(ctx.toolsBtn, DebugJS.ST_TOOLS, DebugJS.TOOLS_BTN_COLOR); }, updateExtBtn: function(ctx) { ctx.updateBtnActive(ctx.extBtn, DebugJS.ST_EXT_PANEL, DebugJS.EXT_BTN_COLOR); }, updateSwBtnPanel: function(ctx) { if (!ctx.swBtnPanel) return; var lbl = (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) ? '||' : '>>'; var margin = (2 * ctx.opt.zoom) + 'px'; var btns = DebugJS.ui.createBtnHtml('0', 'DebugJS.ctx.resetStopwatch();', 'margin-right:' + margin) + DebugJS.ui.createBtnHtml(lbl, 'DebugJS.ctx.startStopStopwatch();', 'margin-right:' + margin); ctx.swBtnPanel.innerHTML = btns; }, updatePreserveLogBtn: function(ctx) { ctx.updateBtnActive(ctx.preserveLogBtn, DebugJS.ST_LOG_PRESERVED, DebugJS.LOG_PRESERVE_BTN_COLOR); }, updateSuspendLogBtn: function(ctx) { ctx.updateBtnActive(ctx.suspendLogBtn, DebugJS.ST_LOG_SUSPENDING, DebugJS.LOG_SUSPEND_BTN_COLOR); }, updatePinBtn: function(ctx) { if (ctx.pinBtn) { ctx.setStyle(ctx.pinBtn, 'color', (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) ? DebugJS.COLOR_INACT : DebugJS.PIN_BTN_COLOR); } }, updateBtnActive: function(btn, status, activeColor) { if (btn) { DebugJS.ctx.setStyle(btn, 'color', (DebugJS.ctx.status & status) ? activeColor : DebugJS.COLOR_INACT); } }, updateWinCtrlBtnPanel: function() { var ctx = DebugJS.ctx; if (!ctx.winCtrlBtnPanel) return; var fn = 'DebugJS.ctx.expandDbgWin(\'full\');'; var btn = DebugJS.CHR_WIN_FULL; if (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH) { fn = 'DebugJS.ctx.restoreDbgWin();'; btn = DebugJS.CHR_WIN_RST; } fn += 'DebugJS.ctx.updateWinCtrlBtnPanel();DebugJS.ctx.focusCmdLine();'; var b = '<span class="dbg-btn dbg-nomove" style="float:right;position:relative;top:-1px;margin-right:' + (3 * ctx.opt.zoom) + 'px;font-size:' + (16 * ctx.opt.zoom) + 'px !important;color:#888 !important" onclick="' + fn + '" onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'#ddd\');" onmouseout="DebugJS.ctx.setStyle(this, \'color\', \'#888\');">' + btn + '</span>' + '<span class="dbg-btn dbg-nomove" style="float:right;position:relative;top:-2px;margin-left:' + 2 * ctx.opt.zoom + 'px;margin-right:' + ctx.opt.zoom + 'px;font-size:' + (30 * ctx.opt.zoom) + 'px !important;color:#888 !important" onclick="DebugJS.ctx.resetDbgWinSizePos();DebugJS.ctx.focusCmdLine();" onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'#ddd\');" onmouseout="DebugJS.ctx.setStyle(this, \'color\', \'#888\');">-</span>'; ctx.winCtrlBtnPanel.innerHTML = b; }, printLogs: function() { var ctx = DebugJS.ctx; ctx._printLogs(ctx); if (ctx.uiStatus & DebugJS.UI_ST_LOG_SCROLL) ctx.scrollLogBtm(ctx); }, _printLogs: function(ctx) { if (!ctx.win) return; var opt = ctx.opt; var buf = ctx.logBuf.getAll(); var cnt = ctx.logBuf.count(); var len = buf.length; var lineCnt = cnt - len; var filter = ctx.fltrText; var fltCase = ctx.fltrCase; if (!fltCase) { filter = filter.toLowerCase(); } var logs = ''; for (var i = 0; i < len; i++) { lineCnt++; var data = buf[i]; var msg = (ctx.fltrTxtHtml ? data.msg : DebugJS.escTags(data.msg)); var style = ''; switch (data.type) { case DebugJS.LOG_TYPE_DBG: if (!(ctx.logFilter & DebugJS.LOG_FLTR_DBG)) continue; style = 'color:' + opt.logColorD; break; case DebugJS.LOG_TYPE_INF: if (!(ctx.logFilter & DebugJS.LOG_FLTR_INF)) continue; style = 'color:' + opt.logColorI; break; case DebugJS.LOG_TYPE_ERR: if (!(ctx.logFilter & DebugJS.LOG_FLTR_ERR)) continue; style = 'color:' + opt.logColorE; break; case DebugJS.LOG_TYPE_WRN: if (!(ctx.logFilter & DebugJS.LOG_TYPE_WRN)) continue; style = 'color:' + opt.logColorW; break; case DebugJS.LOG_TYPE_VRB: if (!(ctx.logFilter & DebugJS.LOG_TYPE_VRB)) continue; style = 'color:' + opt.logColorV; break; case DebugJS.LOG_TYPE_SYS: if (!(ctx.logFilter & DebugJS.LOG_FLTR_LOG)) continue; style = 'color:' + opt.logColorS + ';text-shadow:0 0 3px'; break; case DebugJS.LOG_TYPE_MLT: if (!(ctx.logFilter & DebugJS.LOG_FLTR_LOG)) continue; style = 'display:inline-block;width:100%;margin:' + Math.round(ctx.computedFontSize * 0.5) + 'px 0'; break; default: if (!(ctx.logFilter & DebugJS.LOG_FLTR_LOG)) continue; } if (filter != '') { try { var pos = (fltCase ? msg.indexOf(filter) : msg.toLowerCase().indexOf(filter)); if (pos != -1) { var key = msg.substr(pos, filter.length); var hl = '<span class="dbg-txt-hl">' + key + '</span>'; msg = msg.replace(key, hl, 'ig'); } else if (ctx.fltr) { continue; } } catch (e) {} } var lineNum = ''; if ((opt.showLineNums) && (data.type != DebugJS.LOG_TYPE_MLT)) { var diff = DebugJS.digits(cnt) - DebugJS.digits(lineCnt); var pdng = ''; for (var j = 0; j < diff; j++) { pdng += '0'; } lineNum = pdng + lineCnt + ': '; } var color = ''; if ((data.type == DebugJS.LOG_TYPE_RES) || (data.type == DebugJS.LOG_TYPE_ERES)) { msg = DebugJS.quoteStrIfNeeded(DebugJS.setStyleIfObjNA(msg)); if (data.type == DebugJS.LOG_TYPE_RES) { color = opt.promptColor; } else { color = opt.promptColorE; } msg = '<span style=color:' + color + '>&gt;</span> ' + msg; } var m = (((opt.showTimeStamp) && (data.type != DebugJS.LOG_TYPE_MLT)) ? (DebugJS.getTimeStr(data.time) + ' ' + msg) : msg); if (style) { logs += lineNum + '<span style="' + style + '">' + m + '</span>\n'; } else { logs += lineNum + m + '\n'; } } ctx.logPanel.innerHTML = '<pre style="padding:0 3px !important">' + logs + '</pre>'; }, onLogScroll: function(e) { var ctx = DebugJS.ctx; var rect = ctx.logPanel.getBoundingClientRect(); var h = rect.height; var d = ctx.logPanel.scrollHeight - ctx.logPanel.scrollTop; if ((d - 1 <= h) && (h <= d + 1)) { ctx.startLogScrolling(); } else { ctx.stopLogScrolling(); } }, scrollLogBtm: function(ctx) { ctx.logPanel.scrollTop = ctx.logPanel.scrollHeight; }, startLogScrolling: function() { DebugJS.ctx.uiStatus |= DebugJS.UI_ST_LOG_SCROLL; }, stopLogScrolling: function() { DebugJS.ctx.uiStatus &= ~DebugJS.UI_ST_LOG_SCROLL; }, onClr: function() { DebugJS.ctx.clearLog(); DebugJS.ctx.focusCmdLine(); }, clearLog: function() { DebugJS.ctx.logBuf.clear(); DebugJS.ctx.printLogs(); }, toggleLogFilter: function(fltr) { var ctx = DebugJS.ctx; if (fltr == DebugJS.LOG_FLTR_ALL) { if ((ctx.logFilter & ~DebugJS.LOG_FLTR_VRB) == DebugJS.LOG_FLTR_ALL) { ctx.logFilter = 0; } else { ctx.logFilter |= fltr; } } else if (fltr == DebugJS.LOG_FLTR_VRB) { if (ctx.logFilter & DebugJS.LOG_FLTR_VRB) { ctx.logFilter &= ~fltr; } else { ctx.logFilter |= fltr; } } else { if ((ctx.logFilter & ~DebugJS.LOG_FLTR_VRB) == DebugJS.LOG_FLTR_ALL) { ctx.logFilter = fltr; } else { if (ctx.logFilter & fltr) { ctx.logFilter &= ~fltr; } else { ctx.logFilter |= fltr; } } } ctx.updateLogFilterBtns(); ctx.printLogs(); if (fltr == DebugJS.LOG_FLTR_ALL) ctx.scrollLogBtm(ctx); }, updateLogFilterBtns: function() { var ctx = DebugJS.ctx; var opt = ctx.opt; var fltr = ctx.logFilter; ctx.setStyle(ctx.fltrBtnAll, 'color', ((fltr & ~DebugJS.LOG_FLTR_VRB) == DebugJS.LOG_FLTR_ALL) ? opt.btnColor : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnStd, 'color', (fltr & DebugJS.LOG_FLTR_LOG) ? opt.fontColor : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnErr, 'color', (fltr & DebugJS.LOG_FLTR_ERR) ? opt.logColorE : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnWrn, 'color', (fltr & DebugJS.LOG_FLTR_WRN) ? opt.logColorW : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnInf, 'color', (fltr & DebugJS.LOG_FLTR_INF) ? opt.logColorI : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnDbg, 'color', (fltr & DebugJS.LOG_FLTR_DBG) ? opt.logColorD : DebugJS.COLOR_INACT); ctx.setStyle(ctx.fltrBtnVrb, 'color', (fltr & DebugJS.LOG_FLTR_VRB) ? opt.logColorV : DebugJS.COLOR_INACT); }, onchangeLogFilter: function() { DebugJS.ctx.fltrText = DebugJS.ctx.fltrInput.value; DebugJS.ctx.printLogs(); }, toggleFilter: function() { var ctx = DebugJS.ctx; ctx.setFilter(ctx, (ctx.fltr ? false : true)); }, setFilter: function(ctx, f) { ctx.fltr = f; ctx.setStyle(ctx.fltrBtn, 'color', (DebugJS.ctx.fltr) ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT); ctx.onchangeLogFilter(); }, toggleFilterCase: function() { var ctx = DebugJS.ctx; ctx.setFilterCase(ctx, (ctx.fltrCase ? false : true)); }, setFilterCase: function(ctx, f) { ctx.fltrCase = f; ctx.setStyle(ctx.fltrCaseBtn, 'color', (DebugJS.ctx.fltrCase) ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT); ctx.onchangeLogFilter(); }, toggleFilterTxtHtml: function() { var ctx = DebugJS.ctx; ctx.setFilterTxtHtml(ctx, (ctx.fltrTxtHtml ? false : true)); }, setFilterTxtHtml: function(ctx, f) { ctx.fltrTxtHtml = f; ctx.setStyle(ctx.fltrTxtHtmlBtn, 'color', (ctx.fltrTxtHtml ? DebugJS.FLT_BTN_COLOR : DebugJS.COLOR_INACT)); ctx.onchangeLogFilter(); }, applyStyles: function(ctx, styles) { if (ctx.styleEl) document.head.removeChild(ctx.styleEl); ctx.styleEl = document.createElement('style'); document.head.appendChild(ctx.styleEl); ctx.styleEl.appendChild(document.createTextNode('')); var s = ctx.styleEl.sheet; for (var selector in styles) { var props = styles[selector]; var propStr = ''; for (var propName in props) { var propVal = props[propName]; var propImportant = ''; if (propVal[1] === true) { propVal = propVal[0]; propImportant = ' !important'; } propStr += propName + ':' + propVal + propImportant + ';\n'; } s.insertRule(selector + '{' + propStr + '}', s.cssRules.length); } }, setStyle: function(el, n, v) { el.style.setProperty(n, v, 'important'); }, setIntervalL: function(ctx) { if (ctx.clockUpdIntHCnt > 0) { ctx.clockUpdIntHCnt--; } if (ctx.clockUpdIntHCnt == 0) { ctx.clockUpdInt = DebugJS.UPDATE_INTERVAL_L; } }, setIntervalH: function(ctx) { ctx.clockUpdIntHCnt++; ctx.clockUpdInt = DebugJS.UPDATE_INTERVAL_H; }, setupMove: function(ctx) { ctx.winBody.onmousedown = ctx.startMoveM; ctx.winBody.ontouchstart = ctx.startMoveT; }, startMoveM: function(e) { var ctx = DebugJS.ctx; var x = e.clientX; var y = e.clientY; var target = e.target; if (e.button != 0) return; if ((!(ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE)) || !ctx.isMovable(ctx, target, x, y)) { return; } ctx._startMove(ctx, target, x, y); }, startMoveT: function(e) { var ctx = DebugJS.ctx; var x = e.changedTouches[0].pageX; var y = e.changedTouches[0].pageY; var target = e.target; if ((!(ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE)) || !ctx.isMovable(ctx, target, x, y)) { return; } ctx._startMove(ctx, target, x, y); e.preventDefault(); }, _startMove: function(ctx, target, x, y) { ctx.uiStatus |= DebugJS.UI_ST_DRAGGING; ctx.ptOpTm = (new Date()).getTime(); ctx.winBody.style.cursor = 'move'; ctx.disableTextSelect(ctx); ctx.prevOffsetTop = y - ctx.win.offsetTop; ctx.prevOffsetLeft = x - ctx.win.offsetLeft; if (!document.all) { window.getSelection().removeAllRanges(); } }, disableTextSelect: function(ctx) { ctx.savedFunc = document.onselectstart; document.onselectstart = function() {return false;}; }, enableTextSelect: function(ctx) { document.onselectstart = ctx.savedFunc; }, isMovable: function(ctx, el, x, y) { if (el.nodeName == 'INPUT') return false; if (el.nodeName == 'TEXTAREA') return false; if (DebugJS.hasClass(el, 'dbg-nomove')) return false; var ua = DebugJS.getBrowserType(); if ((ua.family == 'IE') || (ua.name == 'Firefox')) { if ((el == ctx.logPanel) || (el == ctx.sysInfoPanel) || (el == ctx.elmInfoBodyPanel) || (el == ctx.htmlSrcBodyPanel) || (el == ctx.filePreviewWrapper) || (el == ctx.toolsPanel) || (el == ctx.extPanel) || (el == ctx.extBodyPanel)) { var scrollBarWH = 17; var rect = el.getBoundingClientRect(); var scrollL = rect.left + rect.width - scrollBarWH; var scrollR = rect.left + rect.width; var scrollT = rect.top + rect.height - scrollBarWH; var scrollB = rect.top + rect.height; if (((x >= scrollL) && (x <= scrollR)) || ((y >= scrollT) && (y <= scrollB))) { return false; } } } return true; }, moveDbgWin: function(ctx, x, y) { if (!(ctx.uiStatus & DebugJS.UI_ST_DRAGGING)) return; ctx.ptOpTm = (new Date()).getTime(); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.win.style.top = y - ctx.prevOffsetTop + 'px'; ctx.win.style.left = x - ctx.prevOffsetLeft + 'px'; }, endMove: function(ctx) { ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGING; ctx.enableTextSelect(ctx); ctx.winBody.style.cursor = 'default'; }, startResize: function(ctx, e) { if (e.button != 0) return; ctx.uiStatus |= DebugJS.UI_ST_RESIZING; ctx.clickedPosX = e.clientX; ctx.clickedPosY = e.clientY; ctx.saveSizeAndPos(ctx); ctx.sizeStatus = DebugJS.SIZE_ST_NORMAL; ctx.updateWinCtrlBtnPanel(); ctx.disableTextSelect(ctx); }, resizeDbgWin: function(ctx, x, y) { var currentX = x; var currentY = y; var moveX, moveY, t, l, w, h; var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; if (currentX > clientW) { currentX = clientW; } else if (currentX < 0) { currentX = 0; } if (currentY > clientH) { currentY = clientH; } else if (currentY < 0) { currentY = 0; } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING_N) { moveY = ctx.clickedPosY - currentY; h = ctx.orgSizePos.h + moveY; if (h < ctx.computedMinH) { h = ctx.computedMinH; } else { t = ctx.orgSizePos.t - moveY; ctx.win.style.top = t + 'px'; } ctx.win.style.height = h + 'px'; if (ctx.logPanel.scrollTop != 0) { ctx.scrollLogBtm(ctx); } } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING_W) { moveX = ctx.clickedPosX - currentX; w = ctx.orgSizePos.w + moveX; if (w < ctx.computedMinW) { w = ctx.computedMinW; } else { l = ctx.orgSizePos.l - moveX; ctx.win.style.left = l + 'px'; } ctx.win.style.width = w + 'px'; } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING_E) { moveX = currentX - ctx.clickedPosX; w = ctx.orgSizePos.w + moveX; if (w < ctx.computedMinW) w = ctx.computedMinW; ctx.win.style.width = w + 'px'; } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING_S) { moveY = currentY - ctx.clickedPosY; h = ctx.orgSizePos.h + moveY; if (ctx.initHeight < ctx.computedMinH) { if (h < ctx.initHeight) { h = ctx.initHeight; } } else if (h < ctx.computedMinH) { h = ctx.computedMinH; } ctx.win.style.height = h + 'px'; if (ctx.logPanel.scrollTop != 0) { ctx.scrollLogBtm(ctx); } } ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, endResize: function(ctx) { ctx.uiStatus &= ~DebugJS.UI_ST_RESIZING_ALL; ctx.bodyEl.style.cursor = ctx.bodyCursor; ctx.enableTextSelect(ctx); }, resizeMainHeight: function() { var ctx = DebugJS.ctx; var headPanelH = (ctx.headPanel) ? ctx.headPanel.offsetHeight : 0; var infoPanelH = (ctx.infoPanel) ? ctx.infoPanel.offsetHeight : 0; var cmdPanelH = (ctx.cmdPanel) ? ctx.cmdPanel.offsetHeight : 0; var mainPanelHeight = ctx.win.offsetHeight - headPanelH - infoPanelH - cmdPanelH - DebugJS.WIN_ADJUST; ctx.mainPanel.style.height = mainPanelHeight + 'px'; }, toggleLogSuspend: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_LOG_SUSPENDING) { ctx.resumeLog(); } else { ctx.suspendLog(); } }, suspendLog: function() { var ctx = DebugJS.ctx; ctx.status |= DebugJS.ST_LOG_SUSPENDING; ctx.updateSuspendLogBtn(ctx); }, resumeLog: function() { var ctx = DebugJS.ctx; ctx.status &= ~DebugJS.ST_LOG_SUSPENDING; ctx.updateSuspendLogBtn(ctx); }, toggleLogPreserve: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_LOG_PRESERVED) { ctx.setLogPreserve(ctx, false); } else { ctx.setLogPreserve(ctx, true); } }, setLogPreserve: function(ctx, f) { if (f) { ctx.status |= DebugJS.ST_LOG_PRESERVED; } else { ctx.status &= ~DebugJS.ST_LOG_PRESERVED; } ctx.updatePreserveLogBtn(ctx); }, toggleMeasure: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_MEASURE) { ctx.closeScreenMeasure(ctx); } else { ctx.openScreenMeasure(ctx); } }, openScreenMeasure: function(ctx, q) { if (!q) DebugJS._log.s('Screen Measure ON'); ctx.status |= DebugJS.ST_MEASURE; ctx.featStack.push(DebugJS.ST_MEASURE); ctx.bodyCursor = ctx.bodyEl.style.cursor; ctx.bodyEl.style.cursor = 'default'; ctx.updateMeasBtn(ctx); }, closeScreenMeasure: function(ctx, q) { ctx.stopMeasure(ctx); ctx.bodyEl.style.cursor = ctx.bodyCursor; ctx.status &= ~DebugJS.ST_MEASURE; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_MEASURE); if (!q) DebugJS._log.s('Screen Measure OFF'); ctx.updateMeasBtn(ctx); }, toggleDraggable: function() { var ctx = DebugJS.ctx; if (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) { ctx.disableDraggable(ctx); } else { ctx.enableDraggable(ctx); } }, enableDraggable: function(ctx) { ctx.uiStatus |= DebugJS.UI_ST_DRAGGABLE; ctx.winBody.style.cursor = 'default'; ctx.updatePinBtn(ctx); }, disableDraggable: function(ctx) { ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGABLE; ctx.winBody.style.cursor = 'auto'; ctx.updatePinBtn(ctx); }, enableResize: function(ctx) { ctx.uiStatus |= DebugJS.UI_ST_RESIZABLE; }, disableResize: function(ctx) { ctx.uiStatus &= ~DebugJS.UI_ST_RESIZABLE; }, startStopStopwatch: function() { if (DebugJS.ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { DebugJS.ctx.stopStopwatch(); } else { DebugJS.ctx.startStopwatch(); } }, startStopwatch: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_STOPWATCH_END) ctx.resetStopwatch(); ctx.status |= DebugJS.ST_STOPWATCH_RUNNING; DebugJS.time.restart(DebugJS.TIMER_NAME_SW_0); ctx.updateSwLabel(); ctx.updateSwBtnPanel(ctx); }, stopStopwatch: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { ctx.status &= ~DebugJS.ST_STOPWATCH_RUNNING; if (ctx.status & DebugJS.ST_STOPWATCH_LAPTIME) { ctx.status &= ~DebugJS.ST_STOPWATCH_LAPTIME; ctx.resetStopwatch(); } DebugJS.time.pause(DebugJS.TIMER_NAME_SW_0); } ctx.updateSwLabel(); ctx.updateSwBtnPanel(ctx); }, resetStopwatch: function() { var ctx = DebugJS.ctx; ctx.status &= ~DebugJS.ST_STOPWATCH_END; DebugJS.time.reset(DebugJS.TIMER_NAME_SW_0); ctx.updateSwLabel(); }, splitStopwatch: function() { if (DebugJS.ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { DebugJS.time._split(DebugJS.TIMER_NAME_SW_0); } }, endStopwatch: function() { DebugJS.ctx.status |= DebugJS.ST_STOPWATCH_END; DebugJS.ctx.stopStopwatch(); }, updateSwLabel: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { DebugJS.time.updateCount(DebugJS.TIMER_NAME_SW_0); } var str = DebugJS.getTimerStr(DebugJS.time.getCount(DebugJS.TIMER_NAME_SW_0)); if (ctx.swLabel) { if (ctx.status & DebugJS.ST_STOPWATCH_LAPTIME) { str = '<span style="color:' + ctx.opt.timerColor + ' !important">' + str + '</span>'; } else if (ctx.status & DebugJS.ST_STOPWATCH_END) { var now = DebugJS.getDateTime(); if (now.sss > 500) { str = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; } } ctx.swLabel.innerHTML = str; } if ((ctx.status & DebugJS.ST_STOPWATCH_RUNNING) || (ctx.status & DebugJS.ST_STOPWATCH_END)) { setTimeout(ctx.updateSwLabel, DebugJS.UPDATE_INTERVAL_H); } }, collapseLogPanel: function(ctx) { ctx.logPanel.style.height = 'calc(' + (100 - DebugJS.OVERLAY_PANEL_HEIGHT) + '%' + ctx.logPanelHeightAdjust + ')'; ctx.scrollLogBtm(ctx); }, expandLogPanel: function(ctx) { ctx.logPanel.style.height = 'calc(100%' + ctx.logPanelHeightAdjust + ')'; }, openFeature: function(ctx, f, subfnc, opt) { ctx.closeFeature(ctx, f); switch (f) { case DebugJS.ST_MEASURE: ctx.openScreenMeasure(ctx, opt); return true; case DebugJS.ST_SYS_INFO: ctx.openSystemInfo(ctx); return true; case DebugJS.ST_HTML_SRC: ctx.openHtmlSrc(ctx); return true; case DebugJS.ST_ELM_INSPECTING: ctx.openElmInfo(ctx); return true; case DebugJS.ST_JS: ctx.openJsEditor(ctx); return true; case DebugJS.ST_TOOLS: var kind; var param; switch (subfnc) { case 'timer': kind = DebugJS.TOOLS_FNC_TIMER; if (opt == 'clock') { param = DebugJS.TOOL_TIMER_MODE_CLOCK; } else if (opt == 'cu') { param = DebugJS.TOOL_TIMER_MODE_SW_CU; } else if (opt == 'cd') { param = DebugJS.TOOL_TIMER_MODE_SW_CD; } break; case 'text': kind = DebugJS.TOOLS_FNC_TEXT; break; case 'html': kind = DebugJS.TOOLS_FNC_HTML; break; case 'file': kind = DebugJS.TOOLS_FNC_FILE; param = (opt ? opt : ctx.fileVwrMode); break; case 'bat': kind = DebugJS.TOOLS_FNC_BAT; break; case undefined: kind = ctx.toolsActiveFnc; break; default: return false; } ctx.openTools(ctx); ctx.switchToolsFunction(kind, param); return true; case DebugJS.ST_EXT_PANEL: if (ctx.extPanels.length == 0) { DebugJS._log('No extension panel'); return false; } var idx = subfnc; if (idx == undefined) idx = ctx.extActPnlIdx; if (idx < 0) idx = 0; if (idx >= ctx.extPanels.length) { DebugJS._log.e('No such panel: ' + idx + ' (0-' + (ctx.extPanels.length - 1) + ')'); return false; } if (!(ctx.status & DebugJS.ST_EXT_PANEL)) { ctx.openExtPanel(ctx); } ctx.switchExtPanel(idx); return true; } return false; }, closeFeature: function(ctx, f) { switch (f) { case DebugJS.ST_MEASURE: ctx.closeScreenMeasure(ctx); break; case DebugJS.ST_SYS_INFO: ctx.closeSystemInfo(ctx); break; case DebugJS.ST_HTML_SRC: ctx.closeHtmlSrc(ctx); break; case DebugJS.ST_ELM_INSPECTING: ctx.closeElmInfo(ctx); break; case DebugJS.ST_JS: ctx.closeJsEditor(); break; case DebugJS.ST_TOOLS: ctx.closeTools(ctx); break; case DebugJS.ST_EXT_PANEL: ctx.closeExtPanel(ctx); break; default: return false; } return true; }, closeTopFeature: function(ctx) { var f = ctx.featStack.pop(); return ctx.closeFeature(ctx, f); }, finalizeFeatures: function(ctx) { if ((ctx.uiStatus & DebugJS.UI_ST_DRAGGING) || (ctx.uiStatus & DebugJS.UI_ST_RESIZING)) { ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGING; ctx.endResize(ctx); } ctx.closeAllFeatures(ctx, true); }, closeAllFeatures: function(ctx, q) { if (ctx.status & DebugJS.ST_MEASURE) ctx.closeScreenMeasure(ctx, q); if (ctx.status & DebugJS.ST_SYS_INFO) ctx.closeSystemInfo(ctx); if (ctx.status & DebugJS.ST_HTML_SRC) ctx.closeHtmlSrc(ctx); if (ctx.status & DebugJS.ST_ELM_INSPECTING) ctx.closeElmInfo(ctx); if (ctx.status & DebugJS.ST_JS) ctx.closeJsEditor(); if (ctx.status & DebugJS.ST_TOOLS) ctx.closeTools(ctx); if (ctx.status & DebugJS.ST_EXT_PANEL) ctx.closeExtPanel(ctx); }, launchFnc: function(ctx, fn, subfn, opt) { var a = { measure: DebugJS.ST_MEASURE, sys: DebugJS.ST_SYS_INFO, html: DebugJS.ST_HTML_SRC, dom: DebugJS.ST_ELM_INSPECTING, js: DebugJS.ST_JS, tool: DebugJS.ST_TOOLS, ext: DebugJS.ST_EXT_PANEL }; var f = (a[fn] === undefined ? 0 : a[fn]); return ctx.openFeature(ctx, f, subfn, opt); }, keyHandler: function(e) { var ctx = DebugJS.ctx; var opt = ctx.opt; var cmds; if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD) { DebugJS.bat._resume('cmd'); } switch (e.keyCode) { case 9: // Tab if ((ctx.status & DebugJS.ST_TOOLS) && (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_FILE)) { if (e.shiftKey) { if (ctx.fileVwrMode == 'b64') ctx.toggleShowHideCC(); } else { ctx.switchFileScreen(); } e.preventDefault(); } break; case 13: // Enter if (document.activeElement == ctx.cmdLine) { ctx.startLogScrolling(); ctx.stopErrCb = true; ctx.execCmd(ctx); ctx.stopErrCb = false; e.preventDefault(); } break; case 18: // Alt ctx.disableDraggable(ctx); break; case 27: // ESC if (ctx.props.esc == 'disable') break; if (ctx.uiStatus & DebugJS.UI_ST_DRAGGING) { ctx.endMove(ctx); break; } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING) { ctx.endResize(ctx); break; } if (ctx.closeTopFeature(ctx)) break; ctx.hideDbgWin(ctx); break; case 38: // Up if (document.activeElement == ctx.cmdLine) { cmds = ctx.cmdHistoryBuf.getAll(); if (cmds.length == 0) return; if (cmds.length < ctx.cmdHistoryIdx) { ctx.cmdHistoryIdx = cmds.length; } if (ctx.cmdHistoryIdx == cmds.length) { ctx.cmdTmp = ctx.cmdLine.value; } if (ctx.cmdHistoryIdx > 0) { ctx.cmdHistoryIdx--; } ctx.cmdLine.value = cmds[ctx.cmdHistoryIdx]; e.preventDefault(); } break; case 40: // Dn if (document.activeElement == ctx.cmdLine) { cmds = ctx.cmdHistoryBuf.getAll(); if (cmds.length == 0) return; if (ctx.cmdHistoryIdx < cmds.length) { ctx.cmdHistoryIdx++; } if (ctx.cmdHistoryIdx == cmds.length) { ctx.cmdLine.value = ctx.cmdTmp; } else { ctx.cmdLine.value = cmds[ctx.cmdHistoryIdx]; } } break; case 67: // C if ((e.ctrlKey) && (document.activeElement == ctx.cmdLine)) { if (((ctx.cmdLine.selectionEnd - ctx.cmdLine.selectionStart) == 0)) { if (ctx.status & DebugJS.ST_BAT_RUNNING) { DebugJS.bat.stop(DebugJS.EXIT_SIG + DebugJS.SIGINT); } ctx.startLogScrolling(); ctx._cmdDelayCancel(ctx); DebugJS.point.move.stop(); DebugJS.point.drag.stop(); DebugJS.scrollWinTo.stop(); DebugJS.setText.stop(); DebugJS._log.s(ctx.cmdLine.value + '^C'); ctx.cmdLine.value = ''; DebugJS.callEvtListeners('ctrlc'); } } break; case 112: // F1 if ((e.ctrlKey) && (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC)) { ctx.win.style.top = 0; ctx.win.style.left = 0; ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGING; } break; case opt.keyAssign.key: if (((opt.keyAssign.shift == undefined) || (e.shiftKey == opt.keyAssign.shift)) && ((opt.keyAssign.ctrl == undefined) || (e.ctrlKey == opt.keyAssign.ctrl)) && ((opt.keyAssign.alt == undefined) || (e.altKey == opt.keyAssign.alt)) && ((opt.keyAssign.meta == undefined) || (e.metaKey == opt.keyAssign.meta))) { if ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.isOutOfWin(ctx))) { ctx.resetToOriginalPosition(ctx); } else if (ctx.uiStatus & DebugJS.UI_ST_VISIBLE) { ctx.closeDbgWin(); } else { ctx.showDbgWin(); } } } }, onKeyDown: function(e) { var ctx = DebugJS.ctx; if (ctx.opt.useKeyStatusInfo) { ctx.updateStatusInfoOnKeyDown(ctx, e); } if (ctx.uiStatus & DebugJS.UI_ST_PROTECTED) { ctx.procOnProtectedD(ctx, e); } }, onKeyPress: function(e) { var ctx = DebugJS.ctx; if (ctx.opt.useKeyStatusInfo) { ctx.updateStatusInfoOnKeyPress(ctx, e); } if (ctx.uiStatus & DebugJS.UI_ST_PROTECTED) { ctx.procOnProtectedP(ctx, e); } }, onKeyUp: function(e) { var ctx = DebugJS.ctx; if (ctx.opt.useKeyStatusInfo) { ctx.updateStatusInfoOnKeyUp(ctx, e); } if (e.keyCode == 18) { ctx.enableDraggable(ctx); } }, procOnProtectedD: function(ctx, e) { switch (e.keyCode) { case 17: if (ctx.unlockCode == null) { ctx.unlockCode = ''; } else if (ctx.unlockCode == ctx.opt.lockCode) { ctx.uiStatus &= ~DebugJS.UI_ST_PROTECTED; ctx.unlockCode = null; DebugJS.callEvtListeners('unlock'); } break; case 27: ctx.unlockCode = null; } }, procOnProtectedP: function(ctx, e) { if (ctx.unlockCode == null) return; var ch = DebugJS.key2ch(e.key); if ((DebugJS.isTypographic(ch))) { ctx.unlockCode += ch; } }, updateStatusInfoOnKeyDown: function(ctx, e) { var modKey = DebugJS.checkModKey(e); ctx.keyDownCode = e.keyCode + '(' + e.key + ') ' + modKey; ctx.updateKeyDownLabel(); ctx.keyPressCode = DebugJS.KEY_ST_DFLT; ctx.updateKeyPressLabel(); ctx.keyUpCode = DebugJS.KEY_ST_DFLT; ctx.updateKeyUpLabel(); ctx.resizeMainHeight(); }, updateStatusInfoOnKeyPress: function(ctx, e) { var modKey = DebugJS.checkModKey(e); ctx.keyPressCode = e.keyCode + '(' + e.key + ') ' + modKey; ctx.updateKeyPressLabel(); ctx.resizeMainHeight(); }, updateStatusInfoOnKeyUp: function(ctx, e) { var modKey = DebugJS.checkModKey(e); ctx.keyUpCode = e.keyCode + '(' + e.key + ') ' + modKey; ctx.updateKeyUpLabel(); ctx.resizeMainHeight(); }, onResize: function() { var ctx = DebugJS.ctx; ctx.updateWindowSizeLabel(); ctx.updateClientSizeLabel(); ctx.updateBodySizeLabel(); if (ctx.uiStatus & DebugJS.UI_ST_VISIBLE) { if (ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) { ctx.adjustDbgWinPos(ctx); } else { ctx.adjustWinMax(ctx); } ctx.resizeMainHeight(); } }, onScroll: function() { var ctx = DebugJS.ctx; if (window.scrollX === undefined) { ctx.scrollPosX = document.documentElement.scrollLeft; ctx.scrollPosY = document.documentElement.scrollTop; } else { ctx.scrollPosX = window.scrollX; ctx.scrollPosY = window.scrollY; } ctx.updateScrollPosLabel(); if (ctx.status & DebugJS.ST_SYS_INFO) { ctx.updateSysInfoScrollPosLabel(ctx); } ctx.resizeMainHeight(); }, updateSysInfoScrollPosLabel: function(ctx) { document.getElementById(ctx.id + '-sys-scroll-x').innerHTML = DebugJS.setStyleIfObjNA(window.scrollX); document.getElementById(ctx.id + '-sys-scroll-y').innerHTML = DebugJS.setStyleIfObjNA(window.scrollY); document.getElementById(ctx.id + '-sys-pgoffset-x').innerText = window.pageXOffset; document.getElementById(ctx.id + '-sys-pgoffset-y').innerText = window.pageYOffset; document.getElementById(ctx.id + '-sys-cli-scroll-x').innerText = document.documentElement.scrollLeft; document.getElementById(ctx.id + '-sys-cli-scroll-y').innerText = document.documentElement.scrollTop; }, onMouseDown: function(e) { var ctx = DebugJS.ctx; var posX = e.clientX; var posY = e.clientY; switch (e.button) { case 0: ctx.mouseClick0 = DebugJS.COLOR_ACTIVE; if (ctx.status & DebugJS.ST_MEASURE) { ctx.startMeasure(ctx, posX, posY); } if (ctx.status & DebugJS.ST_STOPWATCH_LAPTIME) { DebugJS._log('<span style="color:' + ctx.opt.timerColor + '">' + DebugJS.getTimerStr(DebugJS.time.getCount(DebugJS.TIMER_NAME_SW_0)) + '</span>'); ctx.resetStopwatch(); } if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD) { DebugJS.bat._resume('cmd'); } break; case 1: ctx.mouseClick1 = DebugJS.COLOR_ACTIVE; break; case 2: ctx.mouseClick2 = DebugJS.COLOR_ACTIVE; if (ctx.status & DebugJS.ST_ELM_INSPECTING) { if (ctx.isOnDbgWin(posX, posY)) { if ((DebugJS.el) && (DebugJS.el != ctx.targetEl)) { ctx.showElementInfo(DebugJS.el); ctx.updateTargetElm(DebugJS.el); } } else { var pointedElm = document.elementFromPoint(posX, posY); ctx.captureElm(pointedElm); } } } if (ctx.opt.useMouseStatusInfo) { ctx.updateMouseClickLabel(); } }, onTouchStart: function(e) { var x = e.changedTouches[0].pageX; var y = e.changedTouches[0].pageY; if (DebugJS.ctx.status & DebugJS.ST_MEASURE) { DebugJS.ctx.startMeasure(DebugJS.ctx, x, y); e.preventDefault(); } }, onMouseMove: function(e) { var x = e.clientX; var y = e.clientY; DebugJS.ctx._onPointerMove(DebugJS.ctx, x, y); }, onTouchMove: function(e) { var x = e.changedTouches[0].pageX; var y = e.changedTouches[0].pageY; DebugJS.ctx._onPointerMove(DebugJS.ctx, x, y); }, _onPointerMove: function(ctx, x, y) { if (ctx.opt.useMouseStatusInfo) { ctx.mousePos.x = x; ctx.mousePos.y = y; ctx.updateMousePosLabel(); } if (ctx.uiStatus & DebugJS.UI_ST_DRAGGING) ctx.moveDbgWin(ctx, x, y); if (ctx.uiStatus & DebugJS.UI_ST_RESIZING) ctx.resizeDbgWin(ctx, x, y); if (ctx.status & DebugJS.ST_MEASURING) ctx.doMeasure(ctx, x, y); if (ctx.status & DebugJS.ST_ELM_INSPECTING) ctx.inspectElement(x, y); if (DebugJS.point.d) DebugJS.point.move(x, y, 0, 0); ctx.resizeMainHeight(); }, onMouseUp: function(e) { var ctx = DebugJS.ctx; switch (e.button) { case 0: ctx.mouseClick0 = DebugJS.COLOR_INACT; ctx._onPointerUp(ctx, e); break; case 1: ctx.mouseClick1 = DebugJS.COLOR_INACT; break; case 2: ctx.mouseClick2 = DebugJS.COLOR_INACT; } if (ctx.opt.useMouseStatusInfo) { ctx.updateMouseClickLabel(); } }, onTouchEnd: function(e) { DebugJS.ctx._onPointerUp(DebugJS.ctx, e); }, _onPointerUp: function(ctx, e) { var el = e.target; if (ctx.status & DebugJS.ST_MEASURING) { ctx.stopMeasure(ctx); } if (ctx.uiStatus & DebugJS.UI_ST_DRAGGING) { ctx.endMove(ctx); if ((el != ctx.extActivePanel) && (!DebugJS.isDescendant(el, ctx.extActivePanel))) { if (((new Date()).getTime() - ctx.ptOpTm) < 300) { ctx.focusCmdLine(); } } } if (ctx.uiStatus & DebugJS.UI_ST_RESIZING) { ctx.endResize(ctx); ctx.focusCmdLine(); } if (DebugJS.point.d) DebugJS.point.endDragging(); }, onDbgWinDblClick: function(e) { var ctx = DebugJS.ctx; var x = e.clientX; var y = e.clientY; if ((!ctx.isMovable(ctx, e.target, x, y)) || (!(ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE))) { return; } if (ctx.sizeStatus != DebugJS.SIZE_ST_NORMAL) { ctx.setWinSize('restore'); } else { ctx.expandDbgWin('expand'); } ctx.focusCmdLine(); }, expandDbgWin: function(mode) { var ctx = DebugJS.ctx; var sp = ctx.getSelfSizePos(); var border = DebugJS.WIN_BORDER * 2; if ((mode == 'expand') && (sp.w == DebugJS.DBGWIN_EXPAND_W + border) && (sp.h == DebugJS.DBGWIN_EXPAND_H + border)) { return; } ctx.saveSizeAndPos(ctx); switch (mode) { case 'full': ctx.setDbgWinFull(ctx); break; case 'expand': if ((sp.w < DebugJS.DBGWIN_EXPAND_W) && (sp.h < DebugJS.DBGWIN_EXPAND_H)) { ctx._expandDbgWin(ctx); } else { ctx._expandDbgWinAuto(ctx, sp); } break; case 'center': ctx._expandDbgWinCenter(ctx); break; default: ctx._expandDbgWinAuto(ctx, sp); } ctx.updateWinCtrlBtnPanel(); }, _expandDbgWin: function(ctx) { var sp = ctx.getSelfSizePos(); var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var expThrW = clientW * 0.6; var expThrH = clientH * 0.6; if ((sp.w > expThrW) || (sp.h > expThrH)) { ctx.setDbgWinFull(ctx); return; } var l = sp.x1 + 3; var t = sp.y1 + 3; var w = DebugJS.DBGWIN_EXPAND_W; var h = DebugJS.DBGWIN_EXPAND_H; if (sp.x1 > (clientW - sp.x2)) { l = (sp.x1 - (DebugJS.DBGWIN_EXPAND_W - sp.w)) + 1; } if (sp.y1 > (clientH - sp.y2)) { t = (sp.y1 - (DebugJS.DBGWIN_EXPAND_H - sp.h)) + 1; } if (l < 0) l = 0; if (clientH < DebugJS.DBGWIN_EXPAND_H) { t = clientH - DebugJS.DBGWIN_EXPAND_H; } ctx.saveSizeAndPos(ctx); ctx.setDbgWinPos(t, l); ctx.setDbgWinSize(w, h); ctx.sizeStatus = DebugJS.SIZE_ST_EXPANDED; ctx.updateWinCtrlBtnPanel(); }, _expandDbgWinAuto: function(ctx, sp) { if ((sp.w >= DebugJS.DBGWIN_EXPAND_W) && (sp.h >= DebugJS.DBGWIN_EXPAND_H)) { ctx.setDbgWinFull(ctx); return; } var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var expThrW = clientW * 0.6; var expThrH = clientH * 0.6; var w = 0, h = 0, t = 0, l = 0; if ((DebugJS.DBGWIN_EXPAND_W > clientW) || (sp.w > expThrW)) { w = clientW; ctx.sizeStatus |= DebugJS.SIZE_ST_FULL_W; if ((DebugJS.DBGWIN_EXPAND_H > clientH) || (sp.h > expThrH)) { h = clientH; } else { t = DebugJS.DBGWIN_POS_NONE; } } else { if ((DebugJS.DBGWIN_EXPAND_H > clientH) || (sp.h > expThrH)) { h = clientH; if ((DebugJS.DBGWIN_EXPAND_W < clientW) && (sp.w < expThrW)) { l = DebugJS.DBGWIN_POS_NONE; } } else { ctx.setDbgWinFull(ctx); return; } } ctx.setDbgWinPos(t, l); ctx.setDbgWinSize(w, h); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; if ((w == clientW) && (h == clientH)) { ctx.sizeStatus = DebugJS.SIZE_ST_FULL_WH; } else if (w == clientW) { ctx.sizeStatus = DebugJS.SIZE_ST_FULL_W; } else if (h == clientH) { ctx.sizeStatus = DebugJS.SIZE_ST_FULL_H; } }, _expandDbgWinCenter: function(ctx) { var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var w = DebugJS.DBGWIN_EXPAND_C_W; var h = DebugJS.DBGWIN_EXPAND_C_H; var l = clientW / 2 - w / 2; var t = clientH / 2 - h / 2; ctx.setDbgWinPos(t, l); ctx.setDbgWinSize(w, h); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.sizeStatus = DebugJS.SIZE_ST_EXPANDED_C; }, setDbgWinFull: function(ctx) { var w = document.documentElement.clientWidth; var h = document.documentElement.clientHeight; var t = 0, l = 0; ctx.setDbgWinPos(t, l); ctx.setDbgWinSize(w, h); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.sizeStatus = DebugJS.SIZE_ST_FULL_WH; ctx.disableDraggable(ctx); ctx.disableResize(ctx); }, setDbgWinPos: function(t, l) { if (t > DebugJS.DBGWIN_POS_NONE) DebugJS.ctx.win.style.top = t + 'px'; if (l > DebugJS.DBGWIN_POS_NONE) DebugJS.ctx.win.style.left = l + 'px'; }, setDbgWinSize: function(w, h) { var ctx = DebugJS.ctx; if (w > 0) ctx.win.style.width = w + 'px'; if (h > 0) ctx.win.style.height = h + 'px'; ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, adjustDbgWinPos: function(ctx) { var sp = ctx.getSelfSizePos(); ctx.setWinPos(ctx.opt.position, sp.w, sp.h); }, adjustWinMax: function(ctx) { if ((ctx.sizeStatus == DebugJS.SIZE_ST_FULL_W) || (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH)) { ctx.win.style.width = document.documentElement.clientWidth + 'px'; } if ((ctx.sizeStatus == DebugJS.SIZE_ST_FULL_H) || (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH)) { ctx.win.style.height = document.documentElement.clientHeight + 'px'; } ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, saveSizeAndPos: function(ctx) { ctx.saveSize(ctx); ctx.savePos(ctx); }, saveSize: function(ctx) { var shadow = (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) ? (DebugJS.WIN_SHADOW / 2) : 0; ctx.orgSizePos.w = (ctx.win.offsetWidth + DebugJS.WIN_BORDER - shadow); ctx.orgSizePos.h = (ctx.win.offsetHeight + DebugJS.WIN_BORDER - shadow); }, savePos: function(ctx) { ctx.orgSizePos.t = ctx.win.offsetTop; ctx.orgSizePos.l = ctx.win.offsetLeft; }, savePosNone: function(ctx) { ctx.orgSizePos.t = DebugJS.DBGWIN_POS_NONE; ctx.orgSizePos.l = DebugJS.DBGWIN_POS_NONE; }, restoreDbgWin: function() { var ctx = DebugJS.ctx; var w = ctx.orgSizePos.w; var h = ctx.orgSizePos.h; var t = ctx.orgSizePos.t; var l = ctx.orgSizePos.l; if (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH) { ctx.enableDraggable(ctx); ctx.enableResize(ctx); } else { var thold = 10; var sp = ctx.getSelfSizePos(); var orgY2 = t + h; var orgX2 = l + w; if (((Math.abs(sp.x1 - l) > thold) && (Math.abs(sp.x2 - orgX2) > thold)) || ((Math.abs(sp.y1 - t) > thold) && (Math.abs(sp.y2 - orgY2) > thold))) { var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var mL = (sp.x1 < 0 ? 0 : sp.x1); var mT = (sp.y1 < 0 ? 0 : sp.y1); var mR = clientW - sp.x2; var mB = clientH - sp.y2; if (mR < 0) mR = 0; if (mB < 0) mB = 0; t = sp.y1 + 3; l = sp.x1 + 3; if (mT > mB) { t = sp.y2 - h; if ((t > clientH) || (t + h > clientH)) { t = clientH - h; } t -= 6; } if (mL > mR) { l = sp.x2 - w; if ((l > clientW) || (l + w > clientW)) { l = clientW - w; } l -= 6; } if (l < 0) l = 0; if (t < 0) t = 0; } } ctx.setDbgWinSize(w, h); ctx.setDbgWinPos(t, l); ctx.scrollLogBtm(ctx); ctx.sizeStatus = DebugJS.SIZE_ST_NORMAL; if (ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) { ctx.adjustDbgWinPos(ctx); } }, resetDbgWinSizePos: function() { DebugJS.ctx._resetDbgWinSizePos(DebugJS.ctx); DebugJS.ctx.updateWinCtrlBtnPanel(); }, _resetDbgWinSizePos: function(ctx) { var w = (ctx.initWidth - (DebugJS.WIN_SHADOW / 2) + DebugJS.WIN_BORDER); var h = (ctx.initHeight - (DebugJS.WIN_SHADOW / 2) + DebugJS.WIN_BORDER); if (ctx.sizeStatus == DebugJS.SIZE_ST_FULL_WH) { ctx.enableDraggable(ctx); ctx.enableResize(ctx); } ctx.setWinPos(ctx.opt.position, ctx.initWidth, ctx.initHeight); ctx.setDbgWinSize(w, h); ctx.scrollLogBtm(ctx); ctx.saveExpandModeOrgSizeAndPos(ctx); ctx.sizeStatus = DebugJS.SIZE_ST_NORMAL; if (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) { ctx.uiStatus |= DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.adjustDbgWinPos(ctx); } }, isOutOfWin: function(ctx) { var sp = ctx.getSelfSizePos(); if ((sp.x1 > document.documentElement.clientWidth) || (sp.y1 > document.documentElement.clientHeight) || (sp.x2 < 0) || (sp.y2 < 0)) { return true; } return false; }, resetToOriginalPosition: function(ctx) { var sp = ctx.getSelfSizePos(); ctx.setWinPos(ctx.opt.position, sp.w, sp.h); if (ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) { ctx.uiStatus |= DebugJS.UI_ST_POS_AUTO_ADJUST; } }, showDbgWin: function() { var ctx = DebugJS.ctx; if ((ctx.win == null) || (ctx.uiStatus & DebugJS.UI_ST_PROTECTED)) return; ctx.win.style.display = 'block'; ctx.uiStatus |= DebugJS.UI_ST_VISIBLE; if ((ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) || ((ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) && (ctx.isOutOfWin(ctx)))) { ctx.uiStatus |= DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.adjustDbgWinPos(ctx); } else { ctx.adjustWinMax(ctx); } if (ctx.uiStatus & DebugJS.UI_ST_LOG_SCROLL) { ctx.scrollLogBtm(ctx); } ctx.resizeMainHeight(); }, showDbgWinOnError: function(ctx) { if ((ctx.status & DebugJS.ST_INITIALIZED) && !(ctx.uiStatus & DebugJS.UI_ST_VISIBLE)) { if (((ctx.errStatus) && (((ctx.opt.popupOnError.scriptError) && (ctx.errStatus & DebugJS.ERR_ST_SCRIPT)) || ((ctx.opt.popupOnError.loadError) && (ctx.errStatus & DebugJS.ERR_ST_LOAD)) || ((ctx.opt.popupOnError.errorLog) && (ctx.errStatus & DebugJS.ERR_ST_LOG)))) || ((ctx.status & DebugJS.ST_BAT_RUNNING) && (DebugJS.bat.hasBatStopCond('error')) && (DebugJS.bat.ctrl.stopReq))) { ctx.showDbgWin(); ctx.errStatus = DebugJS.ERR_ST_NONE; } } }, hideDbgWin: function(ctx) { if ((!ctx.opt.togglableShowHide) || (!ctx.win)) return; ctx.errStatus = DebugJS.ERR_ST_NONE; ctx.uiStatus &= ~DebugJS.UI_ST_DRAGGING; ctx.uiStatus &= ~DebugJS.UI_ST_VISIBLE; ctx.win.style.display = 'none'; }, closeDbgWin: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_MEASURE) { ctx.closeScreenMeasure(ctx); } if (ctx.status & DebugJS.ST_ELM_INSPECTING) { ctx.closeElmInfo(ctx); } ctx.hideDbgWin(ctx); }, lockDbgWin: function(ctx) { ctx.uiStatus |= DebugJS.UI_ST_PROTECTED; ctx.closeDbgWin(); }, focusCmdLine: function() { if (DebugJS.ctx.cmdLine) DebugJS.ctx.cmdLine.focus(); }, startMeasure: function(ctx, x, y) { if (ctx.isOnDbgWin(x, y)) return; ctx.status |= DebugJS.ST_MEASURING; ctx.clickedPosX = x; ctx.clickedPosY = y; if (ctx.measBox == null) { var el = document.createElement('div'); el.style.position = 'fixed'; el.style.zIndex = 0x7fffffff; el.style.top = y + 'px'; el.style.left = x + 'px'; el.style.width = '0px'; el.style.height = '0px'; el.style.border = 'dotted 1px #333'; el.style.background = 'rgba(0,0,0,0.1)'; ctx.measBox = el; ctx.bodyEl.appendChild(el); } ctx.disableTextSelect(ctx); }, doMeasure: function(ctx, posX, posY) { var deltaX = posX - ctx.clickedPosX; var deltaY = posY - ctx.clickedPosY; var clientW = document.documentElement.clientWidth; if (deltaX < 0) { ctx.measBox.style.left = posX + 'px'; deltaX *= -1; } if (deltaY < 0) { ctx.measBox.style.top = posY + 'px'; deltaY *= -1; } ctx.measBox.style.width = deltaX + 'px'; ctx.measBox.style.height = deltaY + 'px'; var sizeLabelW = 210; var sizeLabelH = 40; var sizeLabelY = (deltaY / 2) - (sizeLabelH / 2); var sizeLabelX = (deltaX / 2) - (sizeLabelW / 2); var originY = 'top'; var originX = 'left'; if (deltaX < sizeLabelW) { sizeLabelX = 0; if ((deltaY < sizeLabelH) || (deltaY > ctx.clickedPosY)) { if (ctx.clickedPosY < sizeLabelH) { sizeLabelY = deltaY; } else { sizeLabelY = sizeLabelH * (-1); } } else { sizeLabelY = sizeLabelH * (-1); } } if (posY < sizeLabelH) { if (ctx.clickedPosY > sizeLabelH) { sizeLabelY = (deltaY / 2) - (sizeLabelH / 2); } } if (((ctx.clickedPosX + sizeLabelW) > clientW) && ((posX + sizeLabelW) > clientW)) { sizeLabelX = (sizeLabelW - (clientW - ctx.clickedPosX)) * (-1); } if (posX < ctx.clickedPosX) originX = 'right'; if (posY < ctx.clickedPosY) originY = 'bottom'; var size = '<span style="font-family:' + ctx.opt.fontFamily + ';font-size:32px;color:#fff;background:rgba(0,0,0,0.7);padding:1px 3px;white-space:pre;position:relative;top:' + sizeLabelY + 'px;left:' + sizeLabelX + 'px">W=' + (deltaX | 0) + ' H=' + (deltaY | 0) + '</span>'; var origin = '<span style="font-family:' + ctx.opt.fontFamily + ';font-size:12px;color:#fff;background:rgba(0,0,0,0.3);white-space:pre;position:absolute;' + originY + ':1px;' + originX + ':1px;padding:1px">x=' + ctx.clickedPosX + ',y=' + ctx.clickedPosY + '</span>'; ctx.measBox.innerHTML = origin + size; }, stopMeasure: function(ctx) { if (ctx.measBox) { ctx.bodyEl.removeChild(ctx.measBox); ctx.measBox = null; } ctx.enableTextSelect(ctx); ctx.status &= ~DebugJS.ST_MEASURING; }, addOverlayPanel: function(ctx, panel) { if (ctx.overlayBasePanel == null) { ctx.collapseLogPanel(ctx); ctx.overlayBasePanel = document.createElement('div'); ctx.overlayBasePanel.className = 'dbg-overlay-base-panel'; ctx.mainPanel.appendChild(ctx.overlayBasePanel); //ctx.mainPanel.insertBefore(ctx.overlayBasePanel, ctx.logPanel); // to bottom } ctx.overlayBasePanel.appendChild(panel); ctx.overlayPanels.push(panel); }, removeOverlayPanel: function(ctx, panel) { if (ctx.overlayBasePanel) { for (var i = 0; i < ctx.overlayPanels.length; i++) { if (ctx.overlayPanels[i] == panel) { ctx.overlayPanels.splice(i, 1); ctx.overlayBasePanel.removeChild(panel); break; } } if (ctx.overlayPanels.length == 0) { ctx.mainPanel.removeChild(ctx.overlayBasePanel); ctx.overlayBasePanel = null; ctx.expandLogPanel(ctx); } } }, addOverlayPanelFull: function(panel) { DebugJS.ctx.mainPanel.appendChild(panel); }, removeOverlayPanelFull: function(panel) { if (panel.parentNode) { DebugJS.ctx.mainPanel.removeChild(panel); } }, toggleSystemInfo: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_SYS_INFO) { ctx.closeSystemInfo(ctx); } else { ctx.openSystemInfo(ctx); } }, openSystemInfo: function(ctx) { ctx.status |= DebugJS.ST_SYS_INFO; ctx.featStack.push(DebugJS.ST_SYS_INFO); if (!ctx.sysInfoPanel) ctx.createSysInfoPanel(ctx); ctx.updateSysInfoBtn(ctx); ctx.showSystemInfo(); ctx.setIntervalH(ctx); }, createSysInfoPanel: function(ctx) { ctx.sysInfoPanel = document.createElement('div'); ctx.sysInfoPanel.innerHTML = '<span style="color:' + DebugJS.SYS_BTN_COLOR + '">&lt;SYSTEM INFO&gt;</span><span style="float:right">v' + ctx.v + '</span>'; if (DebugJS.SYS_INFO_FULL_OVERLAY) { ctx.sysInfoPanel.className = 'dbg-overlay-panel-full'; ctx.addOverlayPanelFull(ctx.sysInfoPanel); } else { ctx.sysInfoPanel.className = 'dbg-overlay-panel'; ctx.addOverlayPanel(ctx, ctx.sysInfoPanel); ctx.expandHightIfNeeded(ctx); } ctx.sysTimePanel = document.createElement('div'); ctx.sysTimePanel.style.marginRight = '4px'; ctx.sysTimePanel.color = '#fff'; ctx.sysInfoPanel.appendChild(ctx.sysTimePanel); ctx.sysInfoPanelBody = document.createElement('div'); ctx.sysInfoPanelBody.style.top = ctx.computedFontSize; ctx.sysInfoPanel.appendChild(ctx.sysInfoPanelBody); ctx.updateSystemTime(); }, updateSystemTime: function() { if (!(DebugJS.ctx.status & DebugJS.ST_SYS_INFO)) return; var time = (new Date()).getTime(); var timeBin = DebugJS.formatBin(time.toString(2), false, 1); var html = '<pre><span style="color:' + DebugJS.ITEM_NAME_COLOR + '">SYSTEM TIME</span> : ' + DebugJS.convDateTimeStr(DebugJS.getDateTime(time)) + '\n' + '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '"> RAW</span> (new Date()).getTime() = ' + time + '\n' + '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '"> BIN</span> ' + timeBin + '\n</pre>'; DebugJS.ctx.sysTimePanel.innerHTML = html; setTimeout(DebugJS.ctx.updateSystemTime, DebugJS.UPDATE_INTERVAL_H); }, closeSystemInfo: function(ctx) { if (ctx.sysInfoPanel) { if (DebugJS.SYS_INFO_FULL_OVERLAY) { ctx.removeOverlayPanelFull(ctx.sysInfoPanel); } else { ctx.removeOverlayPanel(ctx, ctx.sysInfoPanel); ctx.resetExpandedHeightIfNeeded(ctx); } ctx.sysInfoPanel = null; } ctx.status &= ~DebugJS.ST_SYS_INFO; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_SYS_INFO); ctx.updateSysInfoBtn(ctx); ctx.setIntervalL(ctx); }, showSystemInfo: function(e) { var ctx = DebugJS.ctx; var INDENT = ' '; var offset = (new Date()).getTimezoneOffset(); var screenSize = 'width = ' + screen.width + ' x height = ' + screen.height; var languages = DebugJS.getLanguages(INDENT); var browser = DebugJS.getBrowserType(); var jq = '<span class="dbg-na">not loaded</span>'; if (typeof jQuery != 'undefined') jq = 'v' + jQuery.fn.jquery; var metaTags = document.getElementsByTagName('meta'); var charset; for (var i = 0; i < metaTags.length; i++) { charset = metaTags[i].getAttribute('charset'); if (charset) { break; } else { charset = metaTags[i].getAttribute('content'); if (charset) { var content = charset.match(/charset=(.*)/); if (content != null) { charset = content[1]; break; } } } } if (charset == null) charset = ''; var INDENT = ' '; var links = document.getElementsByTagName('link'); var loadedStyles = '<span class="dbg-na">not loaded</span>'; for (i = 0; i < links.length; i++) { if (links[i].rel == 'stylesheet') { if (i == 0) { loadedStyles = ctx.createFoldingText(links[i].href, 'linkHref' + i, DebugJS.OMIT_MID); } else { loadedStyles += '\n' + INDENT + ctx.createFoldingText(links[i].href, 'linkHref' + i, DebugJS.OMIT_MID); } } } var scripts = document.getElementsByTagName('script'); var loadedScripts = '<span class="dbg-na">not loaded</span>'; for (i = 0; i < scripts.length; i++) { if (scripts[i].src) { if (i == 0) { loadedScripts = ctx.createFoldingText(scripts[i].src, 'scriptSrc' + i, DebugJS.OMIT_MID); } else { loadedScripts += '\n' + INDENT + ctx.createFoldingText(scripts[i].src, 'scriptSrc' + i, DebugJS.OMIT_MID); } } } var navUserAgent = ctx.createFoldingText(navigator.userAgent, 'navUserAgent', DebugJS.OMIT_LAST); var navAppVersion = ctx.createFoldingText(navigator.appVersion, 'navAppVersion', DebugJS.OMIT_LAST); var winOnload = ctx.createFoldingText(window.onload, 'winOnload', DebugJS.OMIT_LAST); var winOnunload = ctx.createFoldingText(window.onunload, 'winOnunload', DebugJS.OMIT_LAST); var winOnclick = ctx.createFoldingText(window.onclick, 'winOnclick', DebugJS.OMIT_LAST); var winOnmousedown = ctx.createFoldingText(window.onmousedown, 'winOnmousedown', DebugJS.OMIT_LAST); var winOnmousemove = ctx.createFoldingText(window.onmousemove, 'winOnmousemove', DebugJS.OMIT_LAST); var winOnmouseup = ctx.createFoldingText(window.onmousedown, 'winOnmouseup', DebugJS.OMIT_LAST); var winOnkeydown = ctx.createFoldingText(window.onkeydown, 'winOnkeydown', DebugJS.OMIT_LAST); var winOnkeypress = ctx.createFoldingText(window.onkeypress, 'winOnkeypress', DebugJS.OMIT_LAST); var winOnkeyup = ctx.createFoldingText(window.onkeyup, 'winOnkeyup', DebugJS.OMIT_LAST); var winOncontextmenu = ctx.createFoldingText(window.oncontextmenu, 'winOncontextmenu', DebugJS.OMIT_LAST); var winOnresize = ctx.createFoldingText(window.oncontextmenu, 'winOnresize', DebugJS.OMIT_LAST); var winOnscroll = ctx.createFoldingText(window.oncontextmenu, 'winOnscroll', DebugJS.OMIT_LAST); var winOnselect = ctx.createFoldingText(window.oncontextmenu, 'winOnselect', DebugJS.OMIT_LAST); var winOnselectstart = ctx.createFoldingText(window.oncontextmenu, 'winOnselectstart', DebugJS.OMIT_LAST); var winOnerror = ctx.createFoldingText(window.onerror, 'winOnerror', DebugJS.OMIT_LAST); var docOnclick = ctx.createFoldingText(document.onclick, 'documentOnclick', DebugJS.OMIT_LAST); var docOnmousedown = ctx.createFoldingText(document.onmousedown, 'documentOnmousedown', DebugJS.OMIT_LAST); var docOnmousemove = ctx.createFoldingText(document.onmousemove, 'documentOnmousemove', DebugJS.OMIT_LAST); var docOnmouseup = ctx.createFoldingText(document.onmousedown, 'documentOnmouseup', DebugJS.OMIT_LAST); var docOnkeydown = ctx.createFoldingText(document.onkeydown, 'documentOnkeydown', DebugJS.OMIT_LAST); var docOnkeypress = ctx.createFoldingText(document.onkeypress, 'documentOnkeypress', DebugJS.OMIT_LAST); var docOnkeyup = ctx.createFoldingText(document.onkeyup, 'documentOnkeyup', DebugJS.OMIT_LAST); var docOnselectstart = ctx.createFoldingText(document.onselectstart, 'documentOnselectstart', DebugJS.OMIT_LAST); var docOncontextmenu = ctx.createFoldingText(document.oncontextmenu, 'documentOncontextmenu', DebugJS.OMIT_LAST); var html = '<pre>'; html += ' getTimezoneOffset() = ' + offset + ' (UTC' + DebugJS.getTimeOffsetStr(offset, true) + ')\n'; html += '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '">screen.</span> : ' + screenSize + '\n'; html += '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '">Browser</span> : ' + DebugJS.browserColoring(browser.name) + ' ' + browser.version + '\n'; html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('navigator'); html += DebugJS.addSysInfoProp('userAgent ', navUserAgent); html += DebugJS.addSysInfoProp('language ', DebugJS.setStyleIfObjNA(navigator.language)); html += DebugJS.addSysInfoProp('browserLanguage', DebugJS.setStyleIfObjNA(navigator.browserLanguage)); html += DebugJS.addSysInfoProp('userLanguage ', DebugJS.setStyleIfObjNA(navigator.userLanguage)); html += DebugJS.addSysInfoProp('languages ', languages); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('charset', charset); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('css ', loadedStyles); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('script ', loadedScripts); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('jQuery ', jq); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('window'); html += DebugJS.addSysInfoPropH(' location'); html += DebugJS.addSysInfoProp(' href ', ctx.createFoldingText(window.location, 'docLocation', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp(' origin ', ctx.createFoldingText(window.location.origin, 'origin', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp(' protocol', window.location.protocol); html += DebugJS.addSysInfoProp(' host ', ctx.createFoldingText(window.location.host, 'host', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp(' port ', window.location.port); html += DebugJS.addSysInfoProp(' pathname', ctx.createFoldingText(window.location.pathname, 'pathname', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp('devicePixelRatio', window.devicePixelRatio, 'sys-win-h'); html += DebugJS.addSysInfoProp('outerWidth ', window.outerWidth, 'sys-win-w'); html += DebugJS.addSysInfoProp('outerHeight ', window.outerHeight, 'sys-win-h'); html += DebugJS.addSysInfoProp('scrollX ', DebugJS.setStyleIfObjNA(window.scrollX), 'sys-scroll-x'); html += DebugJS.addSysInfoProp('pageXOffset ', window.pageXOffset, 'sys-pgoffset-x'); html += DebugJS.addSysInfoProp('scrollY ', DebugJS.setStyleIfObjNA(window.scrollY), 'sys-scroll-y'); html += DebugJS.addSysInfoProp('pageYOffset ', window.pageYOffset, 'sys-pgoffset-y'); html += DebugJS.addSysInfoProp('onload ', winOnload); html += DebugJS.addSysInfoProp('onunload ', winOnunload); html += DebugJS.addSysInfoProp('onclick ', winOnclick); html += DebugJS.addSysInfoProp('onmousedown ', winOnmousedown); html += DebugJS.addSysInfoProp('onmousemove ', winOnmousemove); html += DebugJS.addSysInfoProp('onmouseup ', winOnmouseup); html += DebugJS.addSysInfoProp('onkeydown ', winOnkeydown); html += DebugJS.addSysInfoProp('onkeypress ', winOnkeypress); html += DebugJS.addSysInfoProp('onkeyup ', winOnkeyup); html += DebugJS.addSysInfoProp('onresize ', winOnresize); html += DebugJS.addSysInfoProp('onscroll ', winOnscroll); html += DebugJS.addSysInfoProp('onselect ', winOnselect); html += DebugJS.addSysInfoProp('onselectstart', winOnselectstart); html += DebugJS.addSysInfoProp('oncontextmenu', winOncontextmenu); html += DebugJS.addSysInfoProp('onerror ', winOnerror); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('navigator'); html += DebugJS.addSysInfoProp('appCodeName ', DebugJS.setStyleIfObjNA(navigator.appCodeName)); html += DebugJS.addSysInfoProp('appName ', DebugJS.setStyleIfObjNA(navigator.appName)); html += DebugJS.addSysInfoProp('appVersion ', navAppVersion); html += DebugJS.addSysInfoProp('buildID ', DebugJS.setStyleIfObjNA(navigator.buildID)); html += DebugJS.addSysInfoProp('product ', DebugJS.setStyleIfObjNA(navigator.product)); html += DebugJS.addSysInfoProp('productSub ', DebugJS.setStyleIfObjNA(navigator.productSub)); html += DebugJS.addSysInfoProp('vendor ', DebugJS.setStyleIfObjNA(navigator.vendor)); html += DebugJS.addSysInfoProp('platform ', DebugJS.setStyleIfObjNA(navigator.platform)); html += DebugJS.addSysInfoProp('oscpu ', DebugJS.setStyleIfObjNA(navigator.oscpu)); html += DebugJS.addSysInfoProp('cookieEnabled', navigator.cookieEnabled); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('document'); html += DebugJS.addSysInfoPropH(' body'); html += DebugJS.addSysInfoProp(' clientWidth ', document.body.clientWidth, 'sys-body-w'); html += DebugJS.addSysInfoProp(' clientHeight', document.body.clientHeight, 'sys-body-h'); html += DebugJS.addSysInfoPropH(' documentElement'); html += DebugJS.addSysInfoProp(' clientWidth ', document.documentElement.clientWidth, 'sys-cli-w'); html += DebugJS.addSysInfoProp(' clientHeight', document.documentElement.clientHeight, 'sys-cli-h'); html += DebugJS.addSysInfoProp(' scrollLeft ', document.documentElement.scrollLeft, 'sys-cli-scroll-x'); html += DebugJS.addSysInfoProp(' scrollTop ', document.documentElement.scrollTop, 'sys-cli-scroll-y'); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('onclick ', docOnclick); html += DebugJS.addSysInfoProp('onmousedown ', docOnmousedown); html += DebugJS.addSysInfoProp('onmousemove ', docOnmousemove); html += DebugJS.addSysInfoProp('onmouseup ', docOnmouseup); html += DebugJS.addSysInfoProp('onkeydown ', docOnkeydown); html += DebugJS.addSysInfoProp('onkeypress ', docOnkeypress); html += DebugJS.addSysInfoProp('onkeyup ', docOnkeyup); html += DebugJS.addSysInfoProp('onselectstart', docOnselectstart); html += DebugJS.addSysInfoProp('oncontextmenu', docOncontextmenu); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoProp('baseURI ', ctx.createFoldingText(document.baseURI, 'docBaseURL', DebugJS.OMIT_MID)); html += DebugJS.addSysInfoProp('cookie', ctx.createFoldingText(document.cookie, 'cookie', DebugJS.OMIT_MID)); html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('localStorage'); if (DebugJS.LS_AVAILABLE) { html += ' <span class="dbg-btn" onclick="DebugJS.ctx.clearLocalStrage();">clear()</span>\n<span id="' + ctx.id + '-sys-ls"></span>\n'; html += DebugJS.ctx.createStorageEditor(ctx, 0); } else { html += ' <span class="dbg-na">undefined</span>'; } html += DebugJS.addPropSep(ctx); html += DebugJS.addSysInfoPropH('sessionStorage'); if (DebugJS.SS_AVAILABLE) { html += ' <span class="dbg-btn" onclick="DebugJS.ctx.clearSessionStrage();">clear()</span>\n<span id="' + ctx.id + '-sys-ss"></span>\n'; html += DebugJS.ctx.createStorageEditor(ctx, 1); } else { html += ' <span class="dbg-na">undefined</span>'; } html += DebugJS.addPropSep(ctx); html += '\n</pre>'; ctx.sysInfoPanelBody.innerHTML = html; if (DebugJS.LS_AVAILABLE) { ctx.updateStrageInfo(0); } if (DebugJS.SS_AVAILABLE) { ctx.updateStrageInfo(1); } }, clearLocalStrage: function() { localStorage.clear(); DebugJS.ctx.updateStrageInfo(0); }, removeLocalStrage: function(key) { localStorage.removeItem(key); DebugJS.ctx.updateStrageInfo(0); }, clearSessionStrage: function() { sessionStorage.clear(); DebugJS.ctx.updateStrageInfo(1); }, removeSessionStrage: function(key) { sessionStorage.removeItem(key); DebugJS.ctx.updateStrageInfo(1); }, updateStrageInfo: function(type) { var ctx = DebugJS.ctx; var strg, nm, rmvFn, id; if (type == 0) { strg = localStorage; nm = 'localStorage'; rmvFn = 'removeLocalStrage'; id = 'ls'; } else { strg = sessionStorage; nm = 'sessionStorage'; rmvFn = 'removeSessionStrage'; id = 'ss'; } var html = ' <span style="color:' + DebugJS.ITEM_NAME_COLOR + '">length</span> = ' + strg.length + '\n' + ' <span style="color:' + DebugJS.ITEM_NAME_COLOR + '">key</span>'; if (DebugJS.LS_AVAILABLE) { for (var i = 0; i < strg.length; i++) { var key = strg.key(i); if (i != 0) html += '\n '; var getCode = nm + '.getItem(\'' + key + '\')'; var rmvCode = nm + '.removeItem(\'' + key + '\')'; html += '(' + i + ') = ' + '<span class="dbg-btn dbg-btn-wh" onclick="DebugJS.ctx.setStrgEdit(' + type + ', ' + getCode + ', \'' + key + '\');" title="' + getCode + '">' + (key == '' ? ' ' : key) + '</span>' + ' <span class="dbg-btn dbg-btn-red" onclick="DebugJS.ctx.' + rmvFn + '(\'' + key + '\');" title="' + rmvCode + '">x</span>'; } } document.getElementById(ctx.id + '-sys-' + id).innerHTML = html; }, createStorageEditor: function(ctx, type) { return '<textarea id="' + ctx.id + '-strg' + type + '" class="dbg-editor dbg-strg"></textarea>\n' + ' <span class="dbg-btn" onclick="DebugJS.ctx.setStrg(' + type + ');">setItem</span>(\'<input id="' + ctx.id + '-strgkey' + type + '" class="dbg-txtbox dbg-strgkey">\', v);'; }, setStrgEdit: function(type, v, k) { document.getElementById(DebugJS.ctx.id + '-strg' + type).value = v; document.getElementById(DebugJS.ctx.id + '-strgkey' + type).value = k; }, setStrg: function(type) { var v = document.getElementById(DebugJS.ctx.id + '-strg' + type).value; var k = document.getElementById(DebugJS.ctx.id + '-strgkey' + type).value; var strg = localStorage; if (type == 1) strg = sessionStorage; strg.setItem(k, v); DebugJS.ctx.updateStrageInfo(type); }, showHideByName: function(name) { var ctx = DebugJS.ctx; var btn = document.getElementById(ctx.id + '-' + name + '__button'); var partialBody = document.getElementById(ctx.id + '-' + name + '__partial-body'); var body = document.getElementById(ctx.id + '-' + name + '__body'); if ((body) && ((!body.style.display) || (body.style.display == 'none'))) { btn.innerHTML = DebugJS.CLOSEBTN; partialBody.style.display = 'none'; body.style.display = 'block'; if (ctx.elmInfoShowHideStatus[name] != undefined) { ctx.elmInfoShowHideStatus[name] = true; } } else { btn.innerHTML = DebugJS.EXPANDBTN; partialBody.style.display = 'inline'; body.style.display = 'none'; if (ctx.elmInfoShowHideStatus[name] != undefined) { ctx.elmInfoShowHideStatus[name] = false; } } }, createFoldingText: function(obj, name, omitpart, lineMaxLen, style, show) { var ctx = DebugJS.ctx; var DFLT_MAX_LEN = 50; var foldingText; if ((lineMaxLen == undefined) || (lineMaxLen < 0)) lineMaxLen = DFLT_MAX_LEN; if (!style) style = 'color:#aaa'; if (!obj) { foldingText = '<span class="dbg-na">' + obj + '</span>'; } else { var btn = DebugJS.EXPANDBTN; var partDisp = 'inline'; var bodyDisp = 'none'; if (show) { btn = DebugJS.CLOSEBTN; partDisp = 'none'; bodyDisp = 'block'; } foldingText = obj + ''; if ((foldingText.indexOf('\n') >= 1) || (foldingText.length > lineMaxLen)) { partial = DebugJS.trimDownText2(foldingText, lineMaxLen, omitpart, style); foldingText = '<span class="dbg-showhide-btn dbg-nomove" id="' + ctx.id + '-' + name + '__button" onclick="DebugJS.ctx.showHideByName(\'' + name + '\')">' + btn + '</span> ' + '<span id="' + ctx.id + '-' + name + '__partial-body" style="display:' + partDisp + '">' + partial + '</span>' + '<div style="display:' + bodyDisp + '" id="' + ctx.id + '-' + name + '__body">' + obj + '</div>'; } else { foldingText = obj; } } return foldingText; }, toggleElmInfo: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_ELM_INSPECTING) { ctx.closeElmInfo(ctx); } else { ctx.openElmInfo(ctx); } }, openElmInfo: function(ctx) { ctx.status |= DebugJS.ST_ELM_INSPECTING; ctx.featStack.push(DebugJS.ST_ELM_INSPECTING); if (!ctx.elmInfoPanel) ctx.createElmInfoPanel(ctx); ctx.updateElmInfoBtn(ctx); ctx.updateElmSelectBtn(); ctx.updateElmHighlightBtn(); }, createElmInfoPanel: function(ctx) { ctx.elmInfoPanel = document.createElement('div'); if (DebugJS.ELM_INFO_FULL_OVERLAY) { ctx.elmInfoPanel.className = 'dbg-overlay-panel-full'; ctx.addOverlayPanelFull(ctx.elmInfoPanel); } else { ctx.elmInfoPanel.className = 'dbg-overlay-panel'; ctx.addOverlayPanel(ctx, ctx.elmInfoPanel); ctx.expandHightIfNeeded(ctx); } ctx.elmInfoHeaderPanel = document.createElement('div'); ctx.elmInfoPanel.appendChild(ctx.elmInfoHeaderPanel); ctx.elmPrevBtn = ctx.createElmInfoHeadBtn('<<', ctx.showPrevElem); ctx.enablePrevElBtn(ctx, false); ctx.elmTitle = document.createElement('span'); ctx.elmTitle.style.marginLeft = '4px'; ctx.elmTitle.style.marginRight = '4px'; ctx.setStyle(ctx.elmTitle, 'color', DebugJS.DOM_BTN_COLOR); ctx.elmTitle.innerText = 'ELEMENT INFO'; ctx.elmInfoHeaderPanel.appendChild(ctx.elmTitle); ctx.elmNextBtn = ctx.createElmInfoHeadBtn('>>', ctx.showNextElem); ctx.enableNextElBtn(ctx, false); ctx.elmSelectBtn = ctx.createElmInfoHeadBtn('SELECT', ctx.toggleElmSelectMode); ctx.elmSelectBtn.style.marginLeft = '8px'; ctx.elmSelectBtn.style.marginRight = '4px'; ctx.elmHighlightBtn = ctx.createElmInfoHeadBtn('HIGHLIGHT', ctx.toggleElmHlMode); ctx.elmHighlightBtn.style.marginLeft = '4px'; ctx.elmHighlightBtn.style.marginRight = '4px'; ctx.elmUpdateBtn = ctx.createElmInfoHeadBtn('UPDATE', ctx.updateElementInfo); ctx.elmUpdateBtn.style.marginLeft = '4px'; ctx.setStyle(ctx.elmUpdateBtn, 'color', DebugJS.COLOR_INACT); var UPDATE_COLOR = '#ccc'; var label1 = DebugJS.ui.addLabel(ctx.elmInfoHeaderPanel, ':'); label1.style.marginRight = '0px'; ctx.setStyle(label1, 'color', UPDATE_COLOR); ctx.elmUpdateInput = DebugJS.ui.addTextInput(ctx.elmInfoHeaderPanel, '30px', 'right', UPDATE_COLOR, ctx.elmUpdateInterval, ctx.onchangeElmUpdateInterval); var label2 = DebugJS.ui.addLabel(ctx.elmInfoHeaderPanel, 'ms'); label2.style.marginLeft = '2px'; ctx.setStyle(label2, 'color', UPDATE_COLOR); ctx.elmNumPanel = document.createElement('span'); ctx.elmNumPanel.style.float = 'right'; ctx.elmNumPanel.style.marginRight = '4px'; ctx.elmInfoHeaderPanel.appendChild(ctx.elmNumPanel); ctx.elmDelBtn = ctx.createElmInfoHeadBtn('DEL', ctx.delTargetElm); ctx.elmDelBtn.style.float = 'right'; ctx.elmDelBtn.style.marginRight = '4px'; ctx.setStyle(ctx.elmDelBtn, 'color', DebugJS.COLOR_INACT); ctx.elmCapBtn = ctx.createElmInfoHeadBtn('CAPTURE', ctx.exportTargetElm); ctx.elmCapBtn.style.float = 'right'; ctx.elmCapBtn.style.marginRight = '4px'; ctx.setStyle(ctx.elmCapBtn, 'color', DebugJS.COLOR_INACT); ctx.elmInfoBodyPanel = document.createElement('div'); ctx.elmInfoBodyPanel.style.width = '100%'; ctx.elmInfoBodyPanel.style.height = 'calc(100% - 1.3em)'; ctx.elmInfoBodyPanel.style.overflow = 'auto'; ctx.elmInfoPanel.appendChild(ctx.elmInfoBodyPanel); ctx.updateElmInfoInterval(); }, createElmInfoHeadBtn: function(label, handler) { return DebugJS.ui.addBtn(DebugJS.ctx.elmInfoHeaderPanel, label, handler); }, closeElmInfo: function(ctx) { if (ctx.targetEl) { if (typeof ctx.targetEl.className == 'string') { DebugJS.removeClass(ctx.targetEl, ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX); } ctx.targetEl = null; } if (ctx.elmInfoPanel) { if (DebugJS.ELM_INFO_FULL_OVERLAY) { ctx.removeOverlayPanelFull(ctx.elmInfoPanel); } else { ctx.removeOverlayPanel(ctx, ctx.elmInfoPanel); ctx.resetExpandedHeightIfNeeded(ctx); } ctx.elmInfoPanel = null; ctx.elmInfoBodyPanel = null; ctx.elmNumPanel = null; } ctx.updateTargetElm(null); ctx.status &= ~DebugJS.ST_ELM_INSPECTING; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_ELM_INSPECTING); ctx.updateElmInfoBtn(ctx); }, inspectElement: function(x, y) { var ctx = DebugJS.ctx; if ((!(ctx.elmInfoStatus & DebugJS.ELMINFO_ST_SELECT)) || (ctx.isOnDbgWin(x, y))) return; var el = document.elementFromPoint(x, y); if (el != ctx.targetEl) { ctx.showElementInfo(el); ctx.updateTargetElm(el); } }, showElementInfo: function(el) { var ctx = DebugJS.ctx; var html = '<pre>'; if (el && el.tagName) { html += ctx.getElmInfo(ctx, el); } html += '</pre>'; ctx.elmInfoBodyPanel.innerHTML = html; ctx.showAllElmNum(); }, getElmInfo: function(ctx, el) { var OMIT_STYLE = 'color:#888'; var OMIT_STYLE2 = 'color:#666'; DebugJS.dom = el; var computedStyle = window.getComputedStyle(el); var rect = el.getBoundingClientRect(); var rectT = Math.round(rect.top); var rectL = Math.round(rect.left); var rectR = Math.round(rect.right); var rectB = Math.round(rect.bottom); var MAX_LEN = 50; var text = ''; if ((el.tagName != 'HTML') && (el.tagName != 'BODY')) { if (el.tagName == 'META') { text = DebugJS.escTags(el.outerHTML); } else { if (el.innerText != undefined) { text = DebugJS.escTags(el.innerText); } } } var txt = ctx.createFoldingText(text, 'text', DebugJS.OMIT_LAST, MAX_LEN, OMIT_STYLE, ctx.elmInfoShowHideStatus.text); var className = el.className + ''; className = className.replace(ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX, '<span style="' + OMIT_STYLE2 + '">' + ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX + '</span>'); var href = (el.href ? ctx.createFoldingText(el.href, 'elHref', DebugJS.OMIT_MID, MAX_LEN, OMIT_STYLE) : DebugJS.setStyleIfObjNA(el.href)); var src = (el.src ? ctx.createFoldingText(el.src, 'elSrc', DebugJS.OMIT_MID, MAX_LEN, OMIT_STYLE) : DebugJS.setStyleIfObjNA(el.src)); var backgroundColor = computedStyle.backgroundColor; var bgColor16 = DebugJS.getElmHexColor(backgroundColor); var color = computedStyle.color; var color16 = DebugJS.getElmHexColor(color); var borderColorT = computedStyle.borderTopColor; var borderColorT16 = DebugJS.getElmHexColor(borderColorT); var borderColorR = computedStyle.borderRightColor; var borderColorR16 = DebugJS.getElmHexColor(borderColorR); var borderColorB = computedStyle.borderBottomColor; var borderColorB16 = DebugJS.getElmHexColor(borderColorB); var borderColorL = computedStyle.borderLeftColor; var borderColorL16 = DebugJS.getElmHexColor(borderColorL); var borderT = 'top : ' + computedStyle.borderTopWidth + ' ' + computedStyle.borderTopStyle + ' ' + borderColorT + ' ' + borderColorT16 + ' ' + DebugJS.getColorBlock(borderColorT); var borderRBL = ' right : ' + computedStyle.borderRightWidth + ' ' + computedStyle.borderRightStyle + ' ' + borderColorR + ' ' + borderColorR16 + ' ' + DebugJS.getColorBlock(borderColorR) + '\n' + ' bottom: ' + computedStyle.borderBottomWidth + ' ' + computedStyle.borderBottomStyle + ' ' + borderColorR + ' ' + borderColorB16 + ' ' + DebugJS.getColorBlock(borderColorB) + '\n' + ' left : ' + computedStyle.borderLeftWidth + ' ' + computedStyle.borderLeftStyle + ' ' + borderColorL + ' ' + borderColorL16 + ' ' + DebugJS.getColorBlock(borderColorL); var allStyles = ''; var MIN_KEY_LEN = 20; for (var k in computedStyle) { if (!(k.match(/^\d.*/))) { if (typeof computedStyle[k] != 'function') { var indent = ''; if (k.length < MIN_KEY_LEN) { for (var i = 0; i < (MIN_KEY_LEN - k.length); i++) { indent += ' '; } } allStyles += ' ' + k + indent + ': ' + computedStyle[k] + '\n'; } } } allStylesFolding = ctx.createFoldingText(allStyles, 'allStyles', DebugJS.OMIT_LAST, 0, OMIT_STYLE, ctx.elmInfoShowHideStatus.allStyles); var name = (el.name == undefined) ? DebugJS.setStyleIfObjNA(el.name) : DebugJS.escTags(el.name); var val = (el.value == undefined) ? DebugJS.setStyleIfObjNA(el.value) : DebugJS.escSpclChr(el.value); var html = '<span style="color:#8f0;display:inline-block;height:14px">#text</span> ' + txt + '\n' + DebugJS.addPropSep(ctx) + 'id : ' + el.id + '\n' + 'className : ' + className + '\n' + DebugJS.addPropSep(ctx) + 'object : ' + Object.prototype.toString.call(el) + '\n' + 'tagName : ' + el.tagName + '\n' + 'type : ' + DebugJS.setStyleIfObjNA(el.type) + '\n' + DebugJS.addPropSep(ctx) + 'display : ' + computedStyle.display + '\n' + 'position : ' + computedStyle.position + '\n' + 'z-index : ' + computedStyle.zIndex + '\n' + 'float : ' + computedStyle.cssFloat + ' / clear: ' + computedStyle.clear + '\n' + 'size : W:' + ((rectR - rectL) + 1) + ' x H:' + ((rectB - rectT) + 1) + ' px\n' + 'margin : ' + computedStyle.marginTop + ' ' + computedStyle.marginRight + ' ' + computedStyle.marginBottom + ' ' + computedStyle.marginLeft + '\n' + 'border : ' + borderT + ' ' + ctx.createFoldingText(borderRBL, 'elBorder', DebugJS.OMIT_LAST, 0, OMIT_STYLE, ctx.elmInfoShowHideStatus.elBorder) + '\n' + 'padding : ' + computedStyle.paddingTop + ' ' + computedStyle.paddingRight + ' ' + computedStyle.paddingBottom + ' ' + computedStyle.paddingLeft + '\n' + 'lineHeight: ' + computedStyle.lineHeight + '\n' + DebugJS.addPropSep(ctx) + 'location : <span style="color:#aaa">winOffset + pageOffset = pos (computedStyle)</span>\n' + ' top : ' + rectT + ' + ' + window.pageYOffset + ' = ' + Math.round(rect.top + window.pageYOffset) + ' px (' + computedStyle.top + ')\n' + ' left : ' + rectL + ' + ' + window.pageXOffset + ' = ' + Math.round(rect.left + window.pageXOffset) + ' px (' + computedStyle.left + ')\n' + ' right : ' + rectR + ' + ' + window.pageXOffset + ' = ' + Math.round(rect.right + window.pageXOffset) + ' px (' + computedStyle.right + ')\n' + ' bottom: ' + rectB + ' + ' + window.pageYOffset + ' = ' + Math.round(rect.bottom + window.pageYOffset) + ' px (' + computedStyle.bottom + ')\n' + 'scroll : top = ' + el.scrollTop + ' / left = ' + el.scrollLeft + '\n' + 'overflow : ' + computedStyle.overflow + '\n' + 'opacity : ' + computedStyle.opacity + '\n' + DebugJS.addPropSep(ctx) + 'bg-color : ' + backgroundColor + ' ' + bgColor16 + ' ' + DebugJS.getColorBlock(backgroundColor) + '\n' + 'bg-image : ' + ctx.createFoldingText(computedStyle.backgroundImage, 'bgimg', DebugJS.OMIT_LAST, -1, OMIT_STYLE) + '\n' + 'color : ' + color + ' ' + color16 + ' ' + DebugJS.getColorBlock(color) + '\n' + 'font : -size : ' + computedStyle.fontSize + '\n' + ' -family: ' + computedStyle.fontFamily + '\n' + ' -weight: ' + computedStyle.fontWeight + '\n' + ' -style : ' + computedStyle.fontStyle + '\n' + DebugJS.addPropSep(ctx) + 'All Styles: window.getComputedStyle(element) ' + allStylesFolding + '\n' + DebugJS.addPropSep(ctx) + 'action : ' + DebugJS.setStyleIfObjNA(el.action) + '\n' + 'method : ' + DebugJS.setStyleIfObjNA(el.method) + '\n' + 'name : ' + name + '\n' + 'value : ' + ctx.createFoldingText(val, 'elValue', DebugJS.OMIT_LAST, MAX_LEN, OMIT_STYLE) + '\n' + 'disabled : ' + DebugJS.setStyleIfObjNA(el.disabled, true) + '\n' + 'hidden : ' + el.hidden + '\n' + 'tabIndex : ' + el.tabIndex + '\n' + 'accessKey : ' + el.accessKey + '\n' + 'maxLength : ' + DebugJS.setStyleIfObjNA(el.maxLength) + '\n' + 'checked : ' + DebugJS.setStyleIfObjNA(el.checked, true) + '\n' + 'htmlFor : ' + DebugJS.setStyleIfObjNA(el.htmlFor) + '\n' + 'selectedIndex: ' + DebugJS.setStyleIfObjNA(el.selectedIndex) + '\n' + 'contentEditable: ' + el.contentEditable + '\n' + DebugJS.addPropSep(ctx) + 'href : ' + href + '\n' + 'src : ' + src + '\n' + DebugJS.addPropSep(ctx) + 'onclick : ' + ctx.getEvtHandlerStr(el.onclick, 'elOnclick') + '\n' + 'ondblclick : ' + ctx.getEvtHandlerStr(el.ondblclick, 'elOnDblClick') + '\n' + 'onmousedown : ' + ctx.getEvtHandlerStr(el.onmousedown, 'elOnMouseDown') + '\n' + 'onmouseup : ' + ctx.getEvtHandlerStr(el.onmouseup, 'elOnMouseUp') + '\n' + 'onmouseover : ' + ctx.getEvtHandlerStr(el.onmouseover, 'elOnMouseOver') + '\n' + 'onmouseout : ' + ctx.getEvtHandlerStr(el.onmouseout, 'elOnMouseOut') + '\n' + 'onmousemove : ' + ctx.getEvtHandlerStr(el.onmousemove, 'elOnMouseMove') + '\n' + 'oncontextmenu: ' + ctx.getEvtHandlerStr(el.oncontextmenu, 'elOnContextmenu') + '\n' + DebugJS.addPropSep(ctx) + 'onkeydown : ' + ctx.getEvtHandlerStr(el.onkeydown, 'elOnKeyDown') + '\n' + 'onkeypress : ' + ctx.getEvtHandlerStr(el.onkeypress, 'elOnKeyPress') + '\n' + 'onkeyup : ' + ctx.getEvtHandlerStr(el.onkeyup, 'elOnKeyUp') + '\n' + DebugJS.addPropSep(ctx) + 'onfocus : ' + ctx.getEvtHandlerStr(el.onfocus, 'elOnFocus') + '\n' + 'onblur : ' + ctx.getEvtHandlerStr(el.onblur, 'elOnBlur') + '\n' + 'onchange : ' + ctx.getEvtHandlerStr(el.onchange, 'elOnChange') + '\n' + 'oninput : ' + ctx.getEvtHandlerStr(el.oninput, 'elOnInput') + '\n' + 'onselect : ' + ctx.getEvtHandlerStr(el.onselect, 'elOnSelect') + '\n' + 'onselectstart: ' + ctx.getEvtHandlerStr(el.onselectstart, 'elOnSelectStart') + '\n' + 'onsubmit : ' + ctx.getEvtHandlerStr(el.onsubmit, 'elOnSubmit') + '\n' + DebugJS.addPropSep(ctx) + 'onscroll : ' + ctx.getEvtHandlerStr(el.onscroll, 'elOnScroll') + '\n' + DebugJS.addPropSep(ctx) + 'dataset (data-*):\n'; if (el.dataset) { html += '{' + ((Object.keys(el.dataset).length > 0) ? '\n' : ''); for (var data in el.dataset) { html += ' ' + data + ': ' + el.dataset[data] + '\n'; } html += '}'; } else { html += '<span style="color:#aaa">' + el.dataset + '</span>'; } var htmlSrc = (el.outerHTML ? el.outerHTML.replace(/</g, '&lt;').replace(/>/g, '&gt;') : DebugJS.setStyleIfObjNA(el.outerHTML)); htmlSrc = ctx.createFoldingText(htmlSrc, 'htmlSrc', DebugJS.OMIT_LAST, 0, OMIT_STYLE, ctx.elmInfoShowHideStatus.htmlSrc); html += DebugJS.addPropSep(ctx) + 'outerHTML: ' + htmlSrc; return html; }, showPrevElem: function() { var ctx = DebugJS.ctx; if (!ctx.targetEl) return; var el = ctx.getPrevElm(ctx, ctx.targetEl); if (el) { ctx.showElementInfo(el); ctx.updateTargetElm(el); } }, showNextElem: function() { var ctx = DebugJS.ctx; if (!ctx.targetEl) return; var el = ctx.getNextElm(ctx, ctx.targetEl); if (el) { ctx.showElementInfo(el); ctx.updateTargetElm(el); } }, getPrevElm: function(ctx, targetElm) { var el = targetElm.previousElementSibling; if ((el != null) && (el.id == ctx.id)) { el = targetElm.previousElementSibling; } if (el == null) { el = targetElm.parentNode; } else { if (el.childElementCount > 0) { var lastChild = el.lastElementChild; while (lastChild.childElementCount > 0) { lastChild = lastChild.lastElementChild; } el = lastChild; } } if (el instanceof HTMLDocument) el = null; return el; }, getNextElm: function(ctx, targetElm) { var el = targetElm.firstElementChild; if ((el == null) || ((el != null) && (el.id == ctx.id))) { el = targetElm.nextElementSibling; if (el == null) { var parent = targetElm.parentNode; if (parent) { do { el = parent.nextElementSibling; if ((el != null) && (el.id != ctx.id)) { break; } parent = parent.parentNode; } while ((parent != null) && (parent.tagName != 'HTML')); } } } return el; }, updateTargetElm: function(el) { var ctx = DebugJS.ctx; if (ctx.elmInfoStatus & DebugJS.ELMINFO_ST_HIGHLIGHT) { ctx.highlightElement(ctx.targetEl, el); } if (el) { ctx.targetEl = el; ctx.enablePrevElBtn(ctx, (ctx.getPrevElm(ctx, el) ? true : false)); ctx.enableNextElBtn(ctx, (ctx.getNextElm(ctx, el) ? true : false)); ctx.setStyle(ctx.elmUpdateBtn, 'color', ctx.opt.btnColor); ctx.setStyle(ctx.elmCapBtn, 'color', ctx.opt.btnColor); ctx.setStyle(ctx.elmDelBtn, 'color', '#a88'); } }, highlightElement: function(removeTarget, setTarget) { if ((removeTarget) && (typeof removeTarget.className == 'string')) { DebugJS.removeClass(removeTarget, DebugJS.ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX); } if ((setTarget) && (typeof setTarget.className == 'string')) { DebugJS.addClass(setTarget, DebugJS.ctx.id + DebugJS.ELM_HL_CLASS_SUFFIX); } }, enablePrevElBtn: function(ctx, f) { ctx.setStyle(ctx.elmPrevBtn, 'color', (f ? ctx.opt.btnColor : DebugJS.COLOR_INACT)); }, enableNextElBtn: function(ctx, f) { ctx.setStyle(ctx.elmNextBtn, 'color', (f ? ctx.opt.btnColor : DebugJS.COLOR_INACT)); }, updateElementInfo: function() { DebugJS.ctx.showAllElmNum(); DebugJS.ctx.showElementInfo(DebugJS.ctx.targetEl); }, showAllElmNum: function() { DebugJS.ctx.elmNumPanel.innerHTML = '(All: ' + document.getElementsByTagName('*').length + ')'; }, onchangeElmUpdateInterval: function() { var ctx = DebugJS.ctx; var v = ctx.elmUpdateInput.value; if (v == '') v = 0; if (isFinite(v)) { ctx.elmUpdateInterval = v; clearTimeout(ctx.elmUpdateTimerId); ctx.elmUpdateTimerId = setTimeout(ctx.updateElmInfoInterval, v); } }, updateElmInfoInterval: function() { var ctx = DebugJS.ctx; if (!(ctx.status & DebugJS.ST_ELM_INSPECTING)) return; ctx.updateElementInfo(); if (ctx.elmUpdateInterval > 0) { ctx.elmUpdateTimerId = setTimeout(ctx.updateElmInfoInterval, ctx.elmUpdateInterval); } }, toggleElmSelectMode: function() { var ctx = DebugJS.ctx; if (ctx.elmInfoStatus & DebugJS.ELMINFO_ST_SELECT) { ctx.elmInfoStatus &= ~DebugJS.ELMINFO_ST_SELECT; } else { ctx.elmInfoStatus |= DebugJS.ELMINFO_ST_SELECT; } ctx.updateElmSelectBtn(); }, updateElmSelectBtn: function() { DebugJS.ctx.setStyle(DebugJS.ctx.elmSelectBtn, 'color', (DebugJS.ctx.elmInfoStatus & DebugJS.ELMINFO_ST_SELECT) ? DebugJS.ctx.opt.btnColor : DebugJS.COLOR_INACT); }, toggleElmHlMode: function() { var ctx = DebugJS.ctx; if (ctx.elmInfoStatus & DebugJS.ELMINFO_ST_HIGHLIGHT) { ctx.elmInfoStatus &= ~DebugJS.ELMINFO_ST_HIGHLIGHT; ctx.highlightElement(ctx.targetEl, null); } else { ctx.elmInfoStatus |= DebugJS.ELMINFO_ST_HIGHLIGHT; ctx.highlightElement(null, ctx.targetEl); } ctx.updateElmHighlightBtn(); }, updateElmHighlightBtn: function() { DebugJS.ctx.setStyle(DebugJS.ctx.elmHighlightBtn, 'color', (DebugJS.ctx.elmInfoStatus & DebugJS.ELMINFO_ST_HIGHLIGHT) ? DebugJS.ctx.opt.btnColor : DebugJS.COLOR_INACT); }, exportTargetElm: function() { if (DebugJS.ctx.targetEl) DebugJS.ctx.captureElm(DebugJS.ctx.targetEl); }, captureElm: function(elm) { DebugJS.el = elm; if (DebugJS.G_EL_AVAILABLE) el = elm; if (DebugJS.ctx.status & DebugJS.ST_ELM_EDIT) { DebugJS.ctx.updateEditable(DebugJS.ctx, elm); } DebugJS._log.s('&lt;' + elm.tagName + '&gt; object has been exported to <span style="color:' + DebugJS.KEYWORD_COLOR + '">' + (DebugJS.G_EL_AVAILABLE ? 'el' : ((dbg == DebugJS) ? 'dbg' : 'DebugJS') + '.el') + '</span>'); }, delTargetElm: function() { var e = DebugJS.ctx.targetEl; if (e) { var p = e.parentNode; if (p) { p.removeChild(e); DebugJS.ctx.showElementInfo(p); DebugJS.ctx.updateTargetElm(p); } } }, updateEditable: function(ctx, el) { if ((ctx.txtChkTargetEl) && (ctx.txtChkTargetEl.contentEditableBak)) { ctx.txtChkTargetEl.contentEditable = ctx.txtChkTargetEl.contentEditableBak; } ctx.txtChkTargetEl = el; ctx.txtChkTargetEl.contentEditableBak = el.contentEditable; ctx.txtChkTargetEl.contentEditable = true; }, getEvtHandlerStr: function(handler, name) { var MAX_LEN = 300; var s = ''; if (handler) { s = handler.toString(); s = s.replace(/\n/g, ''); s = s.replace(/[^.]{1,}\{/, ''); s = s.replace(/\}$/, ''); s = s.replace(/^\s{1,}/, ''); } else { s = '<span style="color:#aaa">null</span>'; } s = DebugJS.ctx.createFoldingText(s, name, DebugJS.OMIT_LAST, MAX_LEN, 'color:#888'); return s; }, toggleHtmlSrc: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_HTML_SRC) { ctx.closeHtmlSrc(ctx); } else { ctx.openHtmlSrc(ctx); } }, openHtmlSrc: function(ctx) { ctx.status |= DebugJS.ST_HTML_SRC; ctx.featStack.push(DebugJS.ST_HTML_SRC); if (!ctx.htmlSrcPanel) ctx.createHtmlSrcPanel(ctx); ctx.updateHtmlSrcBtn(ctx); ctx.showHtmlSrc(); }, createHtmlSrcPanel: function(ctx) { ctx.htmlSrcPanel = document.createElement('div'); if (DebugJS.HTML_SRC_FULL_OVERLAY) { ctx.htmlSrcPanel.className = 'dbg-overlay-panel-full'; ctx.addOverlayPanelFull(ctx.htmlSrcPanel); } else { ctx.htmlSrcPanel.className = 'dbg-overlay-panel'; ctx.addOverlayPanel(ctx, ctx.htmlSrcPanel); } if (DebugJS.HTML_SRC_EXPAND_H) ctx.expandHightIfNeeded(ctx); ctx.htmlSrcHeaderPanel = document.createElement('div'); ctx.htmlSrcPanel.appendChild(ctx.htmlSrcHeaderPanel); ctx.htmlSrcTitle = document.createElement('span'); ctx.setStyle(ctx.htmlSrcTitle, 'color', DebugJS.HTML_BTN_COLOR); ctx.htmlSrcTitle.innerText = 'HTML SOURCE'; ctx.htmlSrcHeaderPanel.appendChild(ctx.htmlSrcTitle); var UPDATE_COLOR = '#fff'; ctx.htmlSrcUpdInpLbl2 = document.createElement('span'); ctx.htmlSrcUpdInpLbl2.style.float = 'right'; ctx.htmlSrcUpdInpLbl2.style.marginLeft = '2px'; ctx.setStyle(ctx.htmlSrcUpdInpLbl2, 'color', UPDATE_COLOR); ctx.htmlSrcUpdInpLbl2.innerText = 'ms'; ctx.htmlSrcHeaderPanel.appendChild(ctx.htmlSrcUpdInpLbl2); ctx.htmlSrcUpdateInput = DebugJS.ui.addTextInput(ctx.htmlSrcHeaderPanel, '50px', 'right', UPDATE_COLOR, ctx.htmlSrcUpdateInterval, ctx.onchangeHtmlSrcUpdateInterval); ctx.htmlSrcUpdateInput.style.float = 'right'; ctx.htmlSrcUpdInpLbl = document.createElement('span'); ctx.htmlSrcUpdInpLbl.style.float = 'right'; ctx.setStyle(ctx.htmlSrcUpdInpLbl, 'color', UPDATE_COLOR); ctx.htmlSrcUpdInpLbl.innerText = ':'; ctx.htmlSrcHeaderPanel.appendChild(ctx.htmlSrcUpdInpLbl); ctx.htmlSrcUpdBtn = DebugJS.ui.addBtn(ctx.htmlSrcHeaderPanel, 'UPDATE', ctx.showHtmlSrc); ctx.htmlSrcUpdBtn.style.float = 'right'; ctx.htmlSrcUpdBtn.style.marginLeft = '4px'; ctx.setStyle(ctx.htmlSrcUpdBtn, 'color', ctx.opt.btnColor); ctx.htmlSrcBodyPanel = document.createElement('div'); ctx.htmlSrcBodyPanel.style.width = '100%'; ctx.htmlSrcBodyPanel.style.height = 'calc(100% - 1.3em)'; ctx.htmlSrcBodyPanel.style.overflow = 'auto'; ctx.htmlSrcPanel.appendChild(ctx.htmlSrcBodyPanel); ctx.htmlSrcBody = document.createElement('pre'); ctx.htmlSrcBodyPanel.appendChild(ctx.htmlSrcBody); }, closeHtmlSrc: function(ctx) { if (ctx.htmlSrcPanel) { if (DebugJS.HTML_SRC_FULL_OVERLAY) { ctx.removeOverlayPanelFull(ctx.htmlSrcPanel); } else { ctx.removeOverlayPanel(ctx, ctx.htmlSrcPanel); } if (DebugJS.HTML_SRC_EXPAND_H) ctx.resetExpandedHeightIfNeeded(ctx); ctx.htmlSrcPanel = null; } ctx.status &= ~DebugJS.ST_HTML_SRC; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_HTML_SRC); ctx.updateHtmlSrcBtn(ctx); }, showHtmlSrc: function() { var ctx = DebugJS.ctx; ctx.htmlSrcBodyPanel.removeChild(ctx.htmlSrcBody); var html = document.getElementsByTagName('html')[0].outerHTML.replace(/</g, '&lt;').replace(/>/g, '&gt;'); ctx.htmlSrcBodyPanel.appendChild(ctx.htmlSrcBody); ctx.htmlSrcBody.innerHTML = html; }, onchangeHtmlSrcUpdateInterval: function() { var ctx = DebugJS.ctx; var interval = ctx.htmlSrcUpdateInput.value; if (interval == '') interval = 0; if (isFinite(interval)) { ctx.htmlSrcUpdateInterval = interval; clearTimeout(ctx.htmlSrcUpdateTimerId); ctx.htmlSrcUpdateTimerId = setTimeout(ctx.updateHtmlSrcInterval, ctx.htmlSrcUpdateInterval); } }, updateHtmlSrcInterval: function() { var ctx = DebugJS.ctx; if (!(ctx.status & DebugJS.ST_HTML_SRC)) return; ctx.showHtmlSrc(); if (ctx.htmlSrcUpdateInterval > 0) { ctx.elmUpdateTimerId = setTimeout(ctx.updateHtmlSrcInterval, ctx.htmlSrcUpdateInterval); } }, toggleJs: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_JS) { ctx.closeJsEditor(); } else { ctx.openJsEditor(ctx); } }, openJsEditor: function(ctx) { ctx.status |= DebugJS.ST_JS; ctx.featStack.push(DebugJS.ST_JS); if (!ctx.jsPanel) ctx.createJsPanel(ctx); ctx.updateJsBtn(ctx); ctx.jsEditor.focus(); }, createJsPanel: function(ctx) { ctx.jsPanel = document.createElement('div'); ctx.jsPanel.className = 'dbg-overlay-panel'; var html = '<div class="dbg-btn dbg-nomove" ' + 'style="position:relative;top:-1px;float:right;' + 'font-size:' + (18 * ctx.opt.zoom) + 'px;color:#888 !important" ' + 'onclick="DebugJS.ctx.closeJsEditor();" ' + 'onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'#d88\');" ' + 'onmouseout="DebugJS.ctx.setStyle(this, \'color\', \'#888\');">x</div>' + '<span style="color:#ccc">JS Editor</span>' + DebugJS.ui.createBtnHtml('[EXEC]', 'DebugJS.ctx.execJavaScript();', 'float:right;margin-right:4px') + DebugJS.ui.createBtnHtml('[CLR]', 'DebugJS.ctx.insertJsSnippet();', 'margin-left:4px;margin-right:4px'); for (var i = 0; i < 5; i++) { html += ctx.createJsSnippetBtn(ctx, i); } ctx.jsPanel.innerHTML = html; ctx.addOverlayPanel(ctx, ctx.jsPanel); ctx.jsEditor = document.createElement('textarea'); ctx.jsEditor.className = 'dbg-editor'; ctx.jsEditor.onblur = ctx.saveJsBuf; ctx.jsEditor.value = ctx.jsBuf; ctx.enableDnDFileLoad(ctx.jsEditor, ctx.onDropOnJS); ctx.jsPanel.appendChild(ctx.jsEditor); }, createJsSnippetBtn: function(ctx, i) { return DebugJS.ui.createBtnHtml('{CODE' + (i + 1) + '}', 'DebugJS.ctx.insertJsSnippet(' + i + ');', 'margin-left:4px'); }, insertJsSnippet: function(n) { var editor = DebugJS.ctx.jsEditor; if (n == undefined) { editor.value = ''; editor.focus(); } else { var code = DebugJS.JS_SNIPPET[n]; var buf = editor.value; var posCursor = editor.selectionStart; var bufL = buf.substr(0, posCursor); var bufR = buf.substr(posCursor, buf.length); buf = bufL + code + bufR; DebugJS.ctx.jsEditor.focus(); DebugJS.ctx.jsEditor.value = buf; editor.selectionStart = editor.selectionEnd = posCursor + code.length; } }, saveJsBuf: function() { DebugJS.ctx.jsBuf = DebugJS.ctx.jsEditor.value; }, execJavaScript: function() { DebugJS.ctx.execCode(DebugJS.ctx.jsBuf, true); }, execCode: function(code, echo) { if (code == '') return; try { var r = eval(code); var res = r; if (typeof r == 'string') { res = DebugJS.quoteStr(r); } if (echo) DebugJS._log.res(res); return r; } catch (e) { DebugJS._log.e(e); } }, closeJsEditor: function() { var ctx = DebugJS.ctx; if (ctx.jsPanel) { ctx.removeOverlayPanel(ctx, ctx.jsPanel); ctx.jsPanel = null; } ctx.status &= ~DebugJS.ST_JS; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_JS); ctx.updateJsBtn(ctx); }, toggleTools: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_TOOLS) { ctx.closeTools(ctx); } else { ctx.openTools(ctx); } }, openTools: function(ctx) { ctx.status |= DebugJS.ST_TOOLS; ctx.featStack.push(DebugJS.ST_TOOLS); if (!ctx.toolsPanel) ctx.createToolsPanel(ctx); ctx.addOverlayPanelFull(ctx.toolsPanel); ctx.resizeImgPreview(); ctx.switchToolsFunction(ctx.toolsActiveFnc); ctx.updateToolsBtns(); ctx.updateToolsBtn(ctx); }, isAvailableTools: function(ctx) { return (ctx.win && ctx.opt.useTools); }, createToolsPanel: function(ctx) { var p = ctx.createSubBasePanel(ctx); ctx.toolsPanel = p.base; ctx.toolsHeaderPanel = p.head; ctx.toolsBodyPanel = p.body; ctx.timerBtn = ctx.createToolsHeaderBtn('TIMER', 'TOOLS_FNC_TIMER', 'timerBtn'); ctx.txtChkBtn = ctx.createToolsHeaderBtn('TEXT', 'TOOLS_FNC_TEXT', 'txtChkBtn'); ctx.htmlPrevBtn = ctx.createToolsHeaderBtn('HTML', 'TOOLS_FNC_HTML', 'htmlPrevBtn'); ctx.fileVwrBtn = ctx.createToolsHeaderBtn('FILE', 'TOOLS_FNC_FILE', 'fileVwrBtn'); ctx.batBtn = ctx.createToolsHeaderBtn('BAT', 'TOOLS_FNC_BAT', 'batBtn'); }, createToolsHeaderBtn: function(label, state, btnObj) { var ctx = DebugJS.ctx; var fn = new Function('DebugJS.ctx.switchToolsFunction(DebugJS.' + state + ');'); var btn = DebugJS.ui.addBtn(ctx.toolsHeaderPanel, '<' + label + '>', fn); btn.style.marginRight = '4px'; btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', DebugJS.SBPNL_COLOR_ACTIVE);'); btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', (DebugJS.ctx.toolsActiveFnc & DebugJS.' + state + ') ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT);'); return btn; }, closeTools: function(ctx) { if (ctx.toolsPanel) { ctx.removeOverlayPanelFull(ctx.toolsPanel); ctx.switchToolsFunction(0); } ctx.status &= ~DebugJS.ST_TOOLS; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_TOOLS); ctx.updateToolsBtn(ctx); }, updateToolsBtns: function() { var ctx = DebugJS.ctx; ctx.setStyle(ctx.timerBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_TIMER) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); ctx.setStyle(ctx.txtChkBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_TEXT) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); ctx.setStyle(ctx.htmlPrevBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_HTML) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); ctx.setStyle(ctx.fileVwrBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_FILE) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); ctx.setStyle(ctx.batBtn, 'color', (ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_BAT) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); }, switchToolsFunction: function(kind, param) { var ctx = DebugJS.ctx; if (kind & DebugJS.TOOLS_FNC_TIMER) { ctx.openTimer(param); } else { ctx.closeTimer(); } if (kind & DebugJS.TOOLS_FNC_TEXT) { ctx.openTextChecker(); } else { ctx.closeTextChecker(); } if (kind & DebugJS.TOOLS_FNC_HTML) { ctx.openHtmlEditor(); } else { ctx.closeHtmlEditor(); } if (kind & DebugJS.TOOLS_FNC_FILE) { ctx.openFileLoader(param); } else { ctx.closeFileLoader(); } if (kind & DebugJS.TOOLS_FNC_BAT) { ctx.openBatEditor(); } else { ctx.closeBatEditor(); } if (kind) ctx.toolsActiveFnc = kind; ctx.updateToolsBtns(); }, removeToolFuncPanel: function(ctx, panel) { if (panel.parentNode) { ctx.toolsBodyPanel.removeChild(panel); } }, openTimer: function(mode) { var ctx = DebugJS.ctx; if (!ctx.timerBasePanel) { ctx.createTimerBasePanel(ctx); } else { ctx.toolsBodyPanel.appendChild(ctx.timerBasePanel); } ctx.setIntervalH(ctx); if ((mode != undefined) && (mode !== '')) { ctx.switchTimerMode(mode); } else { switch (ctx.toolTimerMode) { case DebugJS.TOOL_TIMER_MODE_CLOCK: ctx.updateTimerClock(); break; case DebugJS.TOOL_TIMER_MODE_SW_CU: ctx.updateTimerStopwatchCu(); break; case DebugJS.TOOL_TIMER_MODE_SW_CD: ctx.updateTimerStopwatchCd(); } } }, createTimerBasePanel: function(ctx) { var baseFontSize = ctx.computedFontSize; var fontSize = baseFontSize * 6.5; ctx.timerBasePanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); ctx.timerBasePanel.style.position = 'absolute'; ctx.timerBasePanel.style.height = baseFontSize * 21 + 'px'; ctx.timerBasePanel.style.top = '0'; ctx.timerBasePanel.style.bottom = '0'; ctx.timerBasePanel.style.margin = 'auto'; ctx.setStyle(ctx.timerBasePanel, 'font-size', fontSize + 'px'); ctx.timerBasePanel.style.lineHeight = '1em'; ctx.timerBasePanel.style.textAlign = 'center'; ctx.toolsBodyPanel.appendChild(ctx.timerBasePanel); ctx.createTimerClockSubPanel(); ctx.createTimerStopwatchCuSubPanel(); ctx.createTimerStopwatchCdSubPanel(); ctx.createTimerStopwatchCdInpSubPanel(); if (!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) && !(ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED)) { ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_RST; } ctx.switchTimerMode(ctx.toolTimerMode); }, createTimerClockSubPanel: function() { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize; var btnFontSize = fontSize * 3; ctx.timerClockSubPanel = document.createElement('div'); var marginB = 20 * ctx.opt.zoom; ctx.timerClockLabel = document.createElement('div'); ctx.timerClockLabel.style.marginBottom = marginB + 'px'; ctx.timerClockSubPanel.appendChild(ctx.timerClockLabel); var btns = document.createElement('div'); btns.style.borderTop = 'solid 2px ' + ctx.opt.timerLineColor; btns.style.paddingTop = fontSize + 'px'; btns.style.lineHeight = btnFontSize + 'px'; ctx.timerClockSubPanel.appendChild(btns); ctx.createTimerBtn(btns, 'MODE', ctx.toggleTimerMode, false, btnFontSize); ctx.createTimerBtn(btns, 'RESET', null, true, btnFontSize); ctx.createTimerBtn(btns, '>>', null, true, btnFontSize); ctx.createTimerBtn(btns, 'SPLIT', null, true, btnFontSize); ctx.clockSSSbtn = ctx.createTimerBtn(btns, 'sss', ctx.toggleSSS, false, (fontSize * 1.5)); ctx.updateSSS(ctx); }, toggleSSS: function() { var ctx = DebugJS.ctx; ctx.timerClockSSS = (ctx.timerClockSSS ? false : true); ctx.updateSSS(ctx); }, updateSSS: function(ctx) { var color = (ctx.timerClockSSS ? DebugJS.TOOL_TIMER_BTN_COLOR : '#888'); ctx.setStyle(ctx.clockSSSbtn, 'color', color); }, createTimerStopwatchSubPanel: function(ctx, handlers) { var panel = { basePanel: null, stopWatchLabel: null, btns: null, startStopBtn: null, splitBtn: null }; var fontSize = ctx.computedFontSize; var btnFontSize = fontSize * 3; panel.basePanel = document.createElement('div'); var marginT = 40 * ctx.opt.zoom; var marginB = 39 * ctx.opt.zoom; panel.stopWatchLabel = document.createElement('div'); panel.stopWatchLabel.style.margin = marginT + 'px 0 ' + marginB + 'px 0'; panel.basePanel.appendChild(panel.stopWatchLabel); var btns = document.createElement('div'); btns.style.borderTop = 'solid 2px ' + ctx.opt.timerLineColor; btns.style.paddingTop = fontSize + 'px'; btns.style.lineHeight = btnFontSize + 'px'; panel.basePanel.appendChild(btns); ctx.createTimerBtn(btns, 'MODE', ctx.toggleTimerMode, false, btnFontSize); ctx.createTimerBtn(btns, 'RESET', handlers.reset, false, btnFontSize); panel.startStopBtn = ctx.createTimerBtn(btns, '>>', handlers.startStop, false, btnFontSize); panel.splitBtn = ctx.createTimerBtn(btns, 'SPLIT', handlers.split, false, btnFontSize); panel.btns = btns; return panel; }, createTimerStopwatchCuSubPanel: function() { var ctx = DebugJS.ctx; var handlers = { reset: ctx.resetTimerStopwatchCu, startStop: ctx.startStopTimerStopwatchCu, split: ctx.splitTimerStopwatchCu }; var panel = ctx.createTimerStopwatchSubPanel(ctx, handlers); ctx.timerStopwatchCuSubPanel = panel.basePanel; ctx.timerStopwatchCuLabel = panel.stopWatchLabel; ctx.timerStartStopBtnCu = panel.startStopBtn; ctx.timerSplitBtnCu = panel.splitBtn; }, createTimerStopwatchCdSubPanel: function() { var ctx = DebugJS.ctx; var handlers = { reset: ctx.resetTimerStopwatchCd, startStop: ctx.startStopTimerStopwatchCd, split: ctx.splitTimerStopwatchCd }; var panel = ctx.createTimerStopwatchSubPanel(ctx, handlers); ctx.timerStopwatchCdSubPanel = panel.basePanel; ctx.timerStopwatchCdLabel = panel.stopWatchLabel; ctx.timerStartStopBtnCd = panel.startStopBtn; ctx.timerSplitBtnCd = panel.splitBtn; ctx.timer0CntBtnCd1 = ctx.createTimerBtn(panel.btns, '0=>', ctx.toggle0ContinueTimerStopwatchCd, false, (ctx.computedFontSize * 1.5)); ctx.update0ContinueBtnTimerStopwatchCd(); }, createTimerStopwatchCdInpSubPanel: function() { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize; var baseFontSize = fontSize * 6.5; var btnFontSize = fontSize * 3; var msFontSize = baseFontSize * 0.65; var basePanel = document.createElement('div'); var timerUpBtns = document.createElement('div'); timerUpBtns.style.margin = '0 0 -' + fontSize * 0.8 + 'px 0'; timerUpBtns.style.lineHeight = btnFontSize + 'px'; basePanel.appendChild(timerUpBtns); ctx.createTimerUpDwnBtn(true, 'hh', timerUpBtns, btnFontSize, 3); ctx.createTimerUpDwnBtn(true, 'mi', timerUpBtns, btnFontSize, 3); ctx.createTimerUpDwnBtn(true, 'ss', timerUpBtns, btnFontSize, 2.5); ctx.createTimerUpDwnBtn(true, 'sss', timerUpBtns, btnFontSize, 0); ctx.timerStopwatchCdInput = document.createElement('div'); ctx.timerStopwatchCdInput.style.margin = '0'; ctx.timerStopwatchCdInput.style.lineHeight = baseFontSize + 'px'; basePanel.appendChild(ctx.timerStopwatchCdInput); ctx.timerTxtHH = ctx.createTimerInput(ctx.timerStopwatchCdInput, DebugJS.timestr2struct(ctx.props.timer).hh, baseFontSize); ctx.createTimerInputLabel(ctx.timerStopwatchCdInput, ':', baseFontSize); ctx.timerTxtMI = ctx.createTimerInput(ctx.timerStopwatchCdInput, DebugJS.timestr2struct(ctx.props.timer).mi, baseFontSize); ctx.createTimerInputLabel(ctx.timerStopwatchCdInput, ':', baseFontSize); ctx.timerTxtSS = ctx.createTimerInput(ctx.timerStopwatchCdInput, DebugJS.timestr2struct(ctx.props.timer).ss, baseFontSize); ctx.createTimerInputLabel(ctx.timerStopwatchCdInput, '.', msFontSize); ctx.timerTxtSSS = ctx.createTimerInput(ctx.timerStopwatchCdInput, DebugJS.timestr2struct(ctx.props.timer).sss, msFontSize, '2em'); var timerDwnBtns = document.createElement('div'); var marginT = fontSize * 2; var marginB = fontSize * 1.2; timerDwnBtns.style.margin = '-' + marginT + 'px 0 ' + marginB + 'px 0'; timerDwnBtns.style.lineHeight = btnFontSize + 'px'; ctx.createTimerUpDwnBtn(false, 'hh', timerDwnBtns, btnFontSize, 3); ctx.createTimerUpDwnBtn(false, 'mi', timerDwnBtns, btnFontSize, 3); ctx.createTimerUpDwnBtn(false, 'ss', timerDwnBtns, btnFontSize, 2.5); ctx.createTimerUpDwnBtn(false, 'sss', timerDwnBtns, btnFontSize, 0); basePanel.appendChild(timerDwnBtns); var btns = document.createElement('div'); btns.style.borderTop = 'solid 2px ' + ctx.opt.timerLineColor; btns.style.paddingTop = fontSize + 'px'; btns.style.lineHeight = btnFontSize + 'px'; ctx.createTimerBtn(btns, 'MODE', ctx.toggleTimerMode, false, btnFontSize); ctx.createTimerBtn(btns, 'RESET', ctx.resetTimerStopwatchCd, false, btnFontSize); ctx.timerStartStopBtnCdInp = ctx.createTimerBtn(btns, '>>', ctx.startStopTimerStopwatchCd, false, btnFontSize); ctx.createTimerBtn(btns, 'SPLIT', null, true, btnFontSize); ctx.timer0CntBtnCd2 = ctx.createTimerBtn(btns, '0=>', ctx.toggle0ContinueTimerStopwatchCd, false, (fontSize * 1.5)); basePanel.appendChild(btns); ctx.timerStopwatchCdInpSubPanel = basePanel; }, createTimerInput: function(base, val, fontSize, width) { var ctx = DebugJS.ctx; var el = document.createElement('input'); el.className = 'dbg-timer-inp'; ctx.setStyle(el, 'margin-top', '-' + fontSize * 0.5 + 'px'); ctx.setStyle(el, 'font-size', fontSize + 'px'); if (width) ctx.setStyle(el, 'width', width); el.value = val; el.oninput = ctx.updatePropTimer; base.appendChild(el); return el; }, createTimerInputLabel: function(base, label, fontSize) { var el = document.createElement('span'); el.innerText = label; DebugJS.ctx.setStyle(el, 'font-size', fontSize + 'px'); base.appendChild(el); }, createTimerBtn: function(base, label, handler, disabled, fontSize) { var btn = DebugJS.ui.addBtn(base, label, handler); btn.style.marginRight = '0.5em'; DebugJS.ctx.setStyle(btn, 'color', (disabled ? '#888' : DebugJS.TOOL_TIMER_BTN_COLOR)); if (fontSize) DebugJS.ctx.setStyle(btn, 'font-size', fontSize + 'px'); return btn; }, createTimerUpDwnBtn: function(up, part, area, fontSize, margin) { var lbl = (up ? '+' : '-'); var fn = new Function('DebugJS.ctx.timerUpDwn(\'' + part + '\', ' + up + ')'); var btn = DebugJS.ui.addBtn(area, lbl, fn); btn.style.marginRight = margin + 'em'; DebugJS.ctx.setStyle(btn, 'color', DebugJS.TOOL_TIMER_BTN_COLOR); DebugJS.ctx.setStyle(btn, 'font-size', fontSize + 'px'); return btn; }, timerUpDwn: function(part, up) { var val = DebugJS.ctx.calcTimeupTimeInp(); var ms = {'hh': 3600000, 'mi': 60000, 'ss': 1000, 'sss': 1}; var v = (ms[part] === undefined ? 0 : ms[part]); if (up) { val += v; } else { if (val >= v) val -= v; } DebugJS.ctx.updateTimeupTimeInp(val); DebugJS.ctx.drawStopwatchCd(); }, updatePropTimer: function(v) { var ctx = DebugJS.ctx; ctx.props.timer = ctx.timerTxtHH.value + ':' + ctx.timerTxtMI.value + ':' + ctx.timerTxtSS.value + '.' + ctx.timerTxtSSS.value; }, calcTimeupTimeInp: function() { var ctx = DebugJS.ctx; var h = (ctx.timerTxtHH.value | 0) * 3600000; var m = (ctx.timerTxtMI.value | 0) * 60000; var s = (ctx.timerTxtSS.value | 0) * 1000; var ms = (ctx.timerTxtSSS.value | 0); return h + m + s + ms; }, updateTimeupTimeInp: function(v) { var ctx = DebugJS.ctx; var tm = DebugJS.ms2struct(v, true); ctx.timerTxtHH.value = tm.hh; ctx.timerTxtMI.value = tm.mi; ctx.timerTxtSS.value = tm.ss; ctx.timerTxtSSS.value = tm.sss; ctx.updatePropTimer(); }, toggleTimerMode: function() { var a = [DebugJS.TOOL_TIMER_MODE_CLOCK, DebugJS.TOOL_TIMER_MODE_SW_CU, DebugJS.TOOL_TIMER_MODE_SW_CD]; var nextMode = DebugJS.nextArr(a, DebugJS.ctx.toolTimerMode); DebugJS.ctx.switchTimerMode(nextMode); }, switchTimerMode: function(mode) { if (mode == DebugJS.TOOL_TIMER_MODE_SW_CU) { DebugJS.ctx.switchTimerModeStopwatchCu(); } else if (mode == DebugJS.TOOL_TIMER_MODE_SW_CD) { DebugJS.ctx.switchTimerModeStopwatchCd(); } else { DebugJS.ctx.switchTimerModeClock(); } }, switchTimerModeClock: function() { var ctx = DebugJS.ctx; ctx.replaceTimerSubPanel(ctx.timerClockSubPanel); ctx.toolTimerMode = DebugJS.TOOL_TIMER_MODE_CLOCK; ctx.updateTimerClock(); }, switchTimerModeStopwatchCu: function() { var ctx = DebugJS.ctx; ctx.toolTimerMode = DebugJS.TOOL_TIMER_MODE_SW_CU; ctx.replaceTimerSubPanel(ctx.timerStopwatchCuSubPanel); ctx.drawStopwatchCu(); ctx.updateTimerStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, switchTimerModeStopwatchCd: function() { var ctx = DebugJS.ctx; ctx.toolTimerMode = DebugJS.TOOL_TIMER_MODE_SW_CD; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RST) { ctx.replaceTimerSubPanel(ctx.timerStopwatchCdInpSubPanel); } else { ctx.replaceTimerSubPanel(ctx.timerStopwatchCdSubPanel); ctx.drawStopwatchCd(); ctx.updateTimerStopwatchCd(); } ctx.updateTimerSwBtnsCd(); }, replaceTimerSubPanel: function(panel) { var ctx = DebugJS.ctx; for (var i = ctx.timerBasePanel.childNodes.length - 1; i >= 0; i--) { ctx.timerBasePanel.removeChild(ctx.timerBasePanel.childNodes[i]); } ctx.timerBasePanel.appendChild(panel); }, updateTimerClock: function() { var ctx = DebugJS.ctx; if ((!(ctx.status & DebugJS.ST_TOOLS)) || (ctx.toolTimerMode != DebugJS.TOOL_TIMER_MODE_CLOCK)) return; var tm = DebugJS.getDateTime(); ctx.timerClockLabel.innerHTML = ctx.createClockStr(tm); setTimeout(ctx.updateTimerClock, ctx.clockUpdInt); }, createClockStr: function(tm) { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize * 8; var dtFontSize = fontSize * 0.45; var ssFontSize = fontSize * 0.65; var msFontSize = fontSize * 0.45; var marginT = 20 * ctx.opt.zoom; var marginB = 10 * ctx.opt.zoom; var dot = '.'; if (tm.sss > 500) dot = '&nbsp;'; var date = tm.yyyy + '-' + tm.mm + '-' + tm.dd + ' <span style="color:#' + DebugJS.WDAYS_COLOR[tm.wday] + ' !important;font-size:' + dtFontSize + 'px !important">' + DebugJS.WDAYS[tm.wday] + '</span>'; var time = tm.hh + ':' + tm.mi + '<span style="margin-left:' + (ssFontSize / 5) + 'px;color:' + ctx.opt.fontColor + ' !important;font-size:' + ssFontSize + 'px !important">' + tm.ss + dot + '</span>'; if (ctx.timerClockSSS) { time += '<span style="font-size:' + msFontSize + 'px !important">' + tm.sss + '</span>'; marginB -= 16 * ctx.opt.zoom; } var s = '<div style="color:' + ctx.opt.fontColor + ' !important;font-size:' + dtFontSize + 'px !important">' + date + '</div>' + '<div style="color:' + ctx.opt.fontColor + ' !important;font-size:' + fontSize + 'px !important;margin:-' + marginT + 'px 0 ' + marginB + 'px 0">' + time + '</div>'; return s; }, startStopTimerStopwatchCu: function() { var ctx = DebugJS.ctx; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END) { ctx.resetTimerStopwatchCu(); } if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) { ctx.stopTimerStopwatchCu(); } else { ctx.startTimerStopwatchCu(); } }, startStopTimerStopwatchCd: function() { var ctx = DebugJS.ctx; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) { ctx.stopTimerStopwatchCd(); } else { ctx.startTimerStopwatchCd(); } }, startTimerStopwatchCu: function() { var ctx = DebugJS.ctx; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END) { ctx.resetTimerStopwatchCu(); } ctx.toolStatus |= DebugJS.TOOL_ST_SW_CU_RUNNING; DebugJS.time.restart(DebugJS.TIMER_NAME_SW_CU); ctx.updateTimerStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, stopTimerStopwatchCu: function() { var ctx = DebugJS.ctx; ctx.updateTimerStopwatchCu(); DebugJS.time.pause(DebugJS.TIMER_NAME_SW_CU); ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CU_RUNNING; ctx.drawStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, endTimerStopwatchCu: function() { var ctx = DebugJS.ctx; ctx.updateTimerStopwatchCu(); ctx.toolStatus |= DebugJS.TOOL_ST_SW_CU_END; ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CU_RUNNING; ctx.updateTimerStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, splitTimerStopwatchCu: function() { if (DebugJS.ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) { DebugJS.time._split(DebugJS.TIMER_NAME_SW_CU); } }, resetTimerStopwatchCu: function() { var ctx = DebugJS.ctx; ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CU_END; DebugJS.time.reset(DebugJS.TIMER_NAME_SW_CU); ctx.drawStopwatchCu(); ctx.updateTimerSwBtnsCu(); }, updateTimerStopwatchCu: function() { var ctx = DebugJS.ctx; if ((!(ctx.status & DebugJS.ST_TOOLS)) || (ctx.toolTimerMode != DebugJS.TOOL_TIMER_MODE_SW_CU) || ((!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING)) && (!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END)))) return; if (!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END)) { DebugJS.time.updateCount(DebugJS.TIMER_NAME_SW_CU); } ctx.drawStopwatchCu(); setTimeout(ctx.updateTimerStopwatchCu, DebugJS.UPDATE_INTERVAL_H); }, drawStopwatchCu: function() { var ctx = DebugJS.ctx; var tm = DebugJS.ms2struct(DebugJS.time.getCount(DebugJS.TIMER_NAME_SW_CU), true); ctx.timerStopwatchCuLabel.innerHTML = ctx.createTimeStrCu(tm); }, updateTimerSwBtnsCu: function() { var ctx = DebugJS.ctx; if (!ctx.timerStartStopBtnCu) return; var btn = (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) ? '||' : '>>'; ctx.timerStartStopBtnCu.innerText = btn; ctx.updateTimerLapBtnCu(); }, updateTimerLapBtnCu: function() { var ctx = DebugJS.ctx; var color = '#888'; var fn = null; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) { color = DebugJS.TOOL_TIMER_BTN_COLOR; fn = ctx.splitTimerStopwatchCu; } ctx.setStyle(ctx.timerSplitBtnCu, 'color', color); ctx.timerSplitBtnCu.onclick = fn; }, toggle0ContinueTimerStopwatchCd: function() { var ctx = DebugJS.ctx; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) return; ctx.timerSwTimeCdContinue = (ctx.timerSwTimeCdContinue ? false : true); ctx.update0ContinueBtnTimerStopwatchCd(); }, update0ContinueBtnTimerStopwatchCd: function() { var ctx = DebugJS.ctx; var color = DebugJS.TOOL_TIMER_BTN_COLOR; if (ctx.timerSwTimeCdContinue) { if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { color = ctx.opt.timerColorExpr; } } else { color = '#888'; } ctx.setStyle(ctx.timer0CntBtnCd1, 'color', color); if (ctx.timer0CntBtnCd2) ctx.setStyle(ctx.timer0CntBtnCd2, 'color', color); }, startTimerStopwatchCd: function() { var ctx = DebugJS.ctx; var now = (new Date()).getTime(); if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_END) { ctx.resetTimerStopwatchCd(); } if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RST) { ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_RST; var timeup = ctx.calcTimeupTimeInp(); ctx.timerTimeUpTime = now + timeup; ctx.replaceTimerSubPanel(ctx.timerStopwatchCdSubPanel); } else { if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { ctx.timerTimeUpTime = now - ctx.timerSwTimeCd; } else { ctx.timerTimeUpTime = now + ctx.timerSwTimeCd; } } ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_RUNNING; ctx.updateTimerStopwatchCd(); ctx.updateTimerSwBtnsCd(); }, stopTimerStopwatchCd: function() { var ctx = DebugJS.ctx; ctx.updateTimerStopwatchCd(); ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_RUNNING; ctx.drawStopwatchCd(); ctx.updateTimerSwBtnsCd(); }, splitTimerStopwatchCd: function() { var ctx = DebugJS.ctx; var color = '#fff'; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { color = ctx.opt.timerColorExpr; } var t = DebugJS.TIMER_NAME_SW_CD + ': ' + '<span style="color:' + color + '">' + DebugJS.getTimerStr(ctx.timerSwTimeCd) + '</span>'; DebugJS._log(t); }, resetTimerStopwatchCd: function() { var ctx = DebugJS.ctx; ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_EXPIRED; ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_END; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) { var timeup = ctx.calcTimeupTimeInp(); ctx.timerTimeUpTime = (new Date()).getTime() + timeup; ctx.updateTimerStopwatchCd(); } else { ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_RST; ctx.replaceTimerSubPanel(ctx.timerStopwatchCdInpSubPanel); } ctx.updateTimerSwBtnsCd(); }, updateTimerStopwatchCd: function() { var ctx = DebugJS.ctx; if ((!(ctx.status & DebugJS.ST_TOOLS)) || (ctx.toolTimerMode != DebugJS.TOOL_TIMER_MODE_SW_CD) || ((!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING)) && (!(ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_END)))) return; var now = (new Date()).getTime(); if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { if (ctx.timerSwTimeCdContinue) { ctx.timerSwTimeCd = now - ctx.timerTimeUpTime; } } else { ctx.timerSwTimeCd = ctx.timerTimeUpTime - now; } if (ctx.timerSwTimeCd < 0) { ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_EXPIRED; ctx.update0ContinueBtnTimerStopwatchCd(); if (ctx.timerSwTimeCdContinue) { ctx.timerSwTimeCd *= -1; } else { ctx.toolStatus &= ~DebugJS.TOOL_ST_SW_CD_RUNNING; ctx.toolStatus |= DebugJS.TOOL_ST_SW_CD_END; ctx.updateTimerSwBtnsCd(); ctx.timerSwTimeCd = 0; } } ctx.drawStopwatchCd(); setTimeout(ctx.updateTimerStopwatchCd, DebugJS.UPDATE_INTERVAL_H); }, drawStopwatchCd: function() { var ctx = DebugJS.ctx; var tm = DebugJS.ms2struct(ctx.timerSwTimeCd, true); ctx.timerStopwatchCdLabel.innerHTML = ctx.createTimeStrCd(tm); }, updateTimerSwBtnsCd: function() { var ctx = DebugJS.ctx; if (!ctx.timerStartStopBtnCd) return; var btn = (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) ? '||' : '>>'; ctx.timerStartStopBtnCd.innerText = btn; ctx.timerStartStopBtnCdInp.innerText = btn; ctx.updateTimerLapBtnCd(); ctx.update0ContinueBtnTimerStopwatchCd(); }, updateTimerLapBtnCd: function() { var ctx = DebugJS.ctx; var color = '#888'; var fn = null; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) { color = DebugJS.TOOL_TIMER_BTN_COLOR; fn = ctx.splitTimerStopwatchCd; } ctx.setStyle(ctx.timerSplitBtnCd, 'color', color); ctx.timerSplitBtnCd.onclick = fn; }, createTimeStrCu: function(tm) { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize * 7; var msFontSize = fontSize * 0.65; var str; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_END) { var now = DebugJS.getDateTime(); if (now.sss > 500) { str = '&nbsp;<span style="font-size:' + msFontSize + 'px !important">' + '&nbsp;</span>'; } else { str = tm.hh + ':' + tm.mi + ':' + tm.ss + '<span style="color:' + ctx.opt.fontColor + ' !important;font-size:' + msFontSize + 'px !important">.' + tm.sss + '</span>'; } } else { var dot = (((ctx.toolStatus & DebugJS.TOOL_ST_SW_CU_RUNNING) && (tm.sss > 500)) ? '&nbsp;' : '.'); str = tm.hh + ':' + tm.mi + ':' + tm.ss + '<span style="color:' + ctx.opt.fontColor + ' !important;font-size:' + msFontSize + 'px !important">' + dot + tm.sss + '</span>'; } return '<div style="color:' + ctx.opt.fontColor + ' !important;font-size:' + fontSize + 'px !important">' + str + '</div>'; }, createTimeStrCd: function(tm) { var ctx = DebugJS.ctx; var fontSize = ctx.computedFontSize * 7; var msFontSize = fontSize * 0.65; var color = ctx.opt.fontColor; var str; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_END) { var now = DebugJS.getDateTime(); if (now.sss > 500) { str = '&nbsp;<span style="font-size:' + msFontSize + 'px !important">' + '&nbsp;</span>'; } else { str = tm.hh + ':' + tm.mi + ':' + tm.ss + '<span style="color:' + color + ' !important;font-size:' + msFontSize + 'px !important">.' + tm.sss + '</span>'; } } else { var dot; var styleS = ''; var styleE = ''; if (ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_EXPIRED) { color = ctx.opt.timerColorExpr; dot = (((ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) && (tm.sss > 500)) ? '&nbsp;' : '.'); styleS = '<span style="color:' + color + ' !important;font-size:' + fontSize + 'px !important">'; styleE = '</span>'; } else { dot = (((ctx.toolStatus & DebugJS.TOOL_ST_SW_CD_RUNNING) && (tm.sss < 500)) ? '&nbsp;' : '.'); } str = styleS + tm.hh + ':' + tm.mi + ':' + tm.ss + '<span style="color:' + color + ' !important;font-size:' + msFontSize + 'px !important">' + dot + tm.sss + '</span>' + styleE; } return '<div style="color:' + color + ' !important;font-size:' + fontSize + 'px !important">' + str + '</div>'; }, closeTimer: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_TIMER) && (ctx.timerBasePanel)) { ctx.removeToolFuncPanel(ctx, ctx.timerBasePanel); ctx.setIntervalL(ctx); } }, openTextChecker: function() { var ctx = DebugJS.ctx; if (!ctx.txtChkPanel) { ctx.createTxtChkPanel(ctx); } else { ctx.toolsBodyPanel.appendChild(ctx.txtChkPanel); } }, createTxtChkPanel: function(ctx) { var dfltFontSize = ctx.computedFontSize; var dfltFontFamily = 'Consolas'; var dfltFontWeight = 400; var dfltFgRGB16 = 'fff'; var dfltBgRGB16 = '000'; var panelPadding = 2; ctx.txtChkPanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); var txtPadding = 4; var txtChkTxt = document.createElement('input'); ctx.setStyle(txtChkTxt, 'width', 'calc(100% - ' + ((txtPadding + panelPadding) * 2) + 'px)'); ctx.setStyle(txtChkTxt, 'min-height', (20 * ctx.opt.zoom) + 'px'); ctx.setStyle(txtChkTxt, 'margin-bottom', '8px'); ctx.setStyle(txtChkTxt, 'padding', txtPadding + 'px'); ctx.setStyle(txtChkTxt, 'border', '0'); ctx.setStyle(txtChkTxt, 'border-radius', '0'); ctx.setStyle(txtChkTxt, 'outline', 'none'); ctx.setStyle(txtChkTxt, 'font-size', dfltFontSize + 'px'); ctx.setStyle(txtChkTxt, 'font-family', dfltFontFamily); txtChkTxt.value = 'ABCDEFG.abcdefg 12345-67890_!?'; ctx.txtChkPanel.appendChild(txtChkTxt); ctx.txtChkTxt = txtChkTxt; ctx.txtChkTargetEl = txtChkTxt; ctx.txtChkCtrl = document.createElement('div'); ctx.txtChkPanel.appendChild(ctx.txtChkCtrl); var html = 'font-size: <input type="range" min="0" max="128" step="1" id="' + ctx.id + '-fontsize-range" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeFontSize(true);" onchange="DebugJS.ctx.onChangeFontSize(true);">' + '<input value="' + dfltFontSize + '" id="' + ctx.id + '-font-size" class="dbg-txtbox" style="width:30px;text-align:right" oninput="DebugJS.ctx.onChangeFontSizeTxt()">' + '<input value="px" id="' + ctx.id + '-font-size-unit" class="dbg-txtbox" style="width:20px;" oninput="DebugJS.ctx.onChangeFontSizeTxt()">' + '<span class="dbg-btn dbg-nomove" style="margin-left:5px;color:' + DebugJS.COLOR_INACT + ' !important;font-style:italic;" onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'' + ctx.opt.btnColor + '\');" onmouseout="DebugJS.ctx.updateTxtItalicBtn(this);" onclick="DebugJS.ctx.toggleTxtItalic(this);"> I </span>' + '<span class="dbg-btn dbg-nomove" style="margin-left:5px;color:' + DebugJS.COLOR_INACT + ' !important;" onmouseover="DebugJS.ctx.setStyle(this, \'color\', \'' + ctx.opt.btnColor + '\');" onmouseout="DebugJS.ctx.updateElBtn(this);" onclick="DebugJS.ctx.toggleElmEditable(this);">(el)</span>' + '<br>' + 'font-family: <input value="' + dfltFontFamily + '" class="dbg-txtbox" style="width:110px" oninput="DebugJS.ctx.onChangeFontFamily(this)">&nbsp;&nbsp;' + 'font-weight: <input type="range" min="100" max="900" step="100" value="' + dfltFontWeight + '" id="' + ctx.id + '-fontweight-range" class="dbg-txt-range" style="width:80px !important" oninput="DebugJS.ctx.onChangeFontWeight();" onchange="DebugJS.ctx.onChangeFontWeight();"><span id="' + ctx.id + '-font-weight"></span> ' + '<table class="dbg-txt-tbl">' + '<tr><td colspan="2">FG #<input id="' + ctx.id + '-fg-rgb" class="dbg-txtbox" value="' + dfltFgRGB16 + '" style="width:80px" oninput="DebugJS.ctx.onChangeFgRGB()"></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_R + '">R</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-fg-range-r" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeFgColor(true);" onchange="DebugJS.ctx.onChangeFgColor(true);"></td><td><span id="' + ctx.id + '-fg-r"></span></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_G + '">G</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-fg-range-g" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeFgColor(true);" onchange="DebugJS.ctx.onChangeFgColor(true);"></td><td><span id="' + ctx.id + '-fg-g"></span></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_B + '">B</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-fg-range-b" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeFgColor(true);" onchange="DebugJS.ctx.onChangeFgColor(true);"></td><td><span id="' + ctx.id + '-fg-b"></span></td></tr>' + '<tr><td colspan="2">BG #<input id="' + ctx.id + '-bg-rgb" class="dbg-txtbox" value="' + dfltBgRGB16 + '" style="width:80px" oninput="DebugJS.ctx.onChangeBgRGB()"></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_R + '">R</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-bg-range-r" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeBgColor(true);" onchange="DebugJS.ctx.onChangeBgColor(true);"></td><td><span id="' + ctx.id + '-bg-r"></span></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_G + '">G</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-bg-range-g" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeBgColor(true);" onchange="DebugJS.ctx.onChangeBgColor(true);"></td><td><span id="' + ctx.id + '-bg-g"></span></td></tr>' + '<tr><td><span style="color:' + DebugJS.COLOR_B + '">B</span>:</td><td><input type="range" min="0" max="255" step="1" id="' + ctx.id + '-bg-range-b" class="dbg-txt-range" oninput="DebugJS.ctx.onChangeBgColor(true);" onchange="DebugJS.ctx.onChangeBgColor(true);"></td><td><span id="' + ctx.id + '-bg-b"></span></td></tr>' + '</tbale>'; ctx.txtChkCtrl.innerHTML = html; ctx.txtChkFontSizeRange = document.getElementById(ctx.id + '-fontsize-range'); ctx.txtChkFontSizeInput = document.getElementById(ctx.id + '-font-size'); ctx.txtChkFontSizeUnitInput = document.getElementById(ctx.id + '-font-size-unit'); ctx.txtChkFontWeightRange = document.getElementById(ctx.id + '-fontweight-range'); ctx.txtChkFontWeightLabel = document.getElementById(ctx.id + '-font-weight'); ctx.txtChkInputFgRGB = document.getElementById(ctx.id + '-fg-rgb'); ctx.txtChkRangeFgR = document.getElementById(ctx.id + '-fg-range-r'); ctx.txtChkRangeFgG = document.getElementById(ctx.id + '-fg-range-g'); ctx.txtChkRangeFgB = document.getElementById(ctx.id + '-fg-range-b'); ctx.txtChkLabelFgR = document.getElementById(ctx.id + '-fg-r'); ctx.txtChkLabelFgG = document.getElementById(ctx.id + '-fg-g'); ctx.txtChkLabelFgB = document.getElementById(ctx.id + '-fg-b'); ctx.txtChkInputBgRGB = document.getElementById(ctx.id + '-bg-rgb'); ctx.txtChkRangeBgR = document.getElementById(ctx.id + '-bg-range-r'); ctx.txtChkRangeBgG = document.getElementById(ctx.id + '-bg-range-g'); ctx.txtChkRangeBgB = document.getElementById(ctx.id + '-bg-range-b'); ctx.txtChkLabelBgR = document.getElementById(ctx.id + '-bg-r'); ctx.txtChkLabelBgG = document.getElementById(ctx.id + '-bg-g'); ctx.txtChkLabelBgB = document.getElementById(ctx.id + '-bg-b'); ctx.onChangeFontSizeTxt(); ctx.onChangeFontWeight(); ctx.onChangeFgRGB(); ctx.onChangeBgRGB(); }, toggleTxtItalic: function(btn) { var ctx = DebugJS.ctx; var style = ''; if (ctx.txtChkItalic) { ctx.txtChkItalic = false; } else { ctx.txtChkItalic = true; style = 'italic'; } ctx.setStyle(ctx.txtChkTargetEl, 'font-style', style); ctx.updateTxtItalicBtn(btn); }, updateTxtItalicBtn: function(btn) { var ctx = DebugJS.ctx; var c = (ctx.txtChkItalic ? ctx.opt.btnColor : DebugJS.COLOR_INACT); ctx.setStyle(btn, 'color', c); }, toggleElmEditable: function(btn) { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_ELM_EDIT) { ctx.status &= ~DebugJS.ST_ELM_EDIT; ctx.updateEditable(ctx, ctx.txtChkTxt); } else { ctx.status |= DebugJS.ST_ELM_EDIT; if (DebugJS.el) { ctx.updateEditable(ctx, DebugJS.el); } } ctx.updateElBtn(btn); }, updateElBtn: function(btn) { var ctx = DebugJS.ctx; var c = (ctx.status & DebugJS.ST_ELM_EDIT ? ctx.opt.btnColor : DebugJS.COLOR_INACT); ctx.setStyle(btn, 'color', c); }, onChangeFgRGB: function() { var ctx = DebugJS.ctx; var rgb16 = '#' + ctx.txtChkInputFgRGB.value; var rgb10 = DebugJS.convRGB16to10(rgb16); ctx.txtChkRangeFgR.value = rgb10.r; ctx.txtChkRangeFgG.value = rgb10.g; ctx.txtChkRangeFgB.value = rgb10.b; ctx.onChangeFgColor(null); ctx.setStyle(ctx.txtChkTargetEl, 'color', rgb16); }, onChangeBgRGB: function() { var ctx = DebugJS.ctx; var rgb16 = '#' + ctx.txtChkInputBgRGB.value; var rgb10 = DebugJS.convRGB16to10(rgb16); ctx.txtChkRangeBgR.value = rgb10.r; ctx.txtChkRangeBgG.value = rgb10.g; ctx.txtChkRangeBgB.value = rgb10.b; ctx.onChangeBgColor(null); ctx.setStyle(ctx.txtChkTargetEl, 'background', rgb16); }, onChangeFgColor: function(callFromRange) { var ctx = DebugJS.ctx; var fgR = ctx.txtChkRangeFgR.value; var fgG = ctx.txtChkRangeFgG.value; var fgB = ctx.txtChkRangeFgB.value; var rgb16 = DebugJS.convRGB10to16(fgR + ' ' + fgG + ' ' + fgB); ctx.txtChkLabelFgR.innerText = fgR; ctx.txtChkLabelFgG.innerText = fgG; ctx.txtChkLabelFgB.innerText = fgB; if (callFromRange) { ctx.txtChkInputFgRGB.value = rgb16.r + rgb16.g + rgb16.b; ctx.setStyle(ctx.txtChkTargetEl, 'color', 'rgb(' + fgR + ',' + fgG + ',' + fgB + ')'); } }, onChangeBgColor: function(callFromRange) { var ctx = DebugJS.ctx; var bgR = ctx.txtChkRangeBgR.value; var bgG = ctx.txtChkRangeBgG.value; var bgB = ctx.txtChkRangeBgB.value; var rgb16 = DebugJS.convRGB10to16(bgR + ' ' + bgG + ' ' + bgB); ctx.txtChkLabelBgR.innerText = bgR; ctx.txtChkLabelBgG.innerText = bgG; ctx.txtChkLabelBgB.innerText = bgB; if (callFromRange) { ctx.txtChkInputBgRGB.value = rgb16.r + rgb16.g + rgb16.b; ctx.setStyle(ctx.txtChkTargetEl, 'background', 'rgb(' + bgR + ',' + bgG + ',' + bgB + ')'); } }, onChangeFontSizeTxt: function() { var ctx = DebugJS.ctx; var fontSize = ctx.txtChkFontSizeInput.value; var unit = ctx.txtChkFontSizeUnitInput.value; ctx.txtChkFontSizeRange.value = fontSize; ctx.onChangeFontSize(null); ctx.setStyle(ctx.txtChkTargetEl, 'font-size', fontSize + unit); }, onChangeFontSize: function(callFromRange) { var ctx = DebugJS.ctx; var fontSize = ctx.txtChkFontSizeRange.value; var unit = ctx.txtChkFontSizeUnitInput.value; if (callFromRange) { ctx.txtChkFontSizeInput.value = fontSize; ctx.setStyle(ctx.txtChkTargetEl, 'font-size', fontSize + unit); } }, onChangeFontWeight: function() { var ctx = DebugJS.ctx; var fontWeight = ctx.txtChkFontWeightRange.value; ctx.setStyle(ctx.txtChkTargetEl, 'font-weight', fontWeight); if (fontWeight == 400) { fontWeight += '(normal)'; } else if (fontWeight == 700) { fontWeight += '(bold)'; } ctx.txtChkFontWeightLabel.innerText = fontWeight; }, onChangeFontFamily: function(font) { DebugJS.ctx.setStyle(DebugJS.ctx.txtChkTargetEl, 'font-family', font.value); }, closeTextChecker: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_TEXT) && (ctx.txtChkPanel)) { ctx.removeToolFuncPanel(ctx, ctx.txtChkPanel); } }, openFileLoader: function(fmt) { var ctx = DebugJS.ctx; if (!ctx.fileVwrPanel) { ctx.createFileVwrPanel(ctx); ctx.clearFile(); } else { ctx.toolsBodyPanel.appendChild(ctx.fileVwrPanel); } if (fmt && (ctx.fileVwrMode != fmt)) { ctx.switchFileScreen(); } }, createFileVwrPanel: function(ctx) { var opt = ctx.opt; var fontSize = ctx.computedFontSize + 'px'; ctx.fileVwrPanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); var fileInput = document.createElement('input'); fileInput.type = 'file'; ctx.setStyle(fileInput, 'width', 'calc(100% - ' + (ctx.computedFontSize * 19) + 'px)'); ctx.setStyle(fileInput, 'min-height', (20 * opt.zoom) + 'px'); ctx.setStyle(fileInput, 'margin', '0 0 4px 0'); ctx.setStyle(fileInput, 'padding', '1px'); ctx.setStyle(fileInput, 'border', '0'); ctx.setStyle(fileInput, 'border-radius', '0'); ctx.setStyle(fileInput, 'outline', 'none'); ctx.setStyle(fileInput, 'font-size', fontSize); fileInput.addEventListener('change', ctx.onFileSelected, false); ctx.fileVwrPanel.appendChild(fileInput); ctx.fileInput = fileInput; ctx.fileVwrRadioB64 = document.createElement('input'); ctx.fileVwrRadioB64.type = 'radio'; ctx.fileVwrRadioB64.id = ctx.id + '-load-type-b64'; ctx.fileVwrRadioB64.name = ctx.id + '-load-type'; ctx.fileVwrRadioB64.style.marginLeft = (ctx.computedFontSize * 0.8) + 'px'; ctx.fileVwrRadioB64.value = 'base64'; ctx.fileVwrRadioB64.checked = true; ctx.fileVwrRadioB64.onchange = ctx.openViewerB64; ctx.fileVwrPanel.appendChild(ctx.fileVwrRadioB64); ctx.fileVwrLabelB64 = document.createElement('label'); ctx.fileVwrLabelB64.htmlFor = ctx.id + '-load-type-b64'; ctx.fileVwrLabelB64.innerText = 'Base64'; ctx.fileVwrPanel.appendChild(ctx.fileVwrLabelB64); ctx.fileVwrRadioBin = document.createElement('input'); ctx.fileVwrRadioBin.type = 'radio'; ctx.fileVwrRadioBin.id = ctx.id + '-load-type-bin'; ctx.fileVwrRadioBin.name = ctx.id + '-load-type'; ctx.fileVwrRadioBin.style.marginLeft = (ctx.computedFontSize * 0.8) + 'px'; ctx.fileVwrRadioBin.value = 'binary'; ctx.fileVwrRadioBin.onchange = ctx.openViewerBin; ctx.fileVwrPanel.appendChild(ctx.fileVwrRadioBin); ctx.fileVwrLabelBin = document.createElement('label'); ctx.fileVwrLabelBin.htmlFor = ctx.id + '-load-type-bin'; ctx.fileVwrLabelBin.innerText = 'Binary'; ctx.fileVwrPanel.appendChild(ctx.fileVwrLabelBin); ctx.fileReloadBtn = DebugJS.ui.addBtn(ctx.fileVwrPanel, 'Reload', ctx.reloadFile); ctx.fileReloadBtn.style.marginLeft = (ctx.computedFontSize * 0.8) + 'px'; ctx.fileClrBtn = DebugJS.ui.addBtn(ctx.fileVwrPanel, 'Clear', ctx.clearFile); ctx.fileClrBtn.style.marginLeft = (ctx.computedFontSize * 0.8) + 'px'; ctx.filePreviewWrapper = document.createElement('div'); ctx.setStyle(ctx.filePreviewWrapper, 'width', 'calc(100% - ' + (DebugJS.WIN_ADJUST + 2) + 'px)'); ctx.setStyle(ctx.filePreviewWrapper, 'height', 'calc(100% - ' + ((ctx.computedFontSize * 4) + 10) + 'px)'); ctx.setStyle(ctx.filePreviewWrapper, 'margin-bottom', '4px'); ctx.setStyle(ctx.filePreviewWrapper, 'padding', '2px'); ctx.setStyle(ctx.filePreviewWrapper, 'border', '1px dotted #ccc'); ctx.setStyle(ctx.filePreviewWrapper, 'font-size', fontSize); ctx.setStyle(ctx.filePreviewWrapper, 'overflow', 'auto'); ctx.enableDnDFileLoad(ctx.filePreviewWrapper, ctx.onDropOnFileVwr); ctx.fileVwrPanel.appendChild(ctx.filePreviewWrapper); ctx.filePreview = document.createElement('pre'); ctx.setStyle(ctx.filePreview, 'min-height', 'calc(50% + 10px)'); ctx.setStyle(ctx.filePreview, 'background', 'transparent'); ctx.setStyle(ctx.filePreview, 'color', opt.fontColor); ctx.setStyle(ctx.filePreview, 'font-size', fontSize); ctx.filePreviewWrapper.appendChild(ctx.filePreview); ctx.fileVwrFooter = document.createElement('div'); ctx.fileVwrFooter.style.width = 'calc(100% - ' + (DebugJS.WIN_ADJUST + DebugJS.WIN_SHADOW) + 'px)'; ctx.fileVwrFooter.style.height = (ctx.computedFontSize + 3) + 'px'; ctx.fileVwrFooter.style.opacity = 0; ctx.fileVwrFooter.style.transition = 'opacity 0.5s linear'; ctx.fileVwrPanel.appendChild(ctx.fileVwrFooter); ctx.fileLoadProgBar = document.createElement('div'); ctx.fileLoadProgBar.style.display = 'inline-block'; ctx.fileLoadProgBar.style.width = 'calc(100% - ' + (ctx.computedFontSize * 5) + 'px)'; ctx.fileLoadProgBar.style.height = 'auto'; ctx.fileLoadProgBar.style.padding = 0; ctx.fileLoadProgBar.style.border = '1px solid #ccc'; ctx.fileVwrFooter.appendChild(ctx.fileLoadProgBar); ctx.fileLoadProg = document.createElement('div'); ctx.fileLoadProg.style.width = 'calc(100% - ' + (DebugJS.WIN_BORDER * 2) + 'px)'; ctx.fileLoadProg.style.height = 'auto'; ctx.fileLoadProg.style.padding = '1px'; ctx.fileLoadProg.style.border = 'none'; ctx.fileLoadProg.style.background = '#00f'; ctx.setStyle(ctx.fileLoadProg, 'font-size', (ctx.computedFontSize * 0.8) + 'px'); ctx.fileLoadProg.style.fontFamily = opt.fontFamily + 'px'; ctx.fileLoadProg.innerText = '0%'; ctx.fileLoadProgBar.appendChild(ctx.fileLoadProg); ctx.fileLoadCancelBtn = DebugJS.ui.addBtn(ctx.fileVwrFooter, '[CANCEL]', ctx.cancelLoadFile); ctx.fileLoadCancelBtn.style.position = 'relative'; ctx.fileLoadCancelBtn.style.top = '2px'; ctx.fileLoadCancelBtn.style.float = 'right'; ctx.fileVwrDtUrlWrp = document.createElement('div'); ctx.setStyle(ctx.fileVwrDtUrlWrp, 'height', 'calc(50% - ' + (ctx.computedFontSize + ctx.computedFontSize * 0.5) + 'px)'); ctx.filePreviewWrapper.appendChild(ctx.fileVwrDtUrlWrp); ctx.fileVwrDtUrlScheme = DebugJS.ui.addTextInput(ctx.fileVwrDtUrlWrp, 'calc(100% - 15.5em)', null, ctx.opt.fontColor, '', null); var decodeBtn = DebugJS.ui.addBtn(ctx.fileVwrDtUrlWrp, 'Decode', ctx.decodeFileVwrData); decodeBtn.style.float = 'right'; decodeBtn.style.marginRight = '4px'; ctx.fileVwrDecModeBtn = DebugJS.ui.addBtn(ctx.fileVwrDtUrlWrp, '[B64]', ctx.toggleDecMode); ctx.fileVwrDecModeBtn.style.float = 'right'; ctx.fileVwrDecModeBtn.style.marginRight = (ctx.computedFontSize * 0.5) + 'px'; var imgBtn = DebugJS.ui.addBtn(ctx.fileVwrDtUrlWrp, '<image>', ctx.setDtSchmImg); imgBtn.style.float = 'right'; imgBtn.style.marginRight = (ctx.computedFontSize * 0.5) + 'px'; var txtBtn = DebugJS.ui.addBtn(ctx.fileVwrDtUrlWrp, '<text>', ctx.setDtSchmTxt); txtBtn.style.float = 'right'; txtBtn.style.marginRight = (ctx.computedFontSize * 0.2) + 'px'; ctx.fileVwrDtTxtArea = document.createElement('textarea'); ctx.fileVwrDtTxtArea.className = 'dbg-editor'; ctx.setStyle(ctx.fileVwrDtTxtArea, 'height', 'calc(100% - ' + (ctx.computedFontSize + ctx.computedFontSize * 0.5) + 'px)'); ctx.enableDnDFileLoad(ctx.fileVwrDtTxtArea, ctx.onDropOnFileVwrTxt); ctx.fileVwrDtUrlWrp.appendChild(ctx.fileVwrDtTxtArea); }, closeFileLoader: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_FILE) && (ctx.fileVwrPanel)) { ctx.removeToolFuncPanel(ctx, ctx.fileVwrPanel); } }, enableDnDFileLoad: function(target, cb) { target.addEventListener('dragover', DebugJS.file.onDragOver, false); target.addEventListener('drop', cb, false); }, onFileSelected: function(e) { if (e.target.files.length > 0) { DebugJS.ctx.clearFile(); DebugJS.ctx.loadFile(e.target.files[0], DebugJS.ctx.fileVwrMode); } }, handleDroppedFile: function(ctx, e, fmt, cb) { ctx.clearFile(); try { if (e.dataTransfer.files) { if (e.dataTransfer.files.length > 0) { ctx.fileVwrSysCb = cb; ctx.loadFile(e.dataTransfer.files[0], fmt); } else { DebugJS._log.w('handleDroppedFile() e.dataTransfer.files.length == 0'); if (cb) { cb(ctx, false, null, null); } } } } catch (e) {DebugJS._log.e('handleDroppedFile() ' + e);} }, onDrop: function(e) { e.stopPropagation(); e.preventDefault(); }, onDropOnFileVwr: function(e) { var ctx = DebugJS.ctx; ctx.onDrop(e); ctx.stopErrCb = true; try { var d = e.dataTransfer.getData('text'); if (d) { var s = DebugJS.delAllNL(d.trim()); if (DebugJS.isDataURL(s)) { ctx.decodeDataURL(ctx, s); } else if (DebugJS.isBase64(s)) { var tp = DebugJS.Base64.getMimeType(s); var mime = (tp ? tp.type + '/' + tp.subtype : 'text/plain'); ctx.decodeDataURL(ctx, 'data:' + mime + ';base64,' + s); } } else { ctx.handleDroppedFile(ctx, e, ctx.fileVwrMode, null); } } catch (e) {DebugJS._log.e(e);} ctx.stopErrCb = false; }, onDropOnFileVwrTxt: function(e) { var ctx = DebugJS.ctx; ctx.onDrop(e); ctx.stopErrCb = true; try { var d = e.dataTransfer.getData('text'); if (d) { ctx.fileVwrDtTxtArea.value = d; } else { ctx.handleDroppedFile(ctx, e, ctx.fileVwrMode, null); } } catch (e) {DebugJS._log.e(e);} ctx.stopErrCb = false; }, onDropOnLogPanel: function(e) { var ctx = DebugJS.ctx; ctx.onDrop(e); ctx.stopErrCb = true; try { if (!DebugJS.callEvtListeners('drop', e)) return; var d = e.dataTransfer.getData('text'); if (d) { ctx.onTxtDrop(ctx, d); } else { ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'file', 'b64'); ctx.handleDroppedFile(ctx, e, 'b64', ctx.onFileLoadedAuto); } } catch (e) {DebugJS._log.e(e);} ctx.stopErrCb = false; }, onTxtDrop: function(ctx, t) { if (DebugJS.isBat(t)) { ctx.openBat(ctx, t); } else { var s = DebugJS.delAllNL(t.trim()); if (DebugJS.isDataURL(s)) { ctx.decodeDataURL(ctx, s); } else { if (ctx.decB64(ctx, s)) return; ctx._execCmd('json ' + t, true, false, true); ctx.scrollLogBtm(ctx); } } }, decB64: function(ctx, s) { if (!DebugJS.isBase64(s)) return 0; if (DebugJS.isB64Bat(s)) { var b = DebugJS.decodeB64(s); if (b) { ctx.openBat(ctx, b); return 1; } else { return 0; } } var tp = DebugJS.Base64.getMimeType(s); var mime = (tp ? tp.type + '/' + tp.subtype : 'text/plain'); if (tp || (s.length > 102400)) { ctx.decodeDataURL(ctx, 'data:' + mime + ';base64,' + s); return 1; } ctx._execCmd('base64 -d ' + s, true, false, true); ctx.scrollLogBtm(ctx); return 1; }, openBat: function(ctx, s) { ctx.openFeature(ctx, DebugJS.ST_TOOLS); ctx.onBatLoaded(ctx, null, s); }, onFileLoadedAuto: function(ctx, file, cnt) { if (DebugJS.wBOM(cnt)) cnt = cnt.substr(1); if (DebugJS.isBat(cnt) || DebugJS.isB64Bat(cnt)) { ctx.onBatLoaded(ctx, file, cnt); } else if (file.name.match(/\.js$/)) { ctx.onJsLoaded(ctx, file, cnt); } else if (file.name.match(/\.json$/)) { DebugJS._cmdJson(cnt, true); ctx.closeFeature(ctx, DebugJS.ST_TOOLS); } }, _onDropOnFeat: function(ctx, e, fn) { ctx.onDrop(e); var d = e.dataTransfer.getData('text'); if (d) { fn(ctx, null, d); } else { ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'file', 'b64'); ctx.handleDroppedFile(ctx, e, 'b64', fn); } }, onDropOnBat: function(e) { var ctx = DebugJS.ctx; ctx._onDropOnFeat(ctx, e, ctx.onBatLoaded); }, onBatLoaded: function(ctx, file, cnt) { DebugJS.bat.set(cnt); ctx.switchToolsFunction(DebugJS.TOOLS_FNC_BAT); }, onDropOnJS: function(e) { var ctx = DebugJS.ctx; ctx._onDropOnFeat(ctx, e, ctx.onJsLoaded); }, onJsLoaded: function(ctx, file, cnt) { ctx.closeFeature(ctx, DebugJS.ST_TOOLS); ctx.openFeature(ctx, DebugJS.ST_JS); ctx.jsEditor.value = ctx.jsBuf = cnt; }, loadFile: function(file, fmt) { var ctx = DebugJS.ctx; ctx.fileVwrDataSrcType = 'file'; ctx.fileVwrFile = file; if (!file) return; if ((file.size == 0) && (file.type == '')) { var html = ctx.getFileInfo(file); ctx.updateFilePreview(html); return; } ctx.fileLoadProg.style.width = '0%'; ctx.fileLoadProg.textContent = '0%'; ctx.fileReader = new FileReader(); ctx.fileReader.onloadstart = ctx.onFileLoadStart; ctx.fileReader.onprogress = ctx.onFileLoadProg; ctx.fileReader.onload = ctx.onFileLoaded; ctx.fileReader.onabort = ctx.onAbortLoadFile; ctx.fileReader.onerror = ctx.onFileLoadError; ctx.fileReader.file = file; if (fmt == 'bin') { ctx.fileReader.readAsArrayBuffer(file); } else { ctx.fileReader.readAsDataURL(file); } }, cancelLoadFile: function() { if (DebugJS.ctx.fileReader) DebugJS.ctx.fileReader.abort(); }, onFileLoadStart: function(e) { DebugJS.addClass(DebugJS.ctx.fileVwrFooter, 'dbg-loading'); DebugJS.ctx.updateFilePreview('LOADING...'); }, onFileLoadProg: function(e) { if (e.lengthComputable) { var total = e.total; var loaded = e.loaded; var pct = (total == 0) ? 100 : Math.round((loaded / total) * 100); DebugJS.ctx.fileLoadProg.style.width = 'calc(' + pct + '% - ' + (DebugJS.WIN_BORDER * 2) + 'px)'; DebugJS.ctx.fileLoadProg.textContent = pct + '%'; DebugJS.ctx.updateFilePreview('LOADING...\n' + DebugJS.formatDec(loaded) + ' / ' + DebugJS.formatDec(total) + ' bytes'); } }, onFileLoaded: function(e) { var ctx = DebugJS.ctx; var file = ctx.fileReader.file; var content = ''; try { if (ctx.fileReader.result != null) content = ctx.fileReader.result; } catch (e) { DebugJS._log.e('onFileLoaded: ' + e); } if (ctx.fileVwrMode == 'bin') { ctx.onFileLoadedBin(ctx, file, content); } else { ctx.onFileLoadedB64(ctx, file, content); } setTimeout(ctx.fileLoadFinalize, 1000); var isB64 = (ctx.fileVwrMode == 'b64'); DebugJS.callEvtListeners('fileloaded', file, content, isB64); ctx.fileVwrSysCb = null; DebugJS.file.finalize(); }, onAbortLoadFile: function(e) { DebugJS.ctx.fileVwrSysCb = null; DebugJS.file.finalize(); DebugJS.ctx.updateFilePreview('File read cancelled.'); setTimeout(DebugJS.ctx.fileLoadFinalize, 1000); }, onFileLoadError: function(e) { DebugJS.ctx.fileVwrSysCb = null; DebugJS.file.finalize(); var te = e.target.error; var err; switch (te.code) { case te.NOT_FOUND_ERR: err = 'NOT_FOUND_ERR'; break; case te.SECURITY_ERR: err = 'SECURITY_ERR'; break; case te.NOT_READABLE_ERR: err = 'NOT_READABLE_ERR'; break; case te.ABORT_ERR: err = 'ABORT_ERR'; break; default: err = 'FILE_READ_ERROR (' + te.code + ')'; } DebugJS.ctx.updateFilePreview(err); }, openViewerB64: function() { var ctx = DebugJS.ctx; ctx.fileVwrMode = 'b64'; ctx.filePreviewWrapper.appendChild(ctx.fileVwrDtUrlWrp); var dtSrc = ctx.dataSrcType(); switch (dtSrc) { case 'file': if (ctx.fileVwrByteArray) { ctx.viewBinAsB64(ctx); } else { ctx.loadFile(ctx.fileVwrFile, 'b64'); } break; case 'b64': ctx.showB64Preview(ctx, null, ctx.fileVwrDataSrc.scheme, ctx.fileVwrDataSrc.data); break; case 'bin': case 'hex': ctx.viewBinAsB64(ctx); } }, openViewerBin: function() { var ctx = DebugJS.ctx; ctx.fileVwrMode = 'bin'; if (DebugJS.isChild(ctx.filePreviewWrapper, ctx.fileVwrDtUrlWrp)) { ctx.filePreviewWrapper.removeChild(ctx.fileVwrDtUrlWrp); } var dtSrc = ctx.dataSrcType(); switch (dtSrc) { case 'file': if (ctx.fileVwrDataSrc) { ctx.decodeB64dataAsB(ctx.fileVwrDataSrc.data); } else { ctx.loadFile(ctx.fileVwrFile, 'bin'); } break; case 'b64': case 'bin': case 'hex': ctx.decodeB64dataAsB(ctx.fileVwrDataSrc.data); break; default: ctx.updateFilePreview(''); } }, decodeFileVwrData: function() { var ctx = DebugJS.ctx; var mode = ctx.fileVwrDecMode; var scheme = ctx.fileVwrDtUrlScheme.value; var data = ctx.fileVwrDtTxtArea.value; ctx.clearFile(); if (mode != 'txt') { data = DebugJS.delAllNL(DebugJS.delAllSP(data)); } ctx.fileVwrDataSrc = {scheme: scheme, data: data}; ctx.setDataUrl(ctx, scheme, data); switch (mode) { case 'bin': ctx.fileVwrDataSrcType = 'bin'; ctx.decodeBin(ctx, data); break; case 'hex': ctx.fileVwrDataSrcType = 'hex'; ctx.decodeHex(ctx, data); break; default: if (mode == 'txt') { data = DebugJS.encodeBase64(data); ctx.fileVwrDtTxtArea.value = ctx.fileVwrDataSrc.data = data; } ctx.fileVwrDataSrcType = 'b64'; ctx.showB64Preview(ctx, null, scheme, data); } }, decodeBin: function(ctx, bin) { ctx.fileVwrByteArray = DebugJS.str2binArr(bin, 8, '0b'); ctx.viewBinAsB64(ctx); }, decodeHex: function(ctx, hex) { ctx.fileVwrByteArray = DebugJS.str2binArr(hex, 2, '0x'); ctx.viewBinAsB64(ctx); }, decodeB64dataAsB: function(b64) { var a = DebugJS.Base64.decode(b64); DebugJS.ctx.fileVwrByteArray = a; DebugJS.ctx.showBinDump(DebugJS.ctx, a); }, viewBinAsB64: function(ctx) { var file = ctx.fileVwrFile; var scheme; if (file) { scheme = 'data:' + file.type + ';base64'; } else { scheme = ctx.fileVwrDataSrc.scheme; } var lm = ctx.props.prevlimit; if (file && (file.size > lm)) { ctx.showFileSizeExceeds(ctx, file, lm); } else { var data = DebugJS.Base64.encode(ctx.fileVwrByteArray); ctx.fileVwrDataSrc = {scheme: scheme, data: data}; ctx.setDataUrl(ctx, scheme, data); ctx.showB64Preview(ctx, file, scheme, data); } }, onFileLoadedB64: function(ctx, file, dturl) { if (file) { var LIMIT = ctx.props.prevlimit; if (file.size > LIMIT) { ctx.showFileSizeExceeds(ctx, file, LIMIT); return; } else if (file.size == 0) { ctx.updateFilePreview(ctx.getFileInfo(file)); return; } } var b64cnt = DebugJS.splitDataUrl(dturl); ctx.fileVwrDataSrc = b64cnt; var cType = DebugJS.getContentType(null, file, b64cnt.data); if (cType == 'text') { if (ctx.fileVwrSysCb) { var decoded = DebugJS.decodeB64(b64cnt.data); ctx.fileVwrSysCb(ctx, file, decoded); } } DebugJS.file.onLoaded(file, dturl); ctx.setDataUrl(ctx, b64cnt.scheme, b64cnt.data); ctx.showB64Preview(ctx, file, b64cnt.scheme, b64cnt.data); }, onFileLoadedBin: function(ctx, file, content) { var buf = new Uint8Array(content); ctx.fileVwrByteArray = buf; DebugJS.file.onLoaded(file, buf); ctx.showBinDump(ctx, buf); }, switchFileScreen: function() { var ctx = DebugJS.ctx; if (ctx.fileVwrMode == 'b64') { ctx.fileVwrRadioBin.checked = true; ctx.openViewerBin(); } else { ctx.fileVwrRadioB64.checked = true; ctx.openViewerB64(); } }, toggleDecMode: function() { var ctx = DebugJS.ctx; var a = ['b64', 'hex', 'bin', 'txt']; var mode = DebugJS.nextArr(a, ctx.fileVwrDecMode); ctx.setDecMode(ctx, mode); }, setDecMode: function(ctx, mode) { ctx.fileVwrDecMode = mode; ctx.fileVwrDecModeBtn.innerText = '[' + mode.toUpperCase() + ']'; }, toggleBinMode: function() { var ctx = DebugJS.ctx; var a = ['hex', 'bin', 'dec']; var opt = ctx.fileVwrBinViewOpt; opt.mode = DebugJS.nextArr(a, opt.mode); ctx.showBinDump(ctx, ctx.fileVwrByteArray); }, toggleShowAddr: function() { DebugJS.ctx.toggleBinVwrOpt(DebugJS.ctx, 'addr'); }, toggleShowSpace: function() { DebugJS.ctx.toggleBinVwrOpt(DebugJS.ctx, 'space'); }, toggleShowAscii: function() { DebugJS.ctx.toggleBinVwrOpt(DebugJS.ctx, 'ascii'); }, toggleBinVwrOpt: function(ctx, key) { var ctx = DebugJS.ctx; var opt = ctx.fileVwrBinViewOpt; opt[key] = (opt[key] ? false : true); var file = ctx.fileVwrFile; var html = ''; if (file) html += ctx.getFileInfo(file); html += ctx.getBinDumpHtml(ctx.fileVwrByteArray, opt.mode, opt.addr, opt.space, opt.ascii); ctx.updateFilePreview(html); }, showBinDump: function(ctx, buf) { var file = ctx.fileVwrFile; var opt = ctx.fileVwrBinViewOpt; var html = ''; if (file) html += ctx.getFileInfo(file); html += ctx.getBinDumpHtml(buf, opt.mode, opt.addr, opt.space, opt.ascii); ctx.updateFilePreview(html); }, showB64Preview: function(ctx, file, scheme, data) { var html = ''; if (file) { var LIMIT = ctx.props.prevlimit; if (file.size > LIMIT) { ctx.showFileSizeExceeds(ctx, file, LIMIT); return; } else if (file.size == 0) { ctx.updateFilePreview(html); return; } html += ctx.getFileInfo(file); } var cType = DebugJS.getContentType(scheme, file, data); if (cType == 'image') { html += ctx.getImgPreview(ctx, scheme, data); } else { var decoded = DebugJS.decodeB64(data); html += ctx.getTextPreview(decoded); } ctx.updateFilePreview(html); }, setDataUrl: function(ctx, scheme, data) { scheme = scheme.replace(/,$/, ''); ctx.fileVwrDtUrlScheme.value = scheme + ','; ctx.fileVwrDtTxtArea.value = data; }, getFileInfo: function(file) { var lastMod = (file.lastModified ? file.lastModified : file.lastModifiedDate); var dt = DebugJS.getDateTime(lastMod); var fileDate = DebugJS.convDateTimeStr(dt); var s = '<span style="color:#cff">' + 'file : ' + file.name + '\n' + 'type : ' + file.type + '\n' + 'size : ' + DebugJS.formatDec(file.size) + ' ' + DebugJS.plural('byte', file.size) + '\n' + 'modified: ' + fileDate + '</span>\n'; return s; }, showFileSizeExceeds: function(ctx, file, lm) { var html = ctx.getFileInfo(file) + '<span style="color:' + ctx.opt.logColorW + '">The file size exceeds the limit allowed. (limit=' + lm + ')</span>'; ctx.updateFilePreview(html); }, getTextPreview: function(decoded) { if (decoded.length == 0) return ''; var txt = DebugJS.escTags(decoded); txt = txt.replace(/\r\n/g, DebugJS.CHR_CRLF_S + '\n'); txt = txt.replace(/([^>])\n/g, '$1' + DebugJS.CHR_LF_S + '\n'); txt = txt.replace(/\r/g, DebugJS.CHR_CR_S + '\n'); return (txt + DebugJS.EOF + '\n'); }, toggleShowHideCC: function() { var el = document.getElementsByClassName('dbg-cc'); for (var i = 0; i < el.length; i++) { DebugJS.toggleElShowHide(el[i]); } }, getImgPreview: function(ctx, scheme, data) { var ctxSizePos = ctx.getSelfSizePos(); return '<img src="' + DebugJS.buildDataUrl(scheme, data) + '" id="' + ctx.id + '-img-preview" style="max-width:' + (ctxSizePos.w - 32) + 'px;max-height:' + (ctxSizePos.h - (ctx.computedFontSize * 13) - 8) + 'px">\n'; }, resizeImgPreview: function() { var ctx = DebugJS.ctx; if ((!(ctx.status & DebugJS.ST_TOOLS)) || (!(ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_FILE)) || (!(ctx.fileVwrMode == 'b64'))) { return; } var imgPreview = document.getElementById(ctx.id + '-img-preview'); if (imgPreview == null) return; var ctxSizePos = ctx.getSelfSizePos(); var maxW = (ctxSizePos.w - 32); if (maxW < 100) maxW = 100; var maxH = (ctxSizePos.h - (ctx.computedFontSize * 13) - 8); if (maxH < 100) maxH = 100; imgPreview.style.maxWidth = maxW + 'px'; imgPreview.style.maxHeight = maxH + 'px'; }, getBinDumpHtml: function(buf, mode, showAddr, showSp, showAscii) { if (buf == null) return ''; var ctx = DebugJS.ctx; var lm = ctx.props.hexdumplimit | 0; var lastRows = ctx.props.hexdumplastrows | 0; var lastLen = 0x10 * lastRows; var bLen = buf.length; if (lm == 0) lm = bLen; var len = ((bLen > lm) ? lm : bLen); if (len % 0x10 != 0) { len = (((len / 0x10) + 1) | 0) * 0x10; } var html = '<pre style="white-space:pre !important">'; html += DebugJS.ui.createBtnHtml('[' + mode.toUpperCase() + ']', 'DebugJS.ctx.toggleBinMode()') + ' '; html += DebugJS.ui.createBtnHtml('[ADDR]', 'DebugJS.ctx.toggleShowAddr()', (showAddr ? '' : 'color:' + DebugJS.COLOR_INACT)) + ' '; html += DebugJS.ui.createBtnHtml('[SP]', 'DebugJS.ctx.toggleShowSpace()', (showSp ? '' : 'color:' + DebugJS.COLOR_INACT)) + ' '; html += DebugJS.ui.createBtnHtml('[ASCII]', 'DebugJS.ctx.toggleShowAscii()', (showAscii ? '' : 'color:' + DebugJS.COLOR_INACT)); html += '\n<span style="background:#0cf;color:#000">'; if (showAddr) { html += 'Address '; } if (mode == 'bin') { if (showSp) { html += '+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F '; } else { html += '+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F '; } } else if (mode == 'dec') { if (showSp) { html += ' +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F'; } else { html += ' +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F'; } } else { if (showSp) { html += '+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F'; } else { html += '+0+1+2+3+4+5+6+7+8+9+A+B+C+D+E+F'; } } if (showAscii) { html += ' ASCII '; } html += '</span>\n'; if (showAddr) { html += DebugJS.dumpAddr(0); } for (var i = 0; i < len; i++) { html += ctx.getDump(mode, i, buf, len, showSp, showAddr, showAscii); } if (bLen > lm) { if (bLen - lm > (0x10 * lastRows)) { html += '\n<span style="color:#ccc">...</span>'; } if (lastRows > 0) { var rem = (bLen % 0x10); var start = (rem == 0 ? (bLen - lastLen) : ((bLen - rem) - (0x10 * (lastRows - 1)))); if (start < len) { rem = ((len - start) % 0x10); start = len + rem; } var end = bLen + (rem == 0 ? 0 : (0x10 - rem)); html += '\n'; if (showAddr) { html += DebugJS.dumpAddr(start); } for (i = start; i < end; i++) { html += ctx.getDump(mode, i, buf, end, showSp, showAddr, showAscii); } } } html += '</pre>'; return html; }, getDump: function(mode, i, buf, len, showSp, showAddr, showAscii) { var b; if (mode == 'bin') { b = DebugJS.dumpBin(i, buf); } else if (mode == 'dec') { b = DebugJS.dumpDec(i, buf); } else { b = DebugJS.dumpHex(i, buf); } if ((i + 1) % 0x10 == 0) { if (showAscii) { b += ' ' + DebugJS.dumpAscii(((i + 1) - 0x10), buf, len); } if ((i + 1) < len) { b += '\n'; if (showAddr) { b += DebugJS.dumpAddr(i + 1); } } } else if (showSp) { if ((i + 1) % 8 == 0) { b += ' '; } else { b += ' '; } } return b; }, updateFilePreview: function(html) { DebugJS.ctx.filePreview.innerHTML = html + '\n'; DebugJS.ctx.filePreviewWrapper.scrollTop = 0; }, fileLoadFinalize: function() { DebugJS.removeClass(DebugJS.ctx.fileVwrFooter, 'dbg-loading'); }, reloadFile: function() { DebugJS.ctx.loadFile(DebugJS.ctx.fileVwrFile, DebugJS.ctx.fileVwrMode); }, clearFile: function() { var ctx = DebugJS.ctx; ctx.fileVwrDataSrcType = null; ctx.fileVwrFile = null; ctx.fileVwrDataSrc = null; ctx.fileVwrByteArray = null; ctx.fileReader = null; if (ctx.fileVwrPanel) { ctx.filePreview.innerText = 'Drop a file here'; ctx.setDtSchmTxt(); ctx.fileVwrDtTxtArea.value = ''; } }, dataSrcType: function() { return DebugJS.ctx.fileVwrDataSrcType; }, setDtSchm: function(type) { DebugJS.ctx.fileVwrDtUrlScheme.value = 'data:' + type + ';base64,'; }, setDtSchmTxt: function() { DebugJS.ctx.setDtSchm('text/plain'); }, setDtSchmImg: function() { DebugJS.ctx.setDtSchm('image/jpeg'); }, decodeDataURL: function(ctx, s) { ctx.clearFile(); ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'file', 'b64'); ctx.openViewerB64(); var d = DebugJS.splitDataUrl(s); ctx.setDataUrl(ctx, d.scheme, d.data); ctx.setDecMode(ctx, 'b64'); ctx.decodeFileVwrData(); }, openHtmlEditor: function() { var ctx = DebugJS.ctx; if (!ctx.htmlPrevBasePanel) { ctx.createHtmlPrevBasePanel(ctx); } else { ctx.toolsBodyPanel.appendChild(ctx.htmlPrevBasePanel); } ctx.htmlPrevEditor.focus(); }, createHtmlPrevBasePanel: function(ctx) { ctx.htmlPrevBasePanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); ctx.htmlPrevPrevPanel = document.createElement('div'); ctx.htmlPrevPrevPanel.style.height = '50%'; ctx.htmlPrevPrevPanel.innerHTML = 'HTML PREVIEWER'; ctx.htmlPrevBasePanel.appendChild(ctx.htmlPrevPrevPanel); ctx.htmlPrevEditorPanel = document.createElement('div'); var html = '<span style="color:#ccc">HTML Editor</span>' + DebugJS.ui.createBtnHtml('[DRAW]', 'DebugJS.ctx.drawHtml();DebugJS.ctx.htmlPrevEditor.focus();', 'float:right;margin-right:4px') + DebugJS.ui.createBtnHtml('[CLR]', 'DebugJS.ctx.insertHtmlSnippet();', 'margin-left:4px;margin-right:4px'); for (var i = 0; i < 5; i++) { html += ctx.createHtmlSnippetBtn(ctx, i); } ctx.htmlPrevEditorPanel.innerHTML = html; ctx.htmlPrevBasePanel.appendChild(ctx.htmlPrevEditorPanel); ctx.htmlPrevEditor = document.createElement('textarea'); ctx.htmlPrevEditor.className = 'dbg-editor'; ctx.setStyle(ctx.htmlPrevEditor, 'height', 'calc(50% - ' + (ctx.computedFontSize + 10) + 'px)'); ctx.htmlPrevEditor.onblur = ctx.saveHtmlBuf; ctx.htmlPrevEditor.value = ctx.htmlPrevBuf; ctx.htmlPrevBasePanel.appendChild(ctx.htmlPrevEditor); }, createHtmlSnippetBtn: function(ctx, i) { return DebugJS.ui.createBtnHtml('&lt;CODE' + (i + 1) + '&gt;', 'DebugJS.ctx.insertHtmlSnippet(' + i + ');', 'margin-left:4px'); }, insertHtmlSnippet: function(n) { var editor = DebugJS.ctx.htmlPrevEditor; if (n == undefined) { editor.value = ''; editor.focus(); } else { var code = DebugJS.HTML_SNIPPET[n]; var buf = editor.value; var posCursor = editor.selectionStart; var bufL = buf.substr(0, posCursor); var bufR = buf.substr(posCursor, buf.length); buf = bufL + code + bufR; DebugJS.ctx.htmlPrevEditor.focus(); DebugJS.ctx.htmlPrevEditor.value = buf; editor.selectionStart = editor.selectionEnd = posCursor + code.length; } }, saveHtmlBuf: function() { DebugJS.ctx.htmlPrevBuf = DebugJS.ctx.htmlPrevEditor.value; }, drawHtml: function() { DebugJS.ctx.htmlPrevPrevPanel.innerHTML = DebugJS.ctx.htmlPrevBuf; }, closeHtmlEditor: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_HTML) && (ctx.htmlPrevBasePanel)) { ctx.removeToolFuncPanel(ctx, ctx.htmlPrevBasePanel); } }, openBatEditor: function() { var ctx = DebugJS.ctx; if (!ctx.batBasePanel) { ctx.createBatBasePanel(ctx); } else { ctx.toolsBodyPanel.appendChild(ctx.batBasePanel); } ctx.batTextEditor.focus(); }, createBatBasePanel: function(ctx) { var basePanel = DebugJS.addSubPanel(ctx.toolsBodyPanel); ctx.batResumeBtn = DebugJS.ui.addBtn(basePanel, '[RESUME]', null); ctx.batResumeBtn.style.float = 'right'; ctx.batRunBtn = DebugJS.ui.addBtn(basePanel, '[ RUN ]', ctx.startPauseBat); ctx.batStopBtn = DebugJS.ui.addBtn(basePanel, '[STOP]', DebugJS.bat.terminate); DebugJS.ui.addLabel(basePanel, ' FROM:'); ctx.batStartTxt = DebugJS.ui.addTextInput(basePanel, '45px', 'left', ctx.opt.fontColor, '', null); DebugJS.ui.addLabel(basePanel, ' TO:'); ctx.batEndTxt = DebugJS.ui.addTextInput(basePanel, '45px', 'left', ctx.opt.fontColor, '', null); DebugJS.ui.addLabel(basePanel, ' Arg:'); ctx.batArgTxt = DebugJS.ui.addTextInput(basePanel, '80px', 'left', ctx.opt.fontColor, '', null); DebugJS.ui.addLabel(basePanel, ' L:'); ctx.batCurPc = DebugJS.ui.addLabel(basePanel, '0'); DebugJS.ui.addLabel(basePanel, '/').style.color = '#ccc'; ctx.batTotalLine = DebugJS.ui.addLabel(basePanel, DebugJS.bat.cmds.length); DebugJS.ui.addLabel(basePanel, ' N:'); ctx.batNestLv = DebugJS.ui.addLabel(basePanel, '0'); ctx.batTextEditor = document.createElement('textarea'); ctx.batTextEditor.className = 'dbg-editor'; ctx.setStyle(ctx.batTextEditor, 'height', 'calc(100% - ' + (ctx.computedFontSize * 2) + 'px)'); ctx.enableDnDFileLoad(ctx.batTextEditor, ctx.onDropOnBat); basePanel.appendChild(ctx.batTextEditor); ctx.batBasePanel = basePanel; ctx.setBatTxt(ctx); ctx.setBatArgTxt(ctx); ctx.updateCurPc(); ctx.updateBatNestLv(); ctx.updateBatRunBtn(); ctx.updateBatResumeBtn(); }, startPauseBat: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_BAT_RUNNING) { if (ctx.status & DebugJS.ST_BAT_PAUSE) { DebugJS.bat._resume(); } else { DebugJS.bat.pause(); } } else { ctx.runBat(ctx); } }, runBat: function(ctx) { var bat = DebugJS.bat; bat.store(ctx.batTextEditor.value); var a = ctx.batArgTxt.value; try { bat.setExecArg(eval(a)); } catch (e) { DebugJS._log.e('BAT ARG ERROR (' + e + ')'); return; } var s = ctx.batStartTxt.value; var e = ctx.batEndTxt.value; if (s == '') s = undefined; if (e == '') e = undefined; bat.run(s, e); }, updateBatRunBtn: function() { var ctx = DebugJS.ctx; if (!ctx.batRunBtn) return; var label = ' RUN '; var color = '#0f0'; if (ctx.status & DebugJS.ST_BAT_RUNNING) { if (!(ctx.status & DebugJS.ST_BAT_PAUSE)) { label = 'PAUSE'; color = '#ff0'; } ctx.setStyle(ctx.batStopBtn, 'color', '#f66'); } else { ctx.setStyle(ctx.batStopBtn, 'color', '#a99'); } ctx.batRunBtn.innerText = '[' + label + ']'; ctx.setStyle(ctx.batRunBtn, 'color', color); }, updateBatResumeBtn: function() { var ctx = DebugJS.ctx; if (!ctx.batResumeBtn) return; var color = DebugJS.COLOR_INACT; var fn = null; if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD_KEY) { color = ctx.opt.btnColor; fn = ctx.batResume; } else if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD) { color = ctx.opt.btnColor; } ctx.setStyle(ctx.batResumeBtn, 'color', color); ctx.batResumeBtn.onclick = fn; }, batResume: function() { DebugJS.bat._resume('cmd-key'); }, setBatTxt: function(ctx) { var b = ''; var cmds = DebugJS.bat.cmds; for (var i = 0; i < cmds.length; i++) { b += cmds[i] + '\n'; } if (ctx.batTextEditor) { ctx.batTextEditor.value = b; } }, setBatArgTxt: function(ctx) { if (ctx.batArgTxt) { var a = DebugJS.bat.ctrl.execArg; if ((typeof a == 'string') && (a != '')) {a = '"' + a + '"';} ctx.batArgTxt.value = a + ''; } }, updateCurPc: function(b) { var pc = DebugJS.bat.ctrl.pc; var df = DebugJS.digits(DebugJS.bat.cmds.length) - DebugJS.digits(pc); var pdng = ''; for (var i = 0; i < df; i++) { pdng += '0'; } if (DebugJS.ctx.batCurPc) { DebugJS.ctx.batCurPc.innerText = pdng + pc; DebugJS.ctx.batCurPc.style.color = (b ? '#f66' : ''); } }, updateTotalLine: function() { if (DebugJS.ctx.batTotalLine) { DebugJS.ctx.batTotalLine.innerText = DebugJS.bat.cmds.length; } }, updateBatNestLv: function() { if (DebugJS.ctx.batNestLv) { DebugJS.ctx.batNestLv.innerText = DebugJS.bat.nestLv(); } }, closeBatEditor: function() { var ctx = DebugJS.ctx; if ((ctx.toolsActiveFnc & DebugJS.TOOLS_FNC_BAT) && (ctx.batBasePanel)) { ctx.removeToolFuncPanel(ctx, ctx.batBasePanel); } }, toggleExtPanel: function() { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_EXT_PANEL) { ctx.closeExtPanel(ctx); } else { ctx.openExtPanel(ctx); } }, openExtPanel: function(ctx) { ctx.status |= DebugJS.ST_EXT_PANEL; ctx.featStack.push(DebugJS.ST_EXT_PANEL); ctx.addOverlayPanelFull(ctx.extPanel); var activePanel = ctx.extActPnlIdx; if (activePanel == -1) { var activePanel = ctx.nextValidExtPanelIdx(ctx, activePanel); ctx.switchExtPanel(activePanel); } else { var p = ctx.extPanels[activePanel]; if ((p) && (p.onActive)) ctx.onExtPanelActive(ctx, p); } ctx.updateExtBtns(ctx); ctx.updateExtBtn(ctx); }, createExtHeaderBtn: function(ctx, label, idx) { var MAX_LEN = 20; label = DebugJS.trimDownText(label, MAX_LEN); var fn = new Function('DebugJS.ctx.switchExtPanel(' + idx + ');'); var btn = DebugJS.ui.addBtn(ctx.extHeaderPanel, '<' + label + '>', fn); btn.style.marginRight = '4px'; ctx.setStyle(btn, 'color', DebugJS.SBPNL_COLOR_INACT); btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.extPanels[' + idx + '].btn, \'color\', DebugJS.SBPNL_COLOR_ACTIVE);'); btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.extPanels[' + idx + '].btn, \'color\', (DebugJS.ctx.extActPnlIdx == ' + idx + ') ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT);'); return btn; }, closeExtPanel: function(ctx) { if ((ctx.extPanel) && (ctx.extPanel.parentNode)) { var p = ctx.extPanels[ctx.extActPnlIdx]; if ((p) && (p.onInActive)) ctx.onExtPanelInActive(ctx, p); ctx.removeOverlayPanelFull(ctx.extPanel); } ctx.status &= ~DebugJS.ST_EXT_PANEL; DebugJS.delArrVal(ctx.featStack, DebugJS.ST_EXT_PANEL); ctx.updateExtBtn(ctx); }, switchExtPanel: function(idx) { var ctx = DebugJS.ctx; var pnls = ctx.extPanels; if (ctx.extActPnlIdx == idx) return; if (ctx.extActPnlIdx != -1) { var p2 = pnls[ctx.extActPnlIdx]; if (p2) { if ((ctx.status & DebugJS.ST_EXT_PANEL) && (p2.onInActive)) { ctx.onExtPanelInActive(ctx, p2); } ctx.extBodyPanel.removeChild(p2.base); } } var p1 = pnls[idx]; ctx.extBodyPanel.appendChild(p1.base); if (p1) { if ((ctx.status & DebugJS.ST_EXT_PANEL) && (p1.onActive)) { ctx.onExtPanelActive(ctx, p1); } } ctx.extActPnlIdx = idx; ctx.updateExtBtns(ctx); }, onExtPanelActive: function(ctx, p) { ctx.extActivePanel = p.panel; p.onActive(p.panel); }, onExtPanelInActive: function(ctx, p) { ctx.extActivePanel = null; p.onInActive(p.panel); }, prevValidExtPanelIdx: function(ctx, idx) { if (idx > 0) { for (var i = idx - 1; i >= 0; i--) { if (ctx.extPanels[i] != null) return i; } } return -1; }, nextValidExtPanelIdx: function(ctx, idx) { for (var i = idx + 1; i < ctx.extPanels.length; i++) { if (ctx.extPanels[i] != null) return i; } return -1; }, existsValidExtPanel: function(ctx) { for (var i = 0; i < ctx.extPanels.length; i++) { if (ctx.extPanels[i] != null) return true; } return false; }, updateExtBtns: function(ctx) { var pnls = ctx.extPanels; for (var i = 0; i < pnls.length; i++) { var p = pnls[i]; if (p != null) { ctx.setStyle(p.btn, 'color', (ctx.extActPnlIdx == i) ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT); } } }, createSubBasePanel: function(ctx) { var base = document.createElement('div'); base.className = 'dbg-overlay-panel-full'; var head = document.createElement('div'); head.style.position = 'relative'; head.style.height = ctx.computedFontSize + 'px'; base.appendChild(head); var body = document.createElement('div'); body.style.position = 'relative'; body.style.height = 'calc(100% - ' + ctx.computedFontSize + 'px)'; base.appendChild(body); return {base: base, head: head, body: body}; }, isOnDbgWin: function(x, y) { var sp = DebugJS.ctx.getSelfSizePos(); return (((x >= sp.x1) && (x <= sp.x2)) && ((y >= sp.y1) && (y <= sp.y2))); }, getSelfSizePos: function() { var ctx = DebugJS.ctx; var rect = ctx.win.getBoundingClientRect(); var resizeBoxSize = 6; var sp = {}; sp.w = ctx.win.clientWidth; sp.h = ctx.win.clientHeight; sp.x1 = rect.left - resizeBoxSize / 2; sp.y1 = rect.top - resizeBoxSize / 2; sp.x2 = sp.x1 + ctx.win.clientWidth + resizeBoxSize + DebugJS.WIN_BORDER; sp.y2 = sp.y1 + ctx.win.clientHeight + resizeBoxSize + DebugJS.WIN_BORDER; return sp; }, setSelfSizeW: function(ctx, w) { ctx.win.style.width = w + 'px'; ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, setSelfSizeH: function(ctx, h) { ctx.win.style.height = h + 'px'; ctx.resizeMainHeight(); ctx.resizeImgPreview(); }, expandHight: function(ctx, height) { if (!(ctx.uiStatus & DebugJS.UI_ST_DYNAMIC)) return; ctx.saveExpandModeOrgSizeAndPos(ctx); var clientH = document.documentElement.clientHeight; var sp = ctx.getSelfSizePos(); if (sp.h >= height) { return; } else if (clientH <= height) { height = clientH; } ctx.setSelfSizeH(ctx, height); sp = ctx.getSelfSizePos(); if (ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) { ctx.adjustDbgWinPos(ctx); } else { if (sp.y2 > clientH) { if (clientH < (height + ctx.opt.adjustY)) { ctx.win.style.top = 0; } else { var top = clientH - height - ctx.opt.adjustY; ctx.win.style.top = top + 'px'; } } } }, expandHightIfNeeded: function(ctx) { if (ctx.winExpandCnt == 0) ctx.expandHight(ctx, ctx.winExpandHeight); ctx.winExpandCnt++; }, resetExpandedHeight: function(ctx) { if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { ctx.win.style.width = ctx.expandModeOrg.w + 'px'; ctx.win.style.height = ctx.expandModeOrg.h + 'px'; ctx.resizeMainHeight(); ctx.resizeImgPreview(); ctx.scrollLogBtm(ctx); if (ctx.uiStatus & DebugJS.UI_ST_POS_AUTO_ADJUST) { ctx.adjustDbgWinPos(ctx); } } }, resetExpandedHeightIfNeeded: function(ctx) { ctx.winExpandCnt--; if (ctx.winExpandCnt == 0) ctx.resetExpandedHeight(ctx); }, saveExpandModeOrgSizeAndPos: function(ctx) { var shadow = (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) ? (DebugJS.WIN_SHADOW / 2) : 0; ctx.expandModeOrg.w = (ctx.win.offsetWidth + DebugJS.WIN_BORDER - shadow); ctx.expandModeOrg.h = (ctx.win.offsetHeight + DebugJS.WIN_BORDER - shadow); ctx.expandModeOrg.t = ctx.win.offsetTop; ctx.expandModeOrg.l = ctx.win.offsetLeft; }, turnLed: function(pos, active) { var ctx = DebugJS.ctx; var bit = DebugJS.LED_BIT[pos]; if (active) { ctx.led |= bit; } else { ctx.led &= ~bit; } ctx.updateLedPanel(); }, setLed: function(val) { try { DebugJS.ctx.led = eval(val); DebugJS.ctx.updateLedPanel(); } catch (e) { DebugJS._log.e('Invalid value'); } }, setMsg: function(m) { DebugJS.ctx.msgString = m; DebugJS.ctx.updateMsgLabel(); }, execCmd: function(ctx) { var cl = ctx.cmdLine.value; ctx.cmdLine.value = ''; if (cl == '') { DebugJS._log(''); return; } if (cl.substr(0, 2) == '!!') { var ev = ctx.getLastHistory(); if (ev == '') { DebugJS._log.w('!!: event not found'); return; } cl = ev + cl.substr(2); } else if (cl.substr(0, 1) == '!') { var s = cl.substr(1).match(/(\d*)(.*)/); var num = s[1]; var arg = s[2]; if (num != '') { var ev = ctx.getHistory((num | 0) - 1); if (ev == '') { DebugJS._log.w('!' + num + ': event not found'); return; } cl = ev + arg; } else if (arg != '') { cl = '!' + arg; } } ctx._execCmd(cl, ctx.cmdEchoFlg, false, true); }, _execCmd: function(str, echo, recho, sv) { var ctx = DebugJS.ctx; if (sv) ctx.saveHistory(ctx, str); var setValName = null; var cmdline = str; if (str.match(/^\s*@/)) { echo = false; cmdline = str.substr(str.indexOf('@') + 1); } if (echo) { var echoStr = str; echoStr = DebugJS.escTags(echoStr); echoStr = DebugJS.trimDownText(echoStr, DebugJS.CMD_ECHO_MAX_LEN, 'color:#aaa'); DebugJS._log.s(echoStr); } var cmds = DebugJS.splitCmdLineInTwo(cmdline); var cmd = cmds[0]; var valName = DebugJS.getCmdValName(cmd, '\\$', true); if (valName != null) { var vStartPos = cmdline.indexOf(valName); var restCmd = cmdline.substr(vStartPos + valName.length + 1); if (restCmd.match(/^\s*=/)) { setValName = valName; cmdline = restCmd.substr(restCmd.indexOf('=') + 1); } } var ret; echo = echo || recho; cmds = DebugJS.splitCmdLineInTwo(cmdline); if (cmds[0] == 'code') { ret = ctx.execCode(cmds[1], echo); } else { cmdline = DebugJS.replaceCmdVals(cmdline); ret = ctx.__execCmd(ctx, cmdline, echo); } if (setValName != null) { DebugJS.setCmdVal(setValName, ret); } return ret; }, __execCmd: function(ctx, cmdline, echo, aliased) { cmdline = DebugJS.escCtrlChr(cmdline); var cmds = DebugJS.splitCmdLineInTwo(cmdline); var cmd = cmds[0]; var arg = cmds[1]; if (!aliased) { for (var key in ctx.CMD_ALIAS) { if (cmd == key) { var cl = cmdline.replace(new RegExp(cmd), ctx.CMD_ALIAS[key]); return ctx.__execCmd(ctx, cl, echo, true); } } } for (var i = 0; i < ctx.CMD_TBL.length; i++) { if (cmd == ctx.CMD_TBL[i].cmd) { return ctx.CMD_TBL[i].fn(arg, ctx.CMD_TBL[i], echo); } } if (ctx.opt.disableAllCommands) return; for (i = 0; i < ctx.EXT_CMD_TBL.length; i++) { if (cmd == ctx.EXT_CMD_TBL[i].cmd) { return ctx.EXT_CMD_TBL[i].fn(arg, ctx.EXT_CMD_TBL[i], echo); } } if (cmdline.match(/^\s*http/)) { DebugJS.ctx.doHttpRequest('GET', cmdline); return; } var ret = ctx.cmdRadixConv(cmdline, echo); if (ret) return cmd | 0; ret = ctx.cmdTimeCalc(cmdline, echo); if (ret != null) return ret; ret = ctx.cmdDateCalc(cmdline, echo); if (ret != null) return ret; ret = ctx.cmdDateDiff(cmdline, echo); if (!isNaN(ret)) return ret; ret = ctx.cmdDateConv(cmdline, echo); if (ret != null) return ret; if (DebugJS.isTmStr(cmdline)) { ret = DebugJS.str2ms(cmdline); if (echo) DebugJS._log.res(ret); return ret; } if (cmdline.match(/^\s*U\+/i)) { return ctx.cmdUnicode('-d ' + cmdline, null, echo); } return ctx.execCode(cmdline, echo); }, cmdAlias: function(arg, tbl) { var ctx = DebugJS.ctx; if (DebugJS.countArgs(arg) == 0) { var lst = DebugJS.getKeys(ctx.CMD_ALIAS); return ctx._cmdAliasList(ctx, lst); } var p = arg.indexOf('='); if (p == -1) { return ctx._cmdAliasList(ctx, DebugJS.splitCmdLine(arg)); } var al = arg.substr(0, p).trim(); var v = arg.substring(p + 1, arg.length).trim(); var c = DebugJS.getQuotedStr(v); if (c == null) { c = DebugJS.splitArgs(v)[0]; } ctx.CMD_ALIAS[al] = c; }, _cmdAliasList: function(ctx, lst) { var s = ''; for (var i = 0; i < lst.length; i++) { if (i > 0) s += '\n'; s += ctx._cmdAliasDisp(ctx, lst[i]); } DebugJS._log.mlt(s); }, _cmdAliasDisp: function(ctx, al) { var s = 'alias ' + al; var c = ctx.CMD_ALIAS[al]; if (c == undefined) { s += ': not found'; } else { s += "='" + c + "'"; } return s; }, cmdBase64: function(arg, tbl, echo) { var iIdx = 0; if ((DebugJS.hasOpt(arg, 'd')) || (DebugJS.hasOpt(arg, 'e'))) iIdx++; return DebugJS.ctx.execEncAndDec(arg, tbl, echo, true, DebugJS.encodeB64, DebugJS.decodeB64, iIdx); }, cmdBat: function(arg, tbl, echo) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); var bat = DebugJS.bat; var ret; switch (a[0]) { case 'run': if ((ctx.status & DebugJS.ST_BAT_RUNNING) && (ctx.status & DebugJS.ST_BAT_PAUSE)) { bat._resume(); } else { if (ctx.batTextEditor) bat.store(ctx.batTextEditor.value); var s = DebugJS.getOptVal(arg, 's'); var e = DebugJS.getOptVal(arg, 'e'); var ag = DebugJS.getOptVal(arg, 'arg'); if ((s == null) && (e == null) && (a[1] != '-arg')) { s = a[1]; if ((s != undefined) && (!isNaN(s))) { return bat.exec1(s); } } if (ag == null) ag = undefined; bat.run(s, e, ag); } break; case 'symbols': var t = a[1]; if ((t != 'label') && (t != 'function')) { DebugJS.printUsage('bat symbols label|function "pattern"'); return; } var p = DebugJS.getArgsFrom(arg, 2); try { p = eval(p); } catch (e) { DebugJS._log.e('bat symbols: ' + e); return; } ret = bat.getSymbols(t, p); if (echo) DebugJS._log.p(ret); return ret; case 'list': if (bat.cmds.length == 0) { DebugJS._log('No batch script'); break; } var s = bat.list(a[1], a[2]); DebugJS._log.mlt(s); break; case 'status': var key = a[1]; if (key == undefined) { var st = '\n'; if (bat.cmds.length == 0) { st += 'No batch script'; } else { st += ((ctx.status & DebugJS.ST_BAT_RUNNING) ? '<span style="color:#0f0">RUNNING</span>' : '<span style="color:#f44">STOPPED</span>'); st += '\nNest Lv: ' + bat.nestLv(); } DebugJS._log.p(bat.ctrl, 0, st, false); } else { ret = bat.ctrl[key]; DebugJS._log(ret); } return ret; case 'pc': DebugJS._log.res(bat.ctrl.pc); return bat.ctrl.pc; break; case 'pause': case 'clear': bat[a[0]](); break; case 'set': ctx._cmdBatSet(DebugJS.getArgsFrom(arg, 1), echo); break; case 'stop': bat.terminate(); break; case 'exec': if (a[1] != undefined) { var b = DebugJS.decodeB64(a[1], true); if (b != '') { var ag = DebugJS.getArgsFrom(arg, 2); try { bat(b, eval(ag)); } catch (e) { DebugJS._log.e('BAT ERROR: Illegal argument (' + e + ')'); } } else { DebugJS._log.e('BAT ERROR: script must be encoded in Base64.'); } break; } default: DebugJS.printUsage(tbl.help); } }, _cmdBatSet: function(arg, echo) { var a = DebugJS.splitCmdLine(arg); var key = a[0]; var v = a[1]; if (!v) {DebugJS.printUsage('bat set break|delay val'); return;} try { v = eval(v); } catch (e) { DebugJS._log.e(e); return; } switch (key) { case 'b': case 'break': DebugJS.bat.ctrl.breakP = v; break; case 'delay': break; case 'pc': DebugJS.bat.setPc(v); break; default: DebugJS.printUsage('bat set b|break|delay|pc val'); return; } DebugJS.bat.ctrl[key] = v; if (echo) DebugJS._log.res(v); }, cmdBin: function(arg, tbl) { var data = DebugJS.ctx.radixCmd(arg, tbl); if (data == null) return; var r = DebugJS.convertBin(data); if (r) DebugJS._log(r); }, cmdBSB64: function(arg, tbl, echo) { var iIdx = 0; if ((DebugJS.hasOpt(arg, 'd')) || (DebugJS.hasOpt(arg, 'e'))) iIdx++; var toR = false; var n = DebugJS.getOptVal(arg, 'n'); if (n == null) { n = 1; } else { iIdx += 2; if (n.length > 1) { var d = n.charAt(n.length - 1); if (isNaN(d)) { if (d == 'R') toR = true; n = n.substr(0, n.length - 1); } } } return DebugJS.ctx.execEncAndDec(arg, tbl, echo, true, DebugJS.encodeBSB64, DebugJS.decodeBSB64, iIdx, n | 0, toR); }, cmdCall: function(arg, tbl) { if (DebugJS.bat.isCmdExecutable()) { DebugJS.ctx._cmdJump(DebugJS.ctx, arg, true, 'func'); } }, cmdClose: function(arg, tbl) { var ctx = DebugJS.ctx; var fn = DebugJS.splitArgs(arg)[0]; if (fn == 'all') { ctx.closeAllFeatures(ctx); return; } var d = { 'measure': DebugJS.ST_MEASURE, 'sys': DebugJS.ST_SYS_INFO, 'html': DebugJS.ST_HTML_SRC, 'dom': DebugJS.ST_ELM_INSPECTING, 'js': DebugJS.ST_JS, 'tool': DebugJS.ST_TOOLS, 'ext': DebugJS.ST_EXT_PANEL }; if (d[fn] === undefined) { DebugJS.printUsage(tbl.help); } else { ctx.closeFeature(ctx, d[fn]); } }, cmdClock: function(arg, tbl) { var ctx = DebugJS.ctx; ctx.launchFnc(ctx, 'tool', 'timer', 'clock'); ctx.timerClockSSS = DebugJS.hasOpt(arg, 'sss'); ctx.updateSSS(ctx); }, cmdCls: function(arg, tbl) { DebugJS.ctx.clearLog(); }, cmdCondWait: function(arg, tbl) { var bat = DebugJS.bat; var op = DebugJS.splitCmdLine(arg)[0]; switch (op) { case 'init': bat._initCond(); break; case 'set': var key = DebugJS.getOptVal(arg, 'key'); bat.ctrl.condKey = (key ? DebugJS.delAllSP(key) : key); break; case 'pause': if (bat.ctrl.condKey) { var to = DebugJS.getOptVal(arg, 'timeout'); DebugJS.ctx._cmdPause('key', bat.ctrl.condKey, to); } break; default: DebugJS.printUsage(tbl.help); } }, cmdDbgWin: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); switch (a[0]) { case 'hide': ctx.closeDbgWin(); break; case 'show': ctx.showDbgWin(); break; case 'opacity': var v = a[1]; if ((v <= 1) && (v >= 0.1)) { DebugJS.opacity(v); } else { DebugJS.printUsage('dbgwin opacity 0.1-1'); } break; case 'pos': ctx._cmdDbgWinPos(ctx, a[1], a[2]); break; case 'size': ctx._cmdDbgWinSize(ctx, a[1], a[2]); break; case 'status': ctx._cmdDbgWinStatus(ctx); break; case 'lock': ctx._cmdDbgWinLock(ctx, a); break; default: DebugJS.printUsage(tbl.help); } }, _cmdDbgWinPos: function(ctx, x, y) { if (!(ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) || (ctx.opt.mode == 'kiosk')) { return; } var sp; switch (x) { case 'n': case 'ne': case 'e': case 'se': case 's': case 'sw': case 'w': case 'nw': case 'c': sp = ctx.getSelfSizePos(); ctx.setWinPos(x, sp.w, sp.h); break; default: if (isNaN(x) || isNaN(y)) { sp = ctx.getSelfSizePos(); DebugJS._log('x=' + (sp.x1 + 3) + ' y=' + (sp.y1 + 3)); DebugJS.printUsage('dbgwin pos n|ne|e|se|s|sw|w|nw|c|x y'); break; } x |= 0; y |= 0; DebugJS.ctx.setDbgWinPos(y, x); } }, _cmdDbgWinSize: function(ctx, w, h) { if (!(ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) || (ctx.opt.mode == 'kiosk')) { return; } if (isNaN(w) || isNaN(h)) { var sp = ctx.getSelfSizePos(); DebugJS._log('w=' + (sp.w) + ' h=' + (sp.h)); DebugJS.printUsage('dbgwin size width height'); return; } w |= 0; h |= 0; if (w < ctx.computedMinW) w = ctx.computedMinW; if (h < ctx.computedMinH) h = ctx.computedMinH; ctx.setDbgWinSize(w, h); }, _cmdDbgWinStatus: function(ctx) { var sp = ctx.getSelfSizePos(); var s = 'width : ' + sp.w + '\n' + 'height: ' + sp.h + '\n' + 'posX1 : ' + sp.x1 + '\n' + 'posY1 : ' + sp.y1 + '\n' + 'posX2 : ' + sp.x2 + '\n' + 'posY2 : ' + sp.y2 + '\n'; DebugJS._log.mlt(s); }, _cmdDbgWinLock: function(ctx, a) { var c = a[1]; if (ctx.opt.lockCode == null) { if (c == undefined) { DebugJS.printUsage('dbgwin lock [code]'); return; } ctx.opt.lockCode = c; } ctx.lockDbgWin(ctx); }, cmdDate: function(arg, tbl) { var val = arg; var iso = false; var idx = DebugJS.indexOfOptVal(arg, '-iso'); if (idx >= 0) { iso = true; val = arg.substr(idx); } var d = DebugJS.date(val, iso); if (d == null) { DebugJS.printUsage(tbl.help); } else { if (!DebugJS.hasOpt(arg, 'q')) DebugJS._log.res(d); } return d; }, cmdDateConv: function(arg, echo) { var d = arg.trim(); if (!(DebugJS.isDateFormat(d) || DebugJS.isDateTimeFormat(d) || DebugJS.isDateTimeFormatIso(d) || (d == 'today'))) { return null; } if (d == 'today') d = DebugJS.today('/'); var r = DebugJS.date(d); if (r != null) { if (echo) DebugJS._log.res(r); } return r; }, cmdDateCalc: function(arg, echo) { var ret = null; arg = arg.trim(); if ((!DebugJS.isBasicDateFormat(arg, true)) && (!DebugJS.isDateFormat(arg, true)) && (!DebugJS.startsWith(arg, 'today'))) { return ret; } arg = DebugJS.delAllSP(arg); var sp = arg.charAt(4); if ((sp != '-') && (sp != '/')) sp = '-'; arg = arg.replace(/(\d{4})-(\d{1,})-(\d{1,})/g, '$1/$2/$3'); var op; if (arg.indexOf('+') >= 0) { op = '+'; } else if (arg.indexOf('-') >= 0) { op = '-'; } var v = arg.split(op); if (v.length < 2) return ret; var d1 = DebugJS.ctx._cmdFmtDate(v[0]); if (!DebugJS.isDateFormat(d1)) return ret; var d2 = v[1]; var t1 = DebugJS.getDateTime(d1).time; var t2 = (d2 | 0) * 86400000; var t; if (op == '-') { t = t1 - t2; } else { t = t1 + t2; } var d = DebugJS.getDateTime(t); if (isNaN(d.time)) return ret; ret = DebugJS.convDateStr(d, sp); if (echo) DebugJS._log.res(ret); return ret; }, cmdDateDiff: function(arg, echo) { var ret = NaN; var a = DebugJS.splitArgs(arg); if (a.length < 2) return ret; var d1 = DebugJS.ctx._cmdFmtDate(a[0]); var d2 = DebugJS.ctx._cmdFmtDate(a[1]); if ((!DebugJS.isDateFormat(d1)) || (!DebugJS.isDateFormat(d2))) return ret; d1 = d1.replace(/-/g, '/'); d2 = d2.replace(/-/g, '/'); ret = DebugJS.diffDate(d1, d2); if (echo && !isNaN(ret)) DebugJS._log.res(ret); return ret; }, _cmdFmtDate: function(d) { if ((d.length == 8) && (!isNaN(d))) { d = DebugJS.num2date(d); } else if (d == 'today') { d = DebugJS.today('/'); } return d; }, cmdDelay: function(arg, tbl) { var ctx = DebugJS.ctx; var d = DebugJS.splitArgs(arg)[0]; if (d == '-c') { ctx._cmdDelayCancel(ctx); return; } else if (d.match(/\|/)) { d = DebugJS.calcNextTime(d).t; d = DebugJS.calcTargetTime(d); } else if (DebugJS.isTimeFormat(d)) { d = DebugJS.calcTargetTime(d); } else if (DebugJS.isTmStr(d)) { d = DebugJS.str2ms(d); } else if ((d == '') || (isNaN(d))) { DebugJS.printUsage(tbl.help); return; } var c = DebugJS.getArgsFrom(arg, 1); ctx.cmdDelayData.cmd = c; ctx._cmdDelayCancel(ctx); ctx.cmdDelayData.tmid = setTimeout(ctx._cmdDelayExec, d | 0); }, _cmdDelayExec: function() { var ctx = DebugJS.ctx; ctx.cmdDelayData.tmid = 0; var c = ctx.cmdDelayData.cmd; if (c == '') { DebugJS._log(c); } else { ctx._execCmd(c, false, ctx.cmdEchoFlg); } ctx.cmdDelayData.cmd = null; }, _cmdDelayCancel: function(ctx) { if (ctx.cmdDelayData.tmid > 0) { clearTimeout(ctx.cmdDelayData.tmid); ctx.cmdDelayData.tmid = 0; DebugJS._log('command delay execution has been canceled.'); } }, cmdEcho: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg)[0]; if (a == '') { DebugJS._log(ctx.cmdEchoFlg ? 'on' : 'off');return; } else if (a == 'off') { ctx.cmdEchoFlg = false;return; } else if (a == 'on') { ctx.cmdEchoFlg = true;return; } arg = DebugJS.decodeEsc(arg); try { var s = eval(arg) + ''; DebugJS._log(s); } catch (e) { DebugJS._log.e(e); } }, cmdElements: function(arg, tbl) { arg = arg.trim(); if ((arg == '-h') || (arg == '--help')) { DebugJS.printUsage(tbl.help); } else { return DebugJS.countElements(arg, true); } }, cmdEvent: function(arg, tbl) { var a = DebugJS.splitCmdLine(arg); var op = a[0]; switch (op) { case 'create': if (a[1]) { DebugJS.event.create(a[1]); return; } break; case 'set': if (a[1]) { try { DebugJS.event.set(a[1], eval(a[2])); } catch (e) { DebugJS._log.e(e); } return; } break; case 'dispatch': var target = a[1]; if (target) { if (target.charAt(0) == '(') { target = target.substr(1, target.length - 2); } DebugJS.event.dispatch(target, a[2]); return; } break; case 'clear': DebugJS.event.clear(); return; } DebugJS.printUsage(tbl.help); }, cmdExit: function(arg, tbl) { var ctx = DebugJS.ctx; DebugJS.bat.exit(); ctx._cmdDelayCancel(ctx); ctx.CMDVALS = {}; ctx.finalizeFeatures(ctx); ctx.toolsActiveFnc = DebugJS.TOOLS_DFLT_ACTIVE_FNC; if (ctx.opt.useSuspendLogButton) { ctx.status &= ~DebugJS.ST_LOG_SUSPENDING; ctx.updateSuspendLogBtn(ctx); } if (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { ctx.stopStopwatch(); } ctx.resetStopwatch(); if (ctx.timerBasePanel) { ctx.stopTimerStopwatchCu(); ctx.resetTimerStopwatchCu(); ctx.stopTimerStopwatchCd(); ctx.resetTimerStopwatchCd(); ctx.switchTimerModeClock(); } ctx.setLed(0); ctx.setMsg(''); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (ctx.opt.usePinButton) { ctx.enableDraggable(ctx); } if (ctx.opt.mode != 'kiosk') { ctx.resetDbgWinSizePos(); } } ctx.jsBuf = ''; ctx.fltrText = ''; if (ctx.fltrInput) ctx.fltrInput.value = ''; ctx.closeDbgWin(); ctx.clearLog(); ctx.logFilter = DebugJS.LOG_FLTR_ALL; ctx.updateLogFilterBtns(); }, cmdGoto: function(arg, tbl) { var ctrl = DebugJS.bat.ctrl; if (DebugJS.bat.isCmdExecutable()) { var lbl = DebugJS.splitArgs(arg)[0]; DebugJS.ctx._cmdJump(DebugJS.ctx, arg, false, 'label'); } }, cmdHelp: function(arg, tbl) { var ctx = DebugJS.ctx; var a = arg.trim(); var t1 = ctx.CMD_TBL; var t2 = ctx.EXT_CMD_TBL; if (ctx._cmdHelp(ctx, t1, a)) return; if (ctx._cmdHelp(ctx, t2, a)) return; var s = 'Available Commands:\n<table>' + ctx._cmdHelpTbl(ctx, t1); if (!ctx.opt.disableAllCommands) { if (t2.length > 0) { s += '<tr><td colspan="2">' + '---- ---- ---- ---- ---- ---- ---- ----</td></tr>'; } s += ctx._cmdHelpTbl(ctx, t2); } s += '</table>'; DebugJS._log.mlt(s); }, _cmdHelp: function(ctx, tbl, c) { for (var i = 0; i < tbl.length; i++) { var t = tbl[i]; if ((t.cmd == c) && !(t.attr & DebugJS.CMD_ATTR_HIDDEN) && !(t.attr & DebugJS.CMD_ATTR_DISABLED)) { if (t.help) { DebugJS.printUsage(t.help); } else { DebugJS._log('No help message for this command'); } return true; } } return false; }, _cmdHelpTbl: function(ctx, tbl) { var s = ''; for (var i = 0; i < tbl.length; i++) { if (!(tbl[i].attr & DebugJS.CMD_ATTR_HIDDEN)) { var style1 = ''; var style2 = ''; if (tbl[i].attr & DebugJS.CMD_ATTR_DISABLED) { style1 = '<span style="color:#aaa">'; style2 = '</span>'; } s += '<tr><td class="dbg-cmdtd">' + style1 + tbl[i].cmd + style2 + '</td><td>' + style1 + tbl[i].desc + style2 + '</td></tr>'; } } return s; }, cmdHex: function(arg, tbl) { var data = DebugJS.ctx.radixCmd(arg, tbl); if (data == null) return; try { var v2 = ''; var v16 = ''; var val = eval(data.exp); if (val < 0) { for (var i = (DebugJS.DFLT_UNIT - 1); i >= 0; i--) { v2 += (val & 1 << i) ? '1' : '0'; } v16 = parseInt(v2, 2).toString(16); } else { v16 = parseInt(val).toString(16); } var hex = DebugJS.formatHex(v16, true, false); var ret = hex; if (data.digit > 0) { if (hex.length > data.digit) { ret = hex.slice(data.digit * -1); var omit = hex.substr(0, hex.length - data.digit); ret = '<span style="color:#888">' + omit + '</span>' + ret; } else if (hex.length < data.digit) { var padding = data.digit - hex.length; var zero = ''; for (i = 0; i < padding; i++) { zero += ((val < 0) ? 'F' : '0'); } ret = zero + hex; } } ret = '0x' + ret; DebugJS._log(ret); } catch (e) { DebugJS._log.e('Invalid value'); } }, radixCmd: function(arg, tbl) { var args = DebugJS.splitArgs(arg); if (args[0] == '') { DebugJS.printUsage(tbl.help); return null; } var argLen = args.length; var digit = 0; var exp = args[0]; var expLen; if (argLen == 2) { digit = args[1]; } else if (argLen >= 3) { if (args[0].match(/^\(/)) { if (args[argLen - 2].match(/\)$/)) { digit = args[argLen - 1]; expLen = argLen - 1; } else if (args[argLen - 1].match(/\)$/)) { expLen = argLen; } else { DebugJS._log.e('Invalid value'); return null; } exp = ''; for (var i = 0; i < expLen; i++) { exp += ((i >= 1) ? ' ' : '') + args[i]; } } else { DebugJS._log.e('Invalid value'); return null; } } var data = {exp: exp, digit: (digit | 0)}; return data; }, cmdHistory: function(arg, tbl) { var ctx = DebugJS.ctx; try { if (DebugJS.countArgs(arg) == 0) { ctx.showHistory(); } else if (DebugJS.hasOpt(arg, 'c')) { ctx.clearHistory(); } else { var d = DebugJS.getOptVal(arg, 'd'); if (d != null) { ctx.delHistory(ctx, d | 0); } else { DebugJS.printUsage(tbl.help); } } } catch (e) { DebugJS._log.e(e); } }, initHistory: function(ctx) { if (ctx.cmdHistoryBuf == null) { ctx.CMD_HISTORY_MAX = ctx.opt.cmdHistoryMax; ctx.cmdHistoryBuf = new DebugJS.RingBuffer(ctx.CMD_HISTORY_MAX); } if (DebugJS.LS_AVAILABLE) ctx.loadHistory(ctx); }, showHistory: function() { var bf = DebugJS.ctx.cmdHistoryBuf.getAll(); var s = '<table>'; for (var i = 0; i < bf.length; i++) { var cmd = bf[i]; cmd = DebugJS.escTags(cmd); cmd = DebugJS.trimDownText(cmd, DebugJS.CMD_ECHO_MAX_LEN, 'color:#aaa'); s += '<tr><td class="dbg-cmdtd" style="text-align:right">' + (i + 1) + '</td><td>' + cmd + '</td></tr>'; } s += '</table>'; DebugJS._log.mlt(s); }, saveHistory: function(ctx, cmd) { if (!ctx.cmdHistoryBuf) return; ctx.cmdHistoryBuf.add(cmd); ctx.cmdHistoryIdx = (ctx.cmdHistoryBuf.count() < ctx.CMD_HISTORY_MAX) ? ctx.cmdHistoryBuf.count() : ctx.CMD_HISTORY_MAX; if (DebugJS.LS_AVAILABLE) { var bf = ctx.cmdHistoryBuf.getAll(); var cmds = ''; for (var i = 0; i < bf.length; i++) { cmds += bf[i] + '\n'; } localStorage.setItem('DebugJS-history', cmds); } }, loadHistory: function(ctx) { if (DebugJS.LS_AVAILABLE) { var bf = localStorage.getItem('DebugJS-history'); if (bf != null) { var cmds = bf.split('\n'); for (var i = 0; i < (cmds.length - 1); i++) { ctx.cmdHistoryBuf.add(cmds[i]); ctx.cmdHistoryIdx = (ctx.cmdHistoryBuf.count() < ctx.CMD_HISTORY_MAX) ? ctx.cmdHistoryBuf.count() : ctx.CMD_HISTORY_MAX; } } } }, getHistory: function(idx) { var cmds = DebugJS.ctx.cmdHistoryBuf.getAll(); var c = cmds[idx]; return ((c == undefined) ? '' : c); }, getLastHistory: function() { var cmds = DebugJS.ctx.cmdHistoryBuf.getAll(); var c = cmds[cmds.length - 1]; return ((c == undefined) ? '' : c); }, delHistory: function(ctx, idx) { var cmds = ctx.cmdHistoryBuf.getAll(); ctx.clearHistory(); for (var i = 0; i < cmds.length; i++) { if (cmds.length < ctx.opt.cmdHistoryMax) { if (i != (idx - 1)) { ctx.saveHistory(ctx, cmds[i]); } } else if (cmds.length >= ctx.opt.cmdHistoryMax) { if (i != (idx - 2)) { ctx.saveHistory(ctx, cmds[i]); } } } }, clearHistory: function() { DebugJS.ctx.cmdHistoryBuf.clear(); if (DebugJS.LS_AVAILABLE) localStorage.removeItem('DebugJS-history'); }, cmdHttp: function(arg, tbl) { var a = DebugJS.splitCmdLineInTwo(arg); var method = a[0]; var data = a[1]; if (method == '') { DebugJS.printUsage(tbl.help); return; } else if (method.match(/^\s*http/)) { method = 'GET'; data = arg; } DebugJS.ctx.doHttpRequest(method, data); }, cmdJs: function(arg, tbl) { var a = DebugJS.splitArgs(arg); if (a[0] == 'exec') { DebugJS.ctx.execJavaScript(); } else { DebugJS.printUsage(tbl.help); } }, cmdJson: function(arg, tbl) { if (arg == '') { DebugJS.printUsage(tbl.help); return; } var json = DebugJS.delLeadingSP(arg); var lv = 0; var jsnFlg = true; if (json.charAt(0) == '-') { var opt = json.match(/-p\s/); if (opt != null) jsnFlg = false; opt = json.match(/-l(\d+)/); if (opt) lv = opt[1]; json = json.match(/(\{.*)/); if (json) { json = json[1]; } } if (json) { return DebugJS._cmdJson(json, jsnFlg, lv); } else { DebugJS.printUsage(tbl.help); } }, cmdJump: function(arg, tbl) { if (DebugJS.bat.isCmdExecutable()) { DebugJS.ctx._cmdJump(DebugJS.ctx, arg, true, 'label'); } }, _cmdJump: function(ctx, arg, lnk, type) { var bat = DebugJS.bat; var ctrl = bat.ctrl; var fnArg; var a = DebugJS.splitCmdLineInTwo(arg); var lbl = a[0]; if (lbl.match(/^".+?"$/)) { try { lbl = eval(lbl); } catch (e) { DebugJS._log.e('L' + ctrl.pc + ': Illegal argument (' + lbl + ')'); return; } } var tbl = (type == 'func' ? bat.fncs : bat.labels); var idx = tbl[lbl]; if (idx == undefined) { DebugJS._log.e('L' + ctrl.pc + ': No such ' + type + ' (' + lbl + ')'); return; } if (lnk) { try { fnArg = eval(a[1]); } catch (e) { DebugJS._log.e('L' + ctrl.pc + ': Illegal argument (' + e + ')'); return; } delete ctx.CMDVALS['%RET%']; var fnCtx = { lr: ctrl.pc, fnArg: ctrl.fnArg, block: ctrl.block, label: ctrl.label, fnnm: ctrl.fnnm }; ctrl.stack.push(fnCtx); ctrl.fnArg = fnArg; ctx.CMDVALS['%ARG%'] = fnArg; ctrl.lr = ctrl.pc; } ctrl.startPc = 0; ctrl.block = []; if (type == 'func') { bat.setFnNm(lbl); } else { bat.setLabel(lbl); } ctrl.pc = idx + 1; ctx.updateCurPc(); }, cmdKeyPress: function(arg, tbl) { var keyCode = DebugJS.splitArgs(arg)[0]; if ((keyCode == '') || isNaN(keyCode)) { DebugJS.printUsage(tbl.help); return; } var s = (DebugJS.getOptVal(arg, 'shift') == null ? false : true); var c = (DebugJS.getOptVal(arg, 'ctrl') == null ? false : true); var a = (DebugJS.getOptVal(arg, 'alt') == null ? false : true); var m = (DebugJS.getOptVal(arg, 'meta') == null ? false : true); var opt = {keyCode: keyCode | 0, shift: s, ctrl: c, alt: a, meta: m}; DebugJS.keyPress(opt); }, cmdKeys: function(arg, tbl) { arg = DebugJS.unifySP(arg); if (arg == '') { DebugJS.printUsage(tbl.help); return; } var ags = arg.split(' '); for (var i = 0; i < ags.length; i++) { if (ags[i] == '') continue; var cmd = 'DebugJS.tmp="' + ags[i] + ' = ";DebugJS.tmp+=DebugJS.getKeysStr(' + ags[i] + ');DebugJS._log.mlt(DebugJS.tmp);'; try { eval(cmd); } catch (e) { DebugJS._log.e(e); } } }, cmdLaptime: function(arg, tbl) { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_STOPWATCH_LAPTIME) { ctx.stopStopwatch(); } else { if (ctx.status & DebugJS.ST_STOPWATCH_RUNNING) { ctx.stopStopwatch(); ctx.resetStopwatch(); } ctx.status |= DebugJS.ST_STOPWATCH_LAPTIME; ctx.startStopwatch(); } }, cmdLed: function(arg, tbl) { if (arg == '') { var v = DebugJS.ctx.led; var h = DebugJS.formatHex(DebugJS.toHex(v), true, true); DebugJS._log.res(v + '(' + h + ')'); DebugJS.printUsage(tbl.help); } else { DebugJS.ctx.setLed(arg); } return DebugJS.ctx.led; }, cmdLog: function(arg, tbl, echo) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); var fn = { bufsize: ctx._cmdLogBufsize, dump: ctx._cmdLogDump, filter: ctx._cmdLogFilter, html: ctx._cmdLogHtml, load: ctx._cmdLogLoad, preserve: ctx._cmdLogPreserve, suspend: ctx._cmdLogSuspend, lv: ctx._cmdLogLv }; if (fn[a[0]]) {return fn[a[0]](ctx, arg, echo);} DebugJS.printUsage(tbl.help); }, _cmdLogBufsize: function(ctx, arg) { var n = DebugJS.splitArgs(arg)[1] | 0; if (n > 0) { ctx.initBuf(ctx, n); } else { n = ctx.logBuf.size(); DebugJS._log.res(n); DebugJS.printUsage('log bufsize [size]'); } return n; }, _cmdLogDump: function(ctx, arg) { arg = DebugJS.splitCmdLineInTwo(arg)[1]; var f = (arg.trim() == '-b64' ? true : false); var l = DebugJS.dumpLog('json', f); DebugJS._log.res(l); }, _cmdLogFilter: function(ctx, arg) { var a = DebugJS.getArgsFrom(arg, 1); var s = DebugJS.getOptVal(a, 'case'); if (!s) s = DebugJS.getOptVal(a, 'fl'); if (!s) s = DebugJS.getOptVal(a, '')[0]; if (s == '') { DebugJS.printUsage('log filter [-case] [-fl] "string"'); return; } try { s = eval(s); } catch (e) { DebugJS._log.e(e); return; } ctx.setLogFilter(ctx, s, DebugJS.hasOpt(arg, 'case'), DebugJS.hasOpt(arg, 'fl')); }, _cmdLogHtml: function(ctx, arg) { var op = DebugJS.splitArgs(arg)[1]; if (op == 'on') { ctx.setFilterTxtHtml(ctx, true); } else if (op == 'off') { ctx.setFilterTxtHtml(ctx, false); } else { var st = ctx.fltrTxtHtml; DebugJS.printUsage('log html on|off'); return st; } }, _cmdLogLoad: function(ctx, arg) { arg = DebugJS.splitCmdLineInTwo(arg)[1]; var data = DebugJS.getOptVal(arg, 'b64'); if (DebugJS.countArgs(arg) == 0) { DebugJS.printUsage('log load [-b64] log-buf-json'); } else { try { if (data != null) { DebugJS.loadLog(data, true); } else { DebugJS.loadLog(arg); } ctx.printLogs(); } catch (e) { DebugJS._log.e(e); } } }, _cmdLogPreserve: function(ctx, arg, echo) { var op = DebugJS.splitArgs(arg)[1]; if (op == 'on') { ctx.setLogPreserve(ctx, true); } else if (op == 'off') { ctx.setLogPreserve(ctx, false); } else { var st = ((ctx.status & DebugJS.ST_LOG_PRESERVED) ? true : false); if (echo) { DebugJS._log.res(st); DebugJS.printUsage('log preserve on|off'); } return st; } }, _cmdLogSuspend: function(ctx, arg) { var op = DebugJS.splitArgs(arg)[1]; if (op == 'on') { DebugJS.ctx.suspendLog(); } else if (op == 'off') { DebugJS.ctx.resumeLog(); } else { var st = ((ctx.status & DebugJS.ST_LOG_SUSPENDING) ? true : false); DebugJS.printUsage('log suspend on|off'); return st; } }, _cmdLogLv: function(ctx, arg) { var a = DebugJS.delAllSP(DebugJS.getArgsFrom(arg, 1)); var lv = a.split('|'); if (lv[0] == '') { DebugJS.printUsage('log lv LOG|VRB|DBG|INF|WRN|ERR|ALL|NONE'); return; } var FLT = { LOG: DebugJS.LOG_FLTR_LOG, VRB: DebugJS.LOG_FLTR_VRB, DBG: DebugJS.LOG_FLTR_DBG, INF: DebugJS.LOG_FLTR_INF, WRN: DebugJS.LOG_FLTR_WRN, ERR: DebugJS.LOG_FLTR_ERR, ALL: DebugJS.LOG_FLTR_ALL }; ctx.logFilter = 0; for (var i = 0; i < lv.length; i++) { var f = FLT[lv[i]]; if (f != undefined) ctx.logFilter |= f; } ctx.updateLogFilterBtns(); ctx.printLogs(); }, cmdMsg: function(arg, tbl) { var m = ((DebugJS.hasOpt(arg, 'c') || (arg.trim() == '')) ? '""' : arg); try { DebugJS.ctx.setMsg(eval(m)); } catch (e) { DebugJS._log.e(e); DebugJS.printUsage(tbl.help); } }, cmdNextTime: function(arg, tbl) { var t, ms; var v = arg; var p = true; var idx = DebugJS.indexOfOptVal(arg, '-q'); if (idx >= 0) { p = false; v = arg.substr(idx); } v = v.trim(); if ((v.match(/^T\d{4,6}/))) { t = DebugJS.calcNextTime(v); } else if (ms = DebugJS.parseToMillis(v)) { var dt = DebugJS.getDateTime((new Date()).getTime() + ms); t = {time: dt.time, t: 'T' + dt.hh + dt.mi + dt.ss}; } else if (DebugJS.isNum(v)) { var dt = DebugJS.getDateTime((new Date()).getTime() + (v | 0)); t = {time: dt.time, t: 'T' + dt.hh + dt.mi + dt.ss}; } else { DebugJS.printUsage(tbl.help); return ''; } if (p) { DebugJS.log.res(DebugJS.convDateTimeStr(DebugJS.getDateTime(t.time))); } return t.t; }, cmdNow: function(arg, tbl, echo) { var t = (new Date()).getTime(); if (echo) DebugJS._log.res(t); return t; }, cmdOpen: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var fn = a[0]; var subfn = a[1]; var opt = a[2]; if ((fn == '') || (!DebugJS.ctx.launchFnc(DebugJS.ctx, fn, subfn, opt))) { DebugJS.printUsage(tbl.help); } }, cmdP: function(arg, tbl) { DebugJS._cmdP(arg, tbl); }, cmdPause: function(arg, tbl) { var op = ''; var opts = ['s', 'key']; for (var i = 0; i < opts.length; i++) { if (DebugJS.getOptVal(arg, opts[i]) != null) { op = opts[i]; break; } } var key = DebugJS.getOptVal(arg, 'key'); var to = DebugJS.getOptVal(arg, 'timeout'); if (!(DebugJS.ctx._cmdPause(op, key, to))) { DebugJS.printUsage(tbl.help); } }, _cmdPause: function(op, key, tout) { var ctx = DebugJS.ctx; if (DebugJS.isTmStr(tout)) tout = DebugJS.str2ms(tout); tout |= 0; ctx.CMDVALS['%RESUMED_KEY%'] = null; if (op == 's') { ctx.status |= DebugJS.ST_BAT_PAUSE_CMD; DebugJS._log('Click or press any key to continue...'); } else { if (op == '') { DebugJS._log('Type "resume" to continue...' + ((tout > 0) ? ' (timeout=' + tout + ')' : '')); } else if (op == 'key') { if (key == undefined) key = ''; DebugJS.bat.ctrl.pauseKey = key; DebugJS._log('Type "resume" or "resume -key' + ((key == '') ? '' : ' ' + key) + '" to continue...' + ((tout > 0) ? ' (timeout=' + tout + ')' : '')); } else { return false; } if (tout > 0) { DebugJS.bat.ctrl.pauseTimeout = (new Date()).getTime() + tout; } ctx.status |= DebugJS.ST_BAT_PAUSE_CMD_KEY; } ctx.updateBatResumeBtn(); return true; }, cmdPin: function(arg, tbl) { var op = DebugJS.splitArgs(arg)[0]; if ((op != 'on') && (op != 'off')) { var st = ((DebugJS.ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) ? false : true); DebugJS.printUsage(tbl.help); return st; } else { DebugJS.pin(op == 'on'); } }, cmdPoint: function(arg, tbl, echo) { var ctx = DebugJS.ctx; var args = DebugJS.splitCmdLine(arg); var point = DebugJS.point; var ret; var op = args[0]; var alignX = DebugJS.getOptVal(arg, 'alignX'); var alignY = DebugJS.getOptVal(arg, 'alignY'); if (op == 'init') { point.init(); } else if (op == 'move') { ctx._cmdPointMove(ctx, arg, tbl, args); } else if (op == 'label') { ctx._cmdPointLabel(args, alignX, alignY); } else if (op == 'scroll') { ctx._cmdPointScroll(args); } else if (op == 'selectoption') { ret = ctx._cmdPointSelectOpt(ctx, args); } else if (op == 'getprop') { ret = point.getProp(args[1]); } else if (op == 'setprop') { point.setProp(args[1], DebugJS.getArgsFrom(arg, 2), echo); } else if (op == 'text') { ctx._cmdPointText(arg); } else if (op == 'verify') { ret = ctx._cmdPointVerify(arg); } else if (op == 'event') { ret = point.event(DebugJS.getArgsFrom(arg, 1)); } else if (op == 'cursor') { ctx._cmdPointCursor(args, tbl); } else if (op == 'show') { point.show(); } else if (op == 'hide') { point.hide(); } else if (op == 'hint') { ctx._cmdPointHint(ctx, arg, point, args[1]); } else if (op == 'drag') { point.drag(DebugJS.getArgsFrom(arg, 1)); } else if ((op == 'click') || (op == 'cclick') || (op == 'rclick') || (op == 'dblclick')) { var speed = DebugJS.getOptVal(arg, 'speed'); point.simpleEvent(op, speed); } else if ((op == 'blur') || (op == 'change') || (op == 'contextmenu') || (op == 'focus') || (op == 'mousedown') || (op == 'mouseup')) { point.simpleEvent(op, args[1]); } else if ((op == 'keydown') || (op == 'keypress') || (op == 'keyup')) { if (args[1] != undefined) { point.keyevt(args); } else { DebugJS.printUsage('point keydown|keypress|keyup -keyCode n -code c -key k [-s] [-c] [-a] [-m]'); } } else { ctx._cmdPointJmp(ctx, arg, tbl, args); } return ret; }, _cmdPointJmp: function(ctx, arg, tbl, args) { var point = DebugJS.point; var x, y; if (args[0] == '') { DebugJS._log('x=' + point.x + ', y=' + point.y); DebugJS.printUsage(tbl.help); return; } var p = ctx._cmdPointCalcPos(ctx, args[0], args[1]); if (p) { point(p.x, p.y); } else if (isNaN(args[0])) { var target = args[0]; var idx = args[1]; if (target.charAt(0) == '(') { target = target.substr(1, target.length - 2); } var alignX = DebugJS.getOptVal(arg, 'alignX'); var alignY = DebugJS.getOptVal(arg, 'alignY'); DebugJS.pointBySelector(target, idx, alignX, alignY); } else { x = args[0]; y = args[1]; point(x, y); } }, _cmdPointMove: function(ctx, arg, tbl, args) { var point = DebugJS.point; var target = args[1]; if (target == undefined) { DebugJS.printUsage(tbl.help); return; } var idx; var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); var alignX = DebugJS.getOptVal(arg, 'alignX'); var alignY = DebugJS.getOptVal(arg, 'alignY'); var p = ctx._cmdPointCalcPos(ctx, args[1], args[2]); if (p) { point.move(p.x, p.y, speed, step); } else if (target == 'label') { var label = args[2]; idx = args[3] | 0; try { label = eval(label); } catch (e) { DebugJS._log.e(e); return; } point.moveToLabel(label, idx, speed, step, alignX, alignY); } else if (isNaN(target)) { idx = args[2]; if (target.charAt(0) == '(') { target = target.substr(1, target.length - 2); } point.moveToSelector(target, idx, speed, step, alignX, alignY); } else { var x = args[1]; var y = args[2]; point.move(x, y, speed, step); } }, _cmdPointCalcPos: function(ctx, a1, a2) { var x = a1; var y = a2; if (a1 == 'mouse') { x = ctx.mousePos.x; y = ctx.mousePos.y; } else if (a1 == 'center') { var p = DebugJS.getScreenCenter(); x = p.x; if (a2 == undefined) y = p.y; } else if (a1 == 'left') { x = 0; if (a2 == undefined) y = '+0'; } else if (a1 == 'right') { x = document.documentElement.clientWidth; if (a2 == undefined) y = '+0'; } if (a2 == 'top') { y = 0; } else if (a2 == 'middle') { y = DebugJS.getScreenCenter().y; } else if (a2 == 'bottom') { y = document.documentElement.clientHeight; } if ((x == a1) && (y == a2)) { return null; } return {x: x, y: y}; }, _cmdPointHint: function(ctx, arg, point, op) { var a = DebugJS.getArgsFrom(arg, 2); if (op == 'msg') { if (!a) { DebugJS.printUsage('point hint msg "str"'); } else { point.hint(a, 0, 0); } } else if (op == 'msgseq') { ctx._cmdPointHintMsgSeq(ctx, arg, point); } else if (op == 'hide') { point.hint.hide(); } else if (op == 'show') { point.hint.show(); } else if (op == 'clear') { point.hint.clear(); } else { DebugJS.printUsage('point hint msg|msgseq "str"|show|hide|clear'); } }, _cmdPointHintMsgSeq: function(ctx, arg, point) { var a = DebugJS.splitCmdLine(arg); var m = a[2]; var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); var start = DebugJS.getOptVal(arg, 'start'); var end = DebugJS.getOptVal(arg, 'end'); if (speed == null) speed = ctx.props.textspeed; if (step == null) step = ctx.props.textstep; if (!m) { DebugJS.printUsage('point hint msgseq "str"'); } else { point.hint(m, speed, step, start, end); } }, _cmdPointCursor: function(args, tbl) { var src = args[1]; var w = args[2]; var h = args[3]; if (src == undefined) { DebugJS.printUsage(tbl.help); return; } if (src == 'default') src = ''; DebugJS.point.cursor(src, w, h); }, _cmdPointText: function(arg) { var el = DebugJS.point.getElementFromCurrentPos(); if ((!el) || (!DebugJS.isTxtInp(el))) { DebugJS._log.e('Pointed area is not an input element (' + (el ? el.nodeName : 'null') + ')'); return; } var txt = DebugJS.getArgVal(arg, 1); var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); var start = DebugJS.getOptVal(arg, 'start'); var end = DebugJS.getOptVal(arg, 'end'); try { DebugJS.setText(el, txt, speed, step, start, end); } catch (e) { DebugJS._log.e(e); } }, _cmdPointSelectOpt: function(ctx, args) { var ret; var el = DebugJS.point.getElementFromCurrentPos(); if ((el) && (el.nodeName == 'SELECT')) { var method = args[1]; var type = args[2]; if (((method == 'get') || (method == 'set')) && ((type == 'text') || (type == 'texts') || (type == 'value') || (type == 'values'))) { var val = args[3]; ret = ctx._cmdSelect(el, method, type, val); } else { DebugJS._log.e('Usage: point selectoption get|set text|texts|value|values val'); } } else { DebugJS._log.e('Pointed area is not a select element (' + (el ? el.nodeName : 'null') + ')'); } return ret; }, _cmdPointLabel: function(args, alignX, alignY) { var label = args[1]; try { label = eval(label); } catch (e) { DebugJS._log.e(e); return; } var idx = args[2] | 0; DebugJS.pointByLabel(label, idx, alignX, alignY); }, _cmdPointScroll: function(args) { var x = args[1]; var y = args[2]; var el = DebugJS.point.getElementFromCurrentPos(); if (el) { DebugJS.scrollElTo(el, x, y); } else { DebugJS._log.e('Failed to get element'); } }, _cmdPointVerify: function(arg) { var a = DebugJS.splitCmdLine(arg); var prop = a[1]; var method = a[2]; var exp = DebugJS.getArgsFrom(arg, 3); var label = DebugJS.getOptVal(a, 'label'); if (label != null) { prop = a[3]; method = a[4]; exp = DebugJS.getArgsFrom(arg, 5); } return DebugJS.point.verify(prop, method, exp, label); }, cmdProp: function(arg, tbl) { arg = DebugJS.delLeadingSP(arg); if (arg == '') { DebugJS.printUsage(tbl.help); } else { var v = DebugJS.ctx.props[arg]; if (v != undefined) { DebugJS._log.res(v); return v; } else { DebugJS._log.e(arg + ' is invalid property name.'); } } }, cmdProps: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); if (a[0] == '-reset') { DebugJS.copyProp(ctx.PROPS_DFLT_VALS, ctx.props); DebugJS._log('debug properties have been reset.'); return; } else if (a[0] != '') { DebugJS.printUsage(tbl.help); return; } var s = 'Available properties:\n<table>'; for (var k in ctx.props) { s += '<tr><td>' + k + '</td><td>' + ctx.props[k] + '</td></tr>'; } s += '</table>'; DebugJS._log.mlt(s); }, cmdRandom: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var type = a[0] || DebugJS.RND_TYPE_NUM; var min, max; if (a[0] == '') { type = DebugJS.RND_TYPE_NUM; } else { if ((a[0] == DebugJS.RND_TYPE_NUM) || (a[0] == DebugJS.RND_TYPE_STR)) { type = a[0]; min = a[1]; max = a[2]; } else if (a[0].match(/[0-9]{1,}/)) { type = DebugJS.RND_TYPE_NUM; min = a[0]; max = a[1]; } else { DebugJS.printUsage(tbl.help); return; } } var rnd = DebugJS.getRandom(type, min, max); DebugJS._log(rnd); return rnd; }, cmdRadixConv: function(v, echo) { v = v.trim(); var rdx = DebugJS.checkRadix(v); if ((rdx == 10) || (rdx == 16) || (rdx == 2)) { DebugJS.ctx._cmdRadixConv(v, echo); return true; } else { return false; } }, _cmdRadixConv: function(v, echo) { if (!echo) return; var rdx = DebugJS.checkRadix(v); if (rdx == 10) { v = v.replace(/,/g, ''); DebugJS.convRadixFromDEC(v); } else if (rdx == 16) { DebugJS.convRadixFromHEX(v.substr(2)); } else if (rdx == 2) { DebugJS.convRadixFromBIN(v.substr(2)); } }, cmdResume: function(arg, tbl) { var k = DebugJS.getOptVal(arg, 'key'); if (arg == '') { DebugJS.bat._resume('cmd-key'); } else if (k != null) { DebugJS.bat.resume(k); } else { DebugJS.printUsage(tbl.help); } }, cmdReturn: function(arg, tbl) { DebugJS.bat.ret(arg); }, cmdRGB: function(arg, tbl) { arg = DebugJS.unifySP(arg.trim()); if (arg == '') { DebugJS.printUsage(tbl.help); } else { return DebugJS.convRGB(arg); } }, cmdROT: function(arg, tbl, echo) { var x = DebugJS.splitArgs(arg)[0]; var a = DebugJS.getArgsFrom(arg, 1); var fnE, fnD; switch (x) { case '5': fnE = DebugJS.encodeROT5; fnD = DebugJS.decodeROT5; break; case '13': fnE = DebugJS.encodeROT13; fnD = DebugJS.decodeROT13; break; case '47': fnE = DebugJS.encodeROT47; fnD = DebugJS.decodeROT47; break; default: DebugJS.printUsage(tbl.help); return; } var iIdx = 0; if ((DebugJS.hasOpt(a, 'd')) || (DebugJS.hasOpt(a, 'e'))) { iIdx++; } var n = DebugJS.getOptVal(a, 'n'); if (n == null) { n = x | 0; } else { n = n.replace(/\(|\)/g, '') | 0; iIdx += 2; } return DebugJS.ctx.execEncAndDec(a, tbl, echo, true, fnE, fnD, iIdx, n); }, cmdScrollTo: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); var target = a[0]; if (target == '') { DebugJS.printUsage(tbl.help); } else if (target == 'log') { var pos = a[1]; ctx._cmdScrollToLog(ctx, tbl, pos); } else if (target == 'window') { ctx._cmdScrollToWin(ctx, arg, tbl); } else { var x = a[1]; var y = a[2]; DebugJS.scrollElTo(target, x, y); } }, _cmdScrollToLog: function(ctx, tbl, pos) { if (pos == 'top') { pos = 0; } else if (pos == 'bottom') { pos = ctx.logPanel.scrollHeight; } if ((pos === '') || isNaN(pos)) { DebugJS.printUsage(tbl.help); } else { ctx.logPanel.scrollTop = pos; } }, _cmdScrollToWin: function(ctx, arg, tbl) { var a = DebugJS.getOptVal(arg, ''); var posX = a[1]; var posY = a[2]; var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); if (posX == undefined) { posX = DebugJS.splitCmdLine(arg)[1]; if (posX == undefined) { DebugJS.printUsage(tbl.help); return; } } if (speed == undefined) speed = ctx.props.scrollspeed; if (step == undefined) step = ctx.props.scrollstep; if (isNaN(posX)) { var slct = a[1]; var idx = a[2]; var ps = DebugJS.getElPosSize(slct, idx); if (ps) { var adjX = DebugJS.getOptVal(arg, 'adjX'); var adjY = DebugJS.getOptVal(arg, 'adjY'); try { if (adjX) ps.x += eval(adjX); if (adjY) ps.y += eval(adjY); } catch (e) { DebugJS.log.e('scollto window: ' + e); } DebugJS.scrollWinToTarget(ps, speed, step, null, null, true); return; } } if (posY == undefined) { posY = DebugJS.splitCmdLine(arg)[2]; if (posY == undefined) { DebugJS.printUsage(tbl.help); return; } } var y = ctx._cmdScrollWinGetY(posY); if (y == undefined) { DebugJS.printUsage(tbl.help); return; } var x = ctx._cmdScrollWinGetX(posX); if (x == undefined) { DebugJS.printUsage(tbl.help); return; } if ((speed == '0') || (step == '0')) { window.scroll(x, y); } else { DebugJS.scrollWinTo(x, y, speed, step); } }, _cmdScrollWinGetX: function(posX) { var x; var scrollX = (window.scrollX != undefined ? window.scrollX : window.pageXOffset); if (posX == 'left') { x = 0; } else if (posX == 'center') { x = document.body.clientWidth / 2; } else if (posX == 'right') { x = document.body.clientWidth; } else if (posX == 'current') { x = scrollX; } else if (posX.charAt(0) == '+') { x = scrollX + (posX.substr(1) | 0); } else if (posX.charAt(0) == '-') { x = scrollX - (posX.substr(1) | 0); } else if ((posX == '') || isNaN(posX)) { x = undefined; } else { x = posX; } return x; }, _cmdScrollWinGetY: function(posY) { var y; var scrollY = (window.scrollY != undefined ? window.scrollY : window.pageYOffset); if (posY == 'top') { y = 0; } else if (posY == 'middle') { y = (document.body.clientHeight - document.documentElement.clientHeight) / 2; } else if (posY == 'bottom') { y = document.body.clientHeight; } else if (posY == 'current') { y = scrollY; } else if (posY.charAt(0) == '+') { y = scrollY + (posY.substr(1) | 0); } else if (posY.charAt(0) == '-') { y = scrollY - (posY.substr(1) | 0); } else if ((posY == '') || isNaN(posY)) { y = undefined; } else { y = posY; } return y; }, cmdSelect: function(arg, tbl) { var a = DebugJS.splitCmdLine(arg); var sel = a[0]; var method = a[1]; var type = a[2]; var val = a[3]; if ((sel != '') && (((method == 'set') && (a.length >= 4)) || ((method == 'get') && (a.length >= 3))) && ((type == 'text') || (type == 'texts') || (type == 'value') || (type == 'values'))) { return DebugJS.ctx._cmdSelect(sel, method, type, val); } DebugJS.printUsage(tbl.help); }, _cmdSelect: function(sel, method, type, val) { try { var val = eval(val) + ''; var r = DebugJS.selectOption(sel, method, type, val); if (method == 'get') { if ((type == 'values') || (type == 'texts')) { DebugJS._log.p(r); } else { DebugJS._log.res(r); } } return r; } catch (e) { DebugJS._log.e(e); } }, cmdSet: function(arg, tbl, echo) { var a = DebugJS.splitCmdLine(arg); var nm = a[0]; var v = ((a[1] == undefined) ? '' : a[1]); if ((nm == '') || (v == '')) { DebugJS.printUsage(tbl.help); return; } DebugJS.ctx._cmdSet(DebugJS.ctx, nm, v, echo); }, _cmdSet: function(ctx, nm, val, echo) { var props = ctx.props; if (!props[nm]) { DebugJS._log.e(nm + ' is invalid property name.'); return; } var restriction = ctx.PROPS_RESTRICTION[nm]; if (restriction) { if (!(val + '').match(restriction)) { DebugJS._log.e(val + ' is invalid. (' + restriction + ')'); return; } } var r; if (ctx.PROPS_CB[nm]) { var r = ctx.PROPS_CB[nm](ctx, val); if (r != undefined) props[nm] = r; } props[nm] = (r === undefined ? val : r); if (echo) DebugJS._log.res(props[nm]); }, setPropBatContCb: function(ctx, v) { if (DebugJS.bat.isRunning()) { if (v == 'on') { ctx.status |= DebugJS.ST_BAT_CONT; } else { ctx.status &= ~DebugJS.ST_BAT_CONT; } } }, setPropIndentCb: function(ctx, v) { DebugJS.INDENT_SP = DebugJS.repeatCh(' ', v); }, setPropPointMsgSizeCb: function(ctx, v) { var s; try { s = eval(v); } catch (e) { DebugJS._log.e(e); return ctx.props.pointmsgsize; } ctx.props.pointmsgsize = s; var el = DebugJS.point.hint.pre; if (el) ctx.setStyle(el, 'font-size', s); }, setPropTimerCb: function(ctx, v) { var tm = DebugJS.timestr2struct(v); if (ctx.timerStopwatchCdInput) { ctx.timerTxtHH.value = tm.hh; ctx.timerTxtMI.value = tm.mi; ctx.timerTxtSS.value = tm.ss; ctx.timerTxtSSS.value = tm.sss; } return DebugJS.convTimeStr(tm); }, setPropConsoleLogCb: function(ctx, v) { DebugJS.setConsoleLogOut((v == 'me')); }, cmdSetAttr: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var sel = a[0]; var idx = 0; var nm = a[1]; var vl = a[2]; if (a[3] != undefined) { idx = a[1]; nm = a[2]; vl = a[3]; } if ((sel == '') || (nm == undefined) || (vl == undefined)) { DebugJS.printUsage(tbl.help); return; } var el = DebugJS.getElement(sel, idx); if (!el) { DebugJS._log.e('Element not found: ' + sel); return; } el.setAttribute(nm, vl); }, cmdSleep: function(arg, tbl) { var ms = DebugJS.splitArgs(arg)[0]; if ((ms == '') || isNaN(ms)) { DebugJS.printUsage(tbl.help); return; } DebugJS.sleep(ms); }, cmdTimeCalc: function(arg, echo) { var ret = null; arg = DebugJS.unifySP(arg.trim()); if (!arg.match(/^\d{1,}:{1}\d{2}/)) { return ret; } arg = DebugJS.delAllSP(arg); var op; if (arg.indexOf('-') >= 0) { op = '-'; } else if (arg.indexOf('+') >= 0) { op = '+'; } var vals = arg.split(op); if (vals.length < 2) { return ret; } var timeL = DebugJS.tmStr2ms(vals[0]); var timeR = DebugJS.tmStr2ms(vals[1]); if ((timeL == null) || (timeR == null)) { ret = 'Invalid time format'; DebugJS._log.e(ret); return ret; } var byTheDay = (vals[2] == undefined); if (op == '-') { ret = DebugJS.subTime(timeL, timeR, byTheDay); } else { ret = DebugJS.addTime(timeL, timeR, byTheDay); } if (echo) DebugJS._log.res(ret); return ret; }, cmdTest: function(arg, tbl) { var args = DebugJS.splitCmdLine(arg, 4); var op = args[0]; var test = DebugJS.test; switch (op) { case 'init': var nm = DebugJS.getOptVal(arg, 'name'); try { nm = eval(nm); test.init(nm); DebugJS._log('Test has been initialized.' + (nm == undefined ? '' : ' (' + nm + ')')); } catch (e) { DebugJS._log.e(e); } break; case 'set': DebugJS.ctx._cmdTestSet(arg); break; case 'count': var c = test.data.cnt; if (args[1] != '-d') c = test.getSumCount(); DebugJS._log(test.getCountStr(c)); break; case 'last': var st = test.getLastResult(); DebugJS._log(test.getStyledStStr(st)); return st; case 'result': DebugJS._log(test.result()); break; case 'ttlresult': var st = test.getTotalResult(); DebugJS._log(test.getStyledStStr(st)); return st; case 'status': DebugJS._log.p(test.getStatus(), 0, null, false); break; case 'verify': return DebugJS.ctx._CmdTestVerify(arg); case 'fin': test.fin(); DebugJS._log('Test completed.'); break; default: DebugJS.printUsage(tbl.help); } }, _cmdTestSet: function(arg) { var test = DebugJS.test; var args = DebugJS.splitCmdLine(arg, 3); var target = args[1]; var fn; switch (target) { case 'name': fn = test.setName; break; case 'desc': fn = test.setDesc; break; case 'id': fn = test.setId; break; case 'comment': fn = test.setCmnt; break; case 'result': DebugJS.ctx._cmdTestSetRslt(DebugJS.getArgsFrom(arg, 2)); return; case 'seq': fn = test.setSeq; break; default: DebugJS.printUsage('test set name|desc|id|comment|result|seq val'); return; } try { var v = eval(args[2]); if (v == undefined) v = ''; fn(v + ''); } catch (e) { DebugJS._log.e(e); } }, _CmdTestVerify: function(arg) { var a = DebugJS.splitCmdLine(arg); var got = a[1]; var method = a[2]; var exp = DebugJS.getArgsFrom(arg, 3); var label = DebugJS.getOptVal(a, 'label'); if (label != null) { got = a[3]; method = a[4]; exp = DebugJS.getArgsFrom(arg, 5); } return DebugJS.test.verify(got, method, exp, true, label); }, _cmdTestSetRslt: function(a) { var st = DebugJS.getArgVal(a, 0); var label = DebugJS.getOptVal(a, 'label'); var info = DebugJS.getOptVal(a, 'info'); try { var inf = eval(info); } catch (e) { DebugJS._log.e('Illegal info opt: ' + info); return; } DebugJS.test.setResult(st, label, inf); }, cmdText: function(arg, tbl) { var a = DebugJS.splitCmdLine(arg); var slctr = a[0]; var txt = a[1]; if (txt == undefined) { DebugJS.printUsage(tbl.help); return; } var speed = DebugJS.getOptVal(arg, 'speed'); var step = DebugJS.getOptVal(arg, 'step'); var start = DebugJS.getOptVal(arg, 'start'); var end = DebugJS.getOptVal(arg, 'end'); DebugJS.setText(slctr, txt, speed, step, start, end); }, cmdTime: function(arg, tbl, echo) { if (DebugJS.countArgs(arg) == 0) { DebugJS.printUsage(tbl.help); return; } var t1 = DebugJS.getOptVal(arg, 't1'); var t2 = DebugJS.getOptVal(arg, 't2'); if (((t1 == null) || (t1 == '')) && (t2 == null)) { t1 = arg; } try { t1 = eval(t1); t2 = eval(t2); var s = DebugJS.getTimeDurationStr(t1, t2); if (echo) DebugJS._log.res(s); return s; } catch (e) { DebugJS.printUsage(tbl.help); return; } }, cmdTimer: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var op = a[0]; var tmrNm = a[1]; if (tmrNm == undefined) tmrNm = DebugJS.DFLT_TIMER_NAME; switch (op) { case 'start': DebugJS.time.start(tmrNm); break; case 'split': DebugJS.time._split(tmrNm, false); break; case 'stop': DebugJS.time.end(tmrNm); break; case 'list': DebugJS.time.list(); break; default: DebugJS.printUsage(tbl.help); } }, cmdStopwatch: function(arg, tbl) { var ctx = DebugJS.ctx; var a = DebugJS.splitArgs(arg); var n = 0; var op = a[0]; if (a[0].substr(0, 2) == 'sw') { n = a[0].charAt(2) | 0; op = a[1]; } var r = -1; if ((n == 0) || (n == 1)) { r = ctx._cmdStopwatch(op, n); } else if (n == 2) { r = ctx._cmdStopwatch2(ctx, op); } if (r == -1) DebugJS.printUsage(tbl.help); return r; }, _cmdStopwatch: function(op, n) { var stopwatch = DebugJS.stopwatch; var elps = stopwatch.val(n); switch (op) { case 'start': stopwatch.start(n); break; case 'stop': stopwatch.stop(n); break; case 'reset': stopwatch.reset(n); break; case 'split': stopwatch.split(n); break; case 'end': stopwatch.end(n); break; case 'val': DebugJS._log('sw' + n + ': ' + DebugJS.getTimerStr(elps)); break; default: return -1; } return elps; }, _cmdStopwatch2: function(ctx, op) { if (!ctx.isAvailableTools(ctx)) return false; switch (op) { case 'start': ctx.startTimerStopwatchCd(); break; case 'stop': ctx.stopTimerStopwatchCd(); break; case 'reset': ctx.resetTimerStopwatchCd(); break; case 'split': ctx.splitTimerStopwatchCd(); break; case 'val': DebugJS._log(DebugJS.TIMER_NAME_SW_CD + ': ' + DebugJS.getTimerStr(ctx.timerSwTimeCd)); break; default: return -1; } return 0; }, cmdUnAlias: function(arg, tbl, echo) { var nm = DebugJS.splitArgs(arg); if (nm[0] == '') { DebugJS.printUsage(tbl.help); return; } if (nm[0] == '-a') { DebugJS.ctx.CMD_ALIAS = {}; return; } var tbl = DebugJS.ctx.CMD_ALIAS; for (var i = 0; i < nm.length; i++) { if (tbl[nm[i]] == undefined) { DebugJS._log(nm[i] + ': not found'); } else { delete tbl[nm[i]]; } } }, cmdUnicode: function(arg, tbl, echo) { var iIdx = 0; if ((DebugJS.hasOpt(arg, 'd')) || (DebugJS.hasOpt(arg, 'e'))) iIdx++; return DebugJS.ctx.execEncAndDec(arg, tbl, echo, false, DebugJS.getUnicodePoints, DebugJS.decodeUnicode, iIdx); }, cmdUri: function(arg, tbl, echo) { var iIdx = 0; if ((DebugJS.hasOpt(arg, 'd')) || (DebugJS.hasOpt(arg, 'e'))) iIdx++; return DebugJS.ctx.execEncAndDec(arg, tbl, echo, true, DebugJS.encodeUri, DebugJS.decodeUri, iIdx); }, cmdUtf8: function(arg, tbl, echo) { try { var s = eval(arg); if (typeof s == 'string') { var bf = DebugJS.UTF8.toByte(s); if (echo) DebugJS.ctx._dumpByteSeq(s, bf.length); return bf; } else { DebugJS.printUsage(tbl.help); } } catch (e) { DebugJS._log.e(e); DebugJS.printUsage(tbl.help); } }, _dumpByteSeq: function(str, len) { var s = ''; var cnt = 0; for (var i = 0; i < str.length; i++) { var ch = str.charAt(i); var a = DebugJS.UTF8.toByte(ch); for (var j = 0; j < a.length; j++) { var v = a[j]; s += '[' + DebugJS.strPadding(cnt, ' ', DebugJS.digits(len), 'L') + '] '; s += DebugJS.strPadding(v, ' ', 3, 'L') + ' '; s += DebugJS.toHex(v, true, true, 2) + ' '; s += DebugJS.toBin(v); if (j == 0) { s += ' ' + DebugJS.getUnicodePoints(ch); s += ' ' + DebugJS.hlCtrlChr(ch, true); } s += '\n'; cnt++; } } DebugJS._log.mlt(s); }, cmdV: function(arg, tbl) { DebugJS._log(DebugJS.ctx.v); return DebugJS.ctx.v; }, cmdVals: function(arg, tbl) { var ctx = DebugJS.ctx; var o = DebugJS.getOptVal(arg, 'c'); if (o == null) { ctx._cmdVals(ctx); } else { ctx._cmdValsC(ctx); } }, _cmdVals: function(ctx) { var v = ''; for (var k in ctx.CMDVALS) { v += '<tr><td class="dbg-cmdtd">' + k + '</td><td>' + DebugJS.objDump(ctx.CMDVALS[k], false) + '</td></tr>'; } if (v == '') { DebugJS._log('no variables'); } else { v = '<table>' + v + '</table>'; DebugJS._log.mlt(v); } }, _cmdValsC: function(ctx) { for (var n in ctx.CMDVALS) { if (!DebugJS.isSysVal(n)) delete ctx.CMDVALS[n]; } }, cmdWatchdog: function(arg, tbl) { var a = DebugJS.splitArgs(arg); var op = a[0]; var time = a[1]; switch (op) { case 'start': DebugJS.wd.start(time); break; case 'stop': DebugJS.wd.stop(); break; default: if (DebugJS.ctx.status & DebugJS.ST_WD) { DebugJS._log('Running ' + DebugJS.ctx.props.wdt + 'ms: ' + DebugJS.wd.cnt); } else { DebugJS._log('Not Running'); } DebugJS.printUsage(tbl.help); } }, cmdWin: function(arg, tbl) { var size = arg.trim(); switch (size) { case 'min': case 'normal': case 'full': case 'expand': case 'center': case 'restore': case 'reset': DebugJS.ctx.setWinSize(size); break; default: DebugJS.printUsage(tbl.help); } }, setWinSize: function(opt) { var ctx = DebugJS.ctx; switch (opt) { case 'min': ctx.saveSize(ctx); ctx.savePosNone(ctx); ctx.setDbgWinSize(ctx.computedMinW, ctx.computedMinH); ctx.scrollLogBtm(ctx); ctx.uiStatus &= ~DebugJS.UI_ST_POS_AUTO_ADJUST; ctx.sizeStatus = DebugJS.SIZE_ST_MIN; ctx.updateWinCtrlBtnPanel(); break; case 'normal': var w = (ctx.initWidth - (DebugJS.WIN_SHADOW / 2) + DebugJS.WIN_BORDER); var h = (ctx.initHeight - (DebugJS.WIN_SHADOW / 2) + DebugJS.WIN_BORDER); ctx.setDbgWinSize(w, h); ctx.sizeStatus = DebugJS.SIZE_ST_NORMAL; ctx.updateWinCtrlBtnPanel(); ctx.scrollLogBtm(ctx); break; case 'restore': if (ctx.sizeStatus != DebugJS.SIZE_ST_NORMAL) { ctx.restoreDbgWin(); ctx.updateWinCtrlBtnPanel(); } break; case 'reset': ctx.resetDbgWinSizePos(); break; case 'center': case 'full': case 'expand': ctx.expandDbgWin(opt); ctx.updateWinCtrlBtnPanel(); } }, cmdZoom: function(arg, tbl) { var zm = arg.trim(); if (zm == '') { DebugJS.printUsage(tbl.help); } else if (zm != DebugJS.ctx.opt.zoom) { DebugJS.zoom(zm); } return DebugJS.zoom(); }, cmdNop: function(arg, tbl) {}, execEncAndDec: function(arg, tbl, echo, esc, encFnc, decFnc, iIdx, a1, a2) { if (DebugJS.countArgs(arg) == 0) { DebugJS.printUsage(tbl.help); return; } var fn = encFnc; if (DebugJS.hasOpt(arg, 'd')) { fn = decFnc; } else if (DebugJS.hasOpt(arg, 'e')) { fn = encFnc; } var i = DebugJS.getOptVal(arg, 'i'); try { if (i == null) { i = DebugJS.getArgsFrom(arg, iIdx); } else { i = eval(i); } var ret = fn(i, a1, a2); var r = (esc ? DebugJS.escTags(ret) : ret); if (echo) DebugJS._log.res(DebugJS.quoteStrIfNeeded(r)); return ret; } catch (e) { DebugJS._log.e(e); } }, doHttpRequest: function(method, arg) { var a = DebugJS.splitCmdLineInTwo(arg); var url = a[0]; var data = a[1]; var user = ''; var pass = ''; if (url == '--user') { var parts = DebugJS.splitCmdLineInTwo(data); var auth = parts[0]; var auths = auth.split(':'); if (auths.length > 1) { user = auths[0]; pass = auths[1]; parts = DebugJS.splitCmdLineInTwo(parts[1]); url = parts[0]; data = parts[1]; } } data = DebugJS.encodeURIString(data); method = method.toUpperCase(); var req = 'Sending a request.\n' + method + ' ' + url + '\n' + 'Body: ' + ((data == '') ? '<span style="color:#ccc">null</span>' : data); if (user || pass) { req += '\nuser: ' + user + ':' + (pass ? '*' : ''); } DebugJS._log(req); var request = { url: url, method: method, data: data, async: true, cache: false, user: user, pass: pass //userAgent: 'Mozilla/5.0' }; try { DebugJS.http(request, DebugJS.onHttpRequestDone); } catch (e) { DebugJS._log.e(e); var baseURI = document.baseURI; var reg = new RegExp('^' + baseURI + '(.*?)'); if (!url.match(reg)) { DebugJS._log.w('Cross-Origin Request\nsource : ' + baseURI + '\nrequest: ' + url); } } }, initExtension: function(ctx) { ctx.initExtPanel(ctx); }, initExtPanel: function(ctx) { if (ctx.extPanel == null) { var bp = ctx.createSubBasePanel(ctx); ctx.extPanel = bp.base; ctx.extHeaderPanel = bp.head; ctx.extBodyPanel = bp.body; ctx.extBodyPanel.style.overflow = 'auto'; } var pnls = ctx.extPanels; if (pnls.length > 0) { if (ctx.extBtn) ctx.extBtn.style.display = ''; for (var i = 0; i < pnls.length; i++) { var p = pnls[i]; if ((p != null) && (p.base == null)) { ctx.createExtPanel(ctx, p, i); } DebugJS.x.addFileLdr(p); } } }, redrawExtPanelBtn: function(ctx) { for (var i = ctx.extHeaderPanel.childNodes.length - 1; i >= 0; i--) { ctx.extHeaderPanel.removeChild(ctx.extHeaderPanel.childNodes[i]); } var pnls = ctx.extPanels; if (pnls.length > 0) { for (i = 0; i < pnls.length; i++) { var p = pnls[i]; if (p != null) { ctx.extHeaderPanel.appendChild(p.btn); } } } else { ctx.extBtn.style.display = 'none'; } }, createExtPanel: function(ctx, p, idx) { p.base = document.createElement('div'); p.base.className = 'dbg-sbpnl'; p.btn = ctx.createExtHeaderBtn(ctx, p.name, idx); if (p.panel) { p.base.appendChild(p.panel); } else { p.panel = p.base; } if (p.onCreate) p.onCreate(p.panel); }, existsCmd: function(cmd, tbl) { for (var i = 0; i < tbl.length; i++) { if (tbl[i].cmd == cmd) return true; } return false; } }; DebugJS.addSubPanel = function(base) { var el = document.createElement('div'); el.className = 'dbg-sbpnl'; base.appendChild(el); return el; }; DebugJS.addPropSep = function(ctx) { return '<div class="dbg-sep"></div>'; }; DebugJS.addSysInfoPropH = function(n) { return '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '">' + n + '.</span>\n'; }; DebugJS.addSysInfoProp = function(n, v, id) { var s = '<span style="color:' + DebugJS.ITEM_NAME_COLOR + '"> ' + n + '</span>: '; if (id == undefined) { s += v; } else { s += '<span' + (id == undefined ? '' : ' id="' + DebugJS.ctx.id + '-' + id + '"') + '>' + v + '</span>'; } s += '\n'; return s; }; DebugJS.getColorBlock = function(color) { var w = DebugJS.ctx.computedFontSize / 2; var h = DebugJS.ctx.computedFontSize; return '<span style="background:' + color + ';width:' + w + 'px;height:' + h + 'px;display:inline-block"> </span>'; }; DebugJS.getElmHexColor = function(color) { var hex = ''; if ((color) && (color != 'transparent')) { var color10 = color.replace('rgba', '').replace('rgb', '').replace('(', '').replace(')', '').replace(',', ''); var color16 = DebugJS.convRGB10to16(color10); hex = '#' + color16.r + color16.g + color16.b; } return hex; }; DebugJS.RingBuffer = function(len) { this.buffer = new Array(len); this.len = len; this.cnt = 0; }; DebugJS.RingBuffer.prototype = { add: function(data) { var idx = this.cnt % this.len; this.buffer[idx] = data; this.cnt++; }, set: function(idx, data) { this.buffer[idx] = data; }, get: function(idx) { if (this.len < this.cnt) { idx += this.cnt; } idx %= this.len; return this.buffer[idx]; }, getAll: function() { var buf = []; var len = this.len; var pos = 0; if (this.cnt > len) { pos = (this.cnt % len); } for (var i = 0; i < len; i++) { if (pos >= len) { pos = 0; } if (this.buffer[pos] == undefined) { break; } else { buf[i] = this.buffer[pos]; pos++; } } return buf; }, clear: function() { this.buffer = new Array(this.len); this.cnt = 0; }, count: function() { return this.cnt; }, size: function() { return this.len; }, lastIndex: function() { return ((this.cnt - 1) % this.len); } }; DebugJS.TextBuffer = function(s) { this.b = (s == undefined ? '' : s + '\n'); }; DebugJS.TextBuffer.prototype = { add: function(s) { this.b += s + '\n'; }, toString: function() { return this.b; } }; DebugJS.getCmdValName = function(v, pfix, head) { var m = pfix + '\\{(.+?)\\}'; if (head) m = '^' + m; var re = new RegExp(m); var r = re.exec(v); if (r == null) return null; var idx = r.index; if ((idx > 0) && ((v.charAt(idx - 1) == '\\'))) { return null; } return r[1]; }; DebugJS.replaceCmdVals = function(s) { s = DebugJS._replaceCmdVals(s, true); s = DebugJS._replaceCmdVals(s); return s; }; DebugJS._replaceCmdVals = function(s, il) { var prevN; var pfix = (il ? '%' : '\\$'); while (true) { var name = DebugJS.getCmdValName(s, pfix); if (name == null) return s; if (name == prevN) { DebugJS._log.e('(bug) replaceCmdVals(): ' + name); return s; } prevN = name; var reNm = name; if (name == '?') reNm = '\\?'; var re = new RegExp(pfix + '\\{' + reNm + '\\}', 'g'); var r; if (il) { r = DebugJS.ctx.CMDVALS[name] + ''; } else { r = 'DebugJS.ctx.CMDVALS[\'' + name + '\']'; } s = s.replace(re, r); } }; // " 1 2 3 4 " -> [0]="1" [1]="2" [2]="3" [3]="4" DebugJS.splitArgs = function(arg) { return DebugJS.unifySP(arg.trim()).split(' '); }; // ' 1 "abc" "d ef" "g\"hi" 2 ("jkl" + 3) 4 ' // -> [0]=1 [1]="abc" [2]="d ef" [3]="g\"hi" [4]=2 [5]=("jkl" + 3) [6]=4 DebugJS.splitCmdLine = function(arg, limit) { var args = []; var start = 0; var len = 0; var srch = true; var quoted = null; var paren = 0; var ch = ''; var str = ''; limit = (limit == undefined ? 0 : limit); for (var i = 0; i < arg.length; i++) { len++; ch = arg.charAt(i); switch (ch) { case ' ': if (srch || quoted || (paren > 0)) { continue; } else { srch = true; str = arg.substr(start, len); args.push(str); if (args.length + 1 == limit) { if (i < arg.length - 1) { start = i + 1; len = arg.length - start; str = arg.substr(start, len); args.push(str); i = arg.length; } } } break; case '(': if (srch) { start = i; len = 0; srch = false; } if (!quoted) { paren++; } break; case ')': if (srch) { start = i; len = 0; srch = false; } else if (paren > 0) { if ((i > 0) && (arg.charAt(i - 1) == '\\')) { continue; } paren--; } break; case '"': case "'": if (paren > 0) { continue; } else if (srch) { start = i; len = 0; srch = false; quoted = ch; } else if (ch == quoted) { if ((i > 0) && (arg.charAt(i - 1) == '\\')) { continue; } quoted = null; } break; default: if (srch) { start = i; len = 0; srch = false; } } } len++; if (!srch) { str = arg.substr(start, len); args.push(str); } if (args.length == 0) { args = ['']; } return args; }; // " 1 2 3 4 " -> [0]="1" [1]=" 2 3 4 " DebugJS.splitCmdLineInTwo = function(s) { var r = []; s = DebugJS.delLeadingSP(s); var two = DebugJS.splitCmdLine(s); if (two.length == 1) { r[0] = two[0]; r[1] = ''; } else { r[0] = two[0]; r[1] = s.substr(two[0].length + 1); } return r; }; // " 1 2 3 4 " (2)-> " 3 4 " DebugJS.getArgsFrom = function(s, n) { var r = s; for (var i = 0; i < n; i++) { r = DebugJS.splitCmdLineInTwo(r)[1]; } return r; }; DebugJS.countArgs = function(a) { var b = DebugJS.splitCmdLine(a); var c = b.length; if (b[0] == '') c = 0; return c; }; DebugJS.getArgVal = function(a, idx) { return DebugJS.splitCmdLine(a)[idx]; }; DebugJS.getOptVal = function(args, opt) { var v = DebugJS.getOptVals(args); return (v[opt] == undefined ? null : v[opt]); }; DebugJS.getOptVals = function(args) { var i, k, v; var o = {'': []}; if (typeof args == 'string') { args = DebugJS.splitCmdLine(args); } for (i = 0; i < args.length; i++) { if ((args[i].charAt(0) == '-') && ((k = args[i].substring(1)) != '')) { if ((args[i + 1] != undefined) && (args[i + 1].charAt(0) != '-')) { i++; v = args[i]; } else { v = ''; } o[k] = v; } else { o[''].push(args[i]); } } return o; }; DebugJS.hasOpt = function(arg, opt) { var b = false; var v = DebugJS.getOptVal(arg, opt); if (opt == '') { if (v.length > 0) b = true; } else { if (v != null) b = true; } return b; }; DebugJS.indexOfOptVal = function(a, o) { var r = -1; var i = a.indexOf(o); if (i >= 0) { r = i + o.length + 1; } return r; }; DebugJS.getQuotedStr = function(str) { var r = null; var start = 0; var len = 0; var srch = true; var quoted = null; var ch = ''; for (var i = 0; i < str.length; i++) { len++; ch = str.charAt(i); if ((ch == '"') || (ch == "'")) { if (srch) { start = i; len = 0; srch = false; quoted = ch; } else if (ch == quoted) { if ((i > 0) && (str.charAt(i - 1) == '\\')) { continue; } r = str.substr(start + 1, len - 1); break; } } } return r; }; DebugJS.encodeEsc = function(s) { return s.replace(/\\/g, '\\\\'); }; DebugJS.decodeEsc = function(s) { return s.replace(/\\\\/g, '\\'); }; DebugJS.isNumeric = function(ch) { var c = ch.charCodeAt(); return ((c >= 0x30) && (c <= 0x39)); }; DebugJS.isAlphabetic = function(ch) { var c = ch.charCodeAt(); return (((c >= 0x41) && (c <= 0x5A)) || ((c >= 0x61) && (c <= 0x7A))); }; DebugJS.isUpperCase = function(ch) { var c = ch.charCodeAt(); return ((c >= 0x41) && (c <= 0x5A)); }; DebugJS.isLowerCase = function(ch) { var c = ch.charCodeAt(); return ((c >= 0x61) && (c <= 0x7A)); }; DebugJS.isPunctuation = function(ch) { var c = ch.charCodeAt(); if (((c >= 0x20) && (c <= 0x2F)) || ((c >= 0x3A) && (c <= 0x40)) || ((c >= 0x5B) && (c <= 0x60)) || ((c >= 0x7B) && (c <= 0x7E))) { return true; } return false; }; DebugJS.isNumAlpha = function(ch) { var c = ch.charCodeAt(); return (DebugJS.isNumeric(ch) || DebugJS.isAlphabetic(ch)); }; DebugJS.isTypographic = function(ch) { var c = ch.charCodeAt(); return (DebugJS.isNumAlpha(ch) || DebugJS.isPunctuation(ch)); }; DebugJS.isNum = function(s) { return (s.match(/^\d+$/) ? true : false); }; DebugJS.wBOM = function(s) { return s.charCodeAt(0) == 65279; }; DebugJS.getContentType = function(mime, file, dturlData) { var t = ''; var ext = ['bat', 'csv', 'ini', 'java', 'js', 'json', 'log', 'md']; var re = ''; for (var i = 0; i < ext.length; i++) { if (i > 0) {re += '|';} re += '.' + ext[i] + '$'; } var xmlHead = 'PD94bWw'; if (mime) { if (mime.match(/image\//)) { t = 'image'; } else if (mime.match(/text\//)) { t = 'text'; } } else if (file) { if (file.type.match(/image\//)) { t = 'image'; } else if ((file.type.match(/text\//)) || ((new RegExp(re)).test(file.name)) || DebugJS.startsWith(dturlData, xmlHead)) { t = 'text'; } } return t; }; DebugJS.KEYCH = { Spacebar: ' ', Enter: '\n', Add: '+', Subtract: '-', Multiply: '*', Divide: '/', Del: '.' }; DebugJS.key2ch = function(k) { return (DebugJS.KEYCH[k] == undefined ? k : DebugJS.KEYCH[k]); }; DebugJS.unifySP = function(s) { return s.replace(/\s{2,}/g, ' '); }; DebugJS.delAllSP = function(s) { return s.replace(/\s/g, ''); }; DebugJS.delLeadingSP = function(s) { return s.replace(/^\s{1,}/, ''); }; DebugJS.delTrailingSP = function(s) { return s.replace(/\s+$/, ''); }; DebugJS.delAllNL = function(s) { s = s.replace(/\r/g, ''); s = s.replace(/\n/g, ''); return s; }; DebugJS.quoteStr = function(s) { return '<span style="color:#0ff">"</span>' + s + '<span style="color:#0ff">"</span>'; }; DebugJS.quoteStrIfNeeded = function(s) { s += ''; if ((s.match(/^\s|^&#x3000/)) || (s.match(/\s$|&#x3000$/))) { s = DebugJS.quoteStr(s); } return s; }; DebugJS.escEncString = function(s) { s = DebugJS.escTags(s); s = DebugJS.quoteStr(s); return s; }; DebugJS.styleValue = function(v) { var s = v; if (typeof s == 'string') { s = DebugJS.escTags(s); s = DebugJS.quoteStr(s); } else { s = DebugJS.setStyleIfObjNA(s); } return s; }; DebugJS.getDateTime = function(dt) { if ((dt == undefined) || (dt === '')) { dt = new Date(); } else if (!(dt instanceof Date)) { dt = new Date(dt); } var time = dt.getTime(); var offset = dt.getTimezoneOffset(); var yyyy = dt.getFullYear(); var mm = dt.getMonth() + 1; var dd = dt.getDate(); var hh = dt.getHours(); var mi = dt.getMinutes(); var ss = dt.getSeconds(); var ms = dt.getMilliseconds(); var wd = dt.getDay(); if (mm < 10) mm = '0' + mm; if (dd < 10) dd = '0' + dd; if (hh < 10) hh = '0' + hh; if (mi < 10) mi = '0' + mi; if (ss < 10) ss = '0' + ss; if (ms < 10) {ms = '00' + ms;} else if (ms < 100) {ms = '0' + ms;} var dateTime = {time: time, offset: offset, yyyy: yyyy, mm: mm, dd: dd, hh: hh, mi: mi, ss: ss, sss: ms, wday: wd}; return dateTime; }; DebugJS.getDateTimeIso = function(s) { var p = s.split('T'); var d = p[0]; var t = p[1]; var yyyy = d.substr(0, 4); var mm = d.substr(4, 2); var dd = d.substr(6, 2); var hh = (t.substr(0, 2) + '00').substr(0, 2); var mi = (t.substr(2, 2) + '00').substr(0, 2); var ss = (t.substr(4, 2) + '00').substr(0, 2); var sss = (t.substr(7, 3) + '000').substr(0, 3); var dt = new Date(yyyy, (mm | 0) - 1, dd, hh, mi, ss, sss); return DebugJS.getDateTime(dt); }; DebugJS.getDateTimeEx = function(s) { if (DebugJS.isDateTimeFormatIso(s)) { return DebugJS.getDateTimeIso(s); } if (typeof s == 'string') { s = s.replace(/-/g, '/'); var dec = s.split('.'); if (dec.length > 0) s = dec[0]; s = (new Date(s)).getTime(); if (dec.length > 0) s += (dec[1] | 0); } return DebugJS.getDateTime(s); }; DebugJS.date = function(val, iso) { val += ''; val = val.trim(); var s = null; var dt; if ((val == '') || isNaN(val)) { if (DebugJS.isDateTimeFormatIso(val)) { dt = DebugJS.getDateTimeIso(val); } else { val = val.replace(/(\d{4})-(\d{1,})-(\d{1,})/g, '$1/$2/$3'); dt = DebugJS.getDateTime(val); } var tm = dt.time; if (!isNaN(tm)) { if (iso) { s = DebugJS.date(tm, iso); } else { s = DebugJS.date(tm) + ' (' + tm + ')'; } } } else { val = DebugJS.parseInt(val); dt = DebugJS.getDateTime(val); if (iso) { s = DebugJS.getDateTimeStrIso(dt); } else { s = DebugJS.convDateTimeStr(dt) + ' ' + DebugJS.getTimeOffsetStr(dt.offset); } } return s; }; DebugJS.diffDate = function(d1, d2) { var dt1 = DebugJS.getDateTime(d1); var dt2 = DebugJS.getDateTime(d2); return (dt2.time - dt1.time) / 86400000; }; DebugJS.isDateFormat = function(s, p) { if (s == null) return false; var r = '^\\d{4}[-/]\\d{1,2}[-/]\\d{1,2}'; if (!p) r += '$'; return (s.match(new RegExp(r)) ? true : false); }; DebugJS.isBasicDateFormat = function(s, p) { if (s == null) return false; var r = '^\\d{4}[0-1][0-9][0-3][0-9]'; if (!p) r += '$'; return (s.match(new RegExp(r)) ? true : false); }; DebugJS.isDateTimeFormat = function(s, p) { if (s == null) return false; var r = '^\\d{4}[-/]\\d{1,2}[-/]\\d{1,2} {1,}\\d{1,2}:\\d{2}:?\\d{0,2}.?\\d{0,3}'; if (!p) r += '$'; return (s.match(new RegExp(r)) ? true : false); }; DebugJS.isDateTimeFormatIso = function(s, p) { if (typeof s != 'string') return false; var r = '^\\d{8}T\\d{0,6}.?\\d{0,3}'; if (!p) r += '$'; return (s.match(new RegExp(r)) ? true : false); }; DebugJS.isTimeFormat = function(s) { return ((s.match(/^\d{8}T\d{4,6}$/)) || (s.match(/^T\d{4,6}$/))); }; DebugJS.num2date = function(s) { var d = null; if (DebugJS.isBasicDateFormat(s)) { d = s.substr(0, 4) + '/' + s.substr(4, 2) + '/' + s.substr(6, 2); } return d; }; DebugJS.today = function(s) { return DebugJS.convDateStr(DebugJS.getDateTime(), (s === undefined ? '-' : s)); }; DebugJS.convDateTimeStr = function(d) { return (d.yyyy + '-' + d.mm + '-' + d.dd + ' ' + DebugJS.WDAYS[d.wday] + ' ' + d.hh + ':' + d.mi + ':' + d.ss + '.' + d.sss); }; DebugJS.getDateTimeStrIso = function(d) { return (d.yyyy + d.mm + d.dd + 'T' + d.hh + d.mi + d.ss + '.' + d.sss); }; DebugJS.convDateStr = function(d, s) { return d.yyyy + s + d.mm + s + d.dd; }; DebugJS.convTimeStr = function(d) { return d.hh + ':' + d.mi + ':' + d.ss + '.' + d.sss; }; DebugJS.getTimeStr = function(t) { var d = DebugJS.getDateTime(t); return d.hh + ':' + d.mi + ':' + d.ss + '.' + d.sss; }; DebugJS.getDateTimeStr = function(t) { var d = DebugJS.getDateTime(t); return d.yyyy + '-' + d.mm + '-' + d.dd + ' ' + d.hh + ':' + d.mi + ':' + d.ss + '.' + d.sss; }; DebugJS.getTimerStr = function(ms) { var tm = DebugJS.ms2struct(ms, true); return tm.hh + ':' + tm.mi + ':' + tm.ss + '.' + tm.sss; }; DebugJS.ms2struct = function(ms, fmt) { var wk = ms; var sign = false; if (ms < 0) { sign = true; wk *= (-1); } var d = (wk / 86400000) | 0; var hh = 0; if (wk >= 3600000) { hh = (wk / 3600000) | 0; wk -= (hh * 3600000); } var mi = 0; if (wk >= 60000) { mi = (wk / 60000) | 0; wk -= (mi * 60000); } var ss = (wk / 1000) | 0; var sss = wk - (ss * 1000); var tm = { sign: sign, d: d, hr: hh - d * 24, hh: hh, mi: mi, ss: ss, sss: sss }; if (fmt) { if (tm.hh < 10) tm.hh = '0' + tm.hh; if (tm.mi < 10) tm.mi = '0' + tm.mi; if (tm.ss < 10) tm.ss = '0' + tm.ss; if (tm.sss < 10) { tm.sss = '00' + tm.sss; } else if (tm.sss < 100) { tm.sss = '0' + tm.sss; } } return tm; }; DebugJS.timestr2struct = function(str) { var wk = str.split(':'); var h = wk[0]; var mi = (wk[1] == undefined ? '' : wk[1]); var s = (wk[2] == undefined ? '' : wk[2]); var ss = s.split('.')[0]; var sss = s.split('.')[1]; if (sss == undefined) sss = ''; mi = DebugJS.nan2zero(mi); ss = DebugJS.nan2zero(ss); sss = DebugJS.nan2zero(sss); var st = { hh: DebugJS.nan2zero(h), mi: ('00' + mi).slice(-2), ss: ('00' + ss).slice(-2), sss: ('000' + sss).slice(-3) }; return st; }; DebugJS.getTimeOffsetStr = function(v, e) { var s = '-'; if (v <= 0) { v *= (-1); s = '+'; } var h = (v / 60) | 0; var m = v - h * 60; var str = s + ('0' + h).slice(-2) + (e ? ':' : '') + ('0' + m).slice(-2); return str; }; DebugJS.getTimeDurationStr = function(t1, t2) { var dec; if (isNaN(t1)) t1 = DebugJS.getDateTimeEx(t1).time; var ms = t1; if (t2 != undefined) { if (isNaN(t2)) t2 = DebugJS.getDateTimeEx(t2).time; ms = t2 - t1; } var s = ''; var t = DebugJS.ms2struct(ms); if (t.d) s += t.d + 'd '; if (t.d || t.hr) s += t.hr + 'h '; if (t.d || t.hr || t.mi) s += t.mi + 'm '; if (t.d || t.hr || t.mi || t.ss) { s += t.ss + 's'; if (t.sss) s += ' ' + t.sss + 'ms'; } else { if (!t.sss) { s = '0'; } else { s = '0.' + ('00' + t.sss).slice(-3).replace(/0+$/, ''); } s += 's'; } return s; }; DebugJS.calcTargetTime = function(tgt) { var yyyy, mm, dd, t1; var now = DebugJS.getDateTime(); var dt = tgt.split('T'); var date = dt[0]; var t = dt[1]; var hh = t.substr(0, 2); var mi = t.substr(2, 2); var ss = t.substr(4, 2); if (ss == '') ss = '00'; if (date == '') { yyyy = now.yyyy; mm = now.mm; dd = now.dd; var tgt = DebugJS.getDateTime(now.yyyy + '/' + now.mm + '/' + now.dd + ' ' + hh + ':' + mi + ':' + ss); if (now.time > tgt.time) { t1 = tgt.time + 86400000; } else { t1 = tgt.time; } } else { yyyy = date.substr(0, 4); mm = date.substr(4, 2); dd = date.substr(6, 2); var sd = yyyy + '/' + mm + '/' + dd + ' ' + hh + ':' + mi + ':' + ss; t1 = (new Date(sd)).getTime(); } return (t1 - now.time); }; DebugJS.calcNextTime = function(times) { var now = DebugJS.getDateTime(); ts = times.split('|'); ts.sort(); var ret = {t: ts[0]}; var yyyy = now.yyyy; var mm = now.mm; var dd = now.dd; for (var i = 0; i < ts.length; i++) { var t = ts[i]; t = t.replace(/T/, ''); var hh = t.substr(0, 2); var mi = t.substr(2, 2); var ss = t.substr(4, 2); if (ss == '') ss = '00'; var tgt = DebugJS.getDateTime(now.yyyy + '/' + now.mm + '/' + now.dd + ' ' + hh + ':' + mi + ':' + ss); if (i == 0) ret.time = tgt.time; if (now.time <= tgt.time) { ret.t = ts[i]; ret.time = tgt.time; return ret; } } ret.t = ts[0]; ret.time += 86400000; return ret; }; DebugJS.parseToMillis = function(v) { var d = 0, h = 0, m = 0, s = 0; var a = v.split('d'); if (a.length > 1) { d = a[0]; v = a[1]; } else { v = a[0]; } var a = v.split('h'); if (a.length > 1) { h = a[0]; v = a[1]; } else { v = a[0]; } var a = v.split('m'); if (a.length > 1) { m = a[0]; v = a[1]; } else { v = a[0]; } var a = v.split('s'); if (a.length > 1) { s = a[0]; } return (d * 86400000 + h * 3600000 + m * 60000 + s * 1000) | 0; }; DebugJS.nan2zero = function(v) { return (isNaN(v) ? 0 : v); }; DebugJS.checkModKey = function(e) { var shift = e.shiftKey ? DebugJS.COLOR_ACTIVE : DebugJS.COLOR_INACT; var ctrl = e.ctrlKey ? DebugJS.COLOR_ACTIVE : DebugJS.COLOR_INACT; var alt = e.altKey ? DebugJS.COLOR_ACTIVE : DebugJS.COLOR_INACT; var meta = e.metaKey ? DebugJS.COLOR_ACTIVE : DebugJS.COLOR_INACT; var metaKey = '<span style="color:' + shift + '">S</span><span style="color:' + ctrl + '">C</span><span style="color:' + alt + '">A</span><span style="color:' + meta + '">M</span>'; return metaKey; }; DebugJS._cmdP = function(_arg, _tbl) { var _obj; var _jsn = false; var _dmpLmt = DebugJS.ctx.props.dumplimit; var _vlLen = DebugJS.ctx.props.dumpvallen; var _lvLmt = 0; var _opt = DebugJS.getOptVals(_arg); for (var _k in _opt) { if ((_k == '') && (_opt[_k].length > 0)) { _obj = _opt[_k][0]; } var _lv = _k.match(/l(\d+)/); if (_lv != null) { _lvLmt = _lv[1]; if (!_obj) _obj = _opt[_k]; } if (_k == 'json') { _jsn = true; if (!_obj) _obj = _opt[_k]; } if (_k == 'a') { _dmpLmt = _vlLen = 0; if (!_obj) _obj = _opt[_k]; } } if (!_obj) { DebugJS.printUsage(_tbl.help); return; } var _cl = 'DebugJS.buf=DebugJS.objDump(' + _obj + ', _jsn, ' + _lvLmt + ', ' + _dmpLmt + ', ' + _vlLen + ');DebugJS._log.mlt(DebugJS.buf);'; try { eval(_cl); } catch (e) { DebugJS._log.e(e); } }; DebugJS.INDENT_SP = ' '; DebugJS.objDump = function(obj, toJson, levelLimit, limit, valLenLimit) { if (levelLimit == undefined) levelLimit = 0; if (limit == undefined) limit = DebugJS.ctx.props.dumplimit; if (valLenLimit == undefined) valLenLimit = 0; var arg = {lv: 0, cnt: 0, dump: ''}; if (typeof obj === 'function') { arg.dump += (toJson ? 'function' : '<span style="color:#4c4">function</span>') + '()\n'; } var ret = DebugJS._objDump(obj, arg, toJson, levelLimit, limit, valLenLimit); if ((limit > 0) && (ret.cnt > limit)) { DebugJS._log.w('The object is too large. (>=' + ret.cnt + ')'); } ret.dump = ret.dump.replace(/: {2,}\{/g, ': {'); ret.dump = ret.dump.replace(/\[\n {2,}\]/g, '[]'); return ret.dump; }; DebugJS._objDump = function(obj, arg, toJson, levelLimit, limit, valLenLimit) { var SNIP = (toJson ? '...' : '<span style="color:#aaa">...</span>'); var sibling = 0; try { if ((levelLimit > 0) && (arg.lv > levelLimit)) return arg; if ((limit > 0) && (arg.cnt > limit)) { if ((typeof obj !== 'function') || (Object.keys(obj).length > 0)) { arg.dump += SNIP; arg.cnt++; } return arg; } var indent = ''; for (var i = 0; i < arg.lv; i++) { indent += DebugJS.INDENT_SP; } if ((obj instanceof Array) || (obj instanceof Set)) { arg.cnt++; var len = ((obj instanceof Set) ? obj.size : obj.length); if (toJson) { arg.dump += '['; if (len > 0) { arg.dump += '\n'; } } else { if (obj instanceof Set) { arg.dump += '<span style="color:#6cf">[Set][' + len + ']</span>'; } else { arg.dump += '<span style="color:#e4b">[Array][' + len + ']</span>'; } } if ((levelLimit == 0) || ((levelLimit >= 1) && (arg.lv < levelLimit))) { var avil = true; for (i = 0; i < len; i++) { arg.lv++; indent += DebugJS.INDENT_SP; v = obj[i]; if (obj instanceof Set) { try { var it = obj.entries(); for (var j = 0; j <= i; j++) { v = it.next().value[0]; } } catch (e) {avil = false;} } if (toJson) { if (sibling > 0) { arg.dump += ',\n'; } if ((typeof v == 'number') || (typeof v == 'string') || (typeof v == 'boolean') || (v instanceof Array)) { arg.dump += indent; } } else { arg.dump += '\n' + indent + '[' + i + '] '; } if (avil) { arg = DebugJS._objDump(v, arg, toJson, levelLimit, limit, valLenLimit); } else { arg.dump += 'N/A'; } arg.lv--; indent = indent.replace(DebugJS.INDENT_SP, ''); sibling++; } } if (toJson) { if (sibling > 0) { arg.dump += '\n'; } if (len > 0) { if ((levelLimit >= 1) && (arg.lv >= levelLimit)) { arg.dump += indent + DebugJS.INDENT_SP + SNIP + '\n'; } arg.dump += indent; } arg.dump += ']'; } } else if (obj instanceof Object) { arg.cnt++; if ((typeof obj !== 'function') && (Object.prototype.toString.call(obj) !== '[object Date]') && ((window.ArrayBuffer) && !(obj instanceof ArrayBuffer))) { if (toJson) { arg.dump += indent; } else { arg.dump += '<span style="color:#49f">[Object]</span> '; } if ((toJson) || (levelLimit == 0) || ((levelLimit >= 1) && (arg.lv < levelLimit))) { arg.dump += '{\n'; } } if ((levelLimit == 0) || ((levelLimit >= 1) && (arg.lv < levelLimit))) { indent += DebugJS.INDENT_SP; for (var key in obj) { if (sibling > 0) { if (toJson) { arg.dump += ','; } arg.dump += '\n'; } if (typeof obj[key] === 'function') { arg.dump += indent + (toJson ? 'function' : '<span style="color:#4c4">function</span>'); if (obj[key].toString().match(/\[native code\]/)) { arg.dump += ' [native]'; } arg.dump += ' ' + DebugJS.escTags(key) + '()'; arg.cnt++; if ((levelLimit == 0) || ((levelLimit >= 1) && ((arg.lv + 1) < levelLimit))) { if (Object.keys(obj[key]).length > 0) { arg.dump += ' {\n'; } } } else if (Object.prototype.toString.call(obj[key]) === '[object Date]') { arg.dump += indent; if (toJson) {arg.dump += '"';} arg.dump += (toJson ? key : DebugJS.escTags(key)); if (toJson) {arg.dump += '"';} var dt = DebugJS.getDateTime(obj[key]); var date = dt.yyyy + '-' + dt.mm + '-' + dt.dd + ' ' + DebugJS.WDAYS[dt.wday] + ' ' + dt.hh + ':' + dt.mi + ':' + dt.ss + '.' + dt.sss + ' (' + obj[key].getTime() + ')'; arg.dump += ': '; if (toJson) { arg.dump += '"' + obj[key].toISOString() + '"'; } else { arg.dump += '<span style="color:#f80">[Date]</span> ' + date; } sibling++; continue; } else if ((window.ArrayBuffer) && (obj[key] instanceof ArrayBuffer)) { arg.dump += indent; if (toJson) {arg.dump += '"';} arg.dump += (toJson ? key : DebugJS.escTags(key)); if (toJson) {arg.dump += '"';} arg.dump += ': '; if (toJson) { arg.dump += '{}'; } else { arg.dump += '<span style="color:#d4c">[ArrayBuffer]</span> (byteLength = ' + obj[key].byteLength + ')'; } sibling++; continue; } else { arg.dump += indent; if (toJson) {arg.dump += '"';} arg.dump += (toJson ? key : DebugJS.escTags(key)); if (toJson) {arg.dump += '"';} arg.dump += ': '; } var hasChildren = false; for (var cKey in obj[key]) { hasChildren = true; break; } if ((typeof obj[key] !== 'function') || (hasChildren)) { arg.lv++; arg = DebugJS._objDump(obj[key], arg, toJson, levelLimit, limit, valLenLimit); arg.lv--; } if (typeof obj[key] === 'function') { if ((levelLimit == 0) || ((levelLimit >= 1) && ((arg.lv + 1) < levelLimit))) { if (Object.keys(obj[key]).length > 0) { arg.dump += '\n' + indent + '}'; } } } sibling++; } var empty = false; if (sibling == 0) { if (typeof obj === 'function') { arg.dump += '<span style="color:#4c4">function</span>()'; if (obj.toString().match(/\[native code\]/)) { arg.dump += ' [native]'; } } else if (Object.prototype.toString.call(obj) === '[object Date]') { var dt = DebugJS.getDateTime(obj); var date = dt.yyyy + '-' + dt.mm + '-' + dt.dd + ' ' + DebugJS.WDAYS[dt.wday] + ' ' + dt.hh + ':' + dt.mi + ':' + dt.ss + '.' + dt.sss + ' (' + obj.getTime() + ')'; if (toJson) { arg.dump += '"' + obj.toISOString() + '"'; } else { arg.dump += '<span style="color:#f80">[Date]</span> ' + date; } } else if ((window.ArrayBuffer) && (obj instanceof ArrayBuffer)) { if (toJson) { arg.dump += '{}'; } else { arg.dump += '<span style="color:#d4c">[ArrayBuffer]</span> (byteLength = ' + obj.byteLength + ')'; } } else { empty = true; arg.dump = arg.dump.replace(/\n$/, ''); arg.dump += '}'; } arg.cnt++; } indent = indent.replace(DebugJS.INDENT_SP, ''); if ((typeof obj !== 'function') && (Object.prototype.toString.call(obj) !== '[object Date]') && ((window.ArrayBuffer) && !(obj instanceof ArrayBuffer) && (!empty))) { arg.dump += '\n' + indent + '}'; } } if ((toJson) && (levelLimit >= 1) && (arg.lv >= levelLimit)) { arg.dump += indent + DebugJS.INDENT_SP + SNIP + '\n' + indent + '}'; } } else if (obj === null) { if (toJson) { arg.dump += 'null'; } else { arg.dump += '<span style="color:#ccc">null</span>'; } arg.cnt++; } else if (obj === undefined) { if (toJson) { arg.dump += 'undefined'; } else { arg.dump += '<span style="color:#ccc">undefined</span>'; } arg.cnt++; } else if (typeof obj == 'string') { var str; if ((valLenLimit > 0) && (obj.length > valLenLimit)) { str = obj.substr(0, valLenLimit); if (toJson) { str += '...'; } else { str = DebugJS.escTags(str) + SNIP; } } else { str = (toJson ? obj : DebugJS.escTags(obj)); } str = str.replace(/\\/g, '\\\\'); if (toJson) { str = str.replace(/\n/g, '\\n'); str = str.replace(/\r/g, '\\r'); } else { str = DebugJS.hlCtrlChr(str); } arg.dump += (toJson ? '"' + str.replace(/"/g, '\\"') + '"' : DebugJS.quoteStr(str)); arg.cnt++; } else { arg.dump += obj; arg.cnt++; } } catch (e) { arg.dump += '<span style="color:#f66">parse error: ' + e + '</span>'; arg.cnt++; } return arg; }; DebugJS.getKeys = function(o) { var keys = []; for (var k in o) { keys.push(k); } return keys; }; DebugJS.getKeysStr = function(o) { var keys = ''; for (var k in o) { keys += k + '\n'; } return keys; }; DebugJS.countElements = function(selector, showDetail) { if (!selector) selector = '*'; var cnt = {}; var el = null; var els = []; var total = 0; if (selector.charAt(0) == '#') { el = document.getElementById(selector.substr(1)); } else { if (selector.charAt(0) == '(') { selector = selector.substr(1, selector.length - 2); } els = document.querySelectorAll(selector); } if (el) { DebugJS.getChildElements(el, els); } if (els) { for (var i = 0; i < els.length; i++) { if (!cnt[els[i].tagName]) { cnt[els[i].tagName] = 1; } else { cnt[els[i].tagName]++; } total++; } } if (showDetail) { var l = '<table>'; for (var k in cnt) { l += '<tr><td>' + k + '</td><td style="text-align:right">' + cnt[k] + '</td></tr>'; } l += '<tr><td>Total</td><td style="text-align:right">' + total + '</td></tr></table>'; DebugJS._log.mlt(l); } return total; }; DebugJS.getChildElements = function(el, list) { if (!el.tagName) return; list.push(el); var children = el.childNodes; if (children) { for (var i = 0; i < children.length; i++) { DebugJS.getChildElements(children[i], list); } } }; DebugJS.isDescendant = function(el, t) { if (el) { var p = el.parentNode; while (p) { if (p == t) { return true; } p = p.parentNode; } } return false; }; DebugJS.isChild = function(p, el) { if (el) { var c = p.childNodes; for (var i = 0; i < c.length; i++) { if (c[i] == el) return true; } } return false; }; DebugJS.getHTML = function(b64) { var ctx = DebugJS.ctx; var el = document.getElementsByTagName('html').item(0); var cmdActive = false; if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { cmdActive = (document.activeElement == ctx.cmdLine); ctx.bodyEl.removeChild(ctx.win); } var html = el.outerHTML; if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { ctx.bodyEl.appendChild(ctx.win); ctx.scrollLogBtm(ctx); if (cmdActive) ctx.cmdLine.focus(); } if (b64) html = DebugJS.encodeB64(html); return html; }; DebugJS.formatJSON = function(s) { return DebugJS.fmtJSON(s, true, 0, 0, 0); }; DebugJS.fmtJSON = function(s, f, lv, lmt, vlen) { if (s) s = s.replace(/\\r\\n|\\r|\\n$/g, ''); var j = JSON.parse(s); return DebugJS.objDump(j, f, lv, lmt, vlen); }; DebugJS._cmdJson = function(s, f, lv) { var p = DebugJS.ctx.props; try { var j = DebugJS.fmtJSON(s, f, lv, p.dumplimit, p.dumpvallen); if (f) j = DebugJS.escTags(j); DebugJS._log.mlt(j); return j; } catch (e) { DebugJS._log.e('JSON format error: ' + DebugJS.hlJsonErr(s)); } }; DebugJS.hlJsonErr = function(json) { var jsn = json.trim().split('\\'); var cnt = 0; var res = ''; for (var i = 0; i < jsn.length; i++) { var chnk = jsn[i]; if (chnk == '') { cnt++; } else { if (i == 0) { res += chnk; continue; } if (cnt >= 1) { res += '\\'; for (var j = 0; j < (cnt - 1); j++) { res += '\\'; } if (cnt % 2 == 0) { res += '<span class="dbg-txt-hl">\\</span>'; } else { res += '\\'; } res += chnk; cnt = 0; } else { if (chnk.match(/^n|^r|^t|^b|^"/)) { res += '\\' + chnk; } else { res += '<span class="dbg-txt-hl">\\</span>' + chnk; } } } } res = res.replace(/\t/g, '<span class="dbg-txt-hl">\\t</span>'); res = res.replace(/\r\n/g, '<span class="dbg-txt-hl">\\r\\n</span>'); res = res.replace(/([^\\])\r/g, '$1<span class="dbg-txt-hl">\\r</span>'); res = res.replace(/([^\\])\n/g, '$1<span class="dbg-txt-hl">\\n</span>'); if (!res.match(/^\{/)) { res = '<span class="dbg-txt-hl"> </span>' + res; } res = res.replace(/\}([^}]+)$/, '}<span class="dbg-txt-hl">$1</span>'); if (!res.match(/\}$/)) { res = res + '<span class="dbg-txt-hl"> </span>'; } return res; }; DebugJS.fromJSON = function(j, r) { return JSON.parse(j, r); }; DebugJS.toJSON = function(o, r, s) { return JSON.stringify(o, r, s); }; DebugJS.obj2json = function(o) { return DebugJS.objDump(o, true, 0, 0, 0); }; DebugJS.digits = function(x) { var d = 0; if (x == 0) { d = 1; } else { while (x != 0) { x = (x / 10) | 0; d++; } } return d; }; DebugJS.parseInt = function(v) { var rdx = DebugJS.checkRadix(v); if (rdx == 10) { return parseInt(v, 10); } else if (rdx == 16) { return parseInt(v, 16); } else if (rdx == 2) { v = v.substr(2); return parseInt(v, 2); } return 0; }; DebugJS.checkRadix = function(v) { if (v.match(/^\-{0,1}[0-9,]+$/)) { return 10; } else if (v.match(/^\-{0,1}0x[0-9A-Fa-f]+$/)) { return 16; } else if (v.match(/^\-{0,1}0b[01\s]+$/)) { return 2; } return 0; }; DebugJS.arr2set = function(a, f) { var s = []; for (var i = 0; i < a.length; i++) { var v = a[i]; if (DebugJS.findArrVal(s, v, f) < 0) { s.push(v); } } return s; }; DebugJS.findArrVal = function(a, v, f) { var r = -1; for (var i = 0; i < a.length; i++) { if ((!f && (a[i] == v)) || (f && (a[i] === v))) { r = i; break; } } return r; }; DebugJS.countArrVal = function(a, v, f) { var c = 0; for (var i = 0; i < a.length; i++) { if ((!f && (a[i] == v)) || (f && (a[i] === v))) c++; } return c; }; DebugJS.delArrVal = function(arr, v) { for (var i = 0; i < arr.length; i++) { if (arr[i] == v) { arr.splice(i--, 1); } } }; DebugJS.nextArr = function(a, v) { var r = a[0]; for (var i = 0; i < a.length; i++) { if ((a[i] == v) && (i < (a.length - 1))) { r = a[i + 1];break; } } return r; }; DebugJS.printUsage = function(m) { DebugJS._log('Usage: ' + m); }; DebugJS.convRGB = function(v) { var r, rgb; if (v.indexOf('#') == 0) { rgb = DebugJS.convRGB16to10(v); r = 'rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')'; } else { v = v.replace(/rgb\(/, ''); v = v.replace(/\)/, ''); v = v.replace(/,/g, ' '); v = v.trim(); v = DebugJS.unifySP(v); rgb = DebugJS.convRGB10to16(v); r = '#' + rgb.r + rgb.g + rgb.b; } DebugJS._log(rgb.rgb); return r; }; DebugJS.convRGB16to10 = function(rgb16) { var boxSize = '0.7em'; var r16, g16, b16, r10, g10, b10; rgb16 = rgb16.replace(/\s/g, ''); if (rgb16.length == 7) { r16 = rgb16.substr(1, 2); g16 = rgb16.substr(3, 2); b16 = rgb16.substr(5, 2); } else if (rgb16.length == 4) { r16 = rgb16.substr(1, 1); g16 = rgb16.substr(2, 1); b16 = rgb16.substr(3, 1); r16 += r16; g16 += g16; b16 += b16; } else { return {rgb: '<span style="color:' + DebugJS.ctx.opt.logColorE + '">invalid value</span>'}; } r10 = parseInt(r16, 16); g10 = parseInt(g16, 16); b10 = parseInt(b16, 16); var rgb10 = '<span style="vertical-align:top;display:inline-block;height:1em"><span style="background:rgb(' + r10 + ',' + g10 + ',' + b10 + ');width:' + boxSize + ';height:' + boxSize + ';margin-top:0.2em;display:inline-block"> </span></span> <span style="color:' + DebugJS.COLOR_R + '">' + r10 + '</span> <span style="color:' + DebugJS.COLOR_G + '">' + g10 + '</span> <span style="color:' + DebugJS.COLOR_B + '">' + b10 + '</span>'; var rgb = {r: r10, g: g10, b: b10, rgb: rgb10}; return rgb; }; DebugJS.convRGB10to16 = function(rgb10) { var boxSize = '0.7em'; rgb10 = DebugJS.unifySP(rgb10); var rgb10s = rgb10.split(' ', 3); if ((rgb10s.length != 3) || ((rgb10s[0] < 0) || (rgb10s[0] > 255)) || ((rgb10s[1] < 0) || (rgb10s[1] > 255)) || ((rgb10s[2] < 0) || (rgb10s[2] > 255))) { return {rgb: '<span style="color:' + DebugJS.ctx.opt.logColorE + '">invalid value</span>'}; } var r16 = ('0' + parseInt(rgb10s[0]).toString(16)).slice(-2); var g16 = ('0' + parseInt(rgb10s[1]).toString(16)).slice(-2); var b16 = ('0' + parseInt(rgb10s[2]).toString(16)).slice(-2); if ((r16.charAt(0) == r16.charAt(1)) && (g16.charAt(0) == g16.charAt(1)) && (b16.charAt(0) == b16.charAt(1))) { r16 = r16.substring(0, 1); g16 = g16.substring(0, 1); b16 = b16.substring(0, 1); } var rgb16 = '<span style="vertical-align:top;display:inline-block;height:1em"><span style="background:#' + r16 + g16 + b16 + ';width:' + boxSize + ';height:' + boxSize + ';margin-top:0.2em;display:inline-block"> </span></span> #<span style="color:' + DebugJS.COLOR_R + '">' + r16 + '</span><span style="color:' + DebugJS.COLOR_G + '">' + g16 + '</span><span style="color:' + DebugJS.COLOR_B + '">' + b16 + '</span>'; var rgb = {r: r16, g: g16, b: b16, rgb: rgb16}; return rgb; }; DebugJS.convRadixFromHEX = function(v16) { var v10 = parseInt(v16, 16).toString(10); var bin = DebugJS.convertBin({exp: v10, digit: DebugJS.DFLT_UNIT}); if (v10 > 0xffffffff) { var v2 = parseInt(v10).toString(2); bin = DebugJS.formatBin(v2, true, DebugJS.DISP_BIN_DIGITS_THR); } var hex = DebugJS.formatHex(v16, true, false); if (hex.length >= 2) { hex = '0x' + hex; } DebugJS.printRadixConv(v10, hex, bin); }; DebugJS.convRadixFromDEC = function(v10) { var unit = DebugJS.DFLT_UNIT; var bin = DebugJS.convertBin({exp: v10, digit: DebugJS.DFLT_UNIT}); var v16 = parseInt(v10).toString(16); var v2 = ''; if (v10 < 0) { for (var i = (unit - 1); i >= 0; i--) { v2 += (v10 & 1 << i) ? '1' : '0'; } v16 = parseInt(v2, 2).toString(16); } else if (v10 > 0xffffffff) { v2 = parseInt(v10).toString(2); bin = DebugJS.formatBin(v2, true, DebugJS.DISP_BIN_DIGITS_THR); } var hex = DebugJS.formatHex(v16, true, false); if (hex.length >= 2) { hex = '0x' + hex; } DebugJS.printRadixConv(v10, hex, bin); }; DebugJS.convRadixFromBIN = function(v2) { v2 = v2.replace(/\s/g, ''); var v10 = parseInt(v2, 2).toString(10); var v16 = parseInt(v2, 2).toString(16); var bin = DebugJS.convertBin({exp: v10, digit: DebugJS.DFLT_UNIT}); if (v10 > 0xffffffff) { v2 = parseInt(v10).toString(2); bin = DebugJS.formatBin(v2, true, DebugJS.DISP_BIN_DIGITS_THR); } var hex = DebugJS.formatHex(v16, true, false); if (hex.length >= 2) { hex = '0x' + hex; } DebugJS.printRadixConv(v10, hex, bin); }; DebugJS.printRadixConv = function(v10, hex, bin) { var rdx = DebugJS.ctx.props.radix; var s = ''; if (DebugJS.hasKeyWd(rdx, 'dec', '|')) s += 'DEC ' + DebugJS.formatDec(v10) + '\n'; if (DebugJS.hasKeyWd(rdx, 'hex', '|')) s += 'HEX ' + hex + '\n'; if (DebugJS.hasKeyWd(rdx, 'bin', '|')) s += 'BIN ' + bin + '\n'; DebugJS._log.mlt(s); }; DebugJS.toBin = function(v) { return ('0000000' + v.toString(2)).slice(-8); }; DebugJS.toHex = function(v, uc, pFix, d) { var hex = parseInt(v).toString(16); return DebugJS.formatHex(hex, uc, pFix, d); }; DebugJS.convertBin = function(data) { var digit = data.digit; if (digit == 0) digit = DebugJS.DFLT_UNIT; var val; try { val = eval(data.exp); } catch (e) { DebugJS._log.e('Invalid value: ' + e); return; } var v2 = parseInt(val).toString(2); var v2len = v2.length; var loop = ((digit > v2len) ? digit : v2len); v2 = ''; for (var i = (loop - 1); i >= 0; i--) { v2 += (val & 1 << i) ? '1' : '0'; } var hldigit = v2len; var overflow = false; if (val < 0) { hldigit = digit; } else if ((data.digit > 0) && (v2len > data.digit)) { overflow = true; hldigit = data.digit; } return DebugJS.formatBin(v2, true, DebugJS.DISP_BIN_DIGITS_THR, hldigit, overflow); }; DebugJS.formatBin = function(v2, grouping, n, highlight, overflow) { var len = v2.length; var bin = ''; if (grouping) { if ((highlight > 0) && (len > highlight)) { bin += '<span style="color:#888">'; } for (var i = 0; i < len; i++) { if ((i != 0) && ((len - i) % 4 == 0)) { bin += ' '; } bin += v2.charAt(i); if ((highlight > 0) && ((len - i) == (highlight + 1))) { bin += '</span>'; } } } else { bin = v2; } if (n) { if (len >= n) { var digits = len; if (overflow == false) { digits = highlight; } bin += ' (' + digits + ' bits)'; } } return bin; }; DebugJS.formatDec = function(v10) { v10 += ''; var len = v10.length; var dec = ''; for (var i = 0; i < len; i++) { if ((i != 0) && ((len - i) % 3 == 0)) { if (!((i == 1) && (v10.charAt(0) == '-'))) { dec += ','; } } dec += v10.charAt(i); } return dec; }; DebugJS.formatHex = function(hex, uc, pFix, d) { if (uc) hex = hex.toUpperCase(); if ((d) && (hex.length < d)) { hex = (DebugJS.repeatCh('0', d) + hex).slice(d * (-1)); } if (pFix) hex = '0x' + hex; return hex; }; DebugJS.bit8 = {}; DebugJS.bit8.rotateL = function(v, n) { n = n % 8; return ((v << n) | (v >> (8 - n))) & 255; }; DebugJS.bit8.rotateR = function(v, n) { n = n % 8; return ((v >> n) | (v << (8 - n))) & 255; }; DebugJS.bit8.invert = function(v) { return (~v) & 255; }; DebugJS.UTF8 = {}; DebugJS.UTF8.toByte = function(s) { var a = []; if (!s) return a; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c <= 0x7F) { a.push(c); } else if (c <= 0x07FF) { a.push(((c >> 6) & 0x1F) | 0xC0); a.push((c & 0x3F) | 0x80); } else { a.push(((c >> 12) & 0x0F) | 0xE0); a.push(((c >> 6) & 0x3F) | 0x80); a.push((c & 0x3F) | 0x80); } } return a; }; DebugJS.UTF8.fmByte = function(a) { if (!a) return null; var s = ''; var i, c; while (i = a.shift()) { if (i <= 0x7F) { s += String.fromCharCode(i); } else if (i <= 0xDF) { c = ((i & 0x1F) << 6); c += a.shift() & 0x3F; s += String.fromCharCode(c); } else if (i <= 0xE0) { c = ((a.shift() & 0x1F) << 6) | 0x800; c += a.shift() & 0x3F; s += String.fromCharCode(c); } else { c = ((i & 0x0F) << 12); c += (a.shift() & 0x3F) << 6; c += a.shift() & 0x3F; s += String.fromCharCode(c); } } return s; }; DebugJS.encodeB64 = function(s) { if (!window.btoa) return ''; return DebugJS.encodeBase64(s); }; DebugJS.decodeB64 = function(s, q) { var r = ''; if (!window.btoa) return r; try { r = DebugJS.decodeBase64(s); } catch (e) { if (!q) DebugJS._log.e('decodeB64(): ' + e); } return r; }; DebugJS.encodeBase64 = function(s) { var r; try { r = btoa(s); } catch (e) { r = btoa(encodeURIComponent(s).replace(/%([0-9A-F]{2})/g, function(match, p1) {return String.fromCharCode('0x' + p1);})); } return r; }; DebugJS.decodeBase64 = function(s) { var r = ''; if (!window.atob) return r; try { r = decodeURIComponent(Array.prototype.map.call(atob(s), function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); } catch (e) { r = atob(s); } return r; }; DebugJS.Base64 = {}; DebugJS.Base64.encode = function(arr) { var len = arr.length; if (len == 0) return ''; var tbl = {64: 61, 63: 47, 62: 43}; for (var i = 0; i < 62; i++) { tbl[i] = (i < 26 ? i + 65 : (i < 52 ? i + 71 : i - 4)); } var str = ''; for (i = 0; i < len; i += 3) { str += String.fromCharCode( tbl[arr[i] >>> 2], tbl[(arr[i] & 3) << 4 | arr[i + 1] >>> 4], tbl[(i + 1) < len ? (arr[i + 1] & 15) << 2 | arr[i + 2] >>> 6 : 64], tbl[(i + 2) < len ? (arr[i + 2] & 63) : 64] ); } return str; }; DebugJS.Base64.decode = function(str) { var arr = []; if (str.length == 0) return arr; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); if (!(((c >= 0x30) && (c <= 0x39)) || ((c >= 0x41) && (c <= 0x5A)) || ((c >= 0x61) && (c <= 0x7A)) || (c == 0x2B) || (c == 0x2F) || (c == 0x3D))) { DebugJS._log.e('invalid b64 char: 0x' + c.toString(16).toUpperCase() + ' at ' + i); return arr; } } var tbl = {61: 64, 47: 63, 43: 62}; for (i = 0; i < 62; i++) { tbl[i < 26 ? i + 65 : (i < 52 ? i + 71 : i - 4)] = i; } var buf = []; for (i = 0; i < str.length; i += 4) { for (var j = 0; j < 4; j++) { buf[j] = tbl[str.charCodeAt(i + j) || 0]; } arr.push( buf[0] << 2 | (buf[1] & 63) >>> 4, (buf[1] & 15) << 4 | (buf[2] & 63) >>> 2, (buf[2] & 3) << 6 | buf[3] & 63 ); } if (buf[3] == 64) { arr.pop(); if (buf[2] == 64) { arr.pop(); } } return arr; }; DebugJS.Base64.getMimeType = function(s) { var h = {image: {jpeg: '/9', png: 'iVBORw0KGgo', gif: 'R0lGO', bmp: 'Qk0'}}; for (var tp in h) { for (stp in h[tp]) { if (DebugJS.startsWith(s, h[tp][stp])) { return {type: tp, subtype: stp}; } } } return null; }; DebugJS.isBase64 = function(s) { return (s && s.match(/^[A-Za-z0-9\/+]*=*$/) ? true : false); }; DebugJS.encodeBSB64 = function(s, n, toR) { var a = DebugJS.UTF8.toByte(s); return DebugJS.BSB64.encode(a, n, toR); }; DebugJS.decodeBSB64 = function(s, n, toR) { var a = DebugJS.BSB64.decode(s, n, (toR ? false : true)); return DebugJS.UTF8.fmByte(a); }; DebugJS.BSB64 = {}; DebugJS.BSB64.encode = function(a, n, toR) { var fn = (toR ? DebugJS.bit8.rotateR : DebugJS.bit8.rotateL); if (n % 8 == 0) fn = DebugJS.bit8.invert; var b = []; for (var i = 0; i < a.length; i++) { b.push(fn(a[i], n)); } return DebugJS.Base64.encode(b); }; DebugJS.BSB64.decode = function(s, n, toR) { var fn = (toR ? DebugJS.bit8.rotateR : DebugJS.bit8.rotateL); if (n % 8 == 0) fn = DebugJS.bit8.invert; var b = DebugJS.Base64.decode(s); var a = []; for (var i = 0; i < b.length; i++) { a.push(fn(b[i], n)); } return a; }; DebugJS.encodeROT5 = function(s, n) { if ((n < -9) || (n > 9)) n = n % 10; var r = ''; for (var i = 0; i < s.length; i++) { var c = s.charAt(i); var cc = c.charCodeAt(); if (DebugJS.isNumeric(c)) { cc += n; if (cc > 0x39) { cc = 0x2F + (cc - 0x39); } else if (cc < 0x30) { cc = 0x3A - (0x30 - cc); } r += String.fromCharCode(cc); } else { r += c; } } return r; }; DebugJS.decodeROT5 = function(s, n) { return DebugJS.encodeROT5(s, ((n | 0) * (-1))); }; DebugJS.encodeROT13 = function(s, n) { if ((n < -25) || (n > 25)) n = n % 26; var r = ''; for (var i = 0; i < s.length; i++) { var c = s.charAt(i); var cc = c.charCodeAt(); if (DebugJS.isAlphabetic(c)) { cc += n; if (DebugJS.isUpperCase(c)) { if (cc > 0x5A) { cc = 0x40 + (cc - 0x5A); } else if (cc < 0x41) { cc = 0x5B - (0x41 - cc); } } else if (DebugJS.isLowerCase(c)) { if (cc > 0x7A) { cc = 0x60 + (cc - 0x7A); } else if (cc < 0x61) { cc = 0x7B - (0x61 - cc); } } r += String.fromCharCode(cc); } else { r += c; } } return r; }; DebugJS.decodeROT13 = function(s, n) { return DebugJS.encodeROT13(s, ((n | 0) * (-1))); }; DebugJS.encodeROT47 = function(s, n) { if ((n < -93) || (n > 93)) n = n % 94; var r = ''; for (var i = 0; i < s.length; i++) { var c = s.charAt(i); var cc = c.charCodeAt(); if ((cc >= 0x21) && (cc <= 0x7E)) { if (n < 0) { cc += n; if (cc < 0x21) cc = 0x7F - (0x21 - cc); } else { cc = ((cc - 0x21 + n) % 94) + 0x21; } r += String.fromCharCode(cc); } else { r += c; } } return r; }; DebugJS.decodeROT47 = function(s, n) { return DebugJS.encodeROT47(s, ((n | 0) * (-1))); }; DebugJS.buildDataUrl = function(scheme, data) { scheme = scheme.replace(/,$/, ''); return scheme + ',' + data; }; DebugJS.splitDataUrl = function(url) { var a = url.split(','); var b64cnt = {scheme: a[0], data: (a[1] == undefined ? '' : a[1])}; return b64cnt; }; DebugJS.str2binArr = function(str, blkSize, pFix) { var arr = []; for (var i = 0; i < str.length; i += blkSize) { var v = str.substr(i, blkSize); if (v.length == blkSize) { arr.push(DebugJS.parseInt(pFix + v)); } } return arr; }; DebugJS.decodeUnicode = function(arg) { var str = ''; var a = arg.split(' '); for (var i = 0; i < a.length; i++) { if (a[i] == '') continue; var codePoint = a[i].replace(/^U\+/i, ''); if (codePoint == '20') { str += ' '; } else { str += '&#x' + codePoint; } } return str; }; DebugJS.getUnicodePoints = function(str) { var code = ''; for (var i = 0; i < str.length; i++) { var point = str.charCodeAt(i); if (i > 0) code += ' '; code += 'U+' + DebugJS.toHex(point, true, '', 4); } return code; }; DebugJS.decodeUri = function(s) { return decodeURIComponent(s); }; DebugJS.encodeUri = function(s) { return encodeURIComponent(s); }; DebugJS.tmStr2ms = function(t) { var hour = min = sec = msec = 0; var s = '0'; var times = t.split(':'); if (times.length == 3) { hour = times[0] | 0; min = times[1] | 0; s = times[2]; } else if (times.length == 2) { hour = times[0] | 0; min = times[1] | 0; } else { return null; } var ss = s.split('.'); sec = ss[0] | 0; if (ss.length >= 2) { msec = ss[1] | 0; } var time = (hour * 3600000) + (min * 60000) + (sec * 1000) + msec; return time; }; DebugJS.str2ms = function(t) { var d = 0, h = 0, m = 0, s = 0, ms = 0; var i = t.indexOf('d'); if (i > 0) { d = t.substr(0, i) | 0; t = t.substr(i + 1); } i = t.indexOf('h'); if (i > 0) { h = t.substr(0, i) | 0; t = t.substr(i + 1); } i = t.indexOf('m'); if (i > 0) { m = t.substr(0, i) | 0; t = t.substr(i + 1); } i = t.indexOf('s'); if (i > 0) { s = t.substr(0, i) | 0; t = t.substr(i + 1); } if (!isNaN(t)) ms = t | 0; return d * 86400000 + h * 3600000 + m * 60000 + s * 1000 + ms; }; DebugJS.isTmStr = function(s) { s = (s + '').trim(); if (!s.match(/^\d/) || s.match(/[^\ddhms]/)) return false; var m = s.match(/\d*d?\d*h?\d*m?\d*s?/); return (isNaN(s) && m && (m != '')); }; DebugJS.subTime = function(tL, tR, byTheDay) { var A_DAY = 86400000; var res = tL - tR; var days = 0; if ((res < 0) && (byTheDay)) { res *= (-1); days = ((res / A_DAY) | 0); if (tL == 0) { days = days + ((res % A_DAY != 0) ? 1 : 0); } else { days = days + ((res < A_DAY) ? 1 : 1); if ((res % A_DAY == 0) && (res != A_DAY)) { days += 1; } } res = A_DAY - (res - days * A_DAY); } return DebugJS.calcTime(res, days, byTheDay, true); }; DebugJS.addTime = function(tL, tR, byTheDay) { var res = tL + tR; var days = 0; if (byTheDay) { days = (res / 86400000) | 0; res -= days * 86400000; } return DebugJS.calcTime(res, days, byTheDay, false); }; DebugJS.calcTime = function(res, days, byTheDay, isSub) { var t = DebugJS.ms2struct(res); var ex = ''; if (days > 0) { ex = ' (' + (isSub ? '-' : '+') + days + ' ' + DebugJS.plural('Day', days) + ')'; } var hh = (byTheDay ? t.hr : t.hh); if (hh < 10) hh = '0' + hh; var r = (t.sign ? '-' : '') + hh + ':' + ('0' + t.mi).slice(-2) + ':' + ('0' + t.ss).slice(-2) + '.' + ('00' + t.sss).slice(-3) + ex; return r; }; DebugJS.getElapsedTimeStr = function(t1, t2) { var delta = t2 - t1; return DebugJS.getTimerStr(delta); }; DebugJS.getRandom = function(type, min, max) { if (min !== undefined) { min |= 0; if (max) { max |= 0; } else { if (type == DebugJS.RND_TYPE_NUM) { max = min; min = 0; } else if (type == DebugJS.RND_TYPE_STR) { max = min; } } if (min > max) { var wk = min; min = max; max = wk; } } else { if (type == DebugJS.RND_TYPE_NUM) { min = 0; max = 0x7fffffff; } else if (type == DebugJS.RND_TYPE_STR) { min = 1; max = DebugJS.RND_STR_DFLT_MAX_LEN; } } var rnd; switch (type) { case DebugJS.RND_TYPE_NUM: rnd = DebugJS.getRndNum(min, max); break; case DebugJS.RND_TYPE_STR: rnd = DebugJS.getRndStr(min, max); } return rnd; }; DebugJS.getRndNum = function(min, max) { min |= 0; max |= 0; var minDigit = (min + '').length; var maxDigit = (max + '').length; var digit = ((Math.random() * (maxDigit - minDigit + 1)) | 0) + minDigit; var rndMin = (digit == 1) ? 0 : Math.pow(10, (digit - 1)); var rndMax = Math.pow(10, digit) - 1; if (min < rndMin) min = rndMin; if (max > rndMax) max = rndMax; var rnd = ((Math.random() * (max - min + 1)) | 0) + min; return rnd; }; DebugJS.getRandomChr = function() { return String.fromCharCode(DebugJS.getRndNum(0x20, 0x7e)); }; DebugJS.RND_STR_DFLT_MAX_LEN = 10; DebugJS.RND_STR_MAX_LEN = 1024; DebugJS.getRndStr = function(min, max) { if (min > DebugJS.RND_STR_MAX_LEN) min = DebugJS.RND_STR_MAX_LEN; if (max > DebugJS.RND_STR_MAX_LEN) max = DebugJS.RND_STR_MAX_LEN; var len = DebugJS.getRndNum(min, max); var ch; var s = ''; for (var i = 0; i < len; i++) { var retry = true; while (retry) { ch = DebugJS.getRandomChr(); if ((!(ch.match(/[!-/:-@[-`{-~]/))) && (!(((i == 0) || (i == (len - 1))) && (ch == ' ')))) { retry = false; } } s += ch; } return s; }; DebugJS.http = function(rq, cb) { if (!rq.method) rq.method = 'GET'; if ((rq.data == undefined) || (rq.data == '')) data = null; if (rq.async == undefined) rq.async = true; if (!rq.user) rq.user = ''; if (!rq.pass) rq.pass = ''; rq.method = rq.method.toUpperCase(); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { if (cb) cb(xhr); } }; xhr.open(rq.method, rq.url, rq.async, rq.user, rq.pass); if (rq.contentType) { xhr.setRequestHeader('Content-Type', rq.contentType); } else { xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } if (!rq.cache) { xhr.setRequestHeader('If-Modified-Since', 'Thu, 01 Jun 1970 00:00:00 GMT'); } if (rq.userAgent) { xhr.setRequestHeader('User-Agent', rq.userAgent); } xhr.send(rq.data); }; DebugJS.http.buildParam = function(p) { var s = ''; var cnt = 0; for (k in p) { if (cnt > 0) s += '&'; s += k + '=' + encodeURIComponent(p[k]); cnt++; } return s; }; DebugJS.onHttpRequestDone = function(xhr) { var stmsg = xhr.status + ' ' + xhr.statusText; if (xhr.status == 0) { DebugJS._log.e('Cannot load: ' + stmsg); } else { DebugJS._log(stmsg); } var head = xhr.getAllResponseHeaders(); var txt = xhr.responseText.replace(/</g, '&lt;'); txt = txt.replace(/>/g, '&gt;'); if (head || txt) { var r = '<span style="color:#5ff">' + head + '</span>' + txt; DebugJS._log.mlt(r); } }; DebugJS.encodeURIString = function(data) { var s = encodeURIComponent(data); s = s.replace(/%20/g, '+'); s = s.replace(/%3D/gi, '='); s = s.replace(/%26/g, '&'); return s; }; DebugJS.getWinZoomRatio = function() { return Math.round(window.devicePixelRatio * 100) + '%'; }; DebugJS.getLanguages = function(indent) { var langs; var navLangs = navigator.languages; if (navLangs) { for (var i = 0; i < navLangs.length; i++) { if (i == 0) { langs = '[' + i + '] ' + navLangs[i]; } else { langs += '\n' + indent + '[' + i + '] ' + navLangs[i]; } } } else { langs = DebugJS.setStyleIfObjNA(navLangs); } return langs; }; DebugJS.getBrowserType = function() { var ua = navigator.userAgent; var ver; var brws = {name: '', version: ''}; if (ua.indexOf('Edge') >= 1) { brws.name = 'Edge'; ver = ua.match(/Edge\/(.*)/); if (ver) brws.version = ver[1]; return brws; } if (ua.indexOf('OPR/') >= 1) { brws.name = 'Opera'; ver = ua.match(/OPR\/(.*)/); if (ver) brws.version = ver[1]; return brws; } if (ua.indexOf('Chrome') >= 1) { brws.name = 'Chrome'; ver = ua.match(/Chrome\/(.*)\s/); if (ver) brws.version = ver[1]; return brws; } if (ua.indexOf('Firefox') >= 1) { brws.name = 'Firefox'; ver = ua.match(/Firefox\/(.*)/); if (ver) brws.version = ver[1]; return brws; } if (ua.indexOf('Trident/7.') >= 1) { brws.name = 'IE11'; brws.family = 'IE'; return brws; } if (ua.indexOf('Trident/6.') >= 1) { brws.name = 'IE10'; brws.family = 'IE'; return brws; } if (ua.indexOf('Trident/5.') >= 1) { brws.name = 'IE9'; brws.family = 'IE'; return brws; } if ((ua.indexOf('Safari/') >= 1) && (ua.indexOf('Version/') >= 1)) { brws.name = 'Safari'; ver = ua.match(/Version\/(.*)\sSafari/); if (ver) brws.version = ver[1]; return brws; } return brws; }; DebugJS.browserColoring = function(nm) { var s = nm; switch (nm) { case 'Chrome': s = '<span style="color:#f44">Ch</span>' + '<span style="color:#ff0">ro</span>' + '<span style="color:#4f4">m</span>' + '<span style="color:#6cf">e</span>'; break; case 'Edge': s = '<span style="color:#0af">' + nm + '</span>'; break; case 'Firefox': s = '<span style="color:#e57f25">' + nm + '</span>'; break; case 'Opera': s = '<span style="color:#f44">' + nm + '</span>'; break; case 'IE11': case 'IE10': case 'IE9': s = '<span style="color:#61d5f8">' + nm + '</span>'; break; case 'Safari': s = '<span style="color:#86c8e8">Safa</span>' + '<span style="color:#dd5651">r</span>' + '<span style="color:#ececec">i</span>'; } return s; }; DebugJS.substr = function(txt, len) { var txtLen = txt.length; var cnt = 0; var str = ''; var i, x; if (len >= 0) { for (i = 0; i < txtLen; i++) { x = encodeURIComponent(txt.charAt(i)); if (x.length <= 3) { cnt++; } else { cnt += 2; } if (cnt > len) break; str += txt.charAt(i); } } else { len *= (-1); for (i = (txtLen - 1); i >= 0; i--) { x = encodeURIComponent(txt.charAt(i)); if (x.length <= 3) { cnt++; } else { cnt += 2; } if (cnt >= len) break; } str = txt.substr(i); } return str; }; DebugJS.startsWith = function(s, p, o) { if (o) s = s.substr(o); if ((s == '') && (p == '')) return true; if (p == '') return false; return (s.substr(0, p.length) == p); }; DebugJS.endsWith = function(s, p) { if ((s == '') && (p == '')) return true; if (p == '') return false; return (s.substr(s.length - p.length) == p); }; DebugJS.needNL = function(s, n) { var nl = '\n'; if (n > 1) nl = DebugJS.repeatCh(nl, n); return ((s != '') && (!DebugJS.endsWith(s, nl))); }; DebugJS.strcount = function(s, p) { var i = 0; var pos = s.indexOf(p); while ((p != '') && (pos != -1)) { i++; pos = s.indexOf(p, pos + p.length); } return i; }; DebugJS.strcmpWOsp = function(s1, s2) { return (s1.trim() == s2.trim()); }; DebugJS.strcatWnl = function(s1, s2) { s1 += s2; if (!DebugJS.endsWith(s2, '\n')) s1 += '\n'; return s1; }; DebugJS.strPadding = function(s, c, l, p) { var t = s + ''; var d = l - t.length; if (d <= 0) return t; var pd = DebugJS.repeatCh(c, d); if (p == 'L') { t = pd + t; } else { t += pd; } return t; }; DebugJS.repeatCh = function(c, n) { var s = ''; for (var i = 0; i < n; i++) s += c; return s; }; DebugJS.crlf2lf = function(s) { return s.replace(/\r\n/g, '\n'); }; DebugJS.isStr = function(s) { return (s + '').match(/\s*\"|'/); }; DebugJS.plural = function(s, n) { return (n >= 2 ? (s + 's') : s); }; DebugJS.trimDownText = function(txt, maxLen, style) { var snip = '...'; if (style) snip = '<span style="' + style + '">' + snip + '</span>'; var s = txt; if (txt.length > maxLen) s = DebugJS.substr(s, maxLen) + snip; return s; }; DebugJS.trimDownText2 = function(txt, maxLen, omitpart, style) { var snip = '...'; if (style) snip = '<span style="' + style + '">' + snip + '</span>'; var str = DebugJS.unifySP(txt.replace(/(\r?\n|\r)/g, ' ').replace(/\t/g, ' ')); if (txt.length > maxLen) { switch (omitpart) { case DebugJS.OMIT_FIRST: str = DebugJS.substr(str, (maxLen * (-1))); str = snip + DebugJS.escTags(str); break; case DebugJS.OMIT_MID: var firstLen = maxLen / 2; var latterLen = firstLen; if ((maxLen % 2) != 0) { firstLen = (firstLen | 0); latterLen = firstLen + 1; } var firstText = DebugJS.substr(str, firstLen); var latterText = DebugJS.substr(str, (latterLen * (-1))); str = DebugJS.escTags(firstText) + snip + DebugJS.escTags(latterText); break; default: str = DebugJS.substr(str, maxLen); str = DebugJS.escTags(str) + snip; } } return str; }; DebugJS.hasKeyWd = function(s, k, d) { if (!s) return false; var a = s.split(d); for (var i = 0; i < a.length; i++) { if (a[i] == k) return true; } return false; }; DebugJS.isEmptyVal = function(o) { return ((o === undefined) || (o === null) || (o === false) || (o === '')); }; DebugJS.setStyleIfObjNA = function(obj, exceptFalse) { var s = obj; if ((exceptFalse && ((obj == undefined) || (obj == null))) || ((!exceptFalse) && (obj !== 0) && (obj !== '') && (!obj))) { s = '<span class="dbg-na">' + obj + '</span>'; } return s; }; DebugJS.dumpAddr = function(i) { return ('0000000' + i.toString(16)).slice(-8).toUpperCase() + ' : '; }; DebugJS.dumpBin = function(i, buf) { return ((buf[i] == undefined) ? ' ' : DebugJS.toBin(buf[i])); }; DebugJS.dumpDec = function(i, buf) { return ((buf[i] == undefined) ? ' ' : (' ' + buf[i].toString()).slice(-3)); }; DebugJS.dumpHex = function(i, buf) { return ((buf[i] == undefined) ? ' ' : ('0' + buf[i].toString(16)).slice(-2).toUpperCase()); }; DebugJS.dumpAscii = function(pos, buf, len) { var b = ''; var end = pos + 0x10; for (var i = pos; i < end; i++) { var code = buf[i]; if (code == undefined) break; switch (code) { case 0x0A: b += DebugJS.CHR_LF_S; break; case 0x0D: b += DebugJS.CHR_CR_S; break; case 0x22: b += '&quot;'; break; case 0x26: b += '&amp;'; break; case 0x3C: b += '&lt;'; break; case 0x3E: b += '&gt;'; break; default: if ((code >= 0x20) && (code <= 0x7E)) { b += String.fromCharCode(code); } else { b += ' '; } } } return b; }; DebugJS.escape = function(s, c) { if (c instanceof Array) { for (var i = 0; i < c.length; i++) { s = DebugJS._escape(s, c[i]); } } else { s = DebugJS._escape(s, c); } return s; }; DebugJS._escape = function(s, c) { return s.replace(new RegExp(c, 'g'), '\\' + c); }; DebugJS.escTags = function(s) { s = s.replace(/&/g, '&amp;'); s = s.replace(/</g, '&lt;'); s = s.replace(/>/g, '&gt;'); s = s.replace(/"/g, '&quot;'); s = s.replace(/'/g, '&#39;'); return s; }; DebugJS.escSpclChr = function(s) { s += ''; s = s.replace(/&/g, '&amp;'); s = s.replace(/</g, '&lt;'); s = s.replace(/>/g, '&gt;'); return s; }; DebugJS.escCtrlChr = function(s) { s = s.replace(/\t/g, '\\t'); s = s.replace(/\v/g, '\\v'); s = s.replace(/\r/g, '\\r'); s = s.replace(/\n/g, '\\n'); s = s.replace(/\f/g, '\\f'); return s; }; DebugJS.decCtrlChr = function(s) { s = s.replace(/\\t/g, '\t'); s = s.replace(/\\v/g, '\v'); s = s.replace(/\\r/g, '\r'); s = s.replace(/\\n/g, '\n'); s = s.replace(/\\f/g, '\f'); return s; }; DebugJS.hlCtrlChr = function(s, sp) { var st = '<span class="dbg-txt-hl">'; var et = '</span>'; if (sp) s = s.replace(/ /g, st + ' ' + et); s = s.replace(/\0/g, st + '\\0' + et); s = s.replace(/\t/g, st + '\\t' + et); s = s.replace(/\v/g, st + '\\v' + et); s = s.replace(/\r/g, st + '\\r' + et); s = s.replace(/\n/g, st + '\\n' + et); s = s.replace(/\f/g, st + '\\f' + et); return s; }; DebugJS.html2text = function(html) { var p = document.createElement('pre'); p.innerHTML = html; return p.innerText; }; DebugJS.addClass = function(el, n) { if (DebugJS.hasClass(el, n)) return; if (el.className == '') { el.className = n; } else { el.className += ' ' + n; } }; DebugJS.removeClass = function(el, n) { var names = el.className.split(' '); var nm = ''; for (var i = 0; i < names.length; i++) { if (names[i] != n) { if (i > 0) nm += ' '; nm += names[i]; } } el.className = nm; }; DebugJS.hasClass = function(el, n) { var names = el.className.split(' '); for (var i = 0; i < names.length; i++) { if (names[i] == n) return true; } return false; }; DebugJS.copyProp = function(src, dest) { for (var k in src) { dest[k] = src[k]; } }; DebugJS.sleep = function(ms) { ms |= 0; var t1 = (new Date()).getTime(); while (true) { var t2 = (new Date()).getTime(); if (t2 - t1 > ms) break; } }; DebugJS.getLogBufSize = function() { return DebugJS.ctx.logBuf.size(); }; DebugJS.setLogBufSize = function(n) { if (n > 0) DebugJS.ctx.initBuf(DebugJS.ctx, n); }; DebugJS.dumpLog = function(fmt, b64, fmtTime) { var buf = DebugJS.ctx.logBuf.getAll(); var b = []; var l = ''; for (var i = 0; i < buf.length; i++) { var data = buf[i]; var type = data.type; var time = (fmtTime ? DebugJS.getDateTimeStr(data.time) : data.time); var msg = data.msg; if (fmt == 'json') { l = {type: type, time: time, msg: DebugJS.encodeB64(msg)}; b.push(l); } else { var lv = 'LOG'; switch (type) { case DebugJS.LOG_TYPE_ERR: lv = 'ERR'; break; case DebugJS.LOG_TYPE_WRN: lv = 'WRN'; break; case DebugJS.LOG_TYPE_INF: lv = 'INF'; break; case DebugJS.LOG_TYPE_DBG: lv = 'DBG'; break; case DebugJS.LOG_TYPE_VRB: lv = 'VRB'; break; case DebugJS.LOG_TYPE_SYS: lv = 'SYS'; break; case DebugJS.LOG_TYPE_RES: case DebugJS.LOG_TYPE_ERES: msg = '> ' + msg; } l += time + '\t' + lv + '\t' + msg + '\n'; } } if (fmt == 'json') l = JSON.stringify(b); if (b64) l = DebugJS.encodeB64(l); return l; }; DebugJS.sendLog = function(url, pName, param, extInfo, flg, cb) { var b = DebugJS.createLogData(extInfo, flg); var data = DebugJS.http.buildParam(param); if (data != '') data += '&'; if (DebugJS.isEmptyVal(pName)) pName = 'data'; data += pName + '=' + encodeURIComponent(b); var r = { url: url, method: 'POST', data: data }; DebugJS.http(r, (cb ? cb : DebugJS.sendLogCb)); }; DebugJS.sendLogCb = function(xhr) { var st = xhr.status; if (st == 200) { DebugJS._log('Send Log OK'); } else { DebugJS._log.e('Send Log ERR (' + st + ')'); } }; DebugJS.createLogData = function(extInfo, flg) { var LINE = '------------------------------------------------------------------------\n'; if (flg == undefined) flg = 'head|log'; var info = ['', '', '', '']; if (extInfo) { if (extInfo.info0) info[0] = extInfo.info0; if (extInfo.info1) info[1] = extInfo.info1; if (extInfo.info2) info[2] = extInfo.info2; if (extInfo.info3) info[3] = extInfo.info3; } var b = ''; if (info[0]) { b = DebugJS.strcatWnl(b, info[0]); } if (DebugJS.hasKeyWd(flg, 'head', '|')) { b += LINE + DebugJS.createLogHeader() + LINE; } if (info[1]) { info[1] = DebugJS.crlf2lf(info[1]); b = DebugJS.strcatWnl(b, info[1]); b += LINE; } if (DebugJS.hasKeyWd(flg, 'log', '|')) { var logTxt = DebugJS.dumpLog('text', false, true); logTxt = DebugJS.html2text(logTxt); logTxt = DebugJS.crlf2lf(logTxt); if (DebugJS.needNL(b, 2)) b += '\n'; b += DebugJS.LOG_HEAD + '\n' + logTxt; if (DebugJS.needNL(logTxt, 1)) b += '\n'; } if (info[2]) { b += '\n'; b = DebugJS.strcatWnl(b, info[2]); } if (DebugJS.hasKeyWd(flg, 'b64buf', '|')) { var b64log = DebugJS.dumpLog('json', true, false); if (DebugJS.needNL(b, 2)) b += '\n'; b += DebugJS.LOG_BOUNDARY_BUF + '\n' + b64log + '\n'; } if (info[3]) { b += '\n'; b = DebugJS.strcatWnl(b, info[3]); } return b; }; DebugJS.createLogHeader = function() { var dt = DebugJS.getDateTime(); var brw = DebugJS.getBrowserType(); var s = 'Sending Time : ' + DebugJS.getDateTimeStr(dt.time) + ' ' + DebugJS.getTimeOffsetStr(dt.offset, true) + ' (' + dt.time + ')\n'; s += 'Browser : ' + brw.name + (brw.version == '' ? '' : ' ' + brw.version) + '\n'; s += 'User Agent : ' + navigator.userAgent + '\n'; s += 'Screen Size : w=' + screen.width + ' h=' + screen.height + '\n'; s += 'Window Size : w=' + document.documentElement.clientWidth + ' h=' + document.documentElement.clientHeight + '\n'; s += 'Body Size : w=' + document.body.clientWidth + ' h=' + document.body.clientHeight + '\n'; s += 'Zoom Ratio : ' + DebugJS.getWinZoomRatio() + '\n'; s += 'Language : ' + navigator.language; var navLangs = navigator.languages; if (navLangs) { s += ' ('; for (var i = 0; i < navLangs.length; i++) { if (i > 0) s += ', '; s += navLangs[i]; } s += ')'; } s += '\n'; return s; }; DebugJS.loadLog = function(json, b64) { var ctx = DebugJS.ctx; if (b64) json = DebugJS.decodeB64(json); var buf = JSON.parse(json); if (ctx.logBuf.size() < buf.length) { ctx.logBuf = new DebugJS.RingBuffer(buf.length); } for (var i = 0; i < buf.length; i++) { var bf = buf[i]; bf.msg = DebugJS.decodeB64(bf.msg); ctx.logBuf.add(bf); } }; DebugJS.preserveLog = function() { if (!DebugJS.LS_AVAILABLE) return; var v = DebugJS.dumpLog('json'); localStorage.setItem('DebugJS-log', v); }; DebugJS.restoreLog = function() { if (!DebugJS.LS_AVAILABLE) return; var s = localStorage.getItem('DebugJS-log'); if (!s) return; localStorage.removeItem('DebugJS-log'); DebugJS.loadLog(s); }; DebugJS.saveStatus = function() { if (!DebugJS.LS_AVAILABLE) return; var ctx = DebugJS.ctx; var data = { status: ctx.status, props: ctx.props, timers: ctx.timers, alias: ctx.CMD_ALIAS }; var st = JSON.stringify(data); localStorage.setItem('DebugJS-st', st); }; DebugJS.loadStatus = function() { if (!DebugJS.LS_AVAILABLE) return 0; var st = localStorage.getItem('DebugJS-st'); if (st == null) return null; localStorage.removeItem('DebugJS-st'); var data = JSON.parse(st); return data; }; DebugJS.file = {}; DebugJS.file.loaders = []; DebugJS.file.ongoingLdr = null; DebugJS.file.onDragOver = function(e) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }; DebugJS.file.onDrop = function(e) { var ctx = DebugJS.ctx; ctx.onDrop(e); var loader = null; for (var i = 0; i < DebugJS.file.loaders.length; i++) { loader = DebugJS.file.loaders[i]; if (DebugJS.isTargetEl(e.target, loader.el)) { DebugJS.file.ongoingLdr = loader; break; } } if (i == DebugJS.file.loaders.length) { DebugJS._log.e('onDrop(): loader not found'); return; } var d = e.dataTransfer.getData('text'); if (d) { if (loader.cb) loader.cb(null, d); } else { var f = (ctx.status & DebugJS.ST_TOOLS ? false : true); ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'file', loader.mode); if (f) ctx.closeFeature(ctx, DebugJS.ST_TOOLS); ctx.handleDroppedFile(ctx, e, loader.mode, null); } }; DebugJS.isTargetEl = function(target, el) { do { if (target == el) return true; target = target.parentNode; } while (target != null); return false; }; DebugJS.file.onLoaded = function(file, cnt) { var loader = DebugJS.file.ongoingLdr; if ((!loader) || (!loader.cb)) return; if ((loader.mode == 'b64') && (loader.decode)) { cnt = DebugJS.decodeB64(DebugJS.splitDataUrl(cnt).data); } loader.cb(file, cnt); }; DebugJS.file.finalize = function() { DebugJS.file.ongoingLdr = null; }; DebugJS.addFileLoader = function(el, cb, mode, decode) { el = DebugJS.getElement(el); if (!el) { DebugJS._log.e('addFileLoader(): target element is ' + el); return; } el.addEventListener('dragover', DebugJS.file.onDragOver, false); el.addEventListener('drop', DebugJS.file.onDrop, false); var loader = { el: el, mode: mode, decode: decode, cb: cb }; DebugJS.file.loaders.push(loader); }; DebugJS.getOptionValue = function(k) { return DebugJS.ctx.opt[k]; }; DebugJS.getStatus = function() { return DebugJS.ctx.status; }; DebugJS.getUiStatus = function() { return DebugJS.ctx.uiStatus; }; DebugJS.getFeatureStack = function() { return DebugJS.ctx.featStack.concat(); }; DebugJS.show = function() { DebugJS.ctx.showDbgWin(); }; DebugJS.hide = function() { DebugJS.ctx.closeDbgWin(); }; DebugJS.opacity = function(v) { if (v > 1) { v = 1; } else if (v < 0.1) { v = 0.1; } DebugJS.ctx.win.style.opacity = v; }; DebugJS.isVisible = function() { if (DebugJS.ctx.uiStatus & DebugJS.UI_ST_VISIBLE) return true; return false; }; DebugJS.pos = function(x, y) { DebugJS.ctx._cmdDbgWinPos(DebugJS.ctx, x, y); }; DebugJS.size = function(w, h) { DebugJS.ctx._cmdDbgWinSize(DebugJS.ctx, w, h); }; DebugJS.pin = function(f) { if (f == undefined) return ((DebugJS.ctx.uiStatus & DebugJS.UI_ST_DRAGGABLE) ? false : true); var fn = (f ? 'disableDraggable' : 'enableDraggable'); DebugJS.ctx[fn](DebugJS.ctx); return DebugJS.pin(); }; DebugJS.zoom = function(zm) { var ctx = DebugJS.ctx; if (zm == undefined) return ctx.opt.zoom; var rstrOpt = { cause: DebugJS.INIT_CAUSE_ZOOM, status: ctx.status, sizeStatus: ctx.sizeStatus }; ctx.featStackBak = ctx.featStack.concat(); ctx.finalizeFeatures(ctx); ctx.setWinSize('normal'); ctx.init({zoom: zm}, rstrOpt); return DebugJS.zoom(); }; DebugJS._log = function(m) { if (m instanceof Object) { DebugJS._log.p(m, 0, null, false); } else { DebugJS._log.out(m, DebugJS.LOG_TYPE_LOG); } }; DebugJS._log.e = function(m) { if (DebugJS.bat.hasBatStopCond('error')) { DebugJS.bat.ctrl.stopReq = true; } DebugJS._log.out(m, DebugJS.LOG_TYPE_ERR); DebugJS.ctx.showDbgWinOnError(DebugJS.ctx); if (!DebugJS.ctx.stopErrCb) { DebugJS.callEvtListeners('error'); } }; DebugJS._log.w = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_WRN); }; DebugJS._log.i = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_INF); }; DebugJS._log.d = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_DBG); }; DebugJS._log.v = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_VRB); }; DebugJS._log.s = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_SYS); }; DebugJS._log.p = function(o, l, m, j) { var s = (m ? m : '') + '\n' + DebugJS.objDump(o, j, l, DebugJS.ctx.props.dumplimit, DebugJS.ctx.props.dumpvallen); if (j) s = DebugJS.escTags(s); DebugJS._log.out(s, DebugJS.LOG_TYPE_LOG); }; DebugJS._log.res = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_RES); }; DebugJS._log.res.err = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_ERES); }; DebugJS._log.mlt = function(m) { DebugJS._log.out(m, DebugJS.LOG_TYPE_MLT); }; DebugJS._log.out = function(m, type) { var ctx = DebugJS.ctx; m = DebugJS.setStyleIfObjNA(m); if (typeof m != 'string') {m = m.toString();} var data = {type: type, time: (new Date()).getTime(), msg: m}; ctx.logBuf.add(data); if (!(ctx.status & DebugJS.ST_INITIALIZED)) { if (!DebugJS._init()) return; } ctx.printLogs(); }; DebugJS.stack = function(ldx, q) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; var stk; try { DebugJS.a.b; } catch (e) { stk = e.stack.split('\n'); } ldx |= 0; var cnt = 0, skp = 0; var rslt = ''; for (var i = 0; i < stk.length; i++) { var s = stk[i]; if (s.match(/^TypeError.*/) || s.match(/^DebugJS\.stack@.*/) || s.match(/^\s+at\s.*DebugJS\.stack\s/)) continue; if (skp < ldx) {skp++;continue;} if (cnt > 0) {rslt += '\n';} rslt += DebugJS.delLeadingSP(s).replace(/^at /, '');cnt++; } if (!q) DebugJS._log('Stack:\n' + DebugJS.escTags(rslt)); return rslt; }; DebugJS.stktop = function(idx) { return DebugJS.stack((idx | 0) + 1, true).split('\n')[0]; }; DebugJS.line = function(idx) { return DebugJS._line(DebugJS.stktop((idx | 0) + 1), idx); }; DebugJS._line = function(s, idx) { var a = s.split(':'); var l = a[a.length - 2] | 0; return l; }; DebugJS.funcname = function(idx) { return DebugJS._funcname(DebugJS.stktop((idx | 0) + 1), idx); }; DebugJS._funcname = function(s, idx) { return s.replace(/@/, ' ').replace(/^(.*?)\s.*/, '$1'); }; DebugJS.filename = function(idx, abs) { return DebugJS._filename(DebugJS.stktop((idx | 0) + 1), idx, abs); }; DebugJS._filename = function(s, idx, abs) { if (s == '') return s; var n = s.replace(/@/, ' '); n = n.replace(/^.*?\s/, ''); n = n.replace(/^\(/, ''); n = n.replace(/\)$/, ''); n = n.replace(/:\d+$/, ''); n = n.replace(/:\d+$/, ''); if (!abs) { var p = n.split('/'); n = p[p.length - 1]; if (n == '') { if ((p.length >= 2) && (p.length != 4)) { n = p[p.length - 2]; } n += '/'; } } if ((n == '<anonymous>') || (n == 'Unknown script code')) { n = '&lt;anonymous&gt;'; } else if ((n == 'code (eval code') || (n.match(/> eval$/)) || (n.match(/<anonymous>$/))) { n = '*eval*'; } return n; }; DebugJS.fileline = function(idx, abs) { var s = DebugJS.stktop((idx | 0) + 1); if (s == '') return s; var f = DebugJS._filename(s, idx, abs); var l = DebugJS._line(s, idx); return f + ':' + l; }; DebugJS.time = {}; DebugJS.time.start = function(tmrNm, msg) { var _tmrNm = tmrNm; if ((tmrNm === undefined) || (tmrNm === null)) { _tmrNm = DebugJS.DFLT_TIMER_NAME; } DebugJS.ctx.timers[_tmrNm] = {}; DebugJS.ctx.timers[_tmrNm].start = (new Date()).getTime(); if ((msg === null) || ((tmrNm === null) && (msg === undefined))) { return; } var s; if (msg === undefined) { s = _tmrNm + ': timer started'; } else { s = msg.replace(/%n/g, _tmrNm).replace(/%t/g, '<span style="color:' + DebugJS.ctx.opt.timerColor + '">' + DebugJS.TIME_RST_STR + '</span>'); } DebugJS._log(s); }; DebugJS.time.restart = function(tmrNm) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; if (ctx.timers[tmrNm]) { var paused = now - ctx.timers[tmrNm].pause; ctx.timers[tmrNm].start = now - ctx.timers[tmrNm].count; ctx.timers[tmrNm].pause = 0; ctx.timers[tmrNm].split += paused; } else { ctx.timers[tmrNm] = { start: now, pause: 0, split: 0, count: 0 }; } }; DebugJS.time.split = function(tmrNm, msg) { var t = DebugJS.time._split(tmrNm, false, msg); if ((msg === null) || ((tmrNm === null) && (msg === undefined))) { return t; } }; DebugJS.time._split = function(tmrNm, isEnd, msg) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; var _tmrNm = tmrNm; if ((tmrNm === undefined) || (tmrNm === null)) { _tmrNm = DebugJS.DFLT_TIMER_NAME; } if (!ctx.timers[_tmrNm]) { DebugJS._log.w(_tmrNm + ': timer undefined'); return null; } var prevSplit = ctx.timers[_tmrNm].split; var t = DebugJS.getElapsedTimeStr(ctx.timers[_tmrNm].start, now); var dt = '<span style="color:' + ctx.opt.timerColor + '">' + t + '</span>'; if (isEnd) { delete ctx.timers[_tmrNm]; } else { ctx.timers[_tmrNm].split = now; } if ((msg === null) || ((tmrNm === null) && (msg === undefined))) { return t; } var dtLap = ''; if (prevSplit) { var tLap = DebugJS.getElapsedTimeStr(prevSplit, now); dtLap = '<span style="color:' + ctx.opt.timerColor + '">' + tLap + '</span>'; } else { if (!isEnd) { dtLap = dt; } } var s; if (msg === undefined) { s = _tmrNm + ': ' + dt; if (dtLap != '') { s += '(' + DebugJS.CHR_DELTA + dtLap + ')'; } } else { s = msg.replace(/%n/g, _tmrNm).replace(/%lt/g, dtLap).replace(/%t/g, dt); } DebugJS._log(s); return t; }; DebugJS.time.pause = function(tmrNm) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; if (!ctx.timers[tmrNm]) return; ctx.timers[tmrNm].pause = now; ctx.timers[tmrNm].count = now - ctx.timers[tmrNm].start; }; DebugJS.time.end = function(tmrNm, msg) { var t = DebugJS.time._split(tmrNm, true, msg); if ((msg === null) || ((tmrNm === null) && (msg === undefined))) { return t; } }; DebugJS.time.check = function(tmrNm) { var now = new Date(); if (tmrNm === undefined) tmrNm = DebugJS.DFLT_TIMER_NAME; if (!DebugJS.ctx.timers[tmrNm]) return null; var t = DebugJS.getElapsedTimeStr(DebugJS.ctx.timers[tmrNm].start, now); return t; }; DebugJS.time.list = function() { var l = '<span style="color:#ccc">no timers</span>'; if (Object.keys(DebugJS.ctx.timers).length > 0) { l = '<table>'; for (var k in DebugJS.ctx.timers) { l += '<tr><td>' + k + '</td><td><span style="color:' + DebugJS.ctx.opt.timerColor + '">' + DebugJS.time.check(k) + '</font></td></tr>'; } l += '</table>'; } DebugJS._log.mlt(l); }; DebugJS.time.reset = function(tmrNm) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; ctx.timers[tmrNm] = ctx.timers[tmrNm] || {}; ctx.timers[tmrNm].start = now; ctx.timers[tmrNm].split = now; ctx.timers[tmrNm].pause = now; ctx.timers[tmrNm].count = 0; }; DebugJS.time.getCount = function(tmrNm) { if (!DebugJS.ctx.timers[tmrNm]) { return 0; } else { return DebugJS.ctx.timers[tmrNm].count; } }; DebugJS.time.updateCount = function(tmrNm) { DebugJS.ctx.timers[tmrNm].count = (new Date()).getTime() - DebugJS.ctx.timers[tmrNm].start; }; DebugJS.time.log = function(msg, tmrNm) { var now = (new Date()).getTime(); var ctx = DebugJS.ctx; if (!tmrNm) tmrNm = DebugJS.DFLT_TIMER_NAME; var t; var tLap; if (ctx.timers[tmrNm]) { t = DebugJS.getElapsedTimeStr(ctx.timers[tmrNm].start, now); tLap = DebugJS.getElapsedTimeStr(ctx.timers[tmrNm].split, now); ctx.timers[tmrNm].split = now; } else { ctx.timers[tmrNm] = {}; ctx.timers[tmrNm].start = now; ctx.timers[tmrNm].split = now; t = DebugJS.TIME_RST_STR; tLap = t; } var dt = '<span style="color:' + ctx.opt.timerColor + '">' + t + '</span>'; var dtLap = '<span style="color:' + ctx.opt.timerColor + '">' + tLap + '</span>'; var s = dt + ' ' + msg.replace(/%n/g, tmrNm).replace(/%lt/g, dtLap).replace(/%t/g, dt); DebugJS._log(s); }; DebugJS.stopwatch = function() { var ctx = DebugJS.ctx; if (!ctx.isAvailableTools(ctx)) return false; ctx.showDbgWin(); ctx.openFeature(ctx, DebugJS.ST_TOOLS, 'timer', 'cu'); return true; }; DebugJS.stopwatch.tmNm = [DebugJS.TIMER_NAME_SW_0, DebugJS.TIMER_NAME_SW_CU]; DebugJS.stopwatch.start = function(n, m) { if (n == 0) { DebugJS.ctx.startStopwatch(); } else { n = 1; if (DebugJS.stopwatch()) { DebugJS.ctx.startTimerStopwatchCu(); } } if (m) DebugJS.stopwatch.log(n, m); }; DebugJS.stopwatch.stop = function(n) { if (n == 0) { DebugJS.ctx.stopStopwatch(); } else { if (DebugJS.stopwatch()) { DebugJS.ctx.stopTimerStopwatchCu(); } } }; DebugJS.stopwatch.end = function(n, m) { if (n == 0) { DebugJS.ctx.endStopwatch(); } else { n = 1; if (DebugJS.stopwatch()) { DebugJS.ctx.endTimerStopwatchCu(); } } if (m) DebugJS.stopwatch.log(n, m); return DebugJS.stopwatch.val(n); }; DebugJS.stopwatch.split = function(n, m) { if (n != 0) n = 1; var nm = DebugJS.stopwatch.tmNm[n]; if (DebugJS.ctx.isAvailableTools(DebugJS.ctx)) { m = nm + ': %t(' + DebugJS.CHR_DELTA + '%lt)' + (m == undefined ? '' : ' ' + m); DebugJS.time._split(nm, false, m); } }; DebugJS.stopwatch.reset = function(n) { if (n == 0) { DebugJS.ctx.resetStopwatch(); } else { if (DebugJS.stopwatch()) { DebugJS.ctx.resetTimerStopwatchCu(); } } }; DebugJS.stopwatch.val = function(n) { if (n != 0) n = 1; var nm = DebugJS.stopwatch.tmNm[n]; return DebugJS.time.getCount(nm); }; DebugJS.stopwatch.log = function(n, msg) { var nm = DebugJS.stopwatch.tmNm[n]; var t = DebugJS.getTimerStr(DebugJS.time.getCount(nm)); var m = nm + ': <span style="color:' + DebugJS.ctx.opt.timerColor + '">' + t + '</span>'; if (msg != undefined) m += ' ' + msg; DebugJS._log(m); }; DebugJS.addEvtListener = function(type, listener) { var list = DebugJS.ctx.evtListener[type]; if (!list) { DebugJS._log.e('No such event: ' + type); } else { list.push(listener); } }; DebugJS.callEvtListeners = function(type, a1, a2, a3) { var list = DebugJS.ctx.evtListener[type]; for (var i = 0; i < list.length; i++) { var cb = list[i]; if (cb) { if (cb(a1, a2, a3) === false) return false; } } return true; }; DebugJS.cmd = function(c, echo, sv) { return DebugJS.ctx._execCmd(c, echo, false, sv); }; DebugJS.cmd.set = function(c) { if (DebugJS.ctx.cmdLine) DebugJS.ctx.cmdLine.value = c; }; DebugJS.cmd.exec = function() { if (DebugJS.ctx.cmdLine) DebugJS.ctx.execCmd(DebugJS.ctx); }; DebugJS.cmd.focus = function() { DebugJS.ctx.focusCmdLine(); }; DebugJS.getCmdVal = function(n) { return DebugJS.ctx.CMDVALS[n]; }; DebugJS.setCmdVal = function(n, v) { if (DebugJS.isSysVal(n)) { DebugJS._log.e('Error: ${' + n + '} is read-only'); } else { DebugJS.ctx.CMDVALS[n] = v; } }; DebugJS.isSysVal = function(n) { return (((n == '?') || (n.match(/^%.*%$/))) ? true : false); }; DebugJS.bat = function(b, a, sl, el) { if (!b) return; var bat = DebugJS.bat; if (!(DebugJS.ctx.status & DebugJS.ST_INITIALIZED)) { bat.q = {b: b, a: a, sl: sl, el: el}; return; } if (DebugJS.ctx.status & DebugJS.ST_BAT_RUNNING) bat.stCtx(); bat.set(b); bat.setExecArg(a); bat.run.arg.s = sl; bat.run.arg.e = el; bat.setRunningSt(true); setTimeout(bat._run, 0); }; DebugJS.bat.q = null; DebugJS.bat.cmds = []; DebugJS.bat.ctrl = { pc: 0, lr: 0, startPc: 0, endPc: 0, breakP: 0, delay: 0, echo: true, tmpEchoOff: false, js: 0, tmid: 0, lock: 0, block: [], fnArg: undefined, condKey: null, pauseKey: null, pauseTimeout: 0, cont: false, stopReq: false, execArg: '', label: '', fnnm: '', stack: [] }; DebugJS.bat.labels = {}; DebugJS.bat.fncs = {}; DebugJS.bat.ctx = []; DebugJS.bat.set = function(b) { var bat = DebugJS.bat; if (DebugJS.ctx.status & DebugJS.ST_BAT_RUNNING) { if (bat.nestLv() == 0) { bat.stop(DebugJS.EXIT_CLEARED); } else { bat.stopNext(); } } if (DebugJS.isB64Bat(b)) b = DebugJS.decodeB64(b); if (DebugJS.ctx.batTextEditor) { DebugJS.ctx.batTextEditor.value = b; } bat.store(b); if (bat.nestLv() > 0) { bat.inheritSt(); } }; DebugJS.bat.inheritSt = function() { var bat = DebugJS.bat; var callerCtrl = bat.ctx[bat.nestLv() - 1].ctrl; bat.ctrl.echo = callerCtrl.echo; }; DebugJS.bat.store = function(b) { var bat = DebugJS.bat; b = b.replace(/(\r?\n|\r)/g, '\n'); bat.cmds = b.split('\n'); var last = bat.cmds.pop(); if (last != '') { bat.cmds.push(last); } bat.parseLabelFncs(); bat.initCtrl(true); DebugJS.ctx.updateTotalLine(); DebugJS.ctx.updateBatNestLv(); }; DebugJS.bat.parseLabelFncs = function() { var bat = DebugJS.bat; var cmnt = 0; bat.labels = {}; bat.fncs = {}; for (var i = 0; i < bat.cmds.length; i++) { var c = DebugJS.delLeadingSP(bat.cmds[i]); if (c.substr(0, 2) == '/*') { cmnt++; continue; } if (DebugJS.delTrailingSP(c).slice(-2) == '*/') { cmnt--; continue; } if (cmnt > 0) continue; if ((c.charAt(0) == DebugJS.BAT_TKN_LABEL) && c.length >= 2) { var label = c.substr(1); bat.labels[label] = i; } else if (DebugJS.startsWith(c, DebugJS.BAT_TKN_FNC)) { var fn = DebugJS.splitArgs(c)[1]; bat.fncs[fn] = i; } } }; DebugJS.bat.run = function(s, e, a) { var bat = DebugJS.bat; bat.run.arg.s = s; bat.run.arg.e = e; if (a != undefined) { bat.setExecArg(a); } bat._run(); }; DebugJS.bat._run = function() { var ctx = DebugJS.ctx; var bat = DebugJS.bat; bat.setRunningSt(false); bat.setExitStatus(DebugJS.EXIT_SUCCESS); if (bat.cmds.length == 0) { DebugJS._log('No batch script'); return; } var s = bat.run.arg.s; var e = bat.run.arg.e; var sl, el; if ((s == undefined) || (s == '*')) { sl = 0; } else if (isNaN(s)) { if (s.charAt(0) == DebugJS.BAT_TKN_LABEL) s = s.substr(1); sl = bat.labels[s]; if (sl == undefined) { DebugJS._log.e('No such label: ' + s); return; } } else { sl = (s | 0) - 1; if (sl < 0) sl = 0; } if (sl >= bat.cmds.length) { DebugJS._log.e('Out of range (1-' + bat.cmds.length + ')'); return; } if ((e == undefined) || (e == '*')) { el = bat.cmds.length - 1; } else if (isNaN(e)) { if (e.charAt(0) == DebugJS.BAT_TKN_LABEL) e = e.substr(1); el = bat.labels[e]; if (el == undefined) { DebugJS._log.e('No such label: ' + e); return; } } else { el = (e | 0) - 1; if (el < 0) el = 0; } if (el < sl) { el = sl; } else if (el >= bat.cmds.length) { el = bat.cmds.length - 1; } bat.setRunningSt(true); ctx.updateBatRunBtn(); bat.initCtrl(false); var ctrl = bat.ctrl; if (bat.nestLv() == 0) { ctrl.echo = ctx.cmdEchoFlg; } ctx.updateCurPc(); ctrl.startPc = sl; ctrl.endPc = el; bat.setExecArg(ctrl.execArg); bat.stopNext(); if (bat.nestLv() == 0) DebugJS.callEvtListeners('batstart'); bat.exec(); }; DebugJS.bat.run.arg = {s: 0, e: 0}; DebugJS.bat.clearTimer = function() { var ctrl = DebugJS.bat.ctrl; clearTimeout(ctrl.tmid); ctrl.tmid = 0; }; DebugJS.bat.exec = function() { var ctx = DebugJS.ctx; var bat = DebugJS.bat; var ctrl = bat.ctrl; ctrl.tmid = 0; if ((ctx.status & DebugJS.ST_BAT_PAUSE) || (ctx.status & DebugJS.ST_BAT_PAUSE_CMD)) { return; } if (ctrl.stopReq) { DebugJS._log.e('BAT ERROR STOPPED (L:' + ctrl.pc + ')'); DebugJS._log.e('--------------------------------'); for (var i = -3; i <= 0; i++) { var pc = ctrl.pc + i; var len = bat.cmds.length; if ((pc >= 0) && (pc < len)) { var n = pc + 1; var df = DebugJS.digits(len) - DebugJS.digits(n); var pdng = ''; for (var j = 0; j < df; j++) { pdng += '0'; } var pre = ((pc == (ctrl.pc - 1)) ? '&gt; ' : ' '); DebugJS._log.e(pre + pdng + n + ': ' + DebugJS.trimDownText(bat.cmds[pc], 98)); } } DebugJS._log.e('--------------------------------'); ctrl.stopReq = false; bat._exit(DebugJS.EXIT_FAILURE); return; } if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD_KEY) { if (ctrl.pauseTimeout > 0) { if ((new Date).getTime() >= ctrl.pauseTimeout) { bat._resume('cmd-key', undefined, true); } else { ctrl.tmid = setTimeout(bat.exec, 50); } } return; } if (!(ctx.status & DebugJS.ST_BAT_RUNNING)) { bat.initCtrl(false); return; } if (ctrl.pc > ctrl.endPc) { if ((ctrl.pc == bat.cmds.length) && (ctrl.stack.length > 0)) { bat.ret(); bat.next(0); return; } bat._exit(DebugJS.EXIT_SUCCESS); return; } if (bat.isLocked()) { ctrl.tmid = setTimeout(bat.exec, 50); return; } if (ctx.status & DebugJS.ST_BAT_BREAK) { ctx.status &= ~DebugJS.ST_BAT_BREAK; bat.setPc(--ctrl.pc); } else { if (ctrl.pc + 1 == ctrl.breakP) { ctx.status |= DebugJS.ST_BAT_BREAK; bat.setPc(++ctrl.pc, true); bat.pause(); ctx.showDbgWin(); return; } } var c = bat.cmds[ctrl.pc]; if (c == undefined) { bat._exit(DebugJS.EXIT_CLEARED); return; } c = DebugJS.delLeadingSP(c); ctrl.pc++; var r = bat.prepro(ctx, c); ctx.updateCurPc(); switch (r) { case 1: ctrl.tmpEchoOff = false; bat.next(0); return; case 2: ctrl.tmpEchoOff = false; return; } var echoFlg = (ctrl.echo && !ctrl.tmpEchoOff); ctrl.tmpEchoOff = false; if (ctrl.pc > ctrl.startPc) { ctx._execCmd(c, echoFlg); } bat.next(1); }; DebugJS.bat.next = function(f) { var d = (f == 1 ? DebugJS.bat.ctrl.delay : 0); DebugJS.bat.ctrl.tmid = setTimeout(DebugJS.bat.exec, d); }; DebugJS.bat.exec1 = function(l) { var cmd = DebugJS.bat.cmds[l - 1]; if (cmd == undefined) return; if (DebugJS.bat.isPpTkn(cmd)) { DebugJS._log(cmd); return; } return DebugJS.ctx._execCmd(cmd, true); }; DebugJS.bat.isPpTkn = function(cmd) { var c = DebugJS.splitCmdLineInTwo(cmd)[0]; if (c.match(/^\s*@/)) { c = c.substr(c.indexOf('@') + 1); } if (((c.charAt(0) == '#') || (c.substr(0, 2) == '//')) || (DebugJS.delLeadingSP(cmd).substr(0, 2) == '/*') || (DebugJS.delTrailingSP(cmd).slice(-2) == '*/') || (c.charAt(0) == DebugJS.BAT_TKN_LABEL)) { return 1; } switch (c) { case DebugJS.BAT_TKN_IF: case DebugJS.BAT_TKN_LOOP: case DebugJS.BAT_TKN_BREAK: case DebugJS.BAT_TKN_CONTINUE: case DebugJS.BAT_TKN_JS: case DebugJS.BAT_TKN_TXT: case DebugJS.BAT_TKN_BLOCK_END: return 1; } if (DebugJS.delAllSP(cmd) == DebugJS.RE_ELSE) { return 1; } return 0; }; DebugJS.bat._exit = function(st) { var bat = DebugJS.bat; bat.setExitStatus(st); if (!bat.ldCtx()) bat._stop(st); }; DebugJS.bat.setExecArg = function(a) { a = ((a === undefined) ? '' : a); DebugJS.ctx.CMDVALS['%%ARG%%'] = a; DebugJS.bat.ctrl.execArg = a; DebugJS.ctx.setBatArgTxt(DebugJS.ctx); }; DebugJS.bat.setLabel = function(s) { s = ((s === undefined) ? '' : s); DebugJS.ctx.CMDVALS['%LABEL%'] = s; DebugJS.bat.ctrl.label = s; }; DebugJS.bat.setFnNm = function(s) { s = ((s === undefined) ? '' : s); DebugJS.ctx.CMDVALS['%FUNCNAME%'] = s; DebugJS.bat.ctrl.fnnm = s; }; DebugJS.bat.setExitStatus = function(st) { if ((st == undefined) || (st == '')) { st = DebugJS.EXIT_SUCCESS; } else { try { st = eval(st); } catch (e) { DebugJS._log.e(e); st = DebugJS.EXIT_FAILURE; } } DebugJS.ctx.CMDVALS['?'] = st; }; DebugJS.bat.prepro = function(ctx, cmd) { var bat = DebugJS.bat; var ctrl = bat.ctrl; if (cmd.match(/^\s*@/)) { ctrl.tmpEchoOff = true; cmd = cmd.substr(cmd.indexOf('@') + 1); } cmd = DebugJS.replaceCmdVals(cmd); var cmds = DebugJS.splitCmdLineInTwo(cmd); var c = cmds[0]; for (var key in ctx.CMD_ALIAS) { if (c == key) { cmd = cmd.replace(new RegExp(c), ctx.CMD_ALIAS[key]); cmd = DebugJS.replaceCmdVals(cmd); cmds = DebugJS.splitCmdLineInTwo(cmd); c = cmds[0]; break; } } var a = DebugJS.splitArgs(cmds[1]); var b; var pc = bat.nextExecLine(ctrl.pc - 1); if (pc != ctrl.pc - 1) { bat.setPc(pc); return 1; } if (c == DebugJS.BAT_TKN_FNC) { if (ctrl.stack.length == 0) { pc = bat.findEndOfFnc(ctrl.pc); bat.setPc(pc + 1); } else { DebugJS.bat.ret(); } return 1; } if (c.charAt(0) == DebugJS.BAT_TKN_LABEL) { bat.setLabel(c.substr(1)); return 1; } switch (c) { case 'nop': DebugJS._log(''); case '': return 1; case 'echo': if (a[0] == 'off') { bat.ppEcho(cmd); ctrl[c] = false; return 1; } else if (a[0] == 'on') { bat.ppEcho(cmd); ctrl[c] = true; return 1; } break; case DebugJS.BAT_TKN_IF: if (ctrl.pc <= ctrl.startPc) return 1; var r = bat.ppIf(c, cmds[1], cmd); if (!r.err) { if (r.cond) { ctrl.block.push({t: DebugJS.BAT_TKN_IF}); } else { bat.ppElIf(ctrl.pc); } } return 1; case DebugJS.BAT_TKN_LOOP: if (ctrl.pc <= ctrl.startPc) return 1; var r = bat.ppIf(c, cmds[1], cmd); var endBlk = bat.findEndOfBlock(DebugJS.BAT_TKN_LOOP, ctrl.pc); if (!r.err) { if (r.cond) { if ((ctrl.block.length == 0) || ((ctrl.block.length > 0) && (ctrl.block[ctrl.block.length - 1].s != (ctrl.pc - 1)))) { ctrl.block.push({t: DebugJS.BAT_TKN_LOOP, s: (ctrl.pc - 1), e: endBlk.l}); } } else { if ((ctrl.block.length > 0) && (ctrl.block[ctrl.block.length - 1].s == (ctrl.pc - 1))) { ctrl.block.pop(); } ctrl.pc = endBlk.l + 1; } } return 1; case DebugJS.BAT_TKN_BREAK: case DebugJS.BAT_TKN_CONTINUE: while (ctrl.block.length > 0) { b = ctrl.block.pop(); if (b.t == DebugJS.BAT_TKN_LOOP) { ctrl.pc = (c == DebugJS.BAT_TKN_BREAK ? (b.e + 1) : b.s); break; } } return 1; case DebugJS.BAT_TKN_JS: if (ctrl.js) { ctrl.js = 0; } else { ctrl.js = ((a[0] == 'pure') ? 1 : 2); bat.execJs(); } return 1; case DebugJS.BAT_TKN_TXT: bat.text(); return 1; } if (DebugJS.unifySP(cmd.trim()).match(DebugJS.RE_ELIF)) { b = ctrl.block.pop(); if (b != undefined) { ctrl.pc = bat.findEndOfBlock(DebugJS.BAT_TKN_BLOCK_END, ctrl.pc).l + 1; return 1; } } else if (DebugJS.delAllSP(cmd) == DebugJS.RE_ELSE) { b = ctrl.block.pop(); if (b != undefined) { ctrl.pc = bat.findEndOfBlock(DebugJS.BAT_TKN_IF, ctrl.pc).l + 1; return 1; } } else if (cmd.trim() == DebugJS.BAT_TKN_BLOCK_END) { if (ctrl.block.length > 0) { b = ctrl.block[ctrl.block.length - 1]; if (b.t == DebugJS.BAT_TKN_LOOP) { if (b.e == (ctrl.pc - 1)) { ctrl.pc = b.s; } } else { ctrl.block.pop(); } return 1; } } if (ctrl.pc <= ctrl.startPc) { return 1; } switch (c) { case 'exit': bat.ppEcho(cmd); bat._exit(cmds[1]); return 2; case 'wait': var w = cmds[1]; if (w == '') { w = ctx.props.wait; } else if (DebugJS.isTmStr(w)) { w = DebugJS.str2ms(w); } else if (!((DebugJS.isTimeFormat(w)) || (w.match(/\|/)))) { try { w = eval(w); } catch (e) { DebugJS._log.e(e); } } w += ''; if (w.match(/\|/)) { w = DebugJS.calcNextTime(w).t; } if (DebugJS.isTimeFormat(w)) { w = DebugJS.calcTargetTime(w); } bat.ppEcho(cmd); ctrl.tmid = setTimeout(bat.exec, w | 0); return 2; } if (ctrl.js) { ctrl.pc--; bat.execJs(); return 1; } return 0; }; DebugJS.bat.nextExecLine = function(pc) { var bat = DebugJS.bat; var cmnt = 0; while (pc <= bat.ctrl.endPc) { pc = DebugJS.bat.nextELOC(pc); var cmd = bat.cmds[pc]; if (cmd == undefined) return pc; pc++; var cmds = DebugJS.splitCmdLineInTwo(cmd); var c = cmds[0]; if ((c == DebugJS.BAT_TKN_FNC) && (bat.ctrl.stack.length == 0)) { pc = bat.findEndOfFnc(pc) + 1; } else { pc--; break; } } return pc; }; DebugJS.bat.nextELOC = function(pc) { var bat = DebugJS.bat; var cmnt = 0; while (pc <= bat.ctrl.endPc) { var cmd = bat.cmds[pc]; pc++; var cmds = DebugJS.splitCmdLineInTwo(cmd); var c = cmds[0]; if ((c == '') || (c.charAt(0) == '#') || (c.substr(0, 2) == '//')) { continue; } if (DebugJS.delLeadingSP(cmd).substr(0, 2) == '/*') { cmnt++; continue; } if (DebugJS.delTrailingSP(cmd).slice(-2) == '*/') { cmnt--; if (cmnt < 0) { bat.syntaxErr(cmd); break; } continue; } if (cmnt == 0) { pc--; break; } } return pc; }; DebugJS.bat.ppIf = function(t, cnd, cmd) { var r = {cond: false, err: true}; var v = cnd.trim(); if (DebugJS.endsWith(v, DebugJS.BAT_TKN_BLOCK_START)) { v = v.substr(0, v.length - 1); if ((t == DebugJS.BAT_TKN_LOOP) && (v == '')) { r.cond = true;r.err = false; return r; } v = DebugJS.replaceCmdVals(v); try { r.cond = eval(v); r.err = false; } catch (e) { DebugJS._log.e(e); } } else { DebugJS.bat.syntaxErr(cmd); } return r; }; DebugJS.bat.ppElIf = function(pc) { var bat = DebugJS.bat; var ctrl = bat.ctrl; while (pc <= ctrl.endPc) { var endBlk = bat.findEndOfBlock(DebugJS.BAT_TKN_ELIF, pc); pc = endBlk.l + 1; if (endBlk.endTkn == DebugJS.BAT_TKN_ELSE) { ctrl.block.push({t: DebugJS.BAT_TKN_ELSE}); break; } else if (endBlk.endTkn == DebugJS.BAT_TKN_BLOCK_END) { break; } var cmd = bat.cmds[pc - 1]; var cnd = DebugJS.getArgsFrom(cmd, 3); var r = bat.ppIf(DebugJS.BAT_TKN_IF, cnd, cmd); if (r.err) break; if (r.cond) { ctrl.block.push({t: DebugJS.BAT_TKN_IF}); break; } } ctrl.pc = pc; }; DebugJS.bat.findEndOfBlock = function(type, pc) { var bat = DebugJS.bat; var l = pc; var ignrBlkLv = 0; var data = {l: 0, endTkn: DebugJS.BAT_TKN_BLOCK_END}; while (l <= bat.ctrl.endPc) { var cmd = bat.cmds[l]; var c = DebugJS.splitCmdLineInTwo(cmd)[0]; if (DebugJS.unifySP(cmd.trim()).match(DebugJS.RE_ELIF)) { if (ignrBlkLv == 0) { if (type == DebugJS.BAT_TKN_ELIF) { data.endTkn = DebugJS.BAT_TKN_ELIF; break; } } } else if (DebugJS.delAllSP(cmd) == DebugJS.RE_ELSE) { if (ignrBlkLv == 0) { if ((type == DebugJS.BAT_TKN_IF) || (type == DebugJS.BAT_TKN_ELIF)) { data.endTkn = DebugJS.BAT_TKN_ELSE; break; } } } else if (cmd.trim() == DebugJS.BAT_TKN_BLOCK_END) { if (ignrBlkLv == 0) { break; } ignrBlkLv--; } else if ((c == DebugJS.BAT_TKN_IF) || (c == DebugJS.BAT_TKN_LOOP)) { ignrBlkLv++; } l++; } if (l > bat.ctrl.endPc) { DebugJS._log.e('End of block "' + DebugJS.BAT_TKN_BLOCK_END + '" not found'); DebugJS._log.e('L' + pc + ': ' + bat.cmds[pc - 1]); } data.l = l; return data; }; DebugJS.bat.findEndOfFnc = function(pc) { var blkLv = 0; while (pc <= DebugJS.bat.ctrl.endPc) { var cmd = DebugJS.bat.cmds[pc]; var c = DebugJS.splitCmdLineInTwo(cmd)[0]; var l = DebugJS.bat.nextELOC(pc); if (l != pc) { pc = l; continue; } if ((c == DebugJS.BAT_TKN_IF) || (c == DebugJS.BAT_TKN_LOOP)) { blkLv++; } else if (cmd.trim() == DebugJS.BAT_TKN_BLOCK_END) { blkLv--; } else if (c == DebugJS.BAT_TKN_RET) { if (blkLv == 0) break; } pc++; } return pc; }; DebugJS.bat.execJs = function() { var bat = DebugJS.bat; var ctrl = bat.ctrl; var pure = (ctrl.js == 1); var js = ''; while ((ctrl.pc >= ctrl.startPc) && (ctrl.pc <= ctrl.endPc)) { c = bat.cmds[ctrl.pc]; ctrl.pc++; if (!DebugJS.strcmpWOsp(c, DebugJS.BAT_TKN_JS)) { if (!pure) { c = DebugJS.replaceCmdVals(c); } js += c + '\n'; } if (DebugJS.strcmpWOsp(c, DebugJS.BAT_TKN_JS) || (ctrl.pc > ctrl.endPc)) { try { eval(js); } catch (e) { DebugJS._log.e(e); } ctrl.js = 0; break; } } }; DebugJS.bat.text = function() { var bat = DebugJS.bat; var ctrl = bat.ctrl; var txt = ''; while ((ctrl.pc >= ctrl.startPc) && (ctrl.pc <= ctrl.endPc)) { c = bat.cmds[ctrl.pc]; ctrl.pc++; if (!DebugJS.strcmpWOsp(c, DebugJS.BAT_TKN_TXT)) { txt += c + '\n'; } if (DebugJS.strcmpWOsp(c, DebugJS.BAT_TKN_TXT) || (ctrl.pc > ctrl.endPc)) { DebugJS.ctx.CMDVALS['%TEXT%'] = txt; break; } } }; DebugJS.bat.ppEcho = function(c) { if (DebugJS.bat.ctrl.echo && !DebugJS.bat.ctrl.tmpEchoOff) DebugJS._log.s(c); }; DebugJS.bat.ret = function(arg) { var bat = DebugJS.bat; var ctrl = bat.ctrl; if (bat.isCmdExecutable()) { var fnCtx = ctrl.stack.pop(); if (!fnCtx) { bat.syntaxErr('Illegal return statement'); return; } try { DebugJS.ctx.CMDVALS['%RET%'] = eval(arg); } catch (e) { DebugJS._log.e(e); return; } DebugJS.ctx.CMDVALS['%ARG%'] = fnCtx.fnArg; ctrl.fnArg = fnCtx.fnArg; ctrl.block = fnCtx.block; ctrl.lr = fnCtx.lr; ctrl.pc = ctrl.lr; bat.setLabel(fnCtx.label); bat.setFnNm(fnCtx.fnnm); } }; DebugJS.bat.syntaxErr = function(c) { DebugJS._log.e('BAT SyntaxError: ' + c); }; DebugJS.bat.lock = function() { DebugJS.bat.ctrl.lock++; }; DebugJS.bat.unlock = function() { var ctrl = DebugJS.bat.ctrl; ctrl.lock--; if (ctrl.lock < 0) { ctrl.lock = 0; } }; DebugJS.bat.isLocked = function() { return (DebugJS.bat.ctrl.lock != 0); }; DebugJS.bat.list = function(s, e) { var l = ''; var pc = DebugJS.bat.ctrl.pc; var js = false; var cmds = DebugJS.bat.cmds; var len = cmds.length; if ((s == undefined) || (s == '*')) { s = 0; e = len; } else { s -= 1; if (s < 0) s = 0; if (e == undefined) { e = s + 1; } } if ((e > len) || (e == '*')) { e = len; } s |= 0; e |= 0; if ((s == 0) && (e == len) && (pc == 0)) {l += '>\n';} for (var i = 0; i < len; i++) { var cmd = cmds[i]; var n = i + 1; var df = DebugJS.digits(len) - DebugJS.digits(n); var pdng = ''; for (var j = 0; j < df; j++) { pdng += '0'; } if (DebugJS.startsWith(DebugJS.delLeadingSP(cmd), DebugJS.BAT_TKN_JS)) { if (!js) { l += '<span style="color:#0ff">'; } } if ((i >= s) && (i < e)) { if (i == pc - 1) { l += '>'; } else { l += ' '; } l += ' ' + pdng + n + ': ' + cmd + '\n'; } if (DebugJS.startsWith(DebugJS.delLeadingSP(cmd), DebugJS.BAT_TKN_JS)) { if (js) { l += '</span>'; js = false; } else { js = true; } } } if (js) l += '</span>'; return l; }; DebugJS.bat.pause = function() { DebugJS.ctx.status |= DebugJS.ST_BAT_PAUSE; DebugJS.ctx.updateBatRunBtn(); }; DebugJS.bat.resume = function(key) { var bat = DebugJS.bat; if (key == undefined) { bat._resume(); } else { if (bat.ctrl.pauseKey == '') { bat._resume('cmd-key', key); } else { if (bat.ctrl.pauseKey != null) { if (DebugJS.hasKeyWd(DebugJS.delAllSP(bat.ctrl.pauseKey), key, '|')) { bat._resume('cmd-key', key); } } } } }; DebugJS.bat._resume = function(trigger, key, to, fmCnd) { var ctx = DebugJS.ctx; var bat = DebugJS.bat; var ctrl = bat.ctrl; if (trigger) { var resumed = false; if (trigger == 'cmd') { if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD) { ctx.status &= ~DebugJS.ST_BAT_PAUSE_CMD; ctx.updateBatResumeBtn(); resumed = true; } } else if (trigger == 'cmd-key') { if (ctx.status & DebugJS.ST_BAT_PAUSE_CMD_KEY) { ctx.status &= ~DebugJS.ST_BAT_PAUSE_CMD_KEY; ctrl.pauseKey = null; ctx.CMDVALS['%RESUMED_KEY%'] = (key == undefined ? '' : key); ctx.updateBatResumeBtn(); resumed = true; } } if (resumed) ctrl.pauseTimeout = 0; var msg; if (resumed) { ctrl.pauseKey = null; msg = 'Resumed.'; if (to) msg += ' (timed out)'; if (key != undefined) msg += ' (' + key + ')'; } else { if (!fmCnd) msg = 'not paused.'; } if (msg) DebugJS._log(msg); } else { ctx.status &= ~DebugJS.ST_BAT_PAUSE; ctx.updateBatRunBtn(); } bat.stopNext(); if (bat.isRunning()) { ctrl.tmid = setTimeout(bat.exec, 0); } }; DebugJS.bat.stopNext = function() { if (DebugJS.bat.ctrl.tmid > 0) { DebugJS.bat.clearTimer(); } }; DebugJS.bat.stop = function(st) { DebugJS.bat._stop(st); DebugJS.bat.resetPc(); }; DebugJS.bat._stop = function(st) { var ctx = DebugJS.ctx; var bat = DebugJS.bat; bat.stopNext(); bat.ctx = []; ctx.updateBatNestLv(); ctx.status &= ~DebugJS.ST_BAT_BREAK; ctx.status &= ~DebugJS.ST_BAT_PAUSE_CMD_KEY; ctx.updateBatResumeBtn(); bat.setRunningSt(false); ctx.status &= ~DebugJS.ST_BAT_PAUSE; ctx.updateBatRunBtn(); delete ctx.CMDVALS['%%ARG%%']; delete ctx.CMDVALS['%ARG%']; delete ctx.CMDVALS['%RET%']; delete ctx.CMDVALS['%LABEL%']; delete ctx.CMDVALS['%FUNCNAME%']; delete ctx.CMDVALS['%TEXT%']; bat.setExitStatus(st); DebugJS.callEvtListeners('batstop', ctx.CMDVALS['?']); }; DebugJS.bat.terminate = function() { DebugJS.bat.stop(DebugJS.EXIT_SIG + DebugJS.SIGTERM); }; DebugJS.bat.cancel = function() { DebugJS._log('Canceled.'); DebugJS.bat.terminate(); DebugJS.point.init(); }; DebugJS.bat.exit = function() { DebugJS.bat.terminate(); DebugJS.point.init(); DebugJS.bat.clear(); }; DebugJS.bat.hasBatStopCond = function(key) { return DebugJS.hasKeyWd(DebugJS.ctx.props.batstop, key, '|'); }; DebugJS.bat.setPc = function(v, b) { DebugJS.bat.ctrl.pc = v; DebugJS.ctx.updateCurPc(b); }; DebugJS.bat.resetPc = function() { DebugJS.bat.setPc(0); }; DebugJS.bat.clear = function() { DebugJS.bat.set(''); }; DebugJS.bat.initCtrl = function(all) { var ctrl = DebugJS.bat.ctrl; ctrl.pc = 0; ctrl.lr = 0; ctrl.fnArg = undefined; ctrl.startPc = 0; ctrl.endPc = 0; ctrl.tmpEchoOff = false; ctrl.block = []; ctrl.js = 0; ctrl.lock = 0; ctrl.conddKey = null; ctrl.pauseKey = null; ctrl.pauseTimeout = 0; ctrl.stopReq = false; ctrl.stack = []; if (all) { ctrl.echo = true; ctrl.execArg = ''; DebugJS.ctx.status &= ~DebugJS.ST_BAT_CONT; } if (ctrl.tmid > 0) { clearTimeout(ctrl.tmid); ctrl.tmid = 0; } DebugJS.bat.setLabel(''); DebugJS.bat.setFnNm(''); DebugJS.ctx.updateCurPc(); }; DebugJS.bat.stCtx = function() { var bat = DebugJS.bat; var ctrl = {}; DebugJS.copyProp(bat.ctrl, ctrl); var cmds = bat.cmds.slice(); var batCtx = { cmds: cmds, ctrl: ctrl, labels: bat.labels, fncs: bat.fncs }; bat.ctx.push(batCtx); }; DebugJS.bat.ldCtx = function() { var ctx = DebugJS.ctx; var bat = DebugJS.bat; var batCtx = bat.ctx.pop(); if (!batCtx) return false; DebugJS.copyProp(batCtx.ctrl, bat.ctrl); bat.setExecArg(bat.ctrl.execArg); bat.setLabel(bat.ctrl.label); bat.setFnNm(bat.ctrl.fnnm); bat.cmds = batCtx.cmds; bat.labels = batCtx.labels; bat.fncs = batCtx.fncs; ctx.setBatTxt(ctx); ctx.updateTotalLine(); ctx.updateBatNestLv(); ctx.updateCurPc(); bat.next(1); return true; }; DebugJS.bat.save = function() { if (!DebugJS.LS_AVAILABLE) return; var bt = { ctrl: DebugJS.bat.ctrl, cmds: DebugJS.bat.cmds, ctx: DebugJS.bat.ctx, vals: DebugJS.ctx.CMDVALS }; var b = JSON.stringify(bt); localStorage.setItem('DebugJS-bat', b); }; DebugJS.bat.load = function() { var bat = DebugJS.bat; if (!DebugJS.LS_AVAILABLE) { if (bat.q) bat.lazyExec(); return; } var b = localStorage.getItem('DebugJS-bat'); localStorage.removeItem('DebugJS-bat'); if (b == null) { if (bat.q) bat.lazyExec(); return; } var bt = JSON.parse(b); bat.ctrl = bt.ctrl; bat.cmds = bt.cmds; bat.ctx = bt.ctx; DebugJS.ctx.CMDVALS = bt.vals; bat.setExecArg(bat.ctrl.execArg); bat.parseLabelFncs(); if (DebugJS.ctx.props.batcont == 'on') { if (bat.ctrl.pauseKey != null) { DebugJS.ctx._cmdPause('key', bat.ctrl.pauseKey, 0); } bat.setRunningSt(true); if (bat.q) { bat.lazyExec(); } else { bat.exec(); } } }; DebugJS.bat.lazyExec = function() { var q = DebugJS.bat.q; DebugJS.bat(q.b, q.a, q.sl, q.el); DebugJS.bat.q = null; }; DebugJS.bat.setRunningSt = function(f) { var ctx = DebugJS.ctx; if (f) { ctx.status |= DebugJS.ST_BAT_RUNNING; if (ctx.props.batcont == 'on') { ctx.status |= DebugJS.ST_BAT_CONT; } } else { ctx.status &= ~DebugJS.ST_BAT_RUNNING; ctx.status &= ~DebugJS.ST_BAT_CONT; } }; DebugJS.bat.isRunning = function() { return ((DebugJS.ctx.status & DebugJS.ST_BAT_RUNNING) ? true : false); }; DebugJS.bat.isCmdExecutable = function() { if (DebugJS.ctx.status & DebugJS.ST_BAT_RUNNING) return true; DebugJS._log('BAT dedicated command'); return false; }; DebugJS.bat.status = function() { var ctx = DebugJS.ctx; var st = 'STOPPED'; if (ctx.status & DebugJS.ST_BAT_PAUSE) { st = 'PAUSED'; } else if ((ctx.status & DebugJS.ST_BAT_PAUSE_CMD) || (ctx.status & DebugJS.ST_BAT_PAUSE_CMD_KEY)) { st = 'PAUSED2'; } else if (ctx.status & DebugJS.ST_BAT_RUNNING) { st = 'RUNNING'; } return st; }; DebugJS.bat.getPauseKey = function() { return DebugJS.bat.ctrl.pauseKey; }; DebugJS.bat.getCondKey = function() { return DebugJS.bat.ctrl.condKey; }; DebugJS.bat.setCond = function(key) { var bat = DebugJS.bat; if (DebugJS.hasKeyWd(bat.ctrl.condKey, key, '|')) { bat._resume('cmd-key', key, false, true); bat.ctrl.condKey = null; } }; DebugJS.bat._initCond = function() { var bat = DebugJS.bat; if (bat.ctrl.condKey == null) return; if (bat.ctrl.pauseKey == bat.ctrl.condKey) { bat._resume('cmd-key'); } bat.ctrl.condKey = null; }; DebugJS.bat.getSymbols = function(t, p) { var a = []; var re = null; if (p) { try { var cnd = eval('/' + p + '/'); } catch (e) { DebugJS._log.e('Get symbols error (' + e + ')'); return a; } re = new RegExp(cnd); } var o = (t == 'function' ? DebugJS.bat.fncs : DebugJS.bat.labels); for (var k in o) { if ((!re) || ((re) && (k.match(re)))) { a.push(k); } } return a; }; DebugJS.bat.nestLv = function() { return DebugJS.bat.ctx.length; }; DebugJS.bat.isAvailable = function() { return DebugJS.bat.cmds.length > 0; }; DebugJS.isBat = function(s) { return DebugJS.startsWith(s, DebugJS.BAT_HEAD); }; DebugJS.isB64Bat = function(s) { return DebugJS.startsWith(s, DebugJS.BAT_HEAD_B64); }; DebugJS.isDataURL = function(s) { return DebugJS.startsWith(s, 'data:'); }; DebugJS.led = function(v) { DebugJS.ctx.setLed(v); }; DebugJS.led.on = function(pos) { DebugJS.ctx.turnLed(pos, true); }; DebugJS.led.off = function(pos) { DebugJS.ctx.turnLed(pos, false); }; DebugJS.led.val = function() { return DebugJS.ctx.led; }; DebugJS.msg = function(v) { DebugJS.ctx.setMsg(v); }; DebugJS.msg.clear = function() { DebugJS.ctx.setMsg(''); }; DebugJS.point = function(x, y) { x += ''; y += ''; var point = DebugJS.point; if (point.ptr == null) point.createPtr(); if (x.charAt(0) == '+') { point.x += (x.substr(1) | 0); } else if (x.charAt(0) == '-') { point.x -= (x.substr(1) | 0); } else { point.x = x | 0; } if (y.charAt(0) == '+') { point.y += (y.substr(1) | 0); } else if (y.charAt(0) == '-') { point.y -= (y.substr(1) | 0); } else { point.y = y | 0; } var ptr = point.ptr; ptr.style.top = point.y + 'px'; ptr.style.left = point.x + 'px'; document.body.appendChild(ptr); point.hint.move(); if (DebugJS.ctx.props.mousemovesim == 'true') { var e = DebugJS.event.create('mousemove'); e.clientX = point.x; e.clientY = point.y; var el = point.getElementFromCurrentPos(); if (el) { el.dispatchEvent(e); } else { window.dispatchEvent(e); } } }; DebugJS.point.ptr = null; DebugJS.point.ptrW = 12; DebugJS.point.ptrH = 19; DebugJS.point.x = 0; DebugJS.point.y = 0; DebugJS.point.d = false; DebugJS.point.CURSOR_DFLT = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAATCAMAAACTKxybAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAD9QTFRFCwsY9PT3S0xX1tbYKCg04eHjLCw4wsLJMzM/zs7S+Pn7Q0ROs7S86OjqLi468PDzYWJsGBgkQkNN////////FEPnZwAAABV0Uk5T//////////////////////////8AK9l96gAAAF5JREFUeNpMzlcOwDAIA1Cyulcw9z9rQ0aLv3iSZUFZ/lBmC7DFL8WniqGGro6mgY0NcLMBTjZA4gpXBjQKRwf2vuZIJqSpotziZ3gFkxYiwlXQvvIByweJzyryCjAA+AIPnHnE+0kAAAAASUVORK5CYII='; DebugJS.point.CURSOR_PTR = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAYCAMAAADAi10DAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJZQTFRF////EhQmHyIzPkBPT1Be+fn68fHywcHHFxorWltovr/E4+PmUlNgLS8//Pz8GRwuqquyFBcpSUtZeHqEa2x35ubo6enrQENRw8TKnJ6lTE5bc3R/9/f3paatRkhWKyw8NThHhoiRtra8lJWdFBYo1dbZKi092NjbFxkrMDJCMjVE0NDUx8jM9PT1ZWZyoqOqOz1M////QATI2QAAADJ0Uk5T/////////////////////////////////////////////////////////////////wANUJjvAAAAoUlEQVR42ozQ1xKDIBAF0GuwYO+a3nvn/38uChGFvOTODrNzXpZdMB7TZTIQ4mxdjfaRRTUyAOM/ehY/lCyKmqjU1NwPCVFo1LyPcqVRq5IosNaoBGzA4xRQTjIGAs/OU5WmY8C5KsSOFVCpxDJrALDO7cTZkPyQf+I1oEQsFJ96Wn53JHYnk+4S7HLjEG1SSSzO7wdnV/f3apO9TdF8BBgAC6AoMWCQ0+8AAAAASUVORK5CYII='; DebugJS.point.CURSOR_TXT = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAQCAMAAADtX5XCAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAZQTFRFAAAA////pdmf3QAAAAJ0Uk5T/wDltzBKAAAAGElEQVR42mJgYGBgZAARjIx0xVB7AQIMABYAAFfcyzDzAAAAAElFTkSuQmCC'; DebugJS.point.createPtr = function() { var point = DebugJS.point; point.x = 0; point.y = 0; var el = document.createElement('img'); var st = el.style; st.position = 'fixed'; st.width = point.ptrW + 'px'; st.height = point.ptrH + 'px'; st.top = point.y; st.left = point.x; st.zIndex = 0x7ffffffe; el.src = point.CURSOR_DFLT; el.onmousedown = point.startDragging; document.body.appendChild(el); point.ptr = el; }; DebugJS.point.init = function() { var point = DebugJS.point; point(0, 0); point.cursor(); point.hint.clear(); point.hide(); }; DebugJS.point.show = function() { var point = DebugJS.point; var ptr = point.ptr; if (ptr == null) { point.createPtr(); } else { document.body.appendChild(ptr); } if (point.hint.st.visible) { point.hint.show(); } }; DebugJS.point.hide = function() { var ptr = DebugJS.point.ptr; if ((ptr != null) && (ptr.parentNode)) { document.body.removeChild(ptr); } DebugJS.point.hint.hide(true); }; DebugJS.point.cursor = function(src, w, h) { var point = DebugJS.point; if (point.ptr == null) { point.createPtr(); } if (!src) { src = point.CURSOR_DFLT; } else if (src == 'pointer') { src = point.CURSOR_PTR; } else if (src == 'text') { src = point.CURSOR_TXT; } else if (src == 'none') { src = point.CURSOR_DFLT; w = 0; h = 0; } if (w == undefined) { w = ''; } else { w += 'px'; } if (h == undefined) { h = ''; } else { h += 'px'; } point.ptr.src = src; point.ptr.style.width = w; point.ptr.style.height = h; }; DebugJS.point.event = function(args) { var el = DebugJS.point.getElementFromCurrentPos(); if (!el) return; var type = DebugJS.getArgVal(args, 0); var opts = DebugJS.getOptVals(args); var e = DebugJS.event.create(type); e.clientX = DebugJS.point.x; e.clientY = DebugJS.point.y; for (var k in opts) { try { e[k] = eval(opts[k]); } catch (e) { DebugJS._log.e('Set property error (' + e + ')'); } } return el.dispatchEvent(e); }; DebugJS.point.simpleEvent = function(type, opt) { var point = DebugJS.point; var el = point.getElementFromCurrentPos(); if (!el) return; switch (type) { case 'click': point.click(0, el, opt); break; case 'cclick': point.click(1, el, opt); break; case 'rclick': point.click(2, el, opt); break; case 'dblclick': point.dblclick(el, opt); break; case 'focus': point.focus(el); break; case 'blur': point.blur(el); break; case 'change': DebugJS.dispatchChangeEvt(el); break; case 'contextmenu': point.contextmenu(el); break; case 'mousedown': case 'mouseup': point.mouseevt(el, type, opt); } }; DebugJS.point.click = function(button, target, speed, cb) { var click = DebugJS.point.click; if (click.tmid[button] > 0) { clearTimeout(click.tmid[button]); click.tmid[button] = 0; DebugJS.point.clickUp(button); } DebugJS.bat.lock(); click.target[button] = target; click.cb = cb; DebugJS.point.mouseevt(target, 'mousedown', button); var el = DebugJS.findFocusableEl(target); if (el != null) el.focus(); if (speed == undefined) speed = 100; click.tmid[button] = setTimeout('DebugJS.point.clickUp(' + button + ')', speed); }; DebugJS.point.dblclick = function(target, speed) { var data = DebugJS.point.dblclick.data; if (data.cnt > 1) { if (data.tmid > 0) { clearTimeout(data.tmid); data.tmid = 0; } data.cnt = 0; DebugJS.bat.unlock(); } if (speed == undefined) speed = 100; var clickcpeed = speed / 2 | 0; data.target = target; data.cnt = 0; data.speed = speed; DebugJS.bat.lock(); DebugJS.point._dblclick(); }; DebugJS.point._dblclick = function() { var data = DebugJS.point.dblclick.data; var clickcpeed = data.speed / 2 | 0; DebugJS.point.click(0, data.target, clickcpeed, DebugJS.point.dblclick.onDone); }; DebugJS.point.dblclick.onDone = function() { var data = DebugJS.point.dblclick.data; data.tmid = 0; data.cnt++; if (data.cnt < 2) { data.tmid = setTimeout(DebugJS.point._dblclick, data.speed); } else { DebugJS.point.mouseevt(data.target, 'dblclick', 0); data.cnt = 0; DebugJS.bat.unlock(); } }; DebugJS.point.dblclick.data = { target: null, tmid: 0, cnt: 0, speed: 0 }; DebugJS.point.clickUp = function(n) { var click = DebugJS.point.click; var target = click.target[n]; click.tmid[n] = 0; DebugJS.point.mouseevt(target, 'mouseup', n); switch (n) { case 0: if (!click.invalid) { target.click(); } click.invalid = false; break; case 1: if (click.tmid[0] > 0) { click.invalid = true; } break; case 2: DebugJS.point.contextmenu(target); if (click.tmid[0] > 0) { click.invalid = true; } } click.target[n] = null; DebugJS.bat.unlock(); if (click.cb) { click.cb(); click.cb = null; } }; DebugJS.point.click.target = [null, null, null]; DebugJS.point.click.tmid = [0, 0, 0]; DebugJS.point.click.invalid = false; DebugJS.point.click.cb = null; DebugJS.point.focus = function(el) { el.focus(); }; DebugJS.point.blur = function(el) { el.blur(); }; DebugJS.point.contextmenu = function(el) { var e = DebugJS.event.create('contextmenu'); el.dispatchEvent(e); }; DebugJS.point.mouseevt = function(el, ev, b) { var e = DebugJS.event.create(ev); e.button = b | 0; e.clientX = DebugJS.point.x; e.clientY = DebugJS.point.y; el.dispatchEvent(e); }; DebugJS.point.keyevt = function(args) { var el = DebugJS.point.getElementFromCurrentPos(); if (!el) return; var ev = args[0]; var e = DebugJS.event.create(ev); var keyCode = DebugJS.getOptVal(args, 'keyCode'); if (keyCode != null) {e.keyCode = keyCode | 0;} var code = DebugJS.getOptVal(args, 'code'); if (code != null) e.code = code; var key = DebugJS.getOptVal(args, 'key'); if (key != null) e.key = key; e.shiftKey = false; e.ctrlKey = false; e.altKey = false; e.metaKey = false; e = DebugJS.point.setKeyFlag(e, args); el.dispatchEvent(e); }; DebugJS.point.setKeyFlag = function(e, a) { for (var i = 0; i < a.length; i++) { if (a[i] == '-s') e.shiftKey = true; if (a[i] == '-c') e.ctrlKey = true; if (a[i] == '-a') e.altKey = true; if (a[i] == '-m') e.metaKey = true; } return e; }; DebugJS.point.getElementFromCurrentPos = function() { var ctx = DebugJS.ctx; var point = DebugJS.point; var ptr = point.ptr; var hide = false; var cmdActive = (document.activeElement == ctx.cmdLine); if ((ptr == null) || (!ptr.parentNode)) { return null; } var hint = point.hint.area; var hintFlg = false; if (hint && (hint.parentNode)) { hintFlg = true; ctx.bodyEl.removeChild(hint); } ctx.bodyEl.removeChild(ptr); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (ctx.isOnDbgWin(point.x, point.y)) { hide = true; ctx.bodyEl.removeChild(ctx.win); } } var el = document.elementFromPoint(point.x, point.y); if (ctx.uiStatus & DebugJS.UI_ST_DYNAMIC) { if (hide) { ctx.bodyEl.appendChild(ctx.win); ctx.scrollLogBtm(ctx); if (cmdActive) ctx.cmdLine.focus(); } } ctx.bodyEl.appendChild(ptr); if (hintFlg) { ctx.bodyEl.appendChild(hint); } return el; }; DebugJS.point.getProp = function(prop) { var el = DebugJS.point.getElementFromCurrentPos(); if (!el) return; var p = prop.split('.'); var v = el; for (var i = 0; i < p.length; i++) { v = v[p[i]]; } DebugJS._log(DebugJS.styleValue(v)); return v; }; DebugJS.point.setProp = function(prop, val, echo) { var el = DebugJS.point.getElementFromCurrentPos(); if (!el) return; try { var v = eval(val); } catch (e) { DebugJS._log.e(e); return; } var p = prop.split('.'); var e = el; for (var i = 0; i < (p.length - 1); i++) { e = e[p[i]]; } e[p[(p.length - 1)]] = v; if (echo) DebugJS._log.res(v); }; DebugJS.point.verify = function(prop, method, exp, label) { var test = DebugJS.test; var st = test.STATUS_ERR; var info; var errPfix = 'Verify error: '; if (prop == undefined) { info = errPfix + 'Property name is undefined'; DebugJS._log.e(info); test.addResult(st, label, exp, undefined, method, info); test.onVrfyAftr(st); return st; } var el = DebugJS.point.getElementFromCurrentPos(); if (!el) { info = errPfix + 'No element (x=' + DebugJS.point.x + ', y=' + DebugJS.point.y + ')'; DebugJS._log.e(info); test.addResult(st, label, exp, undefined, method, info); test.onVrfyAftr(st); return st; } var p = prop.split('.'); var got = el; for (var i = 0; i < p.length; i++) { got = got[p[i]]; } return test.verify(got, method, exp, false, label); }; DebugJS.point.move = function(x, y, speed, step) { x += ''; y += ''; var point = DebugJS.point; var dst = point.move.dstPos; if (x.charAt(0) == '+') { dst.x = point.x + (x.substr(1) | 0); } else if (x.charAt(0) == '-') { dst.x = point.x - (x.substr(1) | 0); } else { dst.x = x | 0; } if (y.charAt(0) == '+') { dst.y = point.y + (y.substr(1) | 0); } else if (y.charAt(0) == '-') { dst.y = point.y - (y.substr(1) | 0); } else { dst.y = y | 0; } if (dst.x < 0) dst.x = 0; if (dst.y < 0) dst.y = 0; if ((speed == null) || (speed == undefined) || (speed == 'auto')) { speed = DebugJS.ctx.props.pointspeed; } speed |= 0; if (speed == 0) { point(x, y); } if ((step == null) || (step == undefined) || (step == 'auto')) { step = DebugJS.ctx.props.pointstep; } step |= 0; point.move.speed = speed; if (dst.x >= point.x) { point.move.mvX = step; } else { point.move.mvX = step * (-1); } if (dst.y >= point.y) { point.move.mvY = step; } else { point.move.mvY = step * (-1); } if (point.move.tmid > 0) { DebugJS.bat.unlock(); clearTimeout(point.move.tmid); point.move.tmid = 0; } DebugJS.bat.lock(); point._move(); }; DebugJS.point.move.dstPos = {x: 0, y: 0}; DebugJS.point.move.speed = 10; DebugJS.point.move.step = 10; DebugJS.point.move.tmid = 0; DebugJS.point.move.cb = null; DebugJS.point._move = function() { var point = DebugJS.point; var move = point.move; move.tmid = 0; if ((move.mvX == 0) && (move.mvY == 0)) { DebugJS.bat.unlock(); return; } var dst = move.dstPos; var mvX = move.mvX; var mvY = move.mvY; var x = point.x + mvX; var y = point.y + mvY; if (mvX < 0) { if (x < dst.x) { x = dst.x; } } else { if (x > dst.x) { x = dst.x; } } if (mvY < 0) { if (y < dst.y) { y = dst.y; } } else { if (y > dst.y) { y = dst.y; } } point(x, y); if ((x == dst.x) && (y == dst.y)) { DebugJS.bat.unlock(); if (move.cb) { setTimeout(move.cb, 10); move.cb = null; } } else { move.tmid = setTimeout(point._move, move.speed); } }; DebugJS.point.move.stop = function() { if (DebugJS.point.move.tmid > 0) { clearTimeout(DebugJS.point.move.tmid); DebugJS.point.move.tmid = 0; DebugJS.bat.unlock(); } }; DebugJS.point.startDragging = function() { DebugJS.point.d = true; DebugJS.point.ptr.style.cursor = 'move'; }; DebugJS.point.endDragging = function() { DebugJS.point.d = false; DebugJS.point.ptr.style.cursor = 'auto'; }; DebugJS.point.drag = function(arg) { var data = DebugJS.point.drag.data; DebugJS.point.drag.cancel(); data.step = 0; data.arg = arg; data.mousemovesim = DebugJS.ctx.props.mousemovesim; DebugJS.ctx.props.mousemovesim = 'true'; DebugJS.bat.lock(); DebugJS.point.drag.proc(); }; DebugJS.point.drag.data = { step: 0, arg: null, mousemovesim: undefined }; DebugJS.point.drag.proc = function() { var point = DebugJS.point; var drag = point.drag; var data = drag.data; drag.data.step++; switch (data.step) { case 1: point.simpleEvent('mousedown', 0); setTimeout(drag.proc, 10); break; case 2: point.move.cb = drag.proc; DebugJS.ctx.cmdPoint('move ' + data.arg); break; case 3: point.simpleEvent('mouseup', 0); drag.stop(); } }; DebugJS.point.drag.cancel = function() { if (DebugJS.point.drag.data.step == 2) { DebugJS.point.move.stop(); } DebugJS.point.drag.stop(); }; DebugJS.point.drag.stop = function() { var data = DebugJS.point.drag.data; data.arg = null; data.step = 0; if (data.mousemovesim != undefined) { DebugJS.ctx.props.mousemovesim = data.mousemovesim; } DebugJS.bat.unlock(); }; DebugJS.pointBySelector = function(selector, idx, alignX, alignY) { var el = DebugJS.getElement(selector, idx); if (!el) { DebugJS._log.e(selector + (selector.charAt(0) == '#' ? '' : (idx == undefined ? '' : ' [' + idx + ']')) + ': Element not found'); return; } var ps = DebugJS.getElPosSize(el); DebugJS.scrollWinToTarget(ps); ps = DebugJS.getElPosSize(selector, idx); DebugJS.pointTarget(ps, alignX, alignY); }; DebugJS.pointByLabel = function(label, idx, alignX, alignY) { var el = DebugJS.getLabelEl(label, idx); if (!el) { DebugJS._log.e(label + ' [' + idx + ']: Element not found'); return; } var ps = DebugJS.getElPosSize(el); DebugJS.scrollWinToTarget(ps); el = DebugJS.getLabelEl(label, idx); ps = DebugJS.getElPosSize(el); DebugJS.pointTarget(ps, alignX, alignY); }; DebugJS.pointTarget = function(ps, alignX, alignY) { if (alignX == undefined) alignX = 0.5; if (alignY == undefined) alignY = 0.5; var p = DebugJS.getAlignedPos(ps, alignX, alignY); DebugJS.point(p.x, p.y); }; DebugJS.getCenterPos = function(ps) { return DebugJS.getAlignedPos(ps, 0.5, 0.5); }; DebugJS.getAlignedPos = function(ps, alignX, alignY) { var x = ps.x; var y = ps.y; if (ps.w > 1) x = x + ps.w * alignX; if (ps.h > 1) y = y + ps.h * alignY; return {x: x, y: y}; }; DebugJS.point.moveToSelector = function(selector, idx, speed, step, alignX, alignY) { var data = { selector: selector, idx: idx, speed: speed, step: step, alignX: alignX, alignY: alignY }; var ps = DebugJS.getElPosSize(selector, idx); if (!ps) { DebugJS._log.e(selector + (selector.charAt(0) == '#' ? '' : (idx == undefined ? '' : ' [' + idx + ']')) + ': Element not found'); return; } if (DebugJS.scrollWinToTarget(ps, DebugJS.ctx.props.scrollspeed, DebugJS.ctx.props.scrollstep, DebugJS.point._moveToSelector, data)) { return; } DebugJS.point._moveToSelector(data); }; DebugJS.point._moveToSelector = function(data) { var el = DebugJS.getElement(data.selector, data.idx); var ps = DebugJS.getElPosSize(el); if (data.alignX == undefined) data.alignX = 0.5; if (data.alignY == undefined) data.alignY = 0.5; DebugJS.point.moveToElement(ps, data.speed, data.step, data.alignX, data.alignY); }; DebugJS.point.moveToLabel = function(label, idx, speed, step, alignX, alignY) { var data = { label: label, idx: idx, speed: speed, step: step, alignX: alignX, alignY: alignY }; var el = DebugJS.getLabelEl(label, idx); if (!el) { DebugJS._log.e(label + ' [' + idx + ']: Element not found'); return; } var ps = DebugJS.getElPosSize(el); if (DebugJS.scrollWinToTarget(ps, DebugJS.ctx.props.scrollspeed, DebugJS.ctx.props.scrollstep, DebugJS.point._moveToLabel, data)) { return; } DebugJS.point._moveToLabel(data); }; DebugJS.point._moveToLabel = function(data) { var el = DebugJS.getLabelEl(data.label, data.idx); var ps = DebugJS.getElPosSize(el); if (data.alignX == undefined) data.alignX = 0.5; if (data.alignY == undefined) data.alignY = 0.5; DebugJS.point.moveToElement(ps, data.speed, data.step, data.alignX, data.alignY); }; DebugJS.point.moveToElement = function(ps, speed, step, alignX, alignY) { if (ps) { var p = DebugJS.getAlignedPos(ps, alignX, alignY); if (p) { DebugJS.point.move(p.x, p.y, speed, step); } } }; DebugJS.point.hint = function(msg, speed, step, start, end) { var hint = DebugJS.point.hint; if (hint.area == null) { hint.createArea(); } var area = hint.area; try { var m = eval(msg) + ''; } catch (e) { m = e + ''; } if ((speed) && (step)) { hint.msgseq(msg, m, speed, step, start, end); } else { DebugJS.point.hint.setMsg(DebugJS.point.hint.replaceMsg(m)); } hint.st.hasMsg = true; hint.show(); }; DebugJS.point.hint.area = null; DebugJS.point.hint.pre = null; DebugJS.point.hint.st = {visible: false, hasMsg: false}; DebugJS.point.hint.createArea = function() { var ctx = DebugJS.ctx; var hint = DebugJS.point.hint; var el = document.createElement('div'); el.className = 'dbg-hint'; var sz = ctx.props.pointmsgsize; try { sz = eval(sz); } catch (e) {DebugJS._log.e(e);} var pre = document.createElement('pre'); ctx.setStyle(pre, 'width', 'auto'); ctx.setStyle(pre, 'height', 'auto'); ctx.setStyle(pre, 'margin', 0); ctx.setStyle(pre, 'padding', 0); ctx.setStyle(pre, 'line-height', '1.2'); ctx.setStyle(pre, 'color', ctx.opt.fontColor); ctx.setStyle(pre, 'font-size', sz); ctx.setStyle(pre, 'font-family', ctx.opt.fontFamily); el.appendChild(pre); hint.pre = pre; document.body.appendChild(el); hint.area = el; }; DebugJS.point.hint.setMsg = function(m) { var ctx = DebugJS.ctx; var el = DebugJS.point.hint.pre; ctx.setStyle(el, 'width', 'auto'); ctx.setStyle(el, 'height', 'auto'); el.innerHTML = m; }; DebugJS.point.hint.msgseq = function(msg, m, speed, step, start, end) { var hint = DebugJS.point.hint; var el = hint.pre; var s = window.getComputedStyle(el); DebugJS.point.hint.setMsg(m); DebugJS.ctx.setStyle(el, 'width', s.width); DebugJS.ctx.setStyle(el, 'height', s.height); el.innerHTML = ''; DebugJS.setText(el, msg, speed, step, start, end); }; DebugJS.point.hint.replaceMsg = function(s) { s = s.replace(/\\n/g, '\n'); s = DebugJS.point.hint.rplcBtn(s); if (s.match(/!TEST_COUNT!/)) s = s.replace(/!TEST_COUNT!/g, DebugJS.test.getCountStr(DebugJS.test.getSumCount())); if (s.match(/!TEST_RESULT!/)) s = s.replace(/!TEST_RESULT!/g, DebugJS.test.result()); return s; }; DebugJS.point.hint.rplcBtn = function(s) { var PREFIX = '<span class="dbg-btn dbg-nomove" onclick="DebugJS.'; var SUFFIX = '</span>'; var d = {RESUME: 'ctx.batResume', STOP: 'bat.cancel', CLOSE: 'point.hide'}; for (var k in d) { var re = new RegExp('!' + k + '!', 'g'); if (s.match(re)) { var b = PREFIX + d[k] + '();">[' + k + ']' + SUFFIX; s = s.replace(re, b); } } return s; }; DebugJS.point.hint.move = function() { var point = DebugJS.point; var area = point.hint.area; if (!area) return; var clientW = document.documentElement.clientWidth; var clientH = document.documentElement.clientHeight; var ps = DebugJS.getElPosSize(area); var y = (point.y - ps.h - 2); if (y < 0) { if (ps.h > point.y) { y = point.y + point.ptrH; } else { y = 0; } } var x = point.x; if (x < 0) { x = 0; } if ((y + ps.h) > point.y) { x = point.x + point.ptrW; } if ((x + ps.w) > clientW) { if (ps.w < clientW) { x = clientW - ps.w; } else { x = 0; } } if ((y + ps.h) > clientH) { if (ps.h < clientH) { y = clientH - ps.h; } else { y = 0; } } area.style.top = y + 'px'; area.style.left = x + 'px'; }; DebugJS.point.hint.show = function() { var point = DebugJS.point; var hint = point.hint; if (!hint.st.hasMsg) return; var area = hint.area; if (!area) { hint.createArea(); } else { document.body.appendChild(area); } hint.st.visible = true; hint.move(); }; DebugJS.point.hint.hide = function(hold) { var area = DebugJS.point.hint.area; if (area && area.parentNode) document.body.removeChild(area); if (!hold) DebugJS.point.hint.st.visible = false; }; DebugJS.point.hint.clear = function() { var point = DebugJS.point; var area = point.hint.area; if (area) { point.hint.pre.innerHTML = ''; point.hint.hide(); } point.hint.st.hasMsg = false; }; DebugJS.scrollWinTo = function(x, y, speed, step) { var ctx = DebugJS.ctx; var d = DebugJS.scrollWinTo.data; DebugJS.scrollWinTo.stop(); d.dstX = x - ctx.scrollPosX; d.dstY = y - ctx.scrollPosY; if ((speed == undefined) || (speed == null)) { d.speed = ctx.props.scrollspeed | 0; } else { d.speed = speed | 0; } if ((step == undefined) || (step == null)) { d.step = ctx.props.scrollstep | 0; } else { d.step = step | 0; } DebugJS.bat.lock(); DebugJS._scrollWinTo(); return true; }; DebugJS._scrollWinTo = function() { var d = DebugJS.scrollWinTo.data; d.tmid = 0; if (d.speed == 0) d.step = 0; var dX = DebugJS.calcDestPosAndStep(d.dstX, d.step); d.dstX = dX.dest; var dY = DebugJS.calcDestPosAndStep(d.dstY, d.step); d.dstY = dY.dest; window.scrollBy(dX.step, dY.step); if ((d.dstX == 0) && (d.dstY == 0)) { if (d.cb) d.cb(d.arg); DebugJS.scrollWinTo.fin(); } else { d.tmid = setTimeout(DebugJS._scrollWinTo, d.speed); } }; DebugJS.scrollWinTo.data = {}; DebugJS.scrollWinTo.initData = function() { var d = DebugJS.scrollWinTo.data; d.dstX = 0; d.dstY = 0; d.speed = 10; d.step = 100; d.tmid = 0; d.cb = null; d.arg = null; }; DebugJS.scrollWinTo.initData(); DebugJS.scrollWinTo.stop = function() { var tmid = DebugJS.scrollWinTo.data.tmid; if (tmid > 0) { clearTimeout(tmid); DebugJS.scrollWinTo.fin(); } }; DebugJS.scrollWinTo.fin = function() { DebugJS.scrollWinTo.initData(); DebugJS.bat.unlock(); }; DebugJS.scrollWinToTarget = function(ps, speed, step, cb, arg, top) { if (!ps) return false; var d = DebugJS.scrollWinTo.data; if (d.tmid > 0) { clearTimeout(d.tmid); d.tmid = 0; DebugJS.bat.unlock(); } d.dstX = 0; d.dstY = 0; d.speed = speed | 0; d.cb = cb; d.arg = arg; if ((ps.x < 0) || ((ps.x + ps.w) > document.documentElement.clientWidth)) { d.dstX = ps.x; } var clientH = document.documentElement.clientHeight; var bodyH = document.body.clientHeight; var absScreenBottomT = bodyH - clientH; var absScreenBottomB = bodyH; var relTargetPosYinScreen = (ps.y + window.pageYOffset) - absScreenBottomT; var absTargetPosYinDoc = ps.y + window.pageYOffset; var alignY = (top ? 0 : (clientH / 2)); if (top) { d.dstY = ps.y; } else if (ps.y < 0) { if ((ps.y + window.pageYOffset) < (clientH / 2)) { d.dstY = window.pageYOffset * (-1); } else { d.dstY = ps.y - alignY; } } else if ((ps.y + ps.h) > clientH) { if ((absTargetPosYinDoc >= absScreenBottomT) && (absTargetPosYinDoc <= absScreenBottomB)) { d.dstY = absScreenBottomB - DebugJS.ctx.scrollPosY; } else { d.dstY = ps.y - alignY; } } if ((d.dstX != 0) || (d.dstY != 0)) { if (step >= 0) { d.step = step | 0; } else { d.step = DebugJS.ctx.props.scrollstep | 0; } DebugJS.bat.lock(); DebugJS._scrollWinTo(); return true; } DebugJS.scrollWinTo.initData(); return false; }; DebugJS.scrollElTo = function(target, x, y) { x += ''; y += ''; var el = DebugJS.getElement(target); if (!el) { DebugJS._log.e('Element not found: ' + target); return; } if ((x.charAt(0) == '+') || (x.charAt(0) == '-')) { x = el.scrollLeft + (x | 0); } else { switch (x) { case 'left': x = 0; break; case 'center': el.scrollLeft = el.scrollWidth; var wkX = el.scrollLeft; x = wkX / 2; break; case 'right': x = el.scrollWidth; break; case 'current': x = null; } } if ((y.charAt(0) == '+') || (y.charAt(0) == '-')) { y = el.scrollTop + (y | 0); } else { switch (y) { case 'top': y = 0; break; case 'middle': el.scrollTop = el.scrollHeight; var wkY = el.scrollTop; y = wkY / 2; break; case 'bottom': y = el.scrollHeight; break; case 'current': y = null; } } if (x != null) el.scrollLeft = x; if (y != null) el.scrollTop = y; }; DebugJS.calcDestPosAndStep = function(dest, step) { if (dest < 0) { if (((dest * (-1)) < step) || (step == 0)) { step = dest * (-1); } dest += step; step *= (-1); } else { if ((dest < step) || (step == 0)) { step = dest; } dest -= step; } var d = { dest: dest, step: step }; return d; }; DebugJS.setText = function(elm, txt, speed, step, start, end) { if (txt == undefined) return; var data = DebugJS.setText.data; if (data.tmid > 0) { clearTimeout(data.tmid); data.tmid = 0; DebugJS.bat.unlock(); } var el = DebugJS.getElement(elm); if (!el) { DebugJS._log.e('Element not found: ' + elm); return; } try { txt = eval(txt) + ''; } catch (e) { DebugJS._log.e('setText(): ' + e); } txt = DebugJS.decCtrlChr(txt); data.txt = txt; if ((speed == undefined) || (speed == null) || (speed == '')) { speed = DebugJS.ctx.props.textspeed; } if ((step == undefined) || (step == null) || (step == '')) { step = DebugJS.ctx.props.textstep; } start |= 0; if (start > 0) start -= 1; data.speed = speed; data.step = step | 0; data.i = start; data.end = end | 0; data.el = el; data.isInp = DebugJS.isTxtInp(el); DebugJS.bat.lock(); DebugJS._setText(); }; DebugJS._setText = function() { var data = DebugJS.setText.data; var speed = data.speed; var step = data.step; if ((speed == 0) || (step == 0) || (data.end > 0) && (data.i >= data.end)) { data.i = data.txt.length; } else { data.i += step; } data.tmid = 0; var txt = data.txt.substr(0, data.i); if (data.isInp) { data.el.value = txt; var e = DebugJS.event.create('input'); data.el.dispatchEvent(e); } else { data.el.innerText = txt; } if (data.i < data.txt.length) { speed = DebugJS.getSpeed(speed) | 0; data.tmid = setTimeout(DebugJS._setText, speed); } else { DebugJS.setText.stop(); } }; DebugJS.setText.stop = function() { DebugJS.setText.finalize(); DebugJS.bat.unlock(); }; DebugJS.setText.finalize = function() { var data = DebugJS.setText.data; if (data.tmid > 0) { clearTimeout(data.tmid); data.tmid = 0; } data.el = null; data.isInp = false; data.txt = ''; data.speed = 0; data.end = 0; data.i = 0; }; DebugJS.setText.data = {el: null, isInp: false, txt: '', speed: 0, end: 0, i: 0, tmid: 0}; DebugJS.getSpeed = function(v) { v += ''; if (v.indexOf('-') == -1) return v; var a = v.split('-'); var min = a[0]; var max = a[1]; if ((min == '') || (max == '')) return 0; return DebugJS.getRndNum(min, max); }; DebugJS.selectOption = function(elm, method, type, val) { var i; var el = DebugJS.getElement(elm); if (!el) { DebugJS._log.e('Element not found: ' + elm); return; } if (el.tagName != 'SELECT') { DebugJS._log.e('Element is not select (' + el + ')'); return; } if (method == 'set') { if ((type != 'value') && (type != 'text')) return; var prevVal = el.value; for (i = 0; i < el.options.length; i++) { if (((type == 'text') && (el.options[i].innerText == val)) || ((type == 'value') && (el.options[i].value == val))) { el.options[i].selected = true; if (prevVal != val) { DebugJS.dispatchChangeEvt(el); } return; } } } else { var r; var idx = el.selectedIndex; if (type == 'value') { r = el.options[idx].value; } else if (type == 'text') { r = el.options[idx].innerText; } else if ((type == 'values') || (type == 'texts')) { var prop = (type == 'values' ? 'value' : 'innerText'); r = []; for (i = 0; i < el.options.length; i++) { r.push(el.options[i][prop]); } } return r; } DebugJS._log.e('No such option: ' + val); }; DebugJS.dispatchChangeEvt = function(target) { var e = DebugJS.event.create('change'); return target.dispatchEvent(e); }; DebugJS.event = {}; DebugJS.event.evt = null; DebugJS.event.evtDef = { blur: {bubbles: false, cancelable: false}, change: {bubbles: true, cancelable: false}, click: {bubbles: true, cancelable: true}, contextmenu: {bubbles: true, cancelable: true}, dblclick: {bubbles: true, cancelable: true}, dragover: {bubbles: true, cancelable: true}, drop: {bubbles: true, cancelable: true}, focus: {bubbles: false, cancelable: false}, input: {bubbles: true, cancelable: false}, keydown: {bubbles: true, cancelable: true}, keypress: {bubbles: true, cancelable: true}, keyup: {bubbles: true, cancelable: true}, mousedown: {bubbles: true, cancelable: true}, mousemove: {bubbles: true, cancelable: true}, mouseup: {bubbles: true, cancelable: true}, wheel: {bubbles: true, cancelable: true} }; DebugJS.event.create = function(type) { var e = document.createEvent('Events'); e.initEvent(type, true, true); var df = DebugJS.event.evtDef[type]; if (df) { e.bubbles = df.bubbles; e.cancelable = df.cancelable; } DebugJS.event.evt = e; return e; }; DebugJS.event.set = function(prop, v) { var e = DebugJS.event.evt; if (e) { e[prop] = v; } else { DebugJS._log.e('Event is not created'); } }; DebugJS.event.dispatch = function(el, idx) { var target; if (el == 'window') { target = window; } else if (el == 'document') { target = document; } else if (el == 'active') { target = document.activeElement; } else if (el == 'point') { target = DebugJS.point.getElementFromCurrentPos(); } else { target = DebugJS.getElement(el, idx); } if (!target) { DebugJS._log.e('Target is not found'); return false; } var e = DebugJS.event.evt; if (e) { return target.dispatchEvent(e); } else { DebugJS._log.e('Event is not created'); return false; } }; DebugJS.event.clear = function() { DebugJS.event.evt = null; }; DebugJS.keyPress = function(data) { DebugJS.keyPress.data = data; DebugJS.bat.lock(); DebugJS.keyPress.down(); }; DebugJS.keyPress.data = null; DebugJS.keyPress.down = function() { DebugJS.keyPress.send('keydown'); setTimeout(DebugJS.keyPress.up, 10); }; DebugJS.keyPress.up = function() { DebugJS.keyPress.send('keyup'); DebugJS.keyPress.end(); }; DebugJS.keyPress.send = function(type) { var data = DebugJS.keyPress.data; DebugJS.event.create(type); DebugJS.event.set('keyCode', data.keyCode); DebugJS.event.set('shiftKey', data.shift); DebugJS.event.set('ctrlKey', data.ctrl); DebugJS.event.set('altKey', data.alt); DebugJS.event.set('metaKey', data.meta); var target = (DebugJS.isDescendant(document.activeElement, DebugJS.ctx.win) ? 'window' : 'active'); DebugJS.event.dispatch(target); }; DebugJS.keyPress.end = function() { DebugJS.bat.unlock(); }; DebugJS.test = {}; DebugJS.test.STATUS_OK = 'OK'; DebugJS.test.STATUS_NG = 'NG'; DebugJS.test.STATUS_ERR = 'ERR'; DebugJS.test.STATUS_NT = 'NT'; DebugJS.test.COLOR_OK = '#0f0'; DebugJS.test.COLOR_NG = '#f66'; DebugJS.test.COLOR_ERR = '#fa0'; DebugJS.test.STATUS_NT_COLOR = '#fff'; DebugJS.test.data = {}; DebugJS.test.initData = function() { var data = DebugJS.test.data; data.name = ''; data.desc = []; data.running = false; data.startTime = 0; data.endTime = 0; data.seq = 0; data.executingTestId = ''; data.lastRslt = DebugJS.test.STATUS_NT; data.ttlRslt = DebugJS.test.STATUS_NT; data.cnt = {ok: 0, ng: 0, err: 0, nt: 0}; data.results = {}; }; DebugJS.test.initData(); DebugJS.test.init = function(name) { var test = DebugJS.test; test.initData(); DebugJS.ctx.CMDVALS['%TEST_TOTAL_RESULT%'] = test.STATUS_NT; DebugJS.ctx.CMDVALS['%TEST_LAST_RESULT%'] = test.STATUS_NT; var data = test.data; data.name = ((name == undefined) ? '' : name); data.running = true; data.startTime = (new Date()).getTime(); }; DebugJS.test.setName = function(n) { DebugJS.test.data.name = n; DebugJS._log('TestName: ' + n); }; DebugJS.test.setDesc = function(s) { DebugJS.test.data.desc.push(s); DebugJS._log(s); }; DebugJS.test.save = function() { if (!DebugJS.LS_AVAILABLE) return; var d = JSON.stringify(DebugJS.test.data); localStorage.setItem('DebugJS-test', d); }; DebugJS.test.load = function() { if (!DebugJS.LS_AVAILABLE) return; var d = localStorage.getItem('DebugJS-test'); localStorage.removeItem('DebugJS-test'); if (d == null) return; DebugJS.test.data = JSON.parse(d); }; DebugJS.test.fin = function() { DebugJS.test.data.running = false; DebugJS.test.data.endTime = (new Date()).getTime(); }; DebugJS.test.setResult = function(st, label, info) { var test = DebugJS.test; switch (st) { case test.STATUS_OK: case test.STATUS_NG: case test.STATUS_ERR: case test.STATUS_NT: break; default: DebugJS._log.e('Test status must be OK|NG|ERR|NT: ' + st); return; } test.addResult(st, label, null, null, null, info); }; DebugJS.test.addResult = function(st, label, exp, got, method, info) { var ctx = DebugJS.ctx; var test = DebugJS.test; var data = test.data; var lm = ctx.props.testvallimit; switch (st) { case test.STATUS_OK: data.cnt.ok++; break; case test.STATUS_NG: data.cnt.ng++; break; case test.STATUS_ERR: data.cnt.err++; break; case test.STATUS_NT: data.cnt.nt++; } test.setRsltStatus(st); test.setLastResult(st); var id = data.executingTestId; test.prepare(); if (label == null) { label = ''; } else if (label.match(/^".*"$/)) { label = eval(label); } if (typeof exp == 'string') { exp = DebugJS.trimDownText(exp, lm); } if (typeof got == 'string') { got = DebugJS.trimDownText(got, lm); } var rslt = { label: label, status: st, method: method, exp: exp, got: got, info: info }; data.results[id].results.push(rslt); }; DebugJS.test.setRsltStatus = function(st) { var test = DebugJS.test; var data = test.data; switch (st) { case test.STATUS_NT: return; case test.STATUS_OK: if (data.ttlRslt != test.STATUS_NT) return; break; case test.STATUS_NG: if (data.ttlRslt == test.STATUS_ERR) return; } data.ttlRslt = st; DebugJS.ctx.CMDVALS['%TEST_TOTAL_RESULT%'] = st; }; DebugJS.test.setLastResult = function(st) { DebugJS.test.data.lastRslt = st; DebugJS.ctx.CMDVALS['%TEST_LAST_RESULT%'] = st; }; DebugJS.test.getLastResult = function() { return DebugJS.test.data.lastRslt; }; DebugJS.test.getTotalResult = function() { return DebugJS.test.data.ttlRslt; }; DebugJS.test.prepare = function() { DebugJS.test.setId(DebugJS.test.data.executingTestId); }; DebugJS.test.setId = function(id) { if (id.match(/%SEQ%/)) id = id.replace(/%SEQ%/, DebugJS.test.nextSeq()); var data = DebugJS.test.data; if (!data.results[id]) { data.results[id] = {comment: [], results: []}; } data.executingTestId = id; }; DebugJS.test.setSeq = function(v) { if (v != '') DebugJS.test.data.seq = v | 0; }; DebugJS.test.nextSeq = function() { return ++DebugJS.test.data.seq; }; DebugJS.test.setCmnt = function(c) { DebugJS.test.prepare(); DebugJS.test.data.results[DebugJS.test.data.executingTestId].comment.push(c); DebugJS._log('# ' + c); }; DebugJS.test.chkResult = function(results) { var test = DebugJS.test; var r = test.STATUS_NT; for (var i = 0; i < results.length; i++) { var st = results[i].status; if (st == test.STATUS_ERR) { return test.STATUS_ERR; } else if (st == test.STATUS_NG) { r = test.STATUS_NG; } else if ((st == test.STATUS_OK) && (r == test.STATUS_NT)) { r = test.STATUS_OK; } } return r; }; DebugJS.test.getStyledResultStr = function(st, info) { var s = DebugJS.test.getStyledStStr(st); if (info) s += ' ' + info; return s; }; DebugJS.test.getStyledStStr = function(st) { var test = DebugJS.test; var color; switch (st) { case test.STATUS_OK: color = test.COLOR_OK; break; case test.STATUS_NG: color = test.COLOR_NG; break; case test.STATUS_ERR: color = test.COLOR_ERR; break; default: color = test.COLOR_NT; } return '[<span style="color:' + color + '">' + st + '</span>]'; }; DebugJS.test.getStyledInfoStr = function(result) { if (result.info) return result.info; if (!result.method) return ''; var echoExp = result.exp; if (result.method == 'regexp') { echoExp = DebugJS.decodeEsc(echoExp); echoExp = '<span style="color:#0ff">/</span>' + echoExp + '<span style="color:#0ff">/</span>'; } else if (typeof echoExp == 'string') { echoExp = DebugJS.styleValue(echoExp); echoExp = DebugJS.hlCtrlChr(echoExp); } else { echoExp = DebugJS.styleValue(echoExp); } var echoGot = result.got; if (typeof echoGot == 'string') { echoGot = DebugJS.styleValue(echoGot); echoGot = DebugJS.hlCtrlChr(echoGot); } else { echoGot = DebugJS.styleValue(echoGot); } return 'Got=' + echoGot + ' ' + result.method + ' Exp=' + echoExp; }; DebugJS.test.getCountStr = function(cnt) { var test = DebugJS.test; var total = test.countTotal(cnt); return '<span style="color:' + test.COLOR_OK + '">OK</span>:' + cnt.ok + '/' + total + ' <span style="color:' + test.COLOR_NG + '">NG</span>:' + cnt.ng + ' <span style="color:' + test.COLOR_ERR + '">ERR</span>:' + cnt.err + ' <span style="color:' + test.COLOR_NT + '">NT</span>:' + cnt.nt; }; DebugJS.test.getSumCount = function() { var test = DebugJS.test; var cnt = {ok: 0, ng: 0, err: 0, nt: 0}; for (var id in test.data.results) { var st = test.chkResult(test.data.results[id].results); switch (st) { case test.STATUS_OK: cnt.ok++; break; case test.STATUS_NG: cnt.ng++; break; case test.STATUS_ERR: cnt.err++; break; case test.STATUS_NT: cnt.nt++; } } return cnt; }; DebugJS.test.countTotal = function(cnt) { return (cnt.ok + cnt.ng + cnt.err + cnt.nt); }; DebugJS.test.result = function() { var test = DebugJS.test; var data = test.data; var nm = data.name; var ttl = test.getTotalResult(); var cnt = test.getSumCount(); var s = 'Test Result:\n'; if (nm != '') s += '[TEST NAME]\n' + nm + '\n\n'; if (data.desc.length > 0) s += '[DESCRIPTION]\n'; for (var i = 0; i < data.desc.length; i++) { s += data.desc[i] + '\n'; } if (data.desc.length > 0) s += '\n'; if (test.countTotal(cnt) > 0) s += '[RESULTS]\n---------\n'; s += test.getDetailStr(data.results); s += '[SUMMARY]\n' + test.getCountStr(cnt) + ' (' + test.getCountStr(data.cnt) + ')\n'; s += DebugJS.repeatCh('-', ttl.length + 2) + '\n' + test.getStyledStStr(ttl); return s; }; DebugJS.test.getDetailStr = function(results) { var test = DebugJS.test; var M = 16; var n = test.countLongestLabel(); if (n > M) n = M; var details = ''; for (var id in results) { var testId = (id == '' ? '<span style="color:#ccc">&lt;No Test ID&gt;</span>' : id); var st = test.chkResult(results[id].results); var rs = test.getStyledStStr(st); details += rs + ' ' + testId + '\n'; for (var i = 0; i < results[id].comment.length; i++) { var comment = results[id].comment[i]; details += ' # ' + comment + '\n'; } for (i = 0; i < results[id].results.length; i++) { var result = results[id].results[i]; var info = test.getStyledInfoStr(result); details += ' ' + DebugJS.strPadding(result.label, ' ', n, 'R') + ' ' + test.getStyledResultStr(result.status, info) + '\n'; } details += '\n'; } return details; }; DebugJS.test.getResult = function(j) { var data = DebugJS.test.data; var r = { name: data.name, desc: data.desc, startTime: data.startTime, endTime: data.endTime, totalResult: data.ttlRslt, count: data.cnt, results: data.results }; if (j) return DebugJS.toJSON(r); return r; }; DebugJS.test.verify = function(got, method, exp, reqEval, label) { var test = DebugJS.test; var status = test.STATUS_ERR; var info = ''; try { if (method != 'regexp') { exp = eval(exp); if (typeof exp == 'string') { exp = exp.replace(/\r?\n/g, '\n'); } } if (reqEval) { got = eval(got); } if (typeof got == 'string') { got = got.replace(/\r?\n/g, '\n'); } if (method == '==') { if (got == exp) { status = test.STATUS_OK; } else { status = test.STATUS_NG; } } else if (method == '!=') { if (got != exp) { status = test.STATUS_OK; } else { status = test.STATUS_NG; } } else if ((method == 'regexp') || (method == '<') || (method == '<=') || (method == '>') || (method == '>=')) { var evl; if (method == 'regexp') { exp = DebugJS.encodeEsc(exp); var wkGot = got.replace(/\n/g, '\\n'); evl = '(new RegExp(\'' + exp + '\')).test(\'' + wkGot + '\')'; } else { evl = got + method + exp; } try { r = eval(evl); } catch (e) { info = 'Failed to evaluate: ' + e; DebugJS._log.e(info); test.addResult(status, label, exp, got, method, info); test.onVrfyAftr(status); return status; } if (r) { status = test.STATUS_OK; } else { status = test.STATUS_NG; } } else { if (method == undefined) { DebugJS.printUsage('test|point verify [-label:text] got ==|!=|<|>|<=|>=|regexp exp'); } else { info = 'Unknown verify method: ' + method; DebugJS._log.e(info); test.addResult(status, label, exp, got, method, info); test.onVrfyAftr(status); } return status; } } catch (e) { info = e.toString(); } test.addResult(status, label, exp, got, method, info); var s = test.getStyledResultStr(status, info); DebugJS._log(s); test.onVrfyAftr(status); return status; }; DebugJS.test.onVrfyAftr = function(st) { if ((DebugJS.bat.isRunning()) && (DebugJS.bat.hasBatStopCond('test'))) { if (st != DebugJS.test.STATUS_OK) { DebugJS.bat.ctrl.stopReq = true; } } }; DebugJS.test.countLongestLabel = function() { var results = DebugJS.test.data.results; var l = 0; for (var id in results) { for (var i = 0; i < results[id].results.length; i++) { var r = results[id].results[i]; if (r.label.length > l) { l = r.label.length; } } } return l; }; DebugJS.test.getStatus = function() { var data = DebugJS.test.data; var r = { name: data.name, running: data.running, startTime: data.startTime, endTime: data.endTime, seq: data.seq, executingTestId: data.executingTestId, lastRslt: data.lastRslt, ttlRslt: data.ttlRslt, cnt: data.cnt }; return r; }; DebugJS.test.isRunning = function() { return DebugJS.test.data.running; }; DebugJS.getElement = function(selector, idx) { if (typeof selector != 'string') return selector; idx |= 0; var el = null; try { var nodeList = document.querySelectorAll(selector); el = nodeList.item(idx); } catch (e) {} return el; }; DebugJS.getElPosSize = function(el, idx) { el = DebugJS.getElement(el, idx); if (!el) return null; var rect = el.getBoundingClientRect(); var rectT = Math.round(rect.top); var rectL = Math.round(rect.left); var rectR = Math.round(rect.right); var rectB = Math.round(rect.bottom); var ps = { x: rectL, y: rectT, w: ((rectR - rectL) + 1), h: ((rectB - rectT) + 1) }; return ps; }; DebugJS.getScreenCenter = function() { var p = { x: (document.documentElement.clientWidth / 2), y: (document.documentElement.clientHeight / 2) }; return p; }; DebugJS.getLabelEl = function(label, idx) { var el = null; var cnt = 0; var c = document.getElementsByTagName('label'); for (var i = 0; i < c.length; i++) { if (c[i].innerText == label) { if (idx == cnt) { el = c[i]; break; } cnt++; } } return el; }; DebugJS.findFocusableEl = function(e) { var el = e; do { if (el.tagName == 'HTML') { el = null; break; } if (DebugJS.isFocusable(el)) break; el = el.parentNode; } while (el != null); return el; }; DebugJS.isFocusable = function(el) { var a = ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA']; return (a.indexOf(el.tagName) == -1 ? false : true); }; DebugJS.isTxtInp = function(el) { if (el.tagName == 'TEXTAREA') return true; if (el.tagName == 'INPUT') { if ((el.type == 'text') || (el.type == 'password')) return true; } return false; }; DebugJS.toggleElShowHide = function(el) { var v = (el.style.display == 'none' ? '' : 'none'); el.style.display = v; }; DebugJS.random = function(min, max) { return DebugJS.getRandom(DebugJS.RND_TYPE_NUM, min, max); }; DebugJS.randomStr = function(min, max) { return DebugJS.getRandom(DebugJS.RND_TYPE_STR, min, max); }; DebugJS.createResBox = function(m) { return DebugJS._createResBox(m); }; DebugJS.createResBoxErr = function(m) { return DebugJS._createResBox(m, true); }; DebugJS._createResBox = function(m, e) { return '<textarea class="dbg-resbox box ' + (e ? 'err' : 'ok') + '" readonly>' + m + '</textarea>'; }; DebugJS.adjustResBox = function(adj) { DebugJS.adjustResBox.a = adj | 0; setTimeout(DebugJS._adjustResBox, 10); }; DebugJS.adjustResBox.a = 0; DebugJS._adjustResBox = function() { var el = document.getElementsByClassName('dbg-resbox box'); for (var i = 0; i < el.length; i++) { DebugJS.ctx.setStyle(el[i], 'height', (el[i].scrollHeight + DebugJS.adjustResBox.a) + 'px'); } }; DebugJS.getProtocol = function() { return location.protocol; }; DebugJS.getHost = function() { return location.host.split(':')[0]; }; DebugJS.getPort = function() { return location.port; }; DebugJS.getParentPath = function() { return location.href.replace(/(.*\/).*/, '$1'); }; DebugJS.ui = {}; DebugJS.ui.addBtn = function(base, label, onclick) { var el = document.createElement('span'); el.className = 'dbg-btn dbg-nomove'; el.innerText = label; el.onclick = onclick; base.appendChild(el); return el; }; DebugJS.ui.createBtnHtml = function(label, onclick, style) { return '<span class="dbg-btn dbg-nomove" ' + (style == undefined ? '' : 'style="' + style + '" ') + 'onclick="' + onclick + '">' + label + '</span>'; }; DebugJS.ui.addLabel = function(base, label) { var el = document.createElement('span'); el.innerText = label; base.appendChild(el); return el; }; DebugJS.ui.addTextInput = function(base, width, txtAlign, color, val, oninput) { var ctx = DebugJS.ctx; var el = document.createElement('input'); el.className = 'dbg-txtbox'; ctx.setStyle(el, 'width', width); ctx.setStyle(el, 'min-height', ctx.computedFontSize + 'px'); ctx.setStyle(el, 'margin', '0'); ctx.setStyle(el, 'padding', '0'); ctx.setStyle(el, 'color', color); if (txtAlign) ctx.setStyle(el, 'text-align', txtAlign); el.value = val; el.oninput = oninput; base.appendChild(el); return el; }; DebugJS.wd = {}; DebugJS.wd.INTERVAL = 50; DebugJS.wd.wdTmId = 0; DebugJS.wd.wdPetTime = 0; DebugJS.wd.cnt = 0; DebugJS.wd.start = function(interval) { var ctx = DebugJS.ctx; var wd = DebugJS.wd; interval |= 0; if (interval > 0) ctx.props.wdt = interval; ctx.status |= DebugJS.ST_WD; wd.cnt = 0; wd.wdPetTime = (new Date()).getTime(); DebugJS._log.s('Start watchdog (' + ctx.props.wdt + 'ms)'); if (wd.wdTmId > 0) clearTimeout(wd.wdTmId); wd.wdTmId = setTimeout(wd.pet, wd.INTERVAL); }; DebugJS.wd.pet = function() { var ctx = DebugJS.ctx; if (!(ctx.status & DebugJS.ST_WD)) return; var wd = DebugJS.wd; var now = (new Date()).getTime(); var elps = now - wd.wdPetTime; if (elps > ctx.props.wdt) { wd.cnt++; DebugJS._log.w('Watchdog bark! (' + elps + 'ms)'); DebugJS.callEvtListeners('watchdog', elps); } wd.wdPetTime = now; wd.wdTmId = setTimeout(wd.pet, wd.INTERVAL); }; DebugJS.wd.stop = function() { var wd = DebugJS.wd; if (wd.wdTmId > 0) { clearTimeout(wd.wdTmId); wd.wdTmId = 0; } DebugJS.ctx.status &= ~DebugJS.ST_WD; DebugJS._log.s('Stop watchdog'); }; DebugJS.log = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log(m); }; DebugJS.log.e = function(m) { var ctx = DebugJS.ctx; if (ctx.status & DebugJS.ST_LOG_SUSPENDING) return; ctx.errStatus |= DebugJS.ERR_ST_LOG; DebugJS._log.e(m); }; DebugJS.log.w = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.w(m); }; DebugJS.log.i = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.i(m); }; DebugJS.log.d = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.d(m); }; DebugJS.log.v = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.v(m); }; DebugJS.log.t = function(m, n) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS.time.log(m, n); }; DebugJS.log.p = function(o, l, m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.p(o, l, m, false); }; DebugJS.log.json = function(o, l, m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.p(o, l, m, true); }; DebugJS.log.j = DebugJS.log.json; DebugJS.log.res = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.res(m); }; DebugJS.log.res.err = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.res.err(m); }; DebugJS.log.mlt = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS._log.mlt(m); }; DebugJS.log.clear = function() { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; DebugJS.ctx.clearLog(); }; DebugJS.log.suspend = function() { DebugJS.ctx.suspendLog(); }; DebugJS.log.resume = function() { DebugJS.ctx.resumeLog(); }; DebugJS.log.preserve = function(f) { var ctx = DebugJS.ctx; if (f == undefined) { return ((ctx.status & DebugJS.ST_LOG_PRESERVED) ? true : false); } if (DebugJS.LS_AVAILABLE) ctx.setLogPreserve(ctx, f); }; DebugJS.log.toBottom = function() { DebugJS.ctx.scrollLogBtm(DebugJS.ctx); }; DebugJS.log.root = function(m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; if (window.opener) { window.opener.log.root(m); } else if (window.top.opener) { window.top.opener.log.root(m); } else { window.top.DebugJS._log(m); } }; DebugJS.log.root.fn = function(lv, m) { if (DebugJS.ctx.status & DebugJS.ST_LOG_SUSPENDING) return; if (window.opener) { window.opener.log[lv].root(m); } else if (window.top.opener) { window.top.opener.log[lv].root(m); } else { window.top.DebugJS._log[lv](m); } }; DebugJS.rootFncs = function() { var fn = ['v', 'd', 'i', 'w', 'e']; for (var i = 0; i < fn.length; i++) { var lv = fn[i]; DebugJS.log[lv].root = (DebugJS.ENABLE ? DebugJS.log.root.fn.bind(undefined, lv) : DebugJS.f_); } }; DebugJS.setConsoleLogOut = function(f) { if (!window.console) return; if (f) { console.log = function(x) {log(x);}; console.info = function(x) {log.i(x);}; console.warn = function(x) {log.w(x);}; console.error = function(x) {log.e(x);}; console.time = function(x) {DebugJS.time.start(x);}; console.timeEnd = function(x) {DebugJS.time.end(x);}; } else { console.log = DebugJS.bak.console.log; console.info = DebugJS.bak.console.info; console.warn = DebugJS.bak.console.warn; console.error = DebugJS.bak.console.error; console.time = DebugJS.bak.console.time; console.timeEnd = DebugJS.bak.console.timeEnd; } }; DebugJS.restoreStatus = function(ctx) { var data = DebugJS.loadStatus(); if ((data == null) || !((data.status & DebugJS.ST_LOG_PRESERVED) || (data.status & DebugJS.ST_BAT_CONT))) { return; } if (data.status & DebugJS.ST_LOG_PRESERVED) { ctx.status |= DebugJS.ST_LOG_PRESERVED; DebugJS.restoreLog(); } if (data.status & DebugJS.ST_BAT_CONT) { ctx.status |= DebugJS.ST_BAT_CONT; } ctx.timers = data.timers; if (data.status & DebugJS.ST_STOPWATCH_RUNNING) { ctx.startStopwatch(); } else { ctx.updateSwLabel(); } DebugJS.restoreProps(ctx, data.props); DebugJS.ctx.CMD_ALIAS = data.alias; }; DebugJS.restoreProps = function(ctx, props) { for (var k in props) { ctx._cmdSet(ctx, k, props[k], false); } }; DebugJS.ver = function() { return DebugJS.ctx.v; }; DebugJS.x = DebugJS.x || {}; DebugJS.x.addCmdTbl = function(table) { var ctx = DebugJS.ctx; for (var i = 0; i < table.length; i++) { var c = table[i]; if ((ctx.existsCmd(c.cmd, ctx.INT_CMD_TBL)) || (ctx.existsCmd(c.cmd, ctx.EXT_CMD_TBL))) { c.attr |= DebugJS.CMD_ATTR_DISABLED; } ctx.EXT_CMD_TBL.push(c); } }; DebugJS.x.addPanel = function(p) { var ctx = DebugJS.ctx; p.base = null; p.btn = null; var idx = ctx.extPanels.push(p) - 1; if (ctx.status & DebugJS.ST_INITIALIZED) { ctx.initExtPanel(ctx); } return idx; }; DebugJS.x.addFileLdr = function(p) { var d = p.fileloader; if (d) DebugJS.addFileLoader(p.panel, d.cb, d.mode, d.decode); }; DebugJS.x.getPanel = function(idx) { var p = DebugJS.ctx.extPanels[idx]; if (p) return p.panel; return null; }; DebugJS.x.getActivePanel = function() { return DebugJS.x.getPanel(DebugJS.ctx.extActPnlIdx); }; DebugJS.x.removePanel = function(idx) { var ctx = DebugJS.ctx; if (!ctx.extPanels[idx]) return; var nIdx = -1; var p = ctx.extPanels[idx]; ctx.extPanels[idx] = null; if (ctx.extActPnlIdx == idx) { nIdx = ctx.prevValidExtPanelIdx(ctx, idx); if (nIdx == -1) { nIdx = ctx.nextValidExtPanelIdx(ctx, idx); } } if (!(ctx.status & DebugJS.ST_INITIALIZED)) return; if ((ctx.status & DebugJS.ST_EXT_PANEL) && (p.onInActive)) { ctx.onExtPanelInActive(ctx, p); } ctx.redrawExtPanelBtn(ctx); if (ctx.existsValidExtPanel(ctx)) { if (nIdx != -1) { ctx.switchExtPanel(nIdx); } } else { ctx.extActPnlIdx = -1; ctx.extPanels = []; ctx.closeExtPanel(ctx); if (ctx.extBtn) ctx.extBtn.style.display = 'none'; } }; DebugJS.x.setBtnLabel = function(l) { DebugJS.ctx.extBtnLabel = l; if (DebugJS.ctx.extBtn) DebugJS.ctx.extBtn.innerHTML = l; }; DebugJS._init = function() { if (DebugJS.ctx.status & DebugJS.ST_INITIALIZED) { return true; } else { return DebugJS.ctx.init(null, null); } }; DebugJS.init = function(opt) { DebugJS.ctx.init(opt, null); }; DebugJS.onReady = function() { DebugJS._init(); }; DebugJS.onLoad = function() { window.addEventListener('unload', DebugJS.onUnload, true); DebugJS.test.load(); DebugJS.bat.load(); }; DebugJS.onUnload = function() { var ctx = DebugJS.ctx; if (DebugJS.test.data.running) { DebugJS.test.save(); } if ((ctx.status & DebugJS.ST_BAT_RUNNING) && (ctx.props.batcont == 'on')) { DebugJS.bat.save(); } if ((ctx.status & DebugJS.ST_LOG_PRESERVED) || (ctx.status & DebugJS.ST_BAT_CONT)) { DebugJS.saveStatus(); } if (ctx.status & DebugJS.ST_LOG_PRESERVED) { DebugJS.preserveLog(); } }; DebugJS.onError = function(e) { var ctx = DebugJS.ctx; var msg; ctx.errStatus |= DebugJS.ERR_ST_SCRIPT; if ((e.error) && (e.error.stack)) { msg = e.error.stack; } else { if ((e.message == undefined) && (e.filename == undefined)) { if ((e.target) && (e.target.outerHTML)) { ctx.errStatus |= DebugJS.ERR_ST_LOAD; ctx.errStatus &= ~DebugJS.ERR_ST_SCRIPT; msg = 'LOAD_ERROR: ' + (e.target.outerHTML).replace(/</g, '&lt;').replace(/>/g, '&gt;'); } else { msg = 'UNKNOWN_ERROR'; } } else { msg = e.message + ' ' + e.filename + '(' + e.lineno + ':' + e.colno + ')'; } } DebugJS.log.e(msg); }; DebugJS.balse = function() { var x = DebugJS.f_; DebugJS.boot = x; DebugJS.start = x; DebugJS.log = x; DebugJS.log.e = x; DebugJS.log.w = x; DebugJS.log.i = x; DebugJS.log.d = x; DebugJS.log.v = x; DebugJS.log.t = x; DebugJS.log.p = x; DebugJS.log.json = x; DebugJS.log.mlt = x; DebugJS.log.clear = x; DebugJS.log.res = x; DebugJS.log.res.err = x; DebugJS.log.suspend = x; DebugJS.log.resume = x; DebugJS.log.root = x; DebugJS.addEvtListener = x; DebugJS.addFileLoader = x; DebugJS.adjustResBox = x; DebugJS.cmd = x; DebugJS.bat = x; DebugJS.bat.set = x; DebugJS.bat.run = x; DebugJS.bat.pause = x; DebugJS.bat.resume = x; DebugJS.bat.stop = x; DebugJS.bat.list = x; DebugJS.bat.status = x; DebugJS.bat.isRunning = x; DebugJS.bat.setCond = x; DebugJS.countElements = x; DebugJS.getHTML = x; DebugJS.init = x; DebugJS.dumpLog = x; DebugJS.sendLog = x; DebugJS.show = x; DebugJS.hide = x; DebugJS.http = x; DebugJS.led = x; DebugJS.led.on = x; DebugJS.led.off = x; DebugJS.msg = x; DebugJS.msg.clear = x; DebugJS.opacity = x; DebugJS.stack = x; DebugJS.stopwatch = x; DebugJS.stopwatch.start = x; DebugJS.stopwatch.stop = x; DebugJS.stopwatch.end = x; DebugJS.stopwatch.split = x; DebugJS.stopwatch.reset = x; DebugJS.time.start = x; DebugJS.time.split = x; DebugJS.time.end = x; DebugJS.time.check = x; DebugJS.ver = x; DebugJS.wd.start = x; DebugJS.wd.stop = x; DebugJS.x.addCmdTbl = x; DebugJS.x.addPanel = x; DebugJS.x.getPanel = x; DebugJS.x.getActivePanel = x; DebugJS.x.removePanel = x; DebugJS.x.setBtnLabel = x; DebugJS._createResBox = x; }; DebugJS.boot = function() { DebugJS.rootFncs(); DebugJS.ctx = DebugJS.ctx || new DebugJS(); DebugJS.el = null; if (window.el === undefined) DebugJS.G_EL_AVAILABLE = true; try { if (typeof window.localStorage != 'undefined') { DebugJS.LS_AVAILABLE = true; } } catch (e) {} try { if (typeof window.sessionStorage != 'undefined') { DebugJS.SS_AVAILABLE = true; } } catch (e) {} window.addEventListener('DOMContentLoaded', DebugJS.onReady, true); window.addEventListener('load', DebugJS.onLoad, true); window.addEventListener('error', DebugJS.onError, true); DebugJS.bak = { console: { log: console.log, info: console.info, warn: console.warn, error: console.error, time: console.time, timeEnd: console.timeEnd } }; DebugJS.restoreStatus(DebugJS.ctx); }; DebugJS.start = function(o) {DebugJS.init(o);DebugJS.show();}; DebugJS.ENABLE = true; if (DebugJS.ENABLE) { DebugJS.boot(); } else { DebugJS.balse(); } DebugJS.time.s = DebugJS.time.start; DebugJS.time.e = DebugJS.time.end; var dbg = (dbg === undefined ? DebugJS : dbg); var log = (log === undefined ? DebugJS.log : log);
Fix: dbg.balse()
debug.js
Fix: dbg.balse()
<ide><path>ebug.js <ide> * https://debugjs.net/ <ide> */ <ide> var DebugJS = DebugJS || function() { <del> this.v = '201901082111'; <add> this.v = '201901090000'; <ide> <ide> this.DEFAULT_OPTIONS = { <ide> visible: false, <ide> this.ledPanel = null; <ide> this.led = 0; <ide> this.msgLabel = null; <del> this.msgString = ''; <add> this.msgStr = ''; <ide> this.mainPanel = null; <ide> this.overlayBasePanel = null; <ide> this.overlayPanels = []; <ide> if (fontSize) ctx.setStyle(btn, 'font-size', fontSize); <ide> ctx.setStyle(btn, 'color', DebugJS.COLOR_INACT); <ide> btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', DebugJS.' + activeColor + ');'); <del> if (reverse) { <del> btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', (DebugJS.ctx.' + status + ' & DebugJS.' + state + ') ? DebugJS.COLOR_INACT : DebugJS.' + activeColor + ');'); <del> } else { <del> btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', (DebugJS.ctx.' + status + ' & DebugJS.' + state + ') ? DebugJS.' + activeColor + ' : DebugJS.COLOR_INACT);'); <del> } <add> var fnSfx = (reverse ? 'DebugJS.COLOR_INACT : DebugJS.' + activeColor + ');' : 'DebugJS.' + activeColor + ' : DebugJS.COLOR_INACT);'); <add> btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', (DebugJS.ctx.' + status + ' & DebugJS.' + state + ') ? ' + fnSfx); <ide> if (title) btn.title = title; <ide> return btn; <ide> }, <ide> <ide> updateMsgLabel: function() { <ide> var ctx = DebugJS.ctx; <del> var s = ctx.msgString; <add> var s = ctx.msgStr; <ide> if (ctx.msgLabel) { <ide> ctx.msgLabel.innerHTML = '<pre>' + s + '</pre>'; <ide> var o = (s == '' ? 0 : 1); <ide> ctx.batBtn = ctx.createToolsHeaderBtn('BAT', 'TOOLS_FNC_BAT', 'batBtn'); <ide> }, <ide> createToolsHeaderBtn: function(label, state, btnObj) { <del> var ctx = DebugJS.ctx; <ide> var fn = new Function('DebugJS.ctx.switchToolsFunction(DebugJS.' + state + ');'); <del> var btn = DebugJS.ui.addBtn(ctx.toolsHeaderPanel, '<' + label + '>', fn); <add> var btn = DebugJS.ui.addBtn(DebugJS.ctx.toolsHeaderPanel, '<' + label + '>', fn); <ide> btn.style.marginRight = '4px'; <ide> btn.onmouseover = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', DebugJS.SBPNL_COLOR_ACTIVE);'); <ide> btn.onmouseout = new Function('DebugJS.ctx.setStyle(DebugJS.ctx.' + btnObj + ', \'color\', (DebugJS.ctx.toolsActiveFnc & DebugJS.' + state + ') ? DebugJS.SBPNL_COLOR_ACTIVE : DebugJS.SBPNL_COLOR_INACT);'); <ide> }, <ide> <ide> setMsg: function(m) { <del> DebugJS.ctx.msgString = m; <add> DebugJS.ctx.msgStr = m; <ide> DebugJS.ctx.updateMsgLabel(); <ide> }, <ide> <ide> s += t.ss + 's'; <ide> if (t.sss) s += ' ' + t.sss + 'ms'; <ide> } else { <del> if (!t.sss) { <add> if (t.sss) { <add> s = '0.' + ('00' + t.sss).slice(-3).replace(/0+$/, ''); <add> } else { <ide> s = '0'; <del> } else { <del> s = '0.' + ('00' + t.sss).slice(-3).replace(/0+$/, ''); <ide> } <ide> s += 's'; <ide> } <ide> var a = arg.split(' '); <ide> for (var i = 0; i < a.length; i++) { <ide> if (a[i] == '') continue; <del> var codePoint = a[i].replace(/^U\+/i, ''); <del> if (codePoint == '20') { <add> var cdpt = a[i].replace(/^U\+/i, ''); <add> if (cdpt == '20') { <ide> str += ' '; <ide> } else { <del> str += '&#x' + codePoint; <add> str += '&#x' + cdpt; <ide> } <ide> } <ide> return str; <ide> DebugJS.getUnicodePoints = function(str) { <ide> var code = ''; <ide> for (var i = 0; i < str.length; i++) { <del> var point = str.charCodeAt(i); <add> var pt = str.charCodeAt(i); <ide> if (i > 0) code += ' '; <del> code += 'U+' + DebugJS.toHex(point, true, '', 4); <add> code += 'U+' + DebugJS.toHex(pt, true, '', 4); <ide> } <ide> return code; <ide> }; <ide> return false; <ide> }; <ide> <del>DebugJS.copyProp = function(src, dest) { <add>DebugJS.copyProp = function(src, dst) { <ide> for (var k in src) { <del> dest[k] = src[k]; <add> dst[k] = src[k]; <ide> } <ide> }; <ide> <ide> <ide> DebugJS.addEvtListener = function(type, listener) { <ide> var list = DebugJS.ctx.evtListener[type]; <del> if (!list) { <add> if (list) { <add> list.push(listener); <add> } else { <ide> DebugJS._log.e('No such event: ' + type); <del> } else { <del> list.push(listener); <ide> } <ide> }; <ide> DebugJS.callEvtListeners = function(type, a1, a2, a3) { <ide> } catch (e) { <ide> m = e + ''; <ide> } <del> if ((speed) && (step)) { <add> if (speed && step) { <ide> hint.msgseq(msg, m, speed, step, start, end); <ide> } else { <ide> DebugJS.point.hint.setMsg(DebugJS.point.hint.replaceMsg(m)); <ide> var ctx = DebugJS.ctx; <ide> var msg; <ide> ctx.errStatus |= DebugJS.ERR_ST_SCRIPT; <del> if ((e.error) && (e.error.stack)) { <add> if (e.error && e.error.stack) { <ide> msg = e.error.stack; <ide> } else { <ide> if ((e.message == undefined) && (e.filename == undefined)) { <del> if ((e.target) && (e.target.outerHTML)) { <add> if (e.target && e.target.outerHTML) { <ide> ctx.errStatus |= DebugJS.ERR_ST_LOAD; <ide> ctx.errStatus &= ~DebugJS.ERR_ST_SCRIPT; <ide> msg = 'LOAD_ERROR: ' + (e.target.outerHTML).replace(/</g, '&lt;').replace(/>/g, '&gt;'); <ide> DebugJS.stopwatch.end = x; <ide> DebugJS.stopwatch.split = x; <ide> DebugJS.stopwatch.reset = x; <add> DebugJS.stopwatch.val = x; <ide> DebugJS.time.start = x; <ide> DebugJS.time.split = x; <ide> DebugJS.time.end = x;
Java
apache-2.0
cc0f5016af6085be0096d592ed78db3a3024f4c4
0
synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung
package org.synyx.urlaubsverwaltung.sicknote; import org.springframework.data.jpa.domain.AbstractPersistable; import org.synyx.urlaubsverwaltung.period.DayLength; import org.synyx.urlaubsverwaltung.period.Period; import org.synyx.urlaubsverwaltung.person.Person; import org.synyx.urlaubsverwaltung.util.DateFormat; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.ManyToOne; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import static java.time.ZoneOffset.UTC; /** * Entity representing a sick note with information about employee and period. */ @Entity public class SickNote extends AbstractPersistable<Integer> { private static final long serialVersionUID = 8524575678589823089L; /** * One person may have multiple sick notes. */ @ManyToOne private Person person; /** * Type of sick note. * * @since 2.15.0 */ @ManyToOne private SickNoteType sickNoteType; /** * Sick note period: start and end date of the period, the employee is sick. */ private LocalDate startDate; private LocalDate endDate; /** * Time of day for the sick note: morning, noon or full day * * @since 2.9.4 */ @Enumerated(EnumType.STRING) private DayLength dayLength; /** * Period of the AUB (Arbeitsunfähigkeitsbescheinigung), is optional. */ private LocalDate aubStartDate; private LocalDate aubEndDate; private LocalDate lastEdited; @Enumerated(EnumType.STRING) private SickNoteStatus status; public SickNote() { this.lastEdited = LocalDate.now(UTC); } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public SickNoteType getSickNoteType() { return sickNoteType; } public void setSickNoteType(SickNoteType sickNoteType) { this.sickNoteType = sickNoteType; } public LocalDate getStartDate() { if (this.startDate == null) { return null; } return this.startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { if (this.endDate == null) { return null; } return this.endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public DayLength getDayLength() { return dayLength; } public void setDayLength(DayLength dayLength) { this.dayLength = dayLength; } public boolean isAubPresent() { return getAubStartDate() != null && getAubEndDate() != null; } public LocalDate getAubStartDate() { if (this.aubStartDate == null) { return null; } return this.aubStartDate; } public void setAubStartDate(LocalDate aubStartDate) { this.aubStartDate = aubStartDate; } public LocalDate getAubEndDate() { if (this.aubEndDate == null) { return null; } return this.aubEndDate; } public void setAubEndDate(LocalDate aubEndDate) { this.aubEndDate = aubEndDate; } public LocalDate getLastEdited() { if (this.lastEdited == null) { return null; } return this.lastEdited; } public void setLastEdited(LocalDate lastEdited) { this.lastEdited = lastEdited; } public boolean isActive() { return SickNoteStatus.ACTIVE.equals(getStatus()); } public SickNoteStatus getStatus() { return status; } public void setStatus(SickNoteStatus status) { this.status = status; } public Period getPeriod() { return new Period(getStartDate(), getEndDate(), getDayLength()); } @Override public void setId(Integer id) { // NOSONAR - make it public instead of protected super.setId(id); } @Override public String toString() { return "SickNote{" + "id=" + getId() + ", person=" + person + ", sickNoteType=" + sickNoteType + ", startDate=" + startDate + ", endDate=" + endDate + ", dayLength=" + dayLength + ", aubStartDate=" + aubStartDate + ", aubEndDate=" + aubEndDate + ", lastEdited=" + lastEdited + ", status=" + status + '}'; } }
src/main/java/org/synyx/urlaubsverwaltung/sicknote/SickNote.java
package org.synyx.urlaubsverwaltung.sicknote; import org.springframework.data.jpa.domain.AbstractPersistable; import org.synyx.urlaubsverwaltung.period.DayLength; import org.synyx.urlaubsverwaltung.period.Period; import org.synyx.urlaubsverwaltung.person.Person; import org.synyx.urlaubsverwaltung.util.DateFormat; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.ManyToOne; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import static java.time.ZoneOffset.UTC; /** * Entity representing a sick note with information about employee and period. */ @Entity public class SickNote extends AbstractPersistable<Integer> { private static final long serialVersionUID = 8524575678589823089L; /** * One person may have multiple sick notes. */ @ManyToOne private Person person; /** * Type of sick note. * * @since 2.15.0 */ @ManyToOne private SickNoteType sickNoteType; /** * Sick note period: start and end date of the period, the employee is sick. */ private LocalDate startDate; private LocalDate endDate; /** * Time of day for the sick note: morning, noon or full day * * @since 2.9.4 */ @Enumerated(EnumType.STRING) private DayLength dayLength; /** * Period of the AUB (Arbeitsunfähigkeitsbescheinigung), is optional. */ private LocalDate aubStartDate; private LocalDate aubEndDate; private LocalDate lastEdited; @Enumerated(EnumType.STRING) private SickNoteStatus status; public SickNote() { this.lastEdited = LocalDate.now(UTC); } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public SickNoteType getSickNoteType() { return sickNoteType; } public void setSickNoteType(SickNoteType sickNoteType) { this.sickNoteType = sickNoteType; } public LocalDate getStartDate() { if (this.startDate == null) { return null; } return this.startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { if (this.endDate == null) { return null; } return this.endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public DayLength getDayLength() { return dayLength; } public void setDayLength(DayLength dayLength) { this.dayLength = dayLength; } public boolean isAubPresent() { return getAubStartDate() != null && getAubEndDate() != null; } public LocalDate getAubStartDate() { if (this.aubStartDate == null) { return null; } return this.aubStartDate; } public void setAubStartDate(LocalDate aubStartDate) { this.aubStartDate = aubStartDate; } public LocalDate getAubEndDate() { if (this.aubEndDate == null) { return null; } return this.aubEndDate; } public void setAubEndDate(LocalDate aubEndDate) { this.aubEndDate = aubEndDate; } public LocalDate getLastEdited() { if (this.lastEdited == null) { return null; } return this.lastEdited; } public void setLastEdited(LocalDate lastEdited) { this.lastEdited = lastEdited; } public boolean isActive() { return SickNoteStatus.ACTIVE.equals(getStatus()); } public SickNoteStatus getStatus() { return status; } public void setStatus(SickNoteStatus status) { this.status = status; } public Period getPeriod() { return new Period(getStartDate(), getEndDate(), getDayLength()); } @Override public void setId(Integer id) { // NOSONAR - make it public instead of protected super.setId(id); } @Override public String toString() { return "SickNote{" + "id=" + getId() + ", person=" + person + ", sickNoteType=" + sickNoteType + ", startDate=" + startDate + ", endDate=" + endDate + ", dayLength=" + dayLength + ", aubStartDate=" + aubStartDate + ", aubEndDate=" + aubEndDate + ", lastEdited=" + lastEdited + ", status=" + status + '}'; } private Object formatNullable(LocalDate date) { return date != null ? date.format(DateTimeFormatter.ofPattern(DateFormat.PATTERN)) : null; } }
Remove not used method from old toString of SickNote
src/main/java/org/synyx/urlaubsverwaltung/sicknote/SickNote.java
Remove not used method from old toString of SickNote
<ide><path>rc/main/java/org/synyx/urlaubsverwaltung/sicknote/SickNote.java <ide> ", status=" + status + <ide> '}'; <ide> } <del> <del> private Object formatNullable(LocalDate date) { <del> return date != null ? date.format(DateTimeFormatter.ofPattern(DateFormat.PATTERN)) : null; <del> } <ide> }
JavaScript
mit
29eb99ee93d1821e2dfa5e137a90ab05c28eafb8
0
ajcrites/babybel,kaicataldo/babel,garyjN7/babel,Jeremy017/babel,claudiopro/babel,hulkish/babel,ysmood/babel,dekelcohen/babel,iamstarkov/babel,iamchenxin/babel,chengky/babel,nishant8BITS/babel,VukDukic/babel,hzoo/babel,ellbee/babel,megawac/babel,macressler/babel,KualiCo/babel,greyhwndz/babel,samwgoldman/babel,mgcrea/babel,cesarandreu/6to5,macressler/babel,Dignifiedquire/babel,moander/babel,steveluscher/babel,ErikBaath/babel,ryankanno/babel,iamolivinius/babel,forivall/babel,PolymerLabs/babel,douglasduteil/babel,ezbreaks/babel,mcanthony/babel,hulkish/babel,jhen0409/babel,DmitrySoshnikov/babel,johnamiahford/babel,lastjune/babel,PolymerLabs/babel,hzoo/babel,beni55/babel,jhen0409/babel,ramoslin02/babel,ianmstew/babel,zenlambda/babel,cesarandreu/6to5,ramoslin02/babel,CrocoDillon/babel,thejameskyle/babel,zorosteven/babel,james4388/babel,beni55/babel,ortutay/babel,jeffmo/babel,kpdecker/babel,kevhuang/babel,sairion/babel,Victorystick/babel,abdulsam/babel,plemarquand/babel,inikulin/babel,drieks/babel,jridgewell/babel,hulkish/babel,Jeremy017/babel,Skillupco/babel,TheAlphaNerd/babel,jeffmo/babel,mayflower/babel,grasuxxxl/babel,ortutay/babel,grasuxxxl/babel,framewr/babel,james4388/babel,garyjN7/babel,hubli/babel,Victorystick/babel,rmacklin/babel,jridgewell/babel,thorikawa/babel,tricknotes/babel,zorosteven/babel,moander/babel,sairion/babel,bcoe/babel,nmn/babel,iamolivinius/babel,paulcbetts/babel,kedromelon/babel,ccschneidr/babel,aalluri-navaratan/babel,lastjune/babel,vjeux/babel,nmn/babel,1yvT0s/babel,hzoo/babel,ryankanno/babel,kellyselden/babel,shuhei/babel,greyhwndz/babel,CrocoDillon/babel,nvivo/babel,victorenator/babel,mrtrizer/babel,Industrial/babel,krasimir/babel,vadzim/babel,KunGha/babel,manukall/babel,nishant8BITS/babel,existentialism/babel,kellyselden/babel,TheAlphaNerd/babel,1yvT0s/babel,ErikBaath/babel,VukDukic/babel,bcoe/babel,jackmew/babel,claudiopro/babel,cartermarino/babel,ezbreaks/babel,gxr1020/babel,victorenator/babel,michaelficarra/babel,chicoxyzzy/babel,fabiomcosta/babel,hubli/babel,andrewwilkins/babel,Mark-Simulacrum/babel,DmitrySoshnikov/babel,zertosh/babel,ywo/babel,ianmstew/babel,cartermarino/babel,andrejkn/babel,thorikawa/babel,Dignifiedquire/babel,CrabDude/babel,Dignifiedquire/babel,Mark-Simulacrum/babel,rn0/babel,zertosh/babel,vjeux/babel,VukDukic/babel,kaicataldo/babel,jnuine/babel,sethcall/babel,jchip/babel,kedromelon/babel,STRML/babel,ajcrites/babybel,codenamejason/babel,rmacklin/babel,ywo/babel,aalluri-navaratan/babel,existentialism/babel,sethcall/babel,chicoxyzzy/babel,kevhuang/babel,koistya/babel,hzoo/babel,johnamiahford/babel,kaicataldo/babel,chengky/babel,guybedford/babel,guybedford/babel,plemarquand/babel,cartermarino/babel,lxe/babel,framewr/babel,vipulnsward/babel,ccschneidr/babel,rn0/babel,prathamesh-sonpatki/babel,steveluscher/babel,jmptrader/babel,samccone/babel,pixeldrew/babel,mrmayfield/babel,iamstarkov/babel,jmptrader/babel,tricknotes/babel,tricknotes/babel,maurobringolf/babel,PolymerLabs/babel,KunGha/babel,spicyj/babel,kevhuang/babel,Mark-Simulacrum/babel,guybedford/babel,antn/babel,zenlambda/babel,vhf/babel,plemarquand/babel,pixeldrew/babel,tikotzky/babel,krasimir/babel,e-jigsaw/babel,cgvarela/babel,claudiopro/babel,samwgoldman/babel,ameyms/babel,fabiomcosta/babel,hubli/babel,codenamejason/babel,rektide/babel-repl,james4388/babel,johnamiahford/babel,koistya/babel,chicoxyzzy/babel,mrapogee/babel,rn0/babel,forivall/babel,CrabDude/babel,ming-codes/babel,lastjune/babel,mayflower/babel,zjmiller/babel,mayflower/babel,e-jigsaw/babel,vjeux/babel,mrmayfield/babel,vadzim/babel,sethcall/babel,douglasduteil/babel,drieks/babel,jeffmo/babel,iamchenxin/babel,manukall/babel,megawac/babel,jridgewell/babel,andrewwilkins/babel,mrapogee/babel,ming-codes/babel,gxr1020/babel,AgentME/babel,babel/babel,kellyselden/babel,jackmew/babel,mgcrea/babel,inikulin/babel,nvivo/babel,thejameskyle/babel,macressler/babel,Skillupco/babel,nmn/babel,Victorystick/babel,megawac/babel,1yvT0s/babel,zenparsing/babel,abdulsam/babel,KualiCo/babel,cgvarela/babel,beni55/babel,e-jigsaw/babel,sejoker/babel,paulcbetts/babel,ysmood/babel,antn/babel,maurobringolf/babel,CrabDude/babel,codenamejason/babel,kassens/babel,hulkish/babel,grasuxxxl/babel,chengky/babel,kpdecker/babel,rektide/babel-repl,babel/babel,zenparsing/babel,vipulnsward/babel,douglasduteil/babel,vipulnsward/babel,ysmood/babel,ywo/babel,sejoker/babel,babel/babel,jnuine/babel,pingjiang/babel,pixeldrew/babel,dustyjewett/babel-plugin-transform-es2015-modules-commonjs-ember,TheAlphaNerd/babel,samccone/babel,iamchenxin/babel,moander/babel,sairion/babel,iamolivinius/babel,ortutay/babel,kellyselden/babel,forivall-old-repos/tacoscript-babel-shared-history,victorenator/babel,ianmstew/babel,SaltTeam/babel,steveluscher/babel,prathamesh-sonpatki/babel,koistya/babel,mrtrizer/babel,existentialism/babel,mcanthony/babel,paulcbetts/babel,ErikBaath/babel,kassens/babel,ameyms/babel,aalluri-navaratan/babel,samwgoldman/babel,drieks/babel,shuhei/babel,michaelficarra/babel,KualiCo/babel,jmptrader/babel,shuhei/babel,andrewwilkins/babel,inikulin/babel,SaltTeam/babel,zenlambda/babel,manukall/babel,pingjiang/babel,lxe/babel,jridgewell/babel,mgcrea/babel,SaltTeam/babel,benjamn/babel,framewr/babel,benjamn/babel,babel/babel,jnuine/babel,zjmiller/babel,sejoker/babel,dekelcohen/babel,AgentME/babel,pingjiang/babel,jackmew/babel,prathamesh-sonpatki/babel,zorosteven/babel,abdulsam/babel,forivall-old-repos/tacoscript-babel-shared-history,vhf/babel,ming-codes/babel,andrejkn/babel,kaicataldo/babel,spicyj/babel,mrapogee/babel,jchip/babel,andrejkn/babel,cgvarela/babel,ramoslin02/babel,ellbee/babel,tikotzky/babel,chicoxyzzy/babel,ajcrites/babybel,cesarandreu/6to5,maurobringolf/babel,Skillupco/babel,Skillupco/babel,michaelficarra/babel,Industrial/babel,kedromelon/babel,gxr1020/babel,thorikawa/babel,Jeremy017/babel,forivall/babel,ezbreaks/babel,spicyj/babel,ryankanno/babel,greyhwndz/babel,mcanthony/babel,STRML/babel
import * as t from "../../../types"; export var metadata = { group: "builtin-trailing" }; function remap(path, key, create) { // ensure that we're shadowed if (!path.inShadow()) return; var shadowed = path.node._shadowedFunctionLiteral; var fnPath = path.findParent(function (path) { if (shadowed) { return path.node === shadowed; } else { return !path.is("shadow") && (path.isFunction() || path.isProgram()) } }); var cached = fnPath.getData(key); if (cached) return cached; var init = create(); var id = path.scope.generateUidIdentifier(key); fnPath.setData(key, id); fnPath.scope.push({ id, init }); return id; } export var visitor = { ThisExpression() { return remap(this, "this", () => t.thisExpression()); }, ReferencedIdentifier(node) { if (node.name === "arguments") { return remap(this, "arguments", () => t.identifier("arguments")); } } };
src/babel/transformation/transformers/internal/shadow-functions.js
import * as t from "../../../types"; export var metadata = { group: "builtin-trailing" }; function remap(path, key, create) { // ensure that we're shadowed if (!path.inShadow()) return; var fnPath = path.findParent((path) => !path.is("shadow") && (path.isFunction() || path.isProgram())); var shadowed = path.node._shadowedFunctionLiteral; if (shadowed && shadowed !== fnPath.node) return; var cached = fnPath.getData(key); if (cached) return cached; var init = create(); var id = path.scope.generateUidIdentifier(key); fnPath.setData(key, id); fnPath.scope.push({ id, init }); return id; } export var visitor = { ThisExpression() { return remap(this, "this", () => t.thisExpression()); }, ReferencedIdentifier(node) { if (node.name === "arguments") { return remap(this, "arguments", () => t.identifier("arguments")); } } };
rejigger shadowd function findParent logic
src/babel/transformation/transformers/internal/shadow-functions.js
rejigger shadowd function findParent logic
<ide><path>rc/babel/transformation/transformers/internal/shadow-functions.js <ide> // ensure that we're shadowed <ide> if (!path.inShadow()) return; <ide> <del> var fnPath = path.findParent((path) => !path.is("shadow") && (path.isFunction() || path.isProgram())); <add> var shadowed = path.node._shadowedFunctionLiteral; <ide> <del> var shadowed = path.node._shadowedFunctionLiteral; <del> if (shadowed && shadowed !== fnPath.node) return; <add> var fnPath = path.findParent(function (path) { <add> if (shadowed) { <add> return path.node === shadowed; <add> } else { <add> return !path.is("shadow") && (path.isFunction() || path.isProgram()) <add> } <add> }); <ide> <ide> var cached = fnPath.getData(key); <ide> if (cached) return cached;